pyvips icon indicating copy to clipboard operation
pyvips copied to clipboard

How to get count of pixels that meet a specific condition in a Pyvips image

Open Rasaa84 opened this issue 2 years ago • 2 comments

Hi,

How can we get count of pixels that meet a specific condition in a Pyvips image?

Thanks in advance for your help.

Rasaa84 avatar May 10 '23 21:05 Rasaa84

Hi again, just use avg on the boolean result image. libvips uses 255 for true, so divide by 255 to get the number of true pixels.

For example:

$ python
Python 3.11.2 (main, Mar 13 2023, 12:18:29) [GCC 12.2.0] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> import pyvips
>>> x = pyvips.Image.new_from_file("k2.jpg")
>>> x > 128
<pyvips.Image 1450x2048 uchar, 3 bands, srgb>
>>> (x > 128).avg()
80.784033203125
>>> (x > 128).avg() * x.width * x.height * x.bands / 255
2822309.0000000005
>>> 

So 2822309 picture elements (R, G or B values) are over 128.

jcupitt avatar May 11 '23 09:05 jcupitt

Thank you so much! one more question, how can we obtain the physical size of a pixel using Pyvips? When using xres and yres, I am getting a value of 1.0, indicating that the resolution is 1 pixel/mm. However, I expected to obtain a size of around 0.5 micron for each pixel. Is there something that I am overlooking?

Rasaa84 avatar May 14 '23 18:05 Rasaa84