Get lower threshold calculated by AutoThreshold method in python


I have a 16-bit z-stack from which I would like return the value of the lower threshold as calculated by an AutoThreshold method (e.g. Otsu) in a python script.

in an IJ-macro, I could do:

run("T1 Head (2.4M, 16-bits)");
setAutoThreshold("Otsu dark stack");
getThreshold(lower, upper);

which returns 146 for the lower threshold using the Otsu method.

But I have not managed to reproduce this script in python. There seems to be no “IJ.getThreshold”, and as I did not find any alternative, I only managed to get as far as this:

from ij import IJ

imp = IJ.openImage("")
IJ.setAutoThreshold(imp, "Otsu dark stack")

This works so far, but I am missing the step to retrieve the actual threshold value.

I also tried to use AutoThresholder() class, but the value it returns does not match the above:

from ij import IJ
from ij import ImagePlus
from ij.process import StackStatistics
from ij.process import AutoThresholder

imp = IJ.openImage("");
stackstats = StackStatistics(imp)
stack_histogram = stackstats.histogram

autothresh = AutoThresholder()

threshold = autothresh.getThreshold("Otsu", stack_histogram)
print threshold

which returns 41.

Does somebody know what I am missing? Thanks for your help!

The ImageProcessor class has the methods getMinThreshold and getMaxThreshold :wink:
To get the Image Processor for your images (which are ImagePlus) you can do

#@ ImagePlus imp
ImProc = imp.getProcessor()
# And from there you can go on by yourself ;)

The ImageProcessor are contained in the ImagePlus. In practice, they are similar just the ImagePlus has a title attribute (and some other methods) and the ImageProcessor has all the image processing methods.

1 Like

awesome, thanks @LThomas! :slight_smile:

For completeness sake, here the working python code:

from ij import IJ
from ij.process import ImageProcessor

imp = IJ.openImage("")
IJ.setAutoThreshold(imp, "Otsu dark stack")
ImProc = imp.getProcessor()
lower_thr = ImProc.getMinThreshold()
print lower_thr 
1 Like

Actually this line is not even necessary from ij.process import ImageProcessor ^^
Because you get the ImProc object from the ImagePlus so you never really call the full class itself.

It’s really a detail, I don’t know if that can actually accelerate the execution.
Otherwise better be on the safe side and call it indeed.

You can mark this thread as resolve then :wink: