libvips / pyvips

python binding for libvips using cffi
MIT License
640 stars 49 forks source link

Otsu's thresholding in pivips #403

Open Rasaa84 opened 1 year ago

Rasaa84 commented 1 year ago

Hi,

I am wondering if it is possible to do otsu's thresholding in pyvips? your help is much appreciated.

jcupitt commented 1 year ago

Hi @Rasaa84,

Sure, it's a simple loop over a histogram. Use hist_find to make a histogram, then turn it into a python list:

$ python3
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("/home/john/pics/k2.jpg")
>>> x.colourspace('b-w').hist_find().tolist()
[[3472, 11910, 13097, 12246, 10382, 9209, 8585, 7646, 6969, 6719, 6252, ... ]]

Remove the outer [] to make a simple 1D list.