1

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

zabop
  • 6,750
  • 3
  • 39
  • 84
DEVLOPR69
  • 13
  • 7
  • Please show us what you have tried and what was your problem with it. – zabop Jan 09 '21 at 16:41
  • I guess you have a palette image as it is so small and has so few colours - read all about them here... https://stackoverflow.com/a/52307690/2836621 – Mark Setchell Jan 09 '21 at 16:50
  • Ok, so you're not getting the values you expect. How are the values you're getting different from the values you're expecting? – Paul M. Jan 09 '21 at 16:50
  • What do you mean "left to right" and "up to down"? Edit your question and include an example of expected output vs actual output. Make it as easy as possible for people to want to help you. – Paul M. Jan 09 '21 at 16:55

1 Answers1

2

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.

Dharman
  • 30,962
  • 25
  • 85
  • 135