import qupath.lib.images.servers.LabeledImageServer
import qupath.lib.roi.RectangleROI
import qupath.lib.scripting.QP
def imageData = getCurrentImageData()
def project = getProject()
def server = imageData.getServer()
// Define output path (relative to project)
def name = GeneralTools.getNameWithoutExtension(imageData.getServer().getMetadata().getName())
def pathOutput = buildFilePath(PROJECT_BASE_DIR, 'export')
// Define output resolution
double requestedPixelSize = server.getPixelCalibration().getAveragedPixelSize()
double downsample = requestedPixelSize / imageData.getServer().getPixelCalibration().getAveragedPixelSize()
println('Downsample factor : '+downsample)
// Create an ImageServer where the pixels are derived from annotations
def labelServer = new LabeledImageServer.Builder(imageData)
.backgroundLabel(0, ColorTools.BLACK) // Specify background label (usually 0 or 255)
.downsample(downsample) // Choose server resolution; this should match the resolution at which tiles are exported
.useInstanceLabels() //Export as unique label
.multichannelOutput(false) // If true, each label refers to the channel of a multichannel binary image (required for multiclass probability)
annotation = getSelectedObject()
def region = RegionRequest.createInstance(labelServer.getPath(), downsample, annotation.getROI())
def outputPath = buildFilePath(pathOutput, 'labels_mask.ome.tiff')
writeImageRegion(labelServer, region, outputPath)