【问题标题】:Invalid dimension for image data in plt.imshow()plt.imshow() 中图像数据的尺寸无效
【发布时间】:2019-07-06 22:34:46
【问题描述】:

我正在使用 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 格式显示图像。救命!

【问题讨论】:

  • 您应该删除多余的渠道维度。试试plt.imshow(np.squeeze(img_path))
  • @sdcbr 非常感谢。它有效..
  • 这能回答你的问题吗? Showing an image with pylab.imshow()

标签: python-3.x matplotlib keras typeerror mnist


【解决方案1】:

根据@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")

【讨论】:

    【解决方案2】:

    您可以使用tf.squeeze 从张量的形状中删除大小为 1 的维度。

    plt.imshow( tf.shape( tf.squeeze(x_train) ) )
    

    Check out TF2.0 example

    【讨论】:

      【解决方案3】:

      例子:

      plt.imshow(test_images[0])
      

      TypeError:图像数据的形状无效 (28, 28, 1)

      更正:

      plt.imshow((tf.squeeze(test_images[0])))
      

      Number 7

      【讨论】:

        【解决方案4】:

        matplotlib.pyplot.imshow() 不支持形状为(h, w, 1) 的图像。只需将图像重塑为(h, w):newimage = reshape(img,(h,w)),即可移除图像的最后一个维度。

        【讨论】:

          猜你喜欢
          • 2017-09-19
          • 1970-01-01
          • 2012-09-11
          • 2016-07-25
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2011-06-15
          • 1970-01-01
          相关资源
          最近更新 更多