简体   繁体   中英

Can't convert black&white image to grayscale in Opencv

I'm new to opencv so don't mind me!

I want to convert an image which is a black and white image to gray scale image and save it by using cv2.imwrite() . The problem is that after I saved it to my local drive and read it back it returned as a 3 channels image. What is the problem here? Here is my code

import cv2

image = cv2.imread("path/to/image/image01.jpg")
print(image.shape) # return (128, 128, 3)

gray_image = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
print(gray_image.shape) # return (128, 128)
cv2.imwrite("path/to/dir/gray01.jpg", gray_image)

new_gray_img = cv2.imread("path/to/dir/gray01.jpg")
print(new_gray_img.shape) # return (128, 128, 3)

here is the image i want to convert to gray.

cv2.imread loads images with 3 channels by default

You can replace the last two lines of code using:

new_gray_img = cv2.imread("path/to/dir/gray01.jpg",cv2.CV_LOAD_IMAGE_GRAYSCALE)
print(new_gray_img.shape) 

Another method is to load image with scipy :

from scipy.ndimage import imread
new_gray_image=imread("path/to/dir/gray01.jpg")

Try to read the image directly in grayscale cv2.imread("path/to/dir/gray01.jpg", 0)

import cv2

image = cv2.imread("path/to/image/image01.jpg")
print(image.shape) # return (128, 128, 3)

gray_image = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
print(gray_image.shape) # return (128, 128)
cv2.imwrite("path/to/dir/gray01.jpg", gray_image)

# here is the change
new_gray_img = cv2.imread("path/to/dir/gray01.jpg", 0)
print(new_gray_img.shape) # return (128, 128)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM