'numpy.ndarray' 对象没有属性 'imshow'

新手上路,请多包涵

我一直在尽我所能让 pyplot 显示图像 5 次。我不断收到此错误…

这是我的代码

import matplotlib.pyplot as plt
import os.path
import numpy as np

'''Read the image data'''
# Get the directory of this python script
directory = os.path.dirname(os.path.abspath(__file__))
# Build an absolute filename from directory + filename
filename = os.path.join(directory, 'cat.gif')
# Read the image data into an array
img = plt.imread(filename)

'''Show the image data'''
# Create figure with 1 subplot
fig, ax = plt.subplots(1, 5)
# Show the image data in a subplot

for i in ax:
    ax.imshow(img, interpolation='none')
# Show the figure on the screen
fig.show()

我确定它与二维数组有关,但我真的想不通。

我试过了

for i in ax:
    ax[i].imshow(img, interpolation='none')
# Show the figure on the screen
fig.show()

但我只是得到:

IndexError:只有整数、切片( : )、省略号( ... )、numpy.newaxis( None )和索引是有效的整数数组

原文由 Reed Johnson 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 830
2 个回答

这个:

 for i in ax:
    ax[i].imshow(img, interpolation='none')

没有意义,因为 I 不是索引。它是轴对象之一。

你的第一个案例是错误的,因为即使你遍历了这些项目,你还是在 ax 上调用了函数,而不是在各个轴上。

做这个:

 for a in ax:
    a.imshow(img, interpolation='none')

原文由 Arya McCarthy 发布,翻译遵循 CC BY-SA 4.0 许可协议

只需在代码之前的“ ax.flatten() ”之前添加此命令

ax = ax.flatten()
for a in ax:
    a.imshow(img, interpolation='none')
plt.show()

原文由 Mohamed A. Hashem 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题