请选择 进入手机版 | 继续访问电脑版
  • 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    公众号

将Numpy数组保存为图像

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

有一个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)

  • Original source

  • 另见:Rust Port from this question.

  • 使用示例感谢@Evgeni Sergeev:https://stackoverflow.com/a/21034111/432509

第四种办法

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种办法

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

import cv2
import numpy as np

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

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

参考文献

  • Saving a Numpy array as an image


鲜花

握手

雷人

路过

鸡蛋
专题导读
上一篇:
在Pandas中更改列的数据类型【方法总结】发布时间:2022-05-14
下一篇:
使用JUnit配置IntelliJ IDEA进行单元测试发布时间:2022-05-14
热门推荐
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap