Skip to content

Instantly share code, notes, and snippets.

@adyprat
Last active August 11, 2023 16:04
Show Gist options
  • Save adyprat/f35053cad781f75fea84382ade0c54e7 to your computer and use it in GitHub Desktop.
Save adyprat/f35053cad781f75fea84382ade0c54e7 to your computer and use it in GitHub Desktop.
ExportQuPath Annotations As TIF
import qupath.lib.regions.*
import ij.*
import java.awt.*
import java.awt.image.BufferedImage
import javax.imageio.ImageIO
import java.awt.Color
// Set downsampling factor for saving image. Leave it at 1 for default resoluiton.
// downsample of n reduces image size by 1/n.
double downsample = 1.0
// add or remove objects from list
//if there's an overlap in annotations only higher value pixel is retained
def keepObjects = [:]
keepObjects['Kidney'] = 1
keepObjects['Grafts'] = 2
// sort objects by their numerical order
keepObjects = keepObjects.sort { a, b -> a.value <=> b.value }
//To add a new class, say Class1 to a new integer 3
// keepObjects['Class1'] = 3
def server = getCurrentImageData().getServer()
int w = (server.getWidth() / downsample) as int
int h = (server.getHeight() / downsample) as int
ImagePlus result1 = IJ.createImage("Labeling", "8-bit black",w,h, 1)
ip1 = result1.getProcessor()
//def g2d = img.createGraphics()
ip1.scale(1.0/downsample, 1.0/downsample)
ip1.setColor(Color.black)
int iCnt = 1
// run for each key in keepObjects (sorted by their values)
for (key in keepObjects.keySet()){
def val = keepObjects[key]
for (annotation in getAnnotationObjects()) {
def pClass = annotation.getPathClass().toString()
if (keepObjects.containsKey(pClass)) {
if (val==keepObjects[pClass]) {
def iVal = keepObjects[pClass]
println("$pClass:$iVal")
cVal = new Color(iVal)
//print(iCnt, cVal);
roi = annotation.getROI()
def roiX = IJTools.convertToIJRoi(roi, 0, 0, 1) // or getROI for membrane
def shape = roi.getShape()
ip1.setColor(iVal)
ip1.fill(roiX)
roiX.setStrokeWidth(2)
ip1.setColor(0)
ip1.draw(roiX)
}}
}
}
result1.show( "glasbey")
//Will prompt for file save
fileName = Dialogs.promptToSaveFile(null,null,'annotations.tif',null,'.tif')
println(fileName)
IJ.save(result1,fileName.toString())
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment