Converting Image To Grayscale
Solution 1:
You've encountered a spot where Python's type system isn't protecting you in the way that C++ would.
cv2.IMREAD_GRAYSCALE
and cv2.COLOR_BGR2GRAY
are values from different enumerations. The former, whose numerical value is 0, applies to cv2.imread()
. The latter, whose numerical value is 6, applies to cv2.cvtColor()
. C++ would have told you that cv2.IMREAD_GRAYSCALE
can't be passed to cv2.cvtColor()
. Python quietly accepts the corresponding int value.
Thus, you think you're asking cv2 to convert a color image to gray, but by passing cv2.IMREAD_GRAYSCALE
, cv2.cvtColor()
sees the value 0, and thinks you're passing cv2.COLOR_BGR2BGRA
. Instead of a grayscale image, you get the original image with an alpha channel added.
gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
is what you need instead.
The other issue you're seeing, assuming you're using a Jupyter notebook, is that cv2
layers color planes in BGR order instead of RGB. To display them properly, first do
image_rgb = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)
and then display the result.
Solution 2:
The images that are not gray are the still 3d arrays, that is to say they still somehow retain color information, the reason you are seeing blue and green is because in those 3d arrays the red and green channels in the first case and the blue & red channels in the second have been reduced to 0 leaving only the blue and green that you see.
In order to read the image as grayscale you would use
img_gray=cv2.cvtColor(img, cv2.COLOR_RGB2GRAY)
This will yield a 2d array with values between 0 and 255 corresponding to how bright the pixel should be instead of how bright each of the 3 color channels of the pixel should be.
Post a Comment for "Converting Image To Grayscale"