plt.imshow 显示 IPython 中灰度图像的彩色图像

plt.imshow shows color images for grayscale images in IPython

我有以下RGB图像 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)

我把它转成灰度图 imGray

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

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

#plotting
plt.imshow(imGray)


问题:为什么灰度图imGray显示为彩色?

imRGB 是一个 3D 矩阵(高 x 宽 x 3)。
现在 imGray 是一个二维矩阵,其中没有颜色,只有 "luminosity" 值。 所以 matplotlib 默认应用颜色图。

阅读this page并尝试应用灰度颜色图或不同的颜色图,检查结果。

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

对色图使用 this page as reference。一些颜色图无法工作,如果它发生尝试另一个颜色图。

如果要显示单通道灰度图,需要将dtype=float32的值重新缩放为[0,1.0],pyplot会用伪彩色渲染灰度图。所以应该选择colormap为gray.

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

根据文档: 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.