QuPath scripting - combining two annotations

Hi, I’ve hit the limit of my scripting abilities again and hoping someone can help.

I’m using the following script to create two annotations:

createAnnotationsFromPixelClassifier("Tissue Detection", 1000000.0, 1000.0, "SELECT_NEW")
runPlugin('qupath.lib.plugins.objects.DilateAnnotationPlugin', '{"radiusMicrons": -40.0,  "lineCap": "Round",  "removeInterior": false,  "constrainToParent": true}');
runPlugin('qupath.lib.plugins.objects.RefineAnnotationsPlugin', '{"minFragmentSizeMicrons": 10000.0,  "maxHoleSizeMicrons": 1000.0}');
createAnnotationsFromPixelClassifier("Vessel Detection", 200.0, 1000.0, "SELECT_NEW")

It’s working nicely, but I then need to subtract the ‘Vessel’ annotation from the ‘Tissue’ annotation - which I can do using Edit Multiple - Subtract but I’d like to add this to the code.

Note: I think I’ve read every post in here about combining annotations but my scripting skills haven’t been able to translate them to this particular circustance.

Can anyone help?

The closest immediate script is probably this recent one by Pete:

Which looks like this with some quick modifications:

def tissue = getAnnotationObjects().find {it.getPathClass() == getPathClass("Positive")}
def vessel = getAnnotationObjects().find {it.getPathClass() == getPathClass("Negative")}
def plane = tissue.getROI().getImagePlane()
if (plane != vessel.getROI().getImagePlane()) {
    println 'Annotations are on different planes!'
// Convert to geometries & compute distance
// Note: see https://locationtech.github.io/jts/javadoc/org/locationtech/jts/geom/Geometry.html#distance-org.locationtech.jts.geom.Geometry-
def g1 = tissue.getROI().getGeometry()
def g2 = vessel.getROI().getGeometry()

def difference = g1.difference(g2)
if (difference.isEmpty())
    println "No intersection between areas"
else {
    def roi = GeometryTools.geometryToROI(difference, plane)
    def annotation = PathObjects.createAnnotationObject(roi, getPathClass('Difference'))
    println "Annotated created for subtraction"

That does not remove the original annotations, you may want to add

removeObject(tissue, true)
removeObject(vessel, true)

May also want to change the final class “Difference” back to “Tissue”.

1 Like

Thank you! You are amazing, that works perfectly!

1 Like