Reapply ROI on crop

Hi all,

I have questions about ROIs on cropped regions and wrote a small script to show it.

from ij import IJ, ImagePlus, ImageStack, WindowManager as wm
from ij.gui import Roi, PolygonRoi
from ij.plugin import Duplicator


# imp = IJ.getImage();
# IJ.run("Blobs (25K)", "");
# imp = IJ.getImage();
# IJ.setTool("polygon");
imp = ImagePlus("http://imagej.nih.gov/ij/images/flybrain.zip")
xpoints = [103,117,153,155,136];
ypoints = [95,61,62,92,100];
new_roi = PolygonRoi(xpoints,ypoints,Roi.POLYGON)
imp.setRoi(new_roi)
print(imp.getRoi().getBounds())
imp2 = Duplicator().run(imp, 1, 1, 1, imp.getNSlices(), 1, 1)
imp2.setRoi(new_roi)
IJ.run(imp2, "Clear Outside","")
print(imp2.getRoi().getBounds())
imp2.show()
imp.show()

This gives an imp2 completely black since the ROI is considered to be outside the boundaries of the image and therefore clear everything. Is there a clever way to reapply a ROI on a cropped region ? Also, why does Restore Selection works if I have the image open (even though I want to avoid displaying the image) ?

Thanks for your help !

Hello lguerard -

Yes (if I understand correctly what you want to do). Use
Roi.setLocation() to move (a copy of) the Roi to the upper
left ((0, 0)) of your cropped image.

So you would modify the relevant section of your script as
follows:

# imp2.setRoi(new_roi)
new_roi2 = new_roi.clone()
new_roi2.setLocation (0, 0)
imp2.setRoi(new_roi2)
IJ.run(imp2, "Clear Outside","")

Thanks, mm

1 Like

Thanks a lot ! That works now ! :slight_smile: (and it makes sense as well !)