Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get x, y values of pixels of certain color with python PIL

I'm really struggling with understanding how to manipulate images with PIL. I'm trying to return the x and y coords of all the pixels that match a certain color. So in pseudo-code:

img = ImageGrab.grab(bbox)
pixels = img.getdata()
for i in range(len(pixels)):
    if pixels[i] == (255, 0, 0, 255) # red for example:
        coords.append(pixels[i].x)
        coords.append(pixels[i].y)

I simply don't know how to do the last bit where you append the x and y. Is there a function for this?

Thanks!

like image 835
dwib Avatar asked Dec 13 '25 04:12

dwib


1 Answers

Like this:

from PIL import ImageGrab

img = ImageGrab.grab()
pixels = img.load()
width, height = img.size
coords = []
for x in range(width):
    for y in range(height):
        if pixels[x, y] == (255, 0, 0):
            coords.append((x, y))
like image 76
Alderven Avatar answered Dec 15 '25 16:12

Alderven



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!