Search code examples
javapluginsimagej

"Make Binary" switches background between single image and stack


I am building a plugin in imagej that will do some pre-processing on an image before conducting an analysis. I would like this plugin to function on both single images and stacks. Here is a sample of my plugin code so far:

import ij.*;
import ij.process.*;
import ij.gui.*;
import java.awt.*;
import ij.plugin.*;



public class My_Analysis implements PlugIn {

    public void run(String arg) {

        ImagePlus imp = IJ.getImage();
        IJ.run(imp, "Find Edges", "stack");
        Prefs.blackBackground = true;
        IJ.run(imp, "Make Binary", "stack");
        IJ.run(imp, "Erode", "stack");
    }
}

There's more after that, but it just is in reference to the analysis and I didn't think it was relevant. In addition, I have a GenericDialog at the front of the code, but also didn't think it was relevant and didn't want to bog down the sample. Of course I can include all of it if someone thinks it is necessary.

My problem is that this works beautifully on a single image but the Make Binary reverses the black/white on a stack. I bet I can simply switch the Prefs.blackBackground to false and that will fix it, but then it won't work on a single image.

Another piece of information is that if I take the "stack" out of the Make Binary line, it will pop open a dialog box that prompts me to select several options, one of which is whether the background is black. If I do select this option, it performs the Make Binary correctly, but doesn't apply it to the whole stack or something, since what I end up with is analysis of only the first image and the rest of the images in the stack looking very strange.

Any help would be greatly appreciated. Thank you very much.


Solution

  • I agree that this behavior of ImageJ1.x is inconsistent. I'm not sure if it is intended, but feel free to report it on the ImageJ forum or the mailing list, so it might be fixed.


    Another piece of information is that if I take the "stack" out of the Make Binary line, it will pop open a dialog box that prompts me to select several options, one of which is whether the background is black.

    This is indeed the path to a working solution here: just add the keyword black to reproduce the behavior in a script or macro, e.g. this Groovy script runs the same on single images and stacks:

    import ij.IJ;
    import ij.ImagePlus;
    import ij.Prefs;
    
    ImagePlus imp = IJ.getImage();
    IJ.run(imp, "Find Edges", "stack");
    Prefs.blackBackground = true;
    IJ.run(imp, "Make Binary", "stack black"); // this line changed
    IJ.run(imp, "Erode", "stack");
    

    You get the required keyword by using the Macro recorder and running Process > Binary > Make binary on a stack.