Save stardist detections back to project

Is there a way to save stardist detections back to project? The following script loops over the images and annotations in the project and runs startdist, but the detections are not save.

When I run stardist.detectObjects for current image and annotation (example code in the documentation), it saves the stardist detections back to the project.

import qupath.tensorflow.stardist.StarDist2D
import qupath.lib.objects.PathObjects

// Specify the model directory (you will need to change this!)
def pathModel = '/PATHtoModel/'

def stardist = StarDist2D.builder(pathModel)
      .threshold(0.5)              // Prediction threshold
      .normalizePercentiles(1, 99) // Percentile normalization
      .pixelSize(0.25)              // Resolution for detection

def project = getProject()
for (entry in project.getImageList()) {
    def imageData = entry.readImageData()
    def hierarchy = imageData.getHierarchy()
    def annotations = hierarchy.getAnnotationObjects()
    for (annotation in annotations) {   // Loop through each annotation in the image
            def pathObjects = hierarchy.getAnnotationObjects()

Is there any reason you are using this kind of loop rather than a the default script? That should work with Run for Project.

Otherwise, the main problem is that you are not saving the imageData, you change it then discard it. Run for Project takes care of that for you.

1 Like

Thanks for the response. Most images have more than one annotation. The default script couldn’t find the parent object. I thought that I needed to loop over the annotations.

Yes, you can do that by using
getAnnotationObjects() instead of getSelectedObjects().

You can even specify which annotations by using something like:

def pathObjects = getAnnotationObjects().findAll{it.getPathClass() == getPathClass("Tumor")}


Thanks for your help. It worked. getAnnotationObjects() found all the annotations and “run for project” looped over the images and added the detections to the project.

1 Like