Intersecting annotations from script

Hi guys,

I’m running analyses in qupath and I have made some annotations I would like to intersect from the script editor.

Say I have two annotations “Annotation 1” and “Annotation 2” that partially overlap and I want to intersect them. They are both from the same class.
From the GUI it’s easy, I select right click > edit multiple > intersect selected
However, I would like to do this from script as I have to run this in ~200 images.

I found this example from Pete: https://petebankhead.github.io/qupath/scripts/2018/08/08/three-regions.html
where I found %annotationobject1%.intersect(%annotationobject2%) should do it.
However I do not know how I can “Get” each annotation object purely based on the annotation name (I did find a script to get by class), and I cannot find that online.
Also when I do it manually I cannot find it in the workflow to copy it from there…

Do you have any suggestions?
Thanks so much in advance,
Best, Justin

Hi Justin,

You can do this to get annotations based on their name:

def annName = "annotation1"
def myAnnotations = getAnnotationObjects().find { it.getName() == annName}
print myAnnotations 

Thanks melvingelbard! That was really useful

It took some more work than I thought it would, so I’ll share if anyone is interested.

It first renames the annotations so that they are ‘Annotation 1’ and ‘Annotation 2’
Then performs the intersecting (I’m sure it can be scripted shorter, but this works)

Best, Justin

//rename annotations
i = 0
def annotations = getAnnotationObjects()
annotations.eachWithIndex {annotation, i -> annotation.setName('Annotation ' + (i+1))}
fireHierarchyUpdate()

//actual intersecting
ann01 = getAnnotationObjects().find { it.getName() == "Annotation 1"}
ann02 = getAnnotationObjects().find { it.getName() == "Annotation 2"}
ann01_roi = ann01.getROI()
ann02_roi = ann02.getROI()
ann01_geo = ann01.getROI().getGeometry()
ann02_geo = ann02.getROI().getGeometry()


import org.locationtech.jts.geom.Geometry
import qupath.lib.common.GeneralTools
import qupath.lib.objects.PathObject
import qupath.lib.objects.PathObjects
import qupath.lib.roi.GeometryTools
import qupath.lib.roi.ROIs

import static qupath.lib.gui.scripting.QPEx.*

def imageData = getCurrentImageData()
def hierarchy = imageData.getHierarchy()
def server = imageData.getServer()

def plane = ann01_roi.getImagePlane()

intersect_geo = ann01_geo.intersection(ann02_geo)

intersect_roi = GeometryTools.geometryToROI(intersect_geo, plane)
intersect_annotation = PathObjects.createAnnotationObject(intersect_roi)
intersect_annotation.setName("Intersection")

hierarchy.addPathObject(intersect_annotation)
1 Like