Skip to content

Instantly share code, notes, and snippets.

@flowernert
Last active December 15, 2022 11:04
Show Gist options
  • Save flowernert/214f4c59c41667190a845ef129756a6c to your computer and use it in GitHub Desktop.
Save flowernert/214f4c59c41667190a845ef129756a6c to your computer and use it in GitHub Desktop.
ImageJ/Fiji script allowing to QUICKLY go through a multichannel .tif z-stack to select for each image which slice you want to keep, then save it in a separate folder
/**
* Macro allowing to select a single slice for each image in a multicolor
* z-stack hyperstack
* Works from tif monochannel folder (XXX ext split) containing z-stacks
*
*/
dir = getDir("Select a folder");
outputDir = File.getParent(dir) + File.separator + File.getName(dir)+ " 1slice/";
File.makeDirectory(outputDir);
filelist = getFileList(dir) ;
//identify number of channels
nbCh = 0;
for (i = 0; i < lengthOf(filelist); i++) {
if (endsWith(filelist[i], ".tif") && filelist[i].contains("C=")) {
fileCh = getChannelFromTitle(filelist[i]);
if (fileCh > nbCh) {
nbCh = fileCh;
}
}
}
nbCh = nbCh+1;
print (nbCh + " channels detected");
//iterate files by the number of detected channels
for (i = 0; i < lengthOf(filelist); i+=nbCh) {
basename = getBaseName(filelist[i]);
//substring(filelist[i], 0, lengthOf(filelist[i])-8);
//open all channels of a same image
for(j = 0 ; j < nbCh ; j++) {
open(dir + filelist[i+j]);
}
//assemble images in a multicolor z-stack
params = "";
for (j = 0 ; j < nbCh ; j++) {
params += "c" + j+1 + "=" + filelist[i+j] + " ";
}
print (params);
run("Merge Channels...", params + "create");
//user selection of the best slice and saving it
waitForUser("Pick a slice", "Select the best slice, then click OK");
Stack.getPosition(channel, slice, frame);
selectedSlice = slice;
print("selected slice : " + selectedSlice);
title = basename + ".tif";
run("Duplicate...", "title=[" + title +"] slices=" + selectedSlice);
close("Composite");
save(outputDir + title);
close("*");
}
print("***sliceChooser ends***");
function getBaseName(monoImgTitle) {
index = monoImgTitle.lastIndexOf("-C=");
return substring(monoImgTitle, 0, index);
}
function getChannelFromTitle(monoImgTitle) {
index = monoImgTitle.lastIndexOf("C=");
return parseInt(monoImgTitle.substring(index+2, index+3));
}
@flowernert
Copy link
Author

V0.1 14 December 2022

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment