如何在 python 中将 RGB 图像转换为灰度图像

how to convert rgb image To grayscale in python

我在以下方面需要帮助...

此代码:

show_picture(x_train[0])
print(x_train.shape)
plt.imshow(x_train,cmap=cm.Greys_r,aspect='equal')

returns 以下:

(267, 100, 100, 3)
TypeError                                 Traceback (most recent call last)
<ipython-input-86-649cf879cecf> in <module>()
2 show_picture(x_train[0])
  3 print(x_train.shape)
 ----> 4 plt.imshow(x_train,cmap=cm.Greys_r,aspect='equal')
  5 

5 frames
/usr/local/lib/python3.7/dist-packages/matplotlib/image.py in set_data(self, A)
697                 or self._A.ndim == 3 and self._A.shape[-1] in [3, 4]):
698             raise TypeError("Invalid shape {} for image data"
--> 699                             .format(self._A.shape))
700 
701         if self._A.ndim == 3:

TypeError: Invalid shape (267, 100, 100, 3) for image data

执行此操作的正确程序是什么

首先,您似乎正在处理一个由 267 个 100x100 RGB 图像组成的数组。我假设您使用的是 NumPy 数组。为了将图像转换为灰度,您可以使用 this 答案中提出的方法:

def rgb2gray(rgb):
    return np.dot(rgb[...,:3], [0.2989, 0.5870, 0.1140])

x_train_gray = rgb2gray(x_train)

请注意,这适用于一次性处理所有图像,生成的形状应为 (267, 100, 100)。但是,np.imshow 一次仅适用于一张图像,因此要绘制灰度图像,您可以执行以下操作:

plt.imshow(x_train_gray[0], cmap=plt.get_cmap('gray'), vmin=0, vmax=1)
plt.show()