I would like to store a PNG image in Python where the RGB values are given by the list
我想在Python中存储一个PNG图像,其中列表给出RGB值
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.
(行、列、RGB三元组),以及默认值[255、255、255]和关于图像总维数的信息。
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.
使用PIL,我当然可以将条目转换成密集的m×n×3矩阵,但这不适合存储;矩阵的维数可以是一万。
Is there another way to create a PNG image with the above information?
是否有其他方法用上述信息创建PNG图像?
2 个解决方案
#1
5
The PurePNG library writes a file line-by-line and only requires a row iterator:
PurePNG库逐行写一个文件,只需要行迭代器:
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
#2
2
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()
#1
5
The PurePNG library writes a file line-by-line and only requires a row iterator:
PurePNG库逐行写一个文件,只需要行迭代器:
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
#2
2
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()