[英]Get Hex Color Code & Coordinate of The Pixel in A Image
想象一下,我有一個 3x3 的圖像和數字,因為它是像素
123
456
789
使用 python 我希望逐行使用十六進制顏色代碼中的每個像素的值,例如使用上面的示例作為圖像,如果運行腳本我應該得到 output 類似:
1st pixel (which is 1) - hex color code
2nd pixel (which is 2) - hex color code
3rd pixel (which is 3) - hex color code
所以請幫助我如何實現這個 output 注意:我的圖像在大多數情況下不會超過 100 像素
我正在使用基於 Python3 和 Debian 的 Linux 發行版
感謝您提前回答
編輯:我嘗試的是
from PIL import Image
img = Image.open('img.png')
pixels = img.load()
width, height = img.size
for x in range(width):
for y in range(height):
r, g, b = pixels[x, y]
# in case your image has an alpha channel
# r, g, b, a = pixels[x, y]
print(x, y, f"#{r:02x}{g:02x}{b:02x}")
但這並沒有給我正確的價值觀
如果要沿 x 軸進行迭代,可以這樣寫:
from PIL import Image
img = Image.open('img.png')
pixels = img.load()
width, height = img.size
for y in range(height): # this row
for x in range(width): # and this row was exchanged
r, g, b = pixels[x, y]
# in case your image has an alpha channel
# r, g, b, a = pixels[x, y]
print(x, y, f"#{r:02x}{g:02x}{b:02x}")
考慮for
語句,x 和 y 將在您的初始代碼中像 (x,y) = (0,0), (0,1),... 一樣發生變化。 你想先迭代 x 然后迭代 y; 您可以在 y 上編寫迭代,在 x 上包裝迭代。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.