Jython code for creating a mask from freehand selection


I am trying to write jython code for creating a binary mask from freehand selection.
The code below

imp = IJ.getImage()
mask_imp=ImagePlus("segmframe", mask)

works well but creates a mask with the dimensions of a rectangle enclosing the selection while I need a mask with the dimensions of image.

Also i need the mask to be passed internally as an ImagePlus object (therefore Selection.run(“mask”) does not work for me.

Changing imp.getMask() to imp.createRoiMask() leads to error:

AttributeError: 'ij.ImagePlus' object has no attribute 'createRoiMask'

Please help

It’s hard to guess your goal from you description. Could you post a screenshot what you want to archive?

Please note that you can use the macro recorder of ImageJ to record GUI commands in BeanShell or JavaScript which are quite similar to the Jython commands (select the language in the combo box!):


Thank you for responding to my question

My goal is to create a binary mask of an image with selection. The binary mask should have the same dimensions as the image. I want to store this mask in an object (e.g. imp). I want to check the value of various selected pixels against this mask.

I am pretty versed with macro recorder. It does not help in this case.

The problem is within a particular class (“Selection”). This class contains the methods for the edit/select/mask command (which you suggest I should record). Yet it only allows to execute commands through class.run() syntaxis and as a result of this command the mask is not passed internally as an object and rather just displayed.

Theoretically in the javadoc there is a method createRoiMask in ImagePlus that is supposed to do exactly what I want. But for some reason it does not work. The only workaround I found is to make a selection, create inverse of it (it has the dimension of a whole image) and the apply imp.getMask() followed by inversion of the values in the Mask.

there must be a more straightforward way to do this

Any help would be VERY APPRECIATED


The following script works for me as expected, when I have an image with a freehand selection open:

#@ ImagePlus imp

from ij import ImagePlus

mask = imp.createRoiMask()

maskImp = ImagePlus("Mask", mask)

The ImagePlus#createRoiMask() method was introduced with ImageJ 1.52f16:

Which version are you using?

Thank you so much! Indeed I was running 1.52e
Updating to 1.52k enabled createRoiMask()
Everything works!