2015-05-06 117 views
0

我遇到了一個奇怪的情況,那就是迄今爲止互聯網還沒有能夠解決。如果我讀取.png文件,然後嘗試顯示它,它可以很好地工作(在下面的示例中,文件是單個藍色像素)。但是,如果我嘗試手動創建此映像陣列,它只會顯示一個空白畫布。有什麼想法嗎?matplotlib.pyplot.imshow()顯示空白畫布

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(),但結果是一樣的。

回答

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陣列。

當你不指定D型,

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

NumPy的可能默認創建的D型int64int32uint8)陣列。


如果指定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.dtypeuint8了。

+0

解決:D感謝瘋狂的快速回復:P – TinyDancer