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

Tags: , , ,



imagine i have a 3×3 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

Answer

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.



Source: stackoverflow