简体   繁体   中英

Why is a BGR image displayed as grayscale?

Context

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.

Issue

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:

BGR 图像显示为灰度

Grayscale image displaying as BGR:

灰度图像显示为 BGR

The assumption, that the original image img is displayed as grayscale in the first picture is wrong from my point of view, because:

  • You already found out, that img has three color channels.
  • It's kind of unlikely, that Matplotlib automatically converts an input image to grayscale.
  • It seems, that there's a slight red-ish "glimmer" on the left side of the image. Side notice: Due to the different color ordering of OpenCV and Matplotlib, I suspect this "glimmer" actually to be blue-ish, which is even more likely in such photographs.

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.

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