2015-11-02 144 views
5

雖然使用我爲某個項目下載的一些代碼並學習Python,但代碼所提取的一些文件是保存爲.npy數據文件的圖像。查看.npy圖像

我對Pythonnumpy比較陌生,我發佈之前瀏覽的很多資源都是關於保存爲.npy的號碼數據。有沒有一種方法可以查看使用此擴展名存儲的圖像以及以該格式保存自己的文件?

回答

6

.npy是numpy的陣列中的文件擴展名 - 您可以使用numpy.load閱讀:

import numpy as np 

img_array = np.load('filename.npy') 

一個來查看他們最簡單的方法是使用matplotlib的imshow功能:

from matplotlib import pyplot as plt 

plt.imshow(img_array, cmap='gray') 
plt.show() 

你可以也可用PIL or pillow

from PIL import Image 

im = Image.fromarray(img_array) 
# this might fail if `img_array` contains a data type that is not supported by PIL, 
# in which case you could try casting it to a different dtype e.g.: 
# im = Image.fromarray(img_array.astype(np.uint8)) 

im.show() 

這些函數不是Python標準庫的一部分,因此如果您尚未安裝matplotlib和/或PIL /枕頭,則可能需要安裝這些函數。我還假設這些文件是像素值的2D [rows, cols](黑白)或3D [rows, cols, rgb(a)](彩色)陣列。如果情況並非如此,那麼您將不得不告訴我們更多關於陣列格式的信息,例如img_array.shapeimg_array.dtype是什麼。

enter image description here

+0

這是足夠的指導,以幫助我弄明白。我認爲它們是圖像,但實際上它們是從讀取圖像的程序生成的數組。 –

+0

在使用PyCharm的Windows 10中發現了這個錯誤https://pastebin.com/CLmS805E –

+0

^錯誤是由於路徑造成的,似乎是一個Python bug! –