將Numpy陣列儲存為影象
有一個Numpy陣列型別的矩陣,如何將它作為影象寫入磁碟?任何格式的影象都行(PNG,JPEG,BMP ...)。
最佳解決辦法
可以使用scipy.misc,程式碼如下:
-
import scipy.misc
-
scipy.misc.imsave('outfile.jpg', image_array)
上面的scipy
版本會標準化所有影象,以便min(資料)變成黑色,max(資料)變成白色。如果資料應該是精確的灰度級或準確的RGB通道,則解決方案為:
-
import scipy.misc
-
scipy.misc.toimage(image_array, cmin=0.0, cmax=...).save('outfile.jpg')
第二種解決辦法
使用PIL。
給定一個numpy陣列"A":
-
from PIL import Image
-
im = Image.fromarray(A)
-
im.save("your_file.jpeg")
你可以用幾乎任何你想要的格式來替換"jpeg"。有關格式詳見here更多細節
第三種辦法
純Python(2& 3),沒有第三方依賴關係的程式碼片段。
此函式寫入壓縮的真彩色(每個畫素4個位元組)RGBA
PNG。
-
def write_png(buf, width, height):
-
""" buf: must be bytes or a bytearray in Python3.x,
-
a regular string in Python2.x.
-
"""
-
import zlib, struct
-
# reverse the vertical line order and add null bytes at the start
-
width_byte_4 = width * 4
-
raw_data = b''.join(b'\x00' + buf[span:span + width_byte_4]
-
for span in range((height - 1) * width_byte_4, -1, - width_byte_4))
-
def png_pack(png_tag, data):
-
chunk_head = png_tag + data
-
return (struct.pack("!I", len(data)) +
-
chunk_head +
-
struct.pack("!I", 0xFFFFFFFF & zlib.crc32(chunk_head)))
-
return b''.join([
-
b'\x89PNG\r\n\x1a\n',
-
png_pack(b'IHDR', struct.pack("!2I5B", width, height, 8, 6, 0, 0, 0)),
-
png_pack(b'IDAT', zlib.compress(raw_data, 9)),
-
png_pack(b'IEND', b'')])
...資料應直接寫入以二進位制開啟的檔案,如下所示:
-
data = write_png(buf, 64, 64)
-
with open("my_image.png", 'wb') as fd:
-
fd.write(data)
第四種辦法
用matplotlib
:
-
import matplotlib
-
matplotlib.image.imsave('name.png', array)
適用於matplotlib 1.3.1,不確定更低的版本是否有效。文件:
-
Arguments:
-
*fname*:
-
A string containing a path to a filename, or a Python file-like object.
-
If *format* is *None* and *fname* is a string, the output
-
format is deduced from the extension of the filename.
-
*arr*:
-
An MxN (luminance), MxNx3 (RGB) or MxNx4 (RGBA) array.
第五種辦法
如果使用matplotlib,也可以這樣做:
-
import matplotlib.pyplot as plt
-
plt.imshow(matrix) #Needs to be in row,col order
-
plt.savefig(filename)
這將儲存plot(而不是影象本身)。
第6種辦法
-
import cv2
-
import numpy as np
-
cv2.imwrite("filename.png", np.zeros((10,10)))
如果你需要做更多的處理,而不是儲存,這個庫比較有用。