1. 程式人生 > >將Numpy陣列儲存為影象

將Numpy陣列儲存為影象

有一個Numpy陣列型別的矩陣,如何將它作為影象寫入磁碟?任何格式的影象都行(PNG,JPEG,BMP ...)。

最佳解決辦法

可以使用scipy.misc,程式碼如下:

  1. import scipy.misc

  2. scipy.misc.imsave('outfile.jpg', image_array)

上面的scipy版本會標準化所有影象,以便min(資料)變成黑色,max(資料)變成白色。如果資料應該是精確的灰度級或準確的RGB通道,則解決方案為:

  1. import scipy.misc

  2. scipy.misc.toimage(image_array, cmin=0.0, cmax=...).save('outfile.jpg')

第二種解決辦法

使用PIL

給定一個numpy陣列"A":

  1. from PIL import Image

  2. im = Image.fromarray(A)

  3. im.save("your_file.jpeg")

你可以用幾乎任何你想要的格式來替換"jpeg"。有關格式詳見here更多細節

第三種辦法

純Python(2& 3),沒有第三方依賴關係的程式碼片段。

此函式寫入壓縮的真彩色(每個畫素4個位元組)RGBA PNG。

  1. def write_png(buf, width, height):

  2. """ buf: must be bytes or a bytearray in Python3.x,

  3. a regular string in Python2.x.

  4. """

  5. import zlib, struct

  6. # reverse the vertical line order and add null bytes at the start

  7. width_byte_4 = width * 4

  8. raw_data = b''.join(b'\x00' + buf[span:span + width_byte_4]

  9. for span in range((height - 1) * width_byte_4, -1, - width_byte_4))

  10. def png_pack(png_tag, data):

  11. chunk_head = png_tag + data

  12. return (struct.pack("!I", len(data)) +

  13. chunk_head +

  14. struct.pack("!I", 0xFFFFFFFF & zlib.crc32(chunk_head)))

  15. return b''.join([

  16. b'\x89PNG\r\n\x1a\n',

  17. png_pack(b'IHDR', struct.pack("!2I5B", width, height, 8, 6, 0, 0, 0)),

  18. png_pack(b'IDAT', zlib.compress(raw_data, 9)),

  19. png_pack(b'IEND', b'')])

...資料應直接寫入以二進位制開啟的檔案,如下所示:

  1. data = write_png(buf, 64, 64)

  2. with open("my_image.png", 'wb') as fd:

  3. fd.write(data)

第四種辦法

matplotlib

  1. import matplotlib

  2. matplotlib.image.imsave('name.png', array)

適用於matplotlib 1.3.1,不確定更低的版本是否有效。文件:

  1. Arguments:

  2. *fname*:

  3. A string containing a path to a filename, or a Python file-like object.

  4. If *format* is *None* and *fname* is a string, the output

  5. format is deduced from the extension of the filename.

  6. *arr*:

  7. An MxN (luminance), MxNx3 (RGB) or MxNx4 (RGBA) array.

python,image,numpy

第五種辦法

如果使用matplotlib,也可以這樣做:

  1. import matplotlib.pyplot as plt

  2. plt.imshow(matrix) #Needs to be in row,col order

  3. plt.savefig(filename)

這將儲存plot(而不是影象本身)。

python,image,numpy

第6種辦法

  1. import cv2

  2. import numpy as np

  3. cv2.imwrite("filename.png", np.zeros((10,10)))

如果你需要做更多的處理,而不是儲存,這個庫比較有用。

參考文獻