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?
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
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()
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With