Getting the binary masks of ROIs in ImageJ

Hi,
I was trying to get binary masks of ROIs. First, I was doing it like checking all the points in the image if the point is contained by ROI. I thought it is not a proper way, so I check some code examples written in JAVA, and they are getting the masks with getProcessor method of ImageRoi. However, types of ROIs are not ImageRoi at first, they first cast it to ImageRoi.(Their code is written in JAVA). When I tried to do this in python, I couldn’t find any way to cast ROIs to ImageROIs.

I am asking that is there any way to get binary masks of ROIs?

Thanks a lot.

1 Like

Hi,

The following will get the roi from an image, create the mask from an roi and display it. The Javadoc is good way to navigate the APIs in python

Cheers,

Chris

from ij import IJ, ImagePlus

imp = IJ.getImage()
roi = imp.getRoi()
mask = roi.getMask()
ImagePlus("mask",mask).show()

Thanks for the fast response, but getMask method returns null for rectangle ROIs, and for the other type of ROIs they return a binary mask with dimensions different than image’s dimensions.

I need a way which works for all type of ROIs and extracts binary masks with the dimensions same as the image’s dimensions.

Thanks.

How about this?

from ij import IJ, ImagePlus

imp = IJ.getImage()
ip = imp.getProcessor()
roi = imp.getRoi()

from ij.process import ByteProcessor
mask = ByteProcessor(ip.width, ip.height)
mask.setValue(255)
mask.setRoi(roi)
if( roi.getType() == roi.RECTANGLE ):
	mask.fill()
else:
	mask.fill(roi.getMask())
ImagePlus("mask",mask).show()

This one solves the second problem, mask has the dimensions same as the image’s dimensions. However, it is not working for rectangle ROIs again. When I tried it with rectangle ROI, it returned all white masks, unlike the other ROI types in which the roi is white on the black surface. So, do you have any suggestions?
Thanks.

I did a sneaky edit above to deal with rectangle - I was hoping it got in before you saw the post.

1 Like

Hi,
Maybe an easier way : just add all your ROI to the ROImanager. Create a new black image of desired size. Use the More>Fill from the ROI manager. This will fill the image with the foreground color.
This can be scripted in a macro :

setForegroundColor(255, 255, 255);
selectImage("mask");
roiManager("Fill");
roiManager("reset");
selectImage("mask");
run("Select None");

Nico

1 Like