cv2.cvtcolor bgr2gray seems get an error image

King Excel picture King Excel · Aug 28, 2018 · Viewed 8.6k times · Source

# the code is as follows, implemented, but the result is possibly wrong, it is not the grayscale i wanted, someone gonna help me with that, it's seems quite simple, but i just don't know what wrong

import cv2 import matplotlib.pyplot as plt import numpy as np import matplotlib.image as mpimg img = cv2.imread('calibration_test.png')

# i want simply convert the rgb image to grayscale and then print it out
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
plt.imshow(gray)
print(gray.shape)
# but the outcome is a colorful image

the original image i used

the ugly outcome

Answer

Hein Wessels picture Hein Wessels · Aug 28, 2018

The grayscale conversion was done correctly. The problem is in how you are displaying the image. Try this:

plt.imshow(gray, cmap='gray')

By default imshow adds it's own colour key to single channel images, to make it easier to view. A typical example is thermal images which usually show blue and red, but all the colours are only dependend on one channel.

Hope this helps!