Reputation: 467
Background:
I'm new to using Python's PIL for photo manipulation, and have very recently found the need for a basic photo processing function within an existing program. My program currently imports an image (effectively a high res shot of the night sky) in which there is a large proportion of black space (obviously) and several bright white maxima.
Question:
What is the best way of finding the coordinates (relative to the canvas coordinates if possible) of every maxima in the imported image?
I have looked through the PIL documentation, and have found ways to obtain the number of pixels of a certain colour, but of course this doesn't fulfil my requirements. As I say, I'm new to PIL/Photo-manipulation with Python, so any help on this would be fantastic.
Thanks in advance! :)
Upvotes: 1
Views: 1854
Reputation: 2215
There is a getextrema()
method that returns the lowest and highest image data used for every band. So in order to find the brightest pixels, you need a grayscale copy of your image first. Then you can iterate over every pixel in the image and check each pixel whether it has the highest grayscale value:
grayscale = image.convert('L')
minima, maxima = grayscale.getextrema()
for width in image.size[0]:
for height in image.size[1]:
if grayscale.getpixel((width, height)) == maxima:
# So here we have one pixel with the highest brightness.
However dependent on what you are actually try to achieve there might be simpler and more efficient ways of doing it. For example when you want to paste all the brightest pixels on a black background, you could do it like that:
grayscale = image.convert('L')
minima, maxima = grayscale.getextrema()
mask = image.point([0] * maxima + [255] * (256 - maxima))
new_image = PIL.Image.new('RGB', image.size)
new_image.paste(image, mask=mask)
Upvotes: 2