将Numpy数组保存为图像

原文链接:https://blog.csdn.net/xijuezhu8128/article/details/79661016

有一个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.  
  7. # reverse the vertical line order and add null bytes at the start

  8. width_byte_4 = width * 4

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

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

  11.  
  12. def png_pack(png_tag, data):

  13. chunk_head = png_tag + data

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

  15. chunk_head +

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

  17.  
  18. return b''.join([

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

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

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

  22. 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.  
  3. 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.

 

将Numpy数组保存为图像

 

第五种办法

如果使用matplotlib,也可以这样做:

 
  1. import matplotlib.pyplot as plt

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

  3. plt.savefig(filename)

这将保存plot(而不是图像本身)。

将Numpy数组保存为图像

 

第6种办法

python的opencv(http://docs.opencv.org/trunk/doc/py_tutorials/py_tutorials.html)。

 
  1. import cv2

  2. import numpy as np

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

如果你需要做更多的处理,而不是保存,这个库比较有用。

参考文献