Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

create PNG image from sparse data

I would like to store a PNG image in Python where the RGB values are given by the list

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

(row, column, RGB triple), together with a default value of [255, 255, 255] and the information about the total dimensions of the image.

Using PIL, I could of course translate entries into a dense m-by-n-by-3 matrix, but that doesn't fit into memory; the matrix dimensions can be in the ten thousands.

Is there another way to create a PNG image with the above information?

like image 868
Nico Schlömer Avatar asked Nov 14 '15 20:11

Nico Schlömer


2 Answers

The PurePNG library writes a file line-by-line and only requires a row iterator:

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
like image 78
Nico Schlömer Avatar answered Oct 19 '22 19:10

Nico Schlömer


You could do it like this:

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()
like image 38
Michiel Overtoom Avatar answered Oct 19 '22 20:10

Michiel Overtoom