Reputation: 71
Is there a way to find a pixel (inside a surface / image) by color? like:
img = python.image.load("image.gif").convert()
img.find((255, 255, 255)) >> (50, 100) = white pixel
If you don't know what I mean, feel free to ask. Thank you!
Upvotes: 1
Views: 269
Reputation: 23480
def findPixel(img, r, g, b):
for x in range(0, img.get_width()):
for y in range(0, img.get_height()):
pixel = img.get_at((x, y))
if pixel[0] >= r and pixel[1] >= g and pixel[2] >= b:
return pixel
return None
This is written of the top of my head. Passing in your image object should word. If not you'll have to input the image.surface
object reference. But the idea of iterating over X and Y should work in theory.
get_width()
etc that you'll need to useget_rect()
Pygame host no function like this, but it does supply you with the ability to get or iterate over pixel positions.
There is a faster way and that is to store the entire image-array prior to the loop and iterate over that array instead of calling the get_at
function i believe, however I don't use Pygame these days so i can't test the optimization difference of the two implementations so i'll leave it at this and leave the optimization to you.
If you're interested in finding all the color values corresponding to your parameters (thanks SuperBiasedMan):
def findPixel(img, r, g, b):
found = []
for x in range(0, img.width):
for y in range(0, img.height):
pixel = img.get_at((x, y))
if pixel[0] >= r and pixel[1] >= g and pixel[2] >= b:
found.append((x, y))
return found
Note that this will be slower, but you'll find all the pixels in one iteration.
Upvotes: 1