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


当前回答

与pygame

所以这应该是我测试的(如果你没有pygame,你必须安装pygame,使用pip -> pip install pygame(有时不工作,所以在这种情况下,你必须下载轮子或其他东西,但你可以在谷歌上查找):

import pygame


pygame.init()
win = pygame.display.set_mode((128, 128))
pygame.surfarray.blit_array(win, yourarray)
pygame.display.update()
pygame.image.save(win, 'yourfilename.png')

只要记住根据你的数组改变显示的宽度和高度

这是一个例子,运行这段代码:

import pygame
from numpy import zeros


pygame.init()
win = pygame.display.set_mode((128, 128))
striped = zeros((128, 128, 3))
striped[:] = (255, 0, 0)
striped[:, ::3] = (0, 255, 255)
pygame.surfarray.blit_array(win, striped)
pygame.display.update()
pygame.image.save(win, 'yourfilename.png')

其他回答

您可以使用PyPNG。它是一个纯Python(无依赖)开源PNG编码器/解码器,它支持将NumPy数组写入图像。

纯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

Imageio是一个Python库,它提供了一个简单的接口来读取和写入广泛的图像数据,包括动画图像、视频、体积数据和科学格式。它是跨平台的,运行在Python 2.7和3.4+上,易于安装。

这是一个灰度图像的例子:

import numpy as np
import imageio

# data is numpy array with grayscale value for each pixel.
data = np.array([70,80,82,72,58,58,60,63,54,58,60,48,89,115,121,119])

# 16 pixels can be converted into square of 4x4 or 2x8 or 8x2
data = data.reshape((4, 4)).astype('uint8')

# save image
imageio.imwrite('pic.jpg', data)

你可以在Python中使用'skimage'库

例子:

from skimage.io import imsave
imsave('Path_to_your_folder/File_name.jpg',your_array)

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

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