How to Open ROI set (zip file) and get count using Python version

I have the following imageJ macro:

roiManager("Open", "RoiSet.zip");
n = roiManager('count');
print(n);
for (i = 0; i < n; i++) {
    roi_name = RoiManager.getName(i);
}

Which works perfectly fine.

What’s the Python equivalent of it?
I’m stuck with this code:

from ij import IJ
from ij.plugin.frame import RoiManager
from ij.gui import Roi
rmimp = IJ.openImage("RoiSet.zip")
n = rmimp.getCount()
print(n)

It gave me

AttributeError: 'NoneType' object has no attribute 'getCount'

Hi @Peverall_Dubois,
The translation from the macro language to jython is not always straightforward.
You can use the macro recorder with Java as language to help you find the commands.
The ImageJ API is otherwise the place to go to search for them

Below a script that should do what you need

#@RoiManager rm
rm.runCommand("open", r"C:/Users/Laurent Thomas/Downloads/RoiSet.zip")
print rm.getCount() # actually not needed to loop on the RoiManager

for roi in rm:
   print roi.getName()

The #@ notation is a script parameter, it’s kind of scijava magic, here to return the RoiManager instance, and if there is none to create a new one automatically.
The #@ script parameters only works in Fiji though, not ImageJ.

Your script was fine, but the openImage does not return anything (well it returns None) when opening a roi.zip, hence the NoneType object error.

And the r before the string path is to prevent any issue with back/forward slashes (r = raw string)

Hi,

I’ve no problem running your code with FIJI IDE console.

But I’d like to code in my own IDE and usually I execute it with command line in the terminal.

I tried your code and running with this command

/Applications/Fiji.app/Contents/MacOS/ImageJ-macosx my-code.py

But it breaks on rm.runCommand(), giving me:
NameError: name 'rm' is not defined

It seems that it can’t recognize: #@RoiManager rm line.

How can I resolve the problem?

Then you need to create an instance of the RoiManager by adding these 2 lines

from ij.plugin.frame import RoiManager
rm = RoiManager() 
# rm = RoiManager(false) # maybe to avoid displaying it ?

I have not tested if that works in headless mode though. It should but anything relying on display will fail so…

1 Like

By the way I believe the script parameters notation should also work from the command line, except you have to explicitly mention to run it as an ImageJ2 headless, while I believe your command above is calling ImageJ1.