Zen35X
Zen35X

Reputation: 28

I want to create lists when the rgb value is the same a list is created and the pixel coordinates are stored inside for the same rgb value

What I am trying to achieve is that whenever I get the same rgb value the pixel coordinates are stored in a list for every different rgb value

Code:


from PIL import Image,ImageOps
file_name = "test.png"
og_image = Image.open(file_name)
gray_image = ImageOps.grayscale(og_image)
gray_scalefile = f"{file_name[:-3]}gray.png"
gray_image.save(gray_scalefile)
img = Image.open(gray_scalefile).convert('RGB')
pixels = img.load()
width, height = img.size
for x in range(width):
    for y in range(height):
        r,g,b = pixels[x,y]
        print(x, y, f'{r},{g},{b}')

This code uses PIL to convert test.png to a grayscale image and then it gets all the pixels and their rgb values I want to take all the pixel coordinates that are in the same rgb value and store them together for each rgb value that comes so an example is like 80,40 255 0 0 and 70, 20 255 0 0 i want these to go in a list together because they have the same rgb value

Upvotes: 0

Views: 243

Answers (1)

quamrana
quamrana

Reputation: 39354

You can just collect all the coordinates by their r,g,b values as keys:

from collections import defaultdict

pixels_by_colour = defaultdict(list)
for x in range(width):
    for y in range(height):
        r,g,b = pixels[x,y]
        pixels_by_colour[(r,g,b)].append((x,y))

Now if you think that you want all the coordinates of colour (r,g,b) (and there are some):

coords = pixels_by_colour[(r,g,b)]
print(coords)

Upvotes: 2

Related Questions