How to view images using plt.imshow() without getting "ValueError: cannot reshape array of size 49152 into shape (128,128)"?

How to view images using plt.imshow() without getting "ValueError: cannot reshape array of size 49152 into shape (128,128)"?

我正在尝试显示来自我的验证集的 9 个图像以及我的模型预测的 class,但由于 plt.imshow() 的重塑元素,我遇到了错误。我的图像的像素和通道数是 (128, 128, 3) (RGB)。我尝试将这些选项的重塑大小更改为 (128, 128, 1)(128, 128, 3) 以及 (1, 128, 128) 和 none。我如何知道这些数字应该是多少才能使 plt.imshow() 成功运行?我知道有相关的 Whosebug 问题,但这些帖子的答案对我没有帮助。

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

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

如果你想删除通道,那类似于将它变成灰度图像。为此,我建议您使用 PIL:

from PIL import Image

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

您必须更改 matplotlib 中的 cmap 才能看到灰度图片。

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

如果您不想将图像变成灰度,您应该让图片保持原样。