pyvips icon indicating copy to clipboard operation
pyvips copied to clipboard

Randomly choosing a pixel with a desired value

Open Rasaa84 opened this issue 2 years ago • 1 comments

Hi,

How can I randomly select a pixel with a particular value from a single-band image? I need to have its coordinates.

Your help is much appreciated.

Best,

Rasaa84 avatar Jun 20 '23 03:06 Rasaa84

Hello @Rasaa84,

You could maybe do:

image == 127

Now the image will have 255 in every position which had the value 127 and 0 elsewhere, so you just need to find the 255s.

If you take the average you can find out how many 255s there are:

$ python
Python 3.11.2 (main, May 30 2023, 17:45:26) [GCC 12.2.0] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> import pyvips
>>> x = pyvips.Image.new_from_file("mono.jpg")
>>> (x == 127).avg() * x.width * x.height / 255.0
20066.0

So 20066 pixels have the value 127 in this case.

You can ask max to make an array of the positions of the N maximum values:

>>> max_value, optional_results = (x == 127).max(x_array=True, y_array=True, size=20066)
>>> len(optional_results['x_array'])
20066
>>> optional_results['x_array'][42], optional_results['y_array'][42]
(637, 88)
>>> 

So it found 20066 255s, and position 43 is at (637, 88).

This will be pretty slow for large images, but it might be fast enough if all your images are small.

jcupitt avatar Jun 20 '23 08:06 jcupitt