Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
175 views
in Technique[技术] by (71.8m points)

python - Get Hex Color Code & Coordinate of The Pixel in A Image

imagine i have a 3x3 image & numbers as it's pixel

123
456
789

using python i want value of each pixel in hex-color code line by line, like using above example as a image if a run the script i should get the output something like:

1st pixel (which is 1) - hex color code
2nd pixel (which is 2) - hex color code
3rd pixel (which is 3) - hex color code

so please help me how can i achieve this output Note: My image in most cases will not be more than 100 pixels

I am Using Python3 & Debian based Linux Distro

Thanks for answering in advance

Edit: What I Tried is

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}")

But this is not giving me correct values

question from:https://stackoverflow.com/questions/65645044/get-hex-color-code-coordinate-of-the-pixel-in-a-image

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

If you want to have iteration along the x-axis, you can write like:

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}")

Thinking of the for statement, x and y are going to change like (x,y) = (0,0), (0,1),... in your initial code. You want to first iterate over x and then iterate over y; you can write iteration over y, wrapping iteration over x.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...