简体   繁体   English

尝试显示从 rgb 转换的灰度图像时出错

[英]Error when trying to display grayscale image converted from rgb

I'm doing a project in deeplearning where I'll train a classifier using the SVHN dataset.我正在做一个深度学习项目,我将使用 SVHN 数据集训练分类器。

Initially, I had train_images and test_images with shapes (73257, 32, 32, 3) and (26032, 32, 32, 3), respectively and they are normally displayed using plt.imshow().最初,我有形状分别为 (73257, 32, 32, 3) 和 (26032, 32, 32, 3) 的 train_images 和 test_images,它们通常使用 plt.imshow() 显示。

I converted the images to greyscale using the following code:我使用以下代码将图像转换为灰度:

f = lambda img: tf.expand_dims(np.average(img, axis=-1), axis=-1).numpy()

train_images = f(train_images)
test_images = f(test_images)

I tried, as well:我也试过:

train_images = tf.image.rgb_to_grayscale(train_images).numpy()
test_images = tf.image.rgb_to_grayscale(test_images).numpy()

On both cases, the output gives images with shape (32, 32, 1) as items in each of the train_images, test_images - the new shapes are, therefore, (73257, 32, 32, 3) and (26032, 32, 32, 1), respectively.在这两种情况下,输出都将形状为 (32, 32, 1) 的图像作为每个 train_images, test_images 中的项目 - 因此,新形状是 (73257, 32, 32, 3) 和 (26032, 32, 32 , 1) 分别。

But, for some reason, when I try to display these new greyscale images, I get the following error : TypeError: Invalid dimensions for image data.但是,出于某种原因,当我尝试显示这些新的灰度图像时,出现以下错误: TypeError: Invalid dimensions for image data.

I have no idea why.我不知道为什么。

I solved the problem by using the following function for transforming to grayscale:我通过使用以下函数转换为灰度解决了这个问题:

f = lambda img: np.mean(img, axis=-1, keepdims=True)

Then displayed the image using:然后使用以下方法显示图像:

img = np.squeeze(array)
plt.imshow(img, cmap='Greys')

Where array is any item on train_images or test_images.其中 array 是 train_images 或 test_images 上的任何项目。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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