首页 > 解决方案 > 如何使用 plt.imshow() 查看图像而不会出现“ValueError:无法将大小为 49152 的数组重塑为形状 (128,128)”?

问题描述

我正在尝试显示来自我的验证集的 9 个图像以及我的模型预测的类,但是由于plt.imshow(). 我的图像的像素和通道数是(128, 128, 3)(RGB)。我已经尝试将重塑大小更改为(128, 128, 1)and(128, 128, 3)并且(1, 128, 128)这些选项都不起作用。我怎么知道这些数字应该是什么才能使 plt.imshow() 成功工作?我知道有相关的 StackOverflow 问题,但这些帖子的答案对我没有帮助。

target_size=(128,128) # target pixel size of each image
batch_size = 20  # the number of images to load per iteration

# configure a data generator which will rescale the images and create a training
# and test split where the test set is 10% of the data
data_gen_3 = tf.keras.preprocessing.image.ImageDataGenerator(rescale=1./255, validation_split=0.1)

val_img = data_gen_3.flow_from_directory(data_path, 
                                               subset='validation',
                                               color_mode='rgb',
                                               target_size=target_size,
                                               batch_size=batch_size,
                                               class_mode='categorical')

# get a sample of 20 (batch_size) validation images
sample_imgs_val, sample_labels_val = next(val_img)

# predict the class for the sample val images using the final model called "convnet"
X_pred_class = convnet.predict(sample_imgs_val)

# get the most likely class number for the prediction for each image
predicted_classes = np.argmax(X_pred_class, axis=1)

# display 9 of the images along with the predicted class
for img in range(9):
    plt.subplot(3, 3, img + 1, frameon=False)
    plt.imshow( np.reshape(sample_imgs_val[img],(128,128)) )
    plt.title(predicted_classes[img])
plt.show()

标签: pythonimagetensorflowreshape

解决方案


matplotlib可以显示彩色图片,例如3通道的图片。我不明白您为什么要尝试删除频道的尺寸。

如果要删除通道,则类似于将其转换为灰度图像。为此,我建议您使用PIL

from PIL import Image

grey_image = np.array(Image.fromarray(color_image).convert('L'))

您将必须更改cmapinmatplotlib才能看到灰度图片。

plt.imshow(grey_image, cmap='Greys')

如果您不想将图像转换为灰度图像,则应将图片保持原样。


推荐阅读