Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Select an option

  • Save petebankhead/df7b083dd84548e80ca9624d8ba05c99 to your computer and use it in GitHub Desktop.

Select an option

Save petebankhead/df7b083dd84548e80ca9624d8ba05c99 to your computer and use it in GitHub Desktop.
Count the annotations for each classification, across all images in a project.
/**
* Count the annotations for each classification, for all images in a project.
*
* This works by looping through all the images in a project, and checking for the existence of a data file.
*
* If a data file is found, read the hierarchy (no need to open the whole image), and print the number of objects,
* the total number of annotations & the number of annotations split by classification.
*
* @author Pete Bankhead
*/
import qupath.lib.gui.QuPathGUI
import qupath.lib.io.PathIO
import qupath.lib.objects.classes.PathClass
import qupath.lib.scripting.QPEx
// Get the current project open in QuPath
def project = QPEx.getProject()
if (project == null) {
print 'No project open!'
return
}
// Store results in a StringBuilder so we can print it all in one go at the end
// Start with a newline (because we probably get a line with INFO: at the beginning)
def sb = new StringBuilder(System.lineSeparator())
// Loop through all the entries in the project
for (entry in project.getImageList()) {
// Print the name
sb << entry.getImageName() << System.lineSeparator()
// Get a reference to the .qpdata file for this entry
def fileData = QuPathGUI.getImageDataFile(project, entry)
// Check if the file exists & print a message if not
if (!fileData.exists()) {
sb << '- No data file found!' << System.lineSeparator()
sb << '-----------------------' << System.lineSeparator()
continue
}
// Read the hierarchy, but *not* anything else (don't need a full ImageData)
def hierarchy = PathIO.readHierarchy(fileData)
// Print the total number of objects
int nObjects = hierarchy.nObjects()
sb << '- Number of objects: ' << nObjects << System.lineSeparator()
// Print the number of annotations
def annotations = hierarchy.getFlattenedObjectList(null).findAll { it.isAnnotation() }
sb << '- Number of annotations: ' << annotations.size() << System.lineSeparator()
// Create a map to store number of annotations with each classification
if (!annotations.isEmpty()) {
def map = annotations.countBy { it.getPathClass() }
map.each { PathClass key, Integer count ->
if (key == null)
sb << '-- Unclassified: '
else
sb << '-- ' << key.toString() << ': '
sb << count << System.lineSeparator()
}
}
sb << '-----------------------' << System.lineSeparator()
}
// Print the results
print sb.toString()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment