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();
#"Blobs (25K)", "");
# imp = IJ.getImage();
# IJ.setTool("polygon");
imp = ImagePlus("")
xpoints = [103,117,153,155,136];
ypoints = [95,61,62,92,100];
new_roi = PolygonRoi(xpoints,ypoints,Roi.POLYGON)
imp2 = Duplicator().run(imp, 1, 1, 1, imp.getNSlices(), 1, 1)
imp2.setRoi(new_roi), "Clear Outside","")

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

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

Thanks, mm

1 Like

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