Skip to main content
 首页 » 编程设计

python之我在使用 im.show() 时遇到错误

2025年02月15日7zengkefu

我正在尝试保存灰度图像 (​​256,256,1) 并将其显示在输出中。

im = data.astype(np.uint8) 
print im.shape 
im = np.transpose(im, (2,1,0))  
print im.shape 
im.show() 

但是,我收到以下错误:

(256, 256, 1) 
Traceback (most recent call last): 
  File "lmdb_reader.py", line 37, in <module> 
    plt.imshow(im) 
  File "/home/se/anaconda2/envs/caffeenv/lib/python2.7/site-packages/matplotlib/pyplot.py", line 3029, in imshow 
    **kwargs) 
  File "/home/se/anaconda2/envs/caffeenv/lib/python2.7/site-packages/matplotlib/__init__.py", line 1819, in inner 
    return func(ax, *args, **kwargs) 
  File "/home/se/anaconda2/envs/caffeenv/lib/python2.7/site-packages/matplotlib/axes/_axes.py", line 4922, in imshow 
    im.set_data(X) 
  File "/home/se/anaconda2/envs/caffeenv/lib/python2.7/site-packages/matplotlib/image.py", line 453, in set_data 
    raise TypeError("Invalid dimensions for image data") 
TypeError: Invalid dimensions for image data 

请您参考如下方法:

请注意 im.show() 不存在,但它可能只是问题中的错字。 真正的问题如下:

Matplotlib 的 pyplot.imshow 可以绘制维度 (N,M)(灰度)或 (N,M,3) 的图像( RGB 颜色)。你的图片是(N,M,1);因此,我们需要摆脱最后一个维度。

import matplotlib.pyplot as plt 
import numpy as np 
#create data of shape (256,256,1) 
data = np.random.rand(256,256,1)*255 
im = data.astype(np.uint8) 
print im.shape # prints (256L, 256L, 1L) 
# (256,256,1) cannot be plotted, therefore  
# we need to get rid of the last dimension: 
im = im[:,:,0] 
print im.shape # (256L, 256L) 
# now the image can be plotted 
plt.imshow(im, cmap="gray") 
plt.show()