Search code examples
javaimage-processingimagej

ImageJ (plugin Java): auto threshold method doesn't work


I try to write Java Plugin to ImageJ, which should:

  • Load image (24-bit).
  • Do some preprocessing operations.
  • Threshold the image in numerous of methods.
  • Do some other operations.

I have problem with threshold operation. Part of my code looks like this:

Opener opener = new Opener();
ImagePlus imp = opener.openImage(source);
// Preprocessing
IJ.run("Threshold..." , method);
// Other operations e.g. "open", "outline" etc.
IJ.saveAs(destination);

My goal is to get binarized image in various methods (e.g. "Default", "Huang", "Intermodes", "IsoData", "Li" etc.). Only way which I can get binarized image is to run:

IJ.run(imp, "8-bit", "");
IJ.run(imp, "Make Binary", "");

however, I get an image binarized by only one method. How to do automatic threshold by running Java code (ImageJ plugin)?


Solution

  • The auto-threshold methods in the Threshold dialog all are algorithms working on single channel (8-bit or 16-bit) images. In the Color Threshold dialog, they are applied exclusively to the Brightness channel of your 24-bit color image.

    To reproduce this in Java, use the following code:

    IJ.run(imp, "HSB Stack", "");
    imp.setSlice(3);
    IJ.setAutoThreshold(imp, "Triangle dark");
    Prefs.blackBackground = true;
    IJ.run(imp, "Convert to Mask", "only");
    

    (Converting your image to 8-bit is nothing else than using the Brightness channel, discarding the Hue and Saturation information. Unless you really make use of the other sliders in the Color Threshold dialog, you can just as well convert the image to 8-bit before applying the threshold.)