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

4

我发现一个奇怪的问题,目前互联网上还没有解决方案。如果我读取一个 .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

另外我也尝试将所有的np.array()替换为np.asarray(),但结果仍然相同。

1个回答

8
根据 im.show 文档 的说明:
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 可以创建一个 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() 

产量 这里输入图片描述
附:如果您检查
im = Image.open('dot.png') # A single blue pixel
im1 = np.asarray(im)
print(im1.dtype)

你会发现im1.dtype也是uint8

1
已解决:D 谢谢你超快的回复 :P - LomaxOnTheRun
你很聪明。原始问题的解决方案。 - Ashish Saini

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接