我正在尝试保存灰度图像(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
答案 0 :(得分:1)
请注意,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()
答案 1 :(得分:0)
您需要在调用matplotlib.pyplot.show()之前指定colormap。 默认情况下,当您传递3D数组时,该函数需要RGB图像。
示例:
im = np.squeeze(im)
plt.imshow(im,cmap='gray')
plt.show()