我有一个Numpy数组类型的矩阵。我怎么把它作为映像写到磁盘上呢?任何格式都可以(png, jpeg, bmp…)一个重要的限制是PIL不存在。


当前回答

使用cv2.imwrite。

import cv2
assert mat.shape[2] == 1 or mat.shape[2] == 3, 'the third dim should be channel'
cv2.imwrite(path, mat) # note the form of data should be height - width - channel  

其他回答

假设你想要一张灰度图像:

im = Image.new('L', (width, height))
im.putdata(an_array.flatten().tolist())
im.save("image.tiff")

一个答案使用PIL(只是在情况下它是有用的)。

给定一个numpy数组" a ":

from PIL import Image
im = Image.fromarray(A)
im.save("your_file.jpeg")

你可以用几乎任何你想要的格式替换“jpeg”。更多关于格式的细节请点击这里

为了将numpy数组保存为image,你有几个选择:

1)其他优点:OpenCV

进口cv2 cv2。Imwrite('扩展名为。jpg ', numpy_array)

2) Matplotlib

从matplotlib导入pyplot作为PLT plt。Imsave('扩展名为。jpg ', numpy_array)

3)药片

来自PIL import Image image = image .fromarray(numpy_array) 的形象。保存('扩展名为。jpg)')

4)...

纯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 fh:
    fh.write(data)

原始来源 参见:Rust Port来自这个问题。 感谢@Evgeni Sergeev的示例用法:https://stackoverflow.com/a/21034111/432509

使用cv2.imwrite。

import cv2
assert mat.shape[2] == 1 or mat.shape[2] == 3, 'the third dim should be channel'
cv2.imwrite(path, mat) # note the form of data should be height - width - channel