从稀疏数据创建 PNG 图像

create PNG image from sparse data

我想将 PNG 图像存储在 Python 中,其中 RGB 值由列表给出

entries = [
    [1, 2, [255, 255, 0]],
    [1, 5, [255, 100, 0]],
    [2, 5, [0, 255, 110]],
    # ...
    ]

(行、列、RGB 三元组),以及默认值 [255, 255, 255] 和有关图像总尺寸的信息。

使用 PIL,我当然可以将 entries 转换为密集的 m-by-n-by-3 矩阵,但是不适合记忆;矩阵维数可以上万

是否有其他方法可以使用上述信息创建 PNG 图像?

你可以这样做:

from PIL import Image

sparse = [
    [1, 2, [255, 255, 0]],
    [1, 5, [255, 100, 0]],
    [2, 5, [0, 255, 110]],
    ]

im = Image.new("RGB", (20, 20), (255, 255, 255))
for item in sparse:
    x, y, color = item
    im.putpixel((x, y), tuple(color))

im.save("schlomer.png")
im.show()

PurePNG library逐行写入一个文件,只需要一个行迭代器:

def write_png(A, filename):
    m, n = A.shape

    w = png.Writer(n, m, greyscale=True, bitdepth=1)

    class RowIterator:
        def __init__(self, A):
            self.A = A.tocsr()
            self.current = 0
            return

        def __iter__(self):
            return self

        def __next__(self):
            if self.current+1 > A.shape[0]:
                raise StopIteration
            out = numpy.ones(A.shape[1], dtype=bool)
            out[self.A[self.current].indices] = False
            self.current += 1
            return out

    with open(filename, 'wb') as f:
        w.write(f, RowIterator(A))

    return