簡體   English   中英

如何將每個像素的 colors 作為元數據添加到 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)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM