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

时间:2017-05-13 20:39:30

标签: python numpy

我一直在尽我所能让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()

我确定它与2D阵列有关,但我真的无法弄明白。

我试过

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

但我得到:

IndexError:只有整数,切片(:),省略号(...),numpy.newaxis(None)和整数或布尔数组才是有效索引

3 个答案:

答案 0 :(得分:5)

此:

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

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

你的第一个案例是错误的,因为即使你循环遍历这些项目,你也可以在ax上调用该函数,而不是单个轴。

这样做:

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

答案 1 :(得分:0)

您可以像下面那样检查斧头

type(ax)
>>> <class 'numpy.ndarray'>

ax
>>> [<matplotlib.axes._subplots.AxesSubplot object at 0x0000028F13AFC668>
 <matplotlib.axes._subplots.AxesSubplot object at 0x0000028F15C6FCF8>
 <matplotlib.axes._subplots.AxesSubplot object at 0x0000028F15CA23C8>
 <matplotlib.axes._subplots.AxesSubplot object at 0x0000028F15CC9A58>
 <matplotlib.axes._subplots.AxesSubplot object at 0x0000028F15CFA160>]

如果您确实要使用“ i”,请像这样使用 enumerate()

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

'axs'是首选,因为它是多个。

最后,您可以在下面进行测试

import numpy as np
import matplotlib.pyplot as plt
from skimage import data

'''Read the image data'''
img = data.chelsea()   # cat image

'''Show the image data'''
# Create figure with 1 subplot
fig, axs = plt.subplots(nrows=1, ncols=5, figsize=(10, 3))

print(axs)
# [<matplotlib.axes._subplots.AxesSubplot object at 0x000001D7A841C710>
#  <matplotlib.axes._subplots.AxesSubplot object at 0x000001D7AA58FCC0>
#  <matplotlib.axes._subplots.AxesSubplot object at 0x000001D7AA5C2390>
#  <matplotlib.axes._subplots.AxesSubplot object at 0x000001D7AA5E9A20>
#  <matplotlib.axes._subplots.AxesSubplot object at 0x000001D7AA61A128>]

print(axs.shape)  # (5,)

# Show the image data in a subplot
for i, ax in enumerate(axs):
    print(ax)     # AxesSubplot(0.125,0.11;0.133621x0.77)
    img_made_changeable = img[i:(i + 2) * 50]
    ax.imshow(img_made_changeable, interpolation='none')

# Show the figure on the screen
plt.show()

答案 2 :(得分:0)

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

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