Last active
January 12, 2024 15:10
-
-
Save adyprat/716f97f43d567f731d3c74befefb4e8b to your computer and use it in GitHub Desktop.
Export all channels as single channel tifs for a given ROI in QP v0.5
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import qupath.lib.images.servers.ImageServers.* | |
import qupath.lib.io.PathIO | |
import qupath.fx.dialogs.* | |
import javax.imageio.ImageIO | |
// Get the current image | |
def imageData = getCurrentImageData() | |
def server = imageData.getServer() | |
// change this to 2 or more to get lower resolution | |
def downSample =1 | |
// Get the number of channels | |
def nChannels = server.nChannels() | |
print nChannels.toString()+" channels" | |
// Prompt the user for the output directory | |
outputDir = FileChoosers.promptForDirectory() | |
if (outputDir == null) { | |
print "No output directory selected. Exiting..." | |
return | |
} | |
def roi = getSelectedROI() | |
def requestROI = RegionRequest.createInstance(server.getPath(), downSample, roi) | |
// Read the region | |
def img = server.readBufferedImage(requestROI) | |
def raster = img.getRaster() | |
// Loop over each channel | |
for (int c = 1; c <= nChannels; c++) { | |
// Create a new single-channel image server | |
// Extract a single channel (e.g., the n-th channel) | |
def channelData = raster.getSamples(0, 0, img.getWidth(), img.getHeight(), c-1, (int[])null) | |
def channelImg = new BufferedImage(img.getWidth(), img.getHeight(), BufferedImage.TYPE_BYTE_GRAY) | |
channelImg.getRaster().setSamples(0, 0, img.getWidth(), img.getHeight(), 0, channelData) | |
def cID = (c-1).toString() | |
print(cID) | |
// Define the output file path | |
if (nChannels <100){ | |
cID = String.format("%02d", c-1) | |
}else { | |
cID = String.format("%03d", c-1) | |
} | |
def outputPath = outputDir.toString()+ "/c" + cID +"_"+server.getChannel(c-1).getName() + ".tif" | |
// Write the image to a .tif file | |
ImageIO.write(channelImg, "TIFF", new File(outputPath)) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment