23

I have the following RGB image imRGB

import cv2
import matplotlib.pyplot as plt

#Loading the RGB image
imRGB = cv2.imread('*path*')

imRGB.shape
>>(128L, 128L, 3L)

#plotting
plt.imshow(imRGB)

imRGB

I convert this to a grayscale image imGray

imGray = cv2.cvtColor(imRGB, cv2.COLOR_BGR2GRAY)

imGray.shape
>>(128L, 128L)

#plotting
plt.imshow(imGray)

imGray


Question: Why does the grayscale image imGray is shown in color?

akilat90
  • 5,436
  • 7
  • 28
  • 42

2 Answers2

41

imRGB was a 3D matrix (height x width x 3).
Now imGray is a 2D matrix in which there are no colors, only a "luminosity" value. So matplotlib applied a colormap by default.

Read this page and try to apply a grayscale colormap or a different colormap, check the results.

plt.imshow(imGray, cmap="gray")

Use this page as reference for colormaps. Some colormap could not work, if it occurs try another colormap.

marcoresk
  • 1,837
  • 2
  • 17
  • 29
  • You can set this as default (specially if you will work only with greyscale images) with this: `plt.rcParams['image.cmap'] = 'gray'` For more, checkout [this question](https://stackoverflow.com/questions/33185037/how-to-set-default-colormap-in-matplotlib) – Rodrigo Laguna Apr 19 '18 at 19:00
1

If you want to display a single-channel grayscale image, you should rescale the values to [0,1.0] with dtype=float32, and pyplot will render the grayscale image with pseudocolor. So should choose the colormap to gray.

plt.imshow(imGray/255.0, cmap='gray')

According to the documentation: Image tutorial

For RGB and RGBA images, matplotlib supports float32 and uint8 data types. For grayscale, matplotlib supports only float32. If your array data does not meet one of these descriptions, you need to rescale it.

...

Pseudocolor can be a useful tool for enhancing contrast and visualizing your data more easily. This is especially useful when making presentations of your data using projectors - their contrast is typically quite poor.

Community
  • 1
  • 1
Charles Sun
  • 550
  • 4
  • 7