Qupath script with pixel classifier

Dear all,
I try to learn how to write a correct code for QuPath-0.2.3
I find how to train the pixel classifier with the RTrees.
I would like to apply this classifier in all my images in a project and export the data (µm2 for each class) and the map/image (red, green, gray etc…) with the class 1,2,3…

For the moment I wrote this script and run it for project.

  • Could you tell me if the script will run the pixel classifier everywhere or in selectAnnotations()
  • Could you help me to export the data?
  • If my image don’t have the good scale (how to set the scale ? pixel/µm)
def classifier = loadPixelClassifier('collagen');
selectAnnotations();
classifyDetectionsByCentroid("collagen");
addPixelClassifierMeasurements("collagen", "collagen");

resetSelection();
print "Done!";

Kind regards,

Quick runthrough:
First line is not necessary if you aren’t using the classifier variable.
Second line selects the annotations, meaning that the third and fourth lines will classify all detections within the annotation using that classifier, and also add measurements to the annotations.

Finally you unselect the annotations.

You can export the whole project’s data using Measurements->Export measurements, otherwise you can script specifically what you want.

If you want to export pictures, there are plenty of forum posts on that, but I would start here. You can either maintain scale, or export as png, or whatever you want.

1 Like

thank you !
But in the script if I use the run for project it will be directly in batch mode
How should I write to work in batch like in Fiji

input = getDirectory("choose the input directory"); 
list = getFileList(input);   
for (i=0; i<list.length; i++) {
	if (endsWith(list[i],".TIF")){
		inputPath= input + list[i];
run("Bio-Formats Importer", "open=inputPath color_mode=Default rois_import=[ROI manager] view=Hyperstack stack_order=XYCZT");
imagesName = getTitle();

Like this I will be able to add at the end

import qupath.lib.gui.tools.MeasurementExporter
import qupath.lib.objects.PathCellObject

// Get the list of all images in the current project
def project = getProject()
def imagesToExport = project.getImageList()

// Separate each measurement value in the output file with a tab ("\t")
def separator = "\t"

// Choose the columns that will be included in the export
// Note: if 'columnsToInclude' is empty, all columns will be included
def columnsToInclude = new String[]{"Name", "Class", "Nucleus: Area"}

// Choose the type of objects that the export will process
// Other possibilities include:
//    1. PathAnnotationObject
//    2. PathDetectionObject
//    3. PathRootObject
// Note: import statements should then be modified accordingly
def exportType = PathCellObject.class

// Choose your *full* output path
def outputPath = "M:/measurements.tsv"
def outputFile = new File(outputPath)

// Create the measurementExporter and start the export
def exporter  = new MeasurementExporter()
                  .imageList(imagesToExport)            // Images from which measurements will be exported
                  .separator(separator)                 // Character that separates values
                  .includeOnlyColumns(columnsToInclude) // Columns are case-sensitive
                  .exportType(exportType)               // Type of objects to export
                  .exportMeasurements(outputFile)        // Start the export process

print "Done!"

AndI would like to export the the prediction like this inside the script. But I really can’t find how to do it.

kind regards,

For the image export, you need to look at the links and or search for posts about exporting the Overlay within QuPath. And at whatever downsample.
For example: Exporting image overlay v0.2.0-m5

The export is probably easier to run as a second script, or use the interface. It should only need to be run once per project, so doesn’t generally need to be scripted. You can approach things using the getProject() approach, but accessing things and saving them tend to get more complicated.

On the other hand, if you want one CSV file per image rather than a summary CSV file, just tack that measurement script onto the end of your per image script, and name the csv file after the image rather than calling it “measurements.”

def name = getProjectEntry().getImageName()

1 Like

Dear @Research_Associate
I found your answer from 2019. But This solutions work when we train the classifier.
I would like to save a picture for all my files inside a project.
But when I load a classifier and I apply it I can’t find how to see and export the prediction map.

Thank you for your time :wink:

@Alex.h Does this help?

It will likely need modification is you want to export predictions for multiple annotations.

Note there can be a difference between exporting the raw values of a prediction (e.g. as TIFF) and the RGB image shown in an overlay.

3 Likes

There is more information here about the prediction image

2 Likes

@petebankhead and @Research_Associate,
thank you for your answer. Usually I use the mask as a quality control to check the results. The RGB images are sufficient for me.

  1. Could I export without ROI because I applied the classifier everywhere?

2) Even If I run the script with an ROI the picture is only white (value = 0)
Did I made an error in my script ?


Edit ok I see what happens your script need the annotations to work properly. So I add

createAnnotationsFromPixelClassifier("Classifier", 10, 10, "DELETE_EXISTING")

But this method is very slow do you have any advice ?

The method I posted doesn’t require creating annotations. Here’s an adapted version (untested, might have typos!):

def imageData = getCurrentImageData()
def classifier = loadPixelClassifier('Classifier')

def predictionServer = PixelClassifierTools.createPixelClassificationServer(imageData, classifier)

def path = buildFilePath(PROJECT_BASE_DIR, 'prediction.tif')

def downsample = predictionServer.getDownsampleForResolution(0)
def request = RegionRequest.createInstance(predictionServer, downsample)
writeImageRegion(predictionServer, request, path)

This gives the raw values, but if your output is a classification – and you use ‘.png’ as the file extension – it should look like the RGB image in most software.

2 Likes

thank you for your time !
kind regards,

2 Likes