[英]how to get the pixel coordinate of image using python
So Question is a bit changed:所以问题有点改变:
I Have this piece of code:我有这段代码:
import re
from PIL import Image
def rgb_to_hex(rgb_color):
[r, g, b] = rgb_color
assert 0 <= r <= 255
assert 0 <= g <= 255
assert 0 <= b <= 255
r = hex(r).lstrip('0x')
g = hex(g).lstrip('0x')
b = hex(b).lstrip('0x')
r = (2 - len(r)) * '0' + r
g = (2 - len(g)) * '0' + g
b = (2 - len(b)) * '0' + b
hex_color = '#' + r + g + b
return hex_color
img = Image.open('img.png')
pix_val = list(img.getdata())
x, y = img.size
a = 0
for element in pix_val:
element = list(element)
del element[-1]
print(rgb_to_hex(element))
a += 1
if a == x:
a = 0
print("")
what this code does is it opens a image file and reads it's data & then column by column it prints the hex code of the pixel or a particular row & column这段代码的作用是打开一个图像文件并读取它的数据,然后逐列打印像素或特定行和列的十六进制代码
so what i want is that i also want to print the coordinate of the pixel.所以我想要的是我也想打印像素的坐标。
for example i have this image so i want the coordinate of the pixel whose pixel value i am printing.例如,我有这个图像,所以我想要我正在打印其像素值的像素的坐标。
Please help me请帮我
Thanks for answering in advance感谢您提前回答
you can try this:你可以试试这个:
import re
from PIL import Image
def rgb_to_hex(rgb_color):
[r, g, b] = rgb_color
assert 0 <= r <= 255
assert 0 <= g <= 255
assert 0 <= b <= 255
r = hex(r).lstrip('0x')
g = hex(g).lstrip('0x')
b = hex(b).lstrip('0x')
r = (2 - len(r)) * '0' + r
g = (2 - len(g)) * '0' + g
b = (2 - len(b)) * '0' + b
hex_color = '#' + r + g + b
return hex_color
img = Image.open('img.png')
pix_val = list(img.getdata())
x, y = img.size
a = 0
for element in pix_val:
element = list(element)
del element[-1]
print(rgb_to_hex(element))
# this line of code here:
print(f"x:{a%x} y:{int(a/x)}")
a += 1
You can also use fstring introduced in python 3.6 like:您还可以使用 python 3.6 中引入的 fstring,例如:
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}")
which outputs:输出:
0 0 #4777b9
0 1 #4878ba
0 2 #4a77ba
0 3 #4a75b9
0 4 #4b73b8
0 5 #4d75ba
...
Reference:参考:
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.