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



我需要以下方面的帮助…

这个代码:

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

返回以下内容:

(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数组。为了将图像转换为灰度,您可以使用以下答案中提出的方法:

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()

最新更新