如何将每个像素的颜色作为元数据添加到 png 图像文件中?

How to add colors of each pixels as metadata to png image file?

我有一个 4x4 的 png 文件。我尝试将所有像素和 RGB 颜色信息添加为元数据,如下所示:

'Dimension' 4x4
'Coordinates' 0,0;4,4
'Colors'
  x y  R    G   B
  0 0  100  45   50
  0 1   45  85  110
  0 2  240  35    0
  . .  .     .   .
  . .  .     .   .
         .
         .

代码如下:

from PIL.PngImagePlugin import PngImageFile, PngInfo
from PIL import Image

im = Image.open('DaVinci2.png')

pix = im.load()
w = im.size[0]
h = im.size[1]
pixelcolor=[]
for j in range(h):
    for i in range(w):
        print(i, j, pix[i, j])
        pixelcolor.append([i,j,pix[i, j]])
        print(pixelcolor)

metadata = PngInfo()
metadata.add_text("Dimension", '4x4')
metadata.add_text("Pixels", 0,0,4,4) #coordinates x1,y1,x2,y2
metadata.add_text("Colors", pixelcolor)

im.save("NewPath.png", pnginfo=metadata)
im = PngImageFile("NewPath.png")

错误如下:

Traceback (most recent call last):
  File "C:\Users\Hilmi\Desktop\Python\My exerises\Pixeldivide\metadata.py",
line 18, in <module>
    metadata.add_text("Pixels", 0,0,4,4) #coordinates x1,y1,x2,y2
TypeError: PngInfo.add_text() takes from 3 to 4 positional arguments but
6 were given

如何修改代码才能成功?

您可以最简单地使用 f-strings 将您的值嵌入到单个字符串中,如下所示:

metadata.add_text('Pixels', f'0,0,{w},{h}')

关于构建颜色字符串,类似于:

colourstring = 'x y R G B'
for j in range(h):
   for i in range(w):
      r, g, b = pix[i,j]
      colourstring += f'\n{i},{j},{r},{g},{b}'

然后:

metadata.add_text("Colors", colourstring)