I'm using Google Colab with OpenCV to work on a .jpg
image. Colab has issues with OpenCV's imshow
function, so matplotlib
is used for the printing of images. I know that OpenCV uses BGR and to display things properly with matplotlib
I need to use cv2
's cvtColor()
function.
When loading an image and displaying it, it displays as grayscale even though by default it should be BGR. Similarly, after converting to grayscale and displaying the image, it shows up as BGR.
Since the images are stored as numpy
arrays I tried finding the dimensions of these arrays. The image that should have been BGR (displayed as grayscale) was a three dimensional array as expected. Similarly, the image after conversion to grayscale was a two dimensional array, as expected, but it still displayed as BGR.
BGR image displaying as grayscale:
Grayscale image displaying as BGR:
The assumption, that the original image img
is displayed as grayscale in the first picture is wrong from my point of view, because:
img
has three color channels.So, for the first picture: Your visual percerption was just fooled by the image itself. :-)
The actual grayscale converted image (your second picture) is shown with the standard colormap of Matplotlib. As Mark and others correctly pointed out, you should change your code as follows to get an actual "grayscale image":
plt.imshow(img, cmap='gray')
Hope that helps!
In the case you want a color image transformed and displayed in grayscale:
import matplotlib as plt
# Reading color image as grayscale
img = cv2.imread(path, 0)
plt.imshow(img, cmap='gray')
plt.show()
where path is file location.
Another method is to the conversion by yourself. The filter you then should use is as follows:
def rgb2gray(rgb):
return np.dot(rgb[...,:3], [0.3, 0.59, 0.11]) # colorspace order [R, G, B]
grey_img = rgb2gray(img)
Where R is red, G is green and B is blue.
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.