Search code examples
jythonimagejroi

How to save ROIs from ROI manager in jython script?


I'm writing a semi-automatic juthon script. At some point the script stops waiting for the user to manually add a few ROIs. What I need is a method to save all the ROIs added to the ROI manager. I have tried the following:

RoiManager.runCommand("Save", ROIsOutpath)

but I get the following error:

TypeError: runCommand(): self arg can't be coerced to ij.plugin.frame.RoiManager

Of course I'm learning jython (and progrmming in general). The short question would be: How do I save multiple ROIs from the ROImanager in Jython?

Thank you!!


Solution

  • The RoiManager#runCommand() method is not static, that means you have to call it on an instance of the RoiManager class. To get this instance, call:

    rm = RoiManager.getInstance();
    if (rm==None):
        rm = RoiManager();
    

    The following code opens a sample image, creates two ROIs, and saves them in the user's home directory:

    from ij.plugin.frame import RoiManager;
    
    rm = RoiManager.getInstance();
    if (rm==None):
        rm = RoiManager();
    imp = IJ.openImage("http://imagej.nih.gov/ij/images/blobs.gif");
    imp.setRoi(100, 80, 50, 80);
    rm.addRoi(imp.getRoi());
    imp.setRoi(180, 140, 30, 40);
    rm.addRoi(imp.getRoi());
    rm.runCommand("Deselect"); # deselect ROIs to save them all
    rm.runCommand("Save", IJ.getDirectory("home") + "RoiSet.zip");
    imp.show();
    

    Hope that helps.