0

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

DEVLOPR69
  • 13
  • 7

2 Answers2

1

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
DarQ
  • 92
  • 9
1

You can also use fstring introduced in python 3.6 like:

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: