matplotlib.pyplot.imshow()显示空白画布

时间:2015-05-06 09:43:56

标签: matplotlib imshow

我遇到了一个奇怪的问题,到目前为止,互联网尚无法解决。如果我在.png文件中读取,然后尝试显示它,它完美地工作(在下面的示例中,文件是单个蓝色像素)。但是,如果我尝试手动创建此图像数组,它只显示一个空白画布。有什么想法吗?

from PIL import Image
import matplotlib.pyplot as plt
import numpy as np

im = Image.open('dot.png') # A single blue pixel
im1 = np.asarray(im)
print im1
# [[[  0 162 232 255]]]

plt.imshow(im1, interpolation='nearest')
plt.show() # Works fine

npArray = np.array([[[0, 162, 232, 255]]])
plt.imshow(npArray, interpolation='nearest')
plt.show() # Blank canvas

npArray = np.array([np.array([np.array([0, 162, 232, 255])])])
plt.imshow(npArray, interpolation='nearest')
plt.show() # Blank canvas

P.S。我也尝试用np.asarray()替换所有的np.array(),但结果是一样的。

1 个答案:

答案 0 :(得分:2)

根据the im.show docs

X : array_like, shape (n, m) or (n, m, 3) or (n, m, 4)
    Display the image in `X` to current axes.  `X` may be a float
    array, a uint8 array or a PIL image.

因此X可能是dtype uint8的数组。

如果未指定dtype,

In [63]: np.array([[[0, 162, 232, 255]]]).dtype
Out[63]: dtype('int64')

默认情况下,NumPy可能会创建一个dtype int64int32 uint8)的数组。

如果明确指定dtype='uint8',则

import matplotlib.pyplot as plt
import numpy as np

npArray = np.array([[[0, 162, 232, 255]]], dtype='uint8')
plt.imshow(npArray, interpolation='nearest')
plt.show() 

的产率 enter image description here

PS。如果你检查

im = Image.open('dot.png') # A single blue pixel
im1 = np.asarray(im)
print(im1.dtype)

你会发现im1.dtype也是uint8