首页 > 解决方案 > plt.imshow() 中图像数据的尺寸无效

问题描述

我正在使用 mnist 数据集在 keras 背景中训练胶囊网络。训练后,我想显示来自 mnist 数据集的图像。对于加载图像,使用 mnist.load_data()。数据存储为 (x_train, y_train),(x_test, y_test)。现在,为了可视化图像,我的代码如下:

img_path = x_test[1]  
print(img_path.shape)
plt.imshow(img_path)
plt.show()

代码给出如下输出:

(28, 28, 1)

plt.imshow(img_path) 上的错误如下:

TypeError: Invalid dimensions for image data

如何以 png 格式显示图像。帮助!

标签: python-3.xmatplotlibkerastypeerrormnist

解决方案


根据@sdcbr 的评论,使用 np.sqeeze 减少了不必要的尺寸。如果图像是二维的,则 imshow 功能可以正常工作。如果图像有 3 个维度,那么您必须减少额外的 1 个维度。但是,对于更高暗度的数据,您必须将其减少到 2 暗度,因此 np.sqeeze 可能会应用多次。(或者您可以使用其他一些调暗功能来获得更高的暗淡数据)

import numpy as np  
import matplotlib.pyplot as plt
img_path = x_test[1]  
print(img_path.shape)
if(len(img_path.shape) == 3):
    plt.imshow(np.squeeze(img_path))
elif(len(img_path.shape) == 2):
    plt.imshow(img_path)
else:
    print("Higher dimensional data")

推荐阅读