Batch process for single and double positive particles in Image J - macros

This is my second go at writing a macro (with virtually zero coding knowledge) after the first one was a success, but I am adding a layer of complexity that I can't seem to make functional.
I am trying to set up a batch process where I count particles of 2 different colors and then which of those particles is positive for both colors. I am getting this error:
Error: ')' expected in line 38:
selectWindow ( "Result of " - "+Title" ) ;
I really don't know what I need to fix because it seems that I have closed all open parentheses. However, I know that the root issue is that I don't know how to generically name the window I am interested in. It is a window that is created by the macro and is not one of the input files.
dir1 = getDirectory("Input");
dir2 = getDirectory("Output");
list = getFileList(dir1);
run("Close All");
setBatchMode(true);
for (i=0; i<list.length; i++) {
file1 = dir1 + list[i];
file2 = dir2 + list[i];
file3 = dir2 + list[i];
file3 = replace(file3, ".tif", ".csv");
open(file1);
Title = getTitle();
Title = replace(Title, ".tif", "");
run("Stack to Images");
selectWindow(Title+"-0002");
rename ("mNG-"+Title);
run("Subtract Background...", "rolling=50");
setAutoThreshold("RenyiEntropy dark");
//run("Threshold...");
run("Convert to Mask");
run("Fill Holes");
run("Watershed");
run("Set Measurements...", "area mean min centroid center perimeter integrated median kurtosis area_fraction stack limit display redirect=None decimal=2");
run("Analyze Particles...", "size=9-475 circularity=0.50-1.00 show=Outlines display exclude summarize in_situ");
run("Fill Holes");
selectWindow(Title+"-0003");
rename ("tdT-"+Title);
run("Subtract Background...", "rolling=50");
setAutoThreshold("RenyiEntropy dark");
//run("Threshold...");
run("Convert to Mask");
run("Fill Holes");
run("Watershed");
run("Set Measurements...", "area mean min centroid center perimeter integrated median kurtosis area_fraction stack limit display redirect=None decimal=2");
run("Analyze Particles...", "size=9-475 circularity=0.50-1.00 show=Outlines display exclude summarize in_situ");
run("Fill Holes");
imageCalculator("Add create", "mNG-"+Title,"tdT-"+Title);
rename ("doublepositive"+Title)
selectWindow(Result of "mNG-"+Title);
run("Analyze Particles...", "size=9-475 circularity=0.50-1.00 show=Outlines display exclude summarize in_situ");
run("Images to Stack", "name=[] title=[] use");
saveAs("Tiff", file2);
run("Close All");
}
setBatchMode(false);
selectWindow("Summary");
saveAs("Results", "file3");
run("Close All");
If I could get help on why my syntax is wrong and also feedback on how to generically name the window with the third result, I would greatly appreciate it.

I think, that you just have to change the whole name in to a string
selectWindow("Result of mNG-"+Title);
or
selectWindow("Result of "+"mNG-"+Title);
If this doesn't help, could you give me an example of your data so I can properly test it.

Thanks so much for all the help! #Petra and another person whose comment appears to have been deleted were super helpful! I have worked out the save issues. Here is the final code. It does work and generally yields good results. The resolution in some of my images isn't great so I do get a few false positives where 2 particles are very close and some unfocused light overlaps from the 2 signals, but I will continue to try to adjust things now that the macro totally works! :)
Here is the final code that I have been working with:
dir1 = getDirectory("Input");
dir2 = getDirectory("Output");
list = getFileList(dir1);
run("Close All");
setBatchMode(true);
for (i=0; i<list.length; i++) {
file1 = dir1 + list[i];
file2 = dir2 + list[i];
file3 = dir2 + list[i];
file4 = dir2 + list[i];
file3 = replace(file3, ".tif", "Summary.csv");
file4 = replace(file4, ".tif", "Results.csv");
open(file1);
Title = getTitle();
Title = replace(Title, ".tif", "");
run("Stack to Images");
selectWindow(Title+"-0001");
rename ("mNG-"+Title);
run("Subtract Background...", "rolling=50");
setAutoThreshold("RenyiEntropy dark");
//run("Threshold...");
setThreshold(400, 65535);
run("Convert to Mask");
run("Fill Holes");
run("Watershed");
run("Set Measurements...", "area mean min centroid center perimeter integrated median kurtosis area_fraction stack limit display redirect=None decimal=2");
run("Analyze Particles...", "size=9-475 circularity=0.50-1.00 show=[Bare Outlines] display exclude summarize in_situ");
run("Fill Holes");
run("Watershed");
selectWindow(Title+"-0002");
rename ("tdT-"+Title);
run("Subtract Background...", "rolling=50");
setAutoThreshold("RenyiEntropy dark");
//run("Threshold...");
run("Convert to Mask");
run("Fill Holes");
run("Watershed");
run("Set Measurements...", "area mean min centroid center perimeter integrated median kurtosis area_fraction stack limit display redirect=None decimal=2");
run("Analyze Particles...", "size=9-475 circularity=0.50-1.00 show=[Bare Outlines] display exclude summarize in_situ");
run("Fill Holes");
run("Watershed");
imageCalculator("ADD create","mNG-"+Title,"tdT-"+Title);
run("Analyze Particles...", "size=9-475 circularity=0.50-1.00 show=Outlines display exclude summarize in_situ");
run("Images to Stack", "name=[] title=[] use");
saveAs(".tif", file2);
run("Close All");
}
setBatchMode(false);
selectWindow("Summary");
saveAs("text", file3);
selectWindow("Results");
saveAs("text", file4);
run("Close All");
Thanks again for all the help!

Related

Trying to loop a macro in FIJI/Image J

So this is the second time I've posted a question like this. Last time I got so much help from a user called #quantixed but I need help again.
My code isn't working, but it's something to do with me trying to isolate images from a stack because I need to analyse each layer separately and look for over lap (double positive and triple positive cells). It runs up until I try to name each layer. I've tried adding "startsWith" because each layer regardless of stack starts with c:1/3, c:2/3 or c:3.
This is the code:
macro "Process My Files" {
dir1 = getDirectory("C:/Users/laure/OneDrive/Documents/MSc Molecular Biology & Biotechnology/Masters Project - Dombrowski Lab/Project Data/LD005 CX5/CellHealthProfiling.V4_03-06-20_09;46;02/CEM-133432_200229080001/");
dir2 = getDirectory("C:/Users/laure/OneDrive/Documents/MSc Molecular Biology & Biotechnology/Masters Project - Dombrowski Lab/Project Data/LD005 CX5/CellHealthProfiling.V4_03-06-20_09;46;02/CEM-133432_200229080001/ImageJ Macro Batch Results");
list = getFileList(dir1);
// Make an array of C01 files only
C01list = newArray(0);
for (i=0; i<list.length; i++) {
if (endsWith(list[i], ".C01")) {
C01list = append(C01list, list[i]);
}
}
x=startsWith("c:1/3")
y=startsWith("c:2/3")
a=startsWith("c:3/3")
b="Result of" + x
c="Result of" + b
d="Drawing of" + x
e="Drawing of" + y
f="Drawing of" + a
g="Drawing of" + b
h="Drawing of" + g
function DAPI() {
selectWindow(x);
run("8-bit");
setThreshold(45, 255);
run("Convert to Mask");
run("Analyze Particles...", "size=30-350 show=Outlines clear summarize add");
}
function OLIG2() {
selectWindow(y);
run("8-bit");
setThreshold(25, 255);
run("Conert to Mask");
run("Analyze Particles...", "size=30-250 show=Outlines clear summarize add");
}
function MBP() {
selectWindow(a);
run("8-bit");
setThreshold(52, 255);
run("Convert to Mask");
run("Analyze Particles...", "size=30.00-250.0 show=Outlines clear summarize add");
}
function DAPI_Olig2_overlay() {
imageCalculator("AND create", x, y);
selectWindow(b);
run("Analyze Particles...", "size=30-250 show=Outlines clear summarize add");
}
function DAPI_Olig2_MBP_overlay() {
imageCalculator("AND create", b, a); //overlay DAPI, Olig2 and Ki-67
selectWindow(d);
run("Analyze Particles...", "size=30-250 show=Outlines clear summarize add");
}
setBatchMode(true);
for (i=0; i<C01list.length; i++) {
showProgress(i+1, C01list.length);
// your code goes here - an example is shown
s = "open=["+dir1+C01list[i]+"] autoscale color_mode=Composite rois_import=[ROI manager] view=Hyperstack stack_order=XYCZT";
DAPI();
OLIG2();
Ki67orMBP();
DAPI_Olig2_overlay();
DAPI_Olig2_Ki67_overlay();
saveAs("tiff", dir2+replace(C01list[i],".C01",".tif"));
close();
// and ends here
}
setBatchMode(false);
}
function append(arr, value) {
arr2 = newArray(arr.length+1);
for (i=0; i<arr.length; i++)
arr2[i] = arr[i];
arr2[arr.length] = value;
return arr2;
}
The problem I'm having is that it reaches x=startsWith("c:1/3"), it can't go any further. I know the rest of the code works, its just having an issue selecting which layer of the stack I want it to analyse. Whenever I hit run I get this error back:
Error: Number or numeric function expected in line 14:
x = startsWith ( "c:1/3" <)>
Any ideas?

ImageJ: Wrong transferrence of Coordinates from picture to picture

for my Thesis I must count cells on pictures stained with Immunofluorescence and I am writing a macro in ImageJ to do it for me.
For this I coloursplit the picture, analyse particles in the red channel (my Antibody´s colour) and then I want to take the coordinates of analysed particles and only count them if at the same coordinates in the blue channel there is also a staining (DAPI - just a general cell staining).
This way I assure that there is as little dirt counted as possible.
The problem is that when I get the coordinates from the results table and use them to makePoint(x,y) the coordinates are "distorted" - usually the correct coordinates but plus 4ish, though never in exactly the same, which is why i can´t simply distract a number from the coordinates
Below I first write down the critical lines of code, then the whole code.
Thank you very much in advance
run("Analyze Particles...", " circularity=r1-r2 display clear in_situ");
roiManager("deselect");
z=nResults;
for (j=0; j<z; j++) { //loops through the Results table and adds to "counter" if a match is found
selectImage(channelsplit[2]); //selects blue window
setThreshold(d,l);
run("Threshold...");
setOption("BlackBackground", true);
run("Convert to Mask", "method=Default background=Default black");
run("Coordinates...", "left=0 right=19373 top=0 bottom=13600"); //I tried to set the boundaries of the pictures equally, but it didnt work
makePoint(getResult("X", j)), (getResult("Y", j));
print ("X" + j + ": " + getResult("X",j)); //this and the following line are not to be in the program, once it works
print ("Y" + j + ": " + getResult("Y",j));
run ("Measure");
if (getResult("Mean", nResults-1)>100) {
counter++;
}
} //for j
print (i + ": " + counter);
setBatchMode(true);
if (isOpen("ROI Manager")) {
r=roiManager("count");
} else {
setBatchMode(false);
exit("You need a ROI Manager open with the ROIs of all the pictures to be measured");
}
Dialog.create ("Variables")
Dialog.addCheckbox ("red", true);
Dialog.addCheckbox ("green", false);
Dialog.addCheckbox ("blue", false);
Dialog.addCheckbox ("watershed", true);
Dialog.addNumber ("Thresholddark:", 110);
Dialog.addNumber ("Thresholdlight:", 255);
Dialog.addNumber ("greenThresholddark:", 110);
Dialog.addNumber ("greenThresholdlight:", 253);
Dialog.addNumber ("pmin:", 15);
Dialog.addNumber ("pmax:", 100);
Dialog.addNumber ("roundness1:", 0.5);
Dialog.addNumber ("roundness2:", 1.0);
Dialog.addMessage("batch - select 'true' for your macro to run faster, but you will not see what it does until finished\nstack - selecht this box if you use unstacked pictures and want them stacked, deselect if you use a readied stack or a single picture\nred - select this box if you want to count red coloured cells \ngreen - select this box if you want to count green coloured cells \nblue - select this box if you want to count blue coloured cells\nall variables are the same for the colours you count. It may be better to adjust variables for each colour and count seperately\nwatershed - select this box only if you have overlapping cells in your image\nThresholdlight - particles lighter than this won't be measured/counted \nThresholddark - particles darker than this won't be measured/counted \nThresholdlight and Thresholddark can be between 0 and 255 \ntry thresholding manually at least once manually to get best results \npmin - particles with a size smaller than this won't be counted \npmax - particles with a size greater than this won't be counted")
Dialog.show ();
cr=Dialog.getCheckbox();
cg=Dialog.getCheckbox();
cb=Dialog.getCheckbox();
w=Dialog.getCheckbox();
d=Dialog.getNumber();
l=Dialog.getNumber();
dg=Dialog.getNumber();
lg=Dialog.getNumber();
pmin=Dialog.getNumber();
pmax=Dialog.getNumber();
r1=Dialog.getNumber();
r2=Dialog.getNumber();
dir = getDirectory("Choose a Directory "); //choose the folder with all the pictures to be measured
listFiles(dir); //I found this in a listFiles recursively Demo and changed it to open my pictures
function listFiles(dir) {
list = getFileList(dir);
for (o=0; o<list.length; o++) { //loops through the file list, opening then analysing then closing one after another
if (endsWith(list[o], "/")) {
listFiles(""+dir+list[i]);
} else {
open(dir + list[o]);
//the previous opens all pictures in a given folder in a way i do not understand
//I only use this function because I could not use the variable list.length outside of it for unknown reasons
//following is my cellcount program to be executed for each picture
//then the picture will be closed before the new one is opened
run("Split Channels");
channelsplit = getList("image.titles");
if (cr==1) {
a=0;
}
if (cg==1) {
a=1;
}
selectImage(channelsplit[a]); //selects red or green window, depending on input in the Dialog
setThreshold(d,l);
run("Threshold...");
setOption("BlackBackground", true);
run("Convert to Mask", "method=Default background=Default black");
run("Coordinates...", "left=0 right=19373 top=0 bottom=13600");
for (i=2*o; i<=((2*o)+1); i++) { //loops through two ROIs of the ROIManager
counter=0;
selectImage(channelsplit[a]);
roiManager("deselect");
roiManager("select", i);
if (w==1) {
run("Watershed", "slice");
}
run("Analyze Particles...", " circularity=r1-r2 display clear in_situ");
roiManager("deselect");
z=nResults;
for (j=0; j<z; j++) { //loops through the Results table and adds to "counter" if a match is found
selectImage(channelsplit[2]); //selects blue window
setThreshold(d,l);
run("Threshold...");
setOption("BlackBackground", true);
run("Convert to Mask", "method=Default background=Default black");
run("Coordinates...", "left=0 right=19373 top=0 bottom=13600"); //I tried to set the boundaries of the pictures equally, but it didnt work
makePoint(getResult("X", j)), (getResult("Y", j));
print ("X" + j + ": " + getResult("X",j)); //this and the following line are not to be in the program, once it works
print ("Y" + j + ": " + getResult("Y",j));
run ("Measure");
if (getResult("Mean", nResults-1)>100) {
counter++;
}
} //for j
print (i + ": " + counter);
close("Results"); //closes Results to get the variables in order for the next window
// IJ.renameResults("res" + i);
} //for i
close("*"); //closes all image windows to save RAM
} //else
} //for o
} //function
setBatchMode(false);

Error in ImageJ macro to lay outlines of particle analysis over original image

I am trying to write an imageJ macro that will
1) Open and split an image into two channels
2) Perform particle analysis on each image and save measurements
3) Save the original image with the particle outlines overlayed
So far I have realised I need to first duplicate the original image so that the ROI can later be saved on top of this. However I at the moment I can't figure out how to rename this duplicated image so I can later select it for flattening:
dir=getDirectory("Choose a Directory");
print(dir);
greenDir=dir + "/Green/";
blueDir=dir + "/Blue/";
print(greenDir);
print(blueDir);
File.makeDirectory(greenDir);
File.makeDirectory(blueDir);
list = getFileList(dir);
for (i=0; i<list.length; i++) {
if (endsWith(list[i], ".tif")){
print(i + ": " + dir+list[i]);
open(dir+list[i]);
imgName=getTitle();
baseNameEnd=indexOf(imgName, ".tif");
baseName=substring(imgName, 0, baseNameEnd);
run("Split Channels");
selectWindow("C1-" + imgName);
run("Duplicate...", "title= imgName + "original");
selectWindow("C1-" + imgName);
setAutoThreshold("Default dark");
//run("Threshold...");
//setThreshold(1, 255);
run("Convert to Mask");
run("Analyze Particles...", "size=60-Infinity pixel show=Outlines display exclude summarize add");
selectWindow(imgName + "original");
roiManager("Show All without labels");
run("Flatten");
saveAs("Tiff", greenDir + baseName + "green.tif");
close();
Sorry in advance if this is something very simple, this is all very new to me and learnt off googling!
I modified my code to this last night and now it is working:
dir=getDirectory("Choose a Directory");
print(dir);
greenDir=dir + "/Green/";
blueDir=dir + "/Blue/";
print(greenDir);
print(blueDir);
File.makeDirectory(greenDir);
File.makeDirectory(blueDir);
list = getFileList(dir);
for (i=0; i<list.length; i++) {
if (endsWith(list[i], ".tif")){
print(i + ": " + dir+list[i]);
open(dir+list[i]);
imgName=getTitle();
baseNameEnd=indexOf(imgName, ".tif");
baseName=substring(imgName, 0, baseNameEnd);
run("Split Channels");
roiManager("Reset");
selectWindow("C1-" + imgName);
run("Duplicate...", "title=");
saveAs("Tiff", greenDir + "originalgreen" + baseName);
selectWindow("C1-" + imgName);
setAutoThreshold("Default dark");
//run("Threshold...");
//setThreshold(1, 255);
setOption("BlackBackground", false);
run("Convert to Mask");
run("Analyze Particles...", "size=60-Infinity pixel show=Outlines display exclude summarize add");
selectWindow("originalgreen" + imgName);
roiManager("Show All with labels");
run("Flatten");
saveAs("Tiff", greenDir + baseName + "overlaygreen.tif");
close();
}
}
for (i=0; i<list.length; i++) {
if (endsWith(list[i], ".tif")){
print(i + ": " + dir+list[i]);
open(dir+list[i]);
imgName=getTitle();
baseNameEnd=indexOf(imgName, ".tif");
baseName=substring(imgName, 0, baseNameEnd);
run("Split Channels");
roiManager("Reset");
selectWindow("C2-" + imgName);
run("Duplicate...", "title=");
saveAs("Tiff", blueDir + "originalblue" + baseName);
selectWindow("C2-" + imgName);
//run("Threshold...");
//setThreshold(23, 255);
setOption("BlackBackground", false);
run("Convert to Mask");
run("Analyze Particles...", "size=60-Infinity pixel show=Outlines display exclude summarize add");
selectWindow("originalblue" + imgName);
roiManager("Show All with labels");
run("Flatten");
saveAs("Tiff", blueDir + baseName + "overlayblue.tif");
run("Close All");
}
}
Every GUI action in ImageJ can be recorded in different script languages with the macro recorder which is a great help, see:
https://imagej.nih.gov/ij/docs/guide/146-31.html#sub:Record...
http://imagej.net/Introduction_into_Macro_Programming
The macro command for rename is simply: rename("YourImageTitle");

ImageJ stack to images & rename images

I have a small problem with imagej:
I have .tif files in a folder, which consist of three different files (blue channel, green channel, red channel).
I would like to convert them to separate pictures, then to only keep the green one
I want to do this with a macro, but i can't get it to work.
I can open the .tif, then convert it to separate images (Image-0001, Image-0002 and Image-0003). But then i want to rename them to blueImage, greenImage and redImage.
Googling got me to this, but this one saves the images as separate files and it gives an error.
macro split_color{
dir1 = getDirectory("InputDir");
list = getFileList(dir1);
dir2 = getDirectory("OutpurDir");
for (i=0; i<list.length; i++) {
open(dir1+list[i]);
title1=File.nameWithoutExtension;
for (j=1; j<=3; j++){
run("Stack to Images")
" slices="+j);
run("8-bit");
if (j==1) c = "blue";
else if(j==2) c = "green";
else c = "red";
saveAs("tif", dir2+title1+"-"+c+".tif");
wait(100);
close();
}
close();
}
showMessage("Macro is finished");
}
I can't get this to work, anyone who could help me?
Thanks

Strange filename import behavior in ImageJ macro

I'm writing an ImageJ macro to iterate through a folder of .lsm confocal microscope images, make a Z Project from each, combine the two channels into red and green, and save as an RGB image. The code works fine for one directory, but now it's throwing an error that has something to do with the filename from getFileList.
Here's the relevant part of the code:
dir1 = getDirectory("Choose Source Directory ");
format = getFormat();
dir2 = getDirectory("Choose Destination Directory ");
list = getFileList(dir1);
setBatchMode(true);
for (i = 0; i < list.length; i++) {
showProgress(i+1, list.length);
open(dir1+list[i]);
run("Z Project...", "projection=[Max Intensity]");
run("Split Channels");
run("Merge Channels...", "c1=C1-MAX_" + list[i] + " c2=C2-MAX_" + list[i]);
saveAs(format, dir2 + list[i]);
close();
}
It's necessary that "C1-MAX_" is appended to the input string because those prefixes are added to the image name during the calls to Z Project and Split Channels.
For reference, the name of the files look like Negative 1 5x.lsm, Negative 2 5x.lsm, Positive 1 5x.lsm, etc. Based on these filenames, I expect ImageJ to call the Merge Channels command with the strings "C1-MAX_Negative 1 5x.lsm" and "C2-MAX_Negative 1 5x.lsm".
Instead, I get the error message "C1-MAX_Negative" is not a valid choice for "C1 (red):"
I don't understand why ImageJ is trying to call Merge Channels with the string "C1-MAX_Negative" and not "C1-MAX_Negative 1 5x.lsm". Why isn't list[i] returning what I think it should?
It is probably because of the space in the filename. Try putting the name in square brackets like that:
run("Merge Channels...", "c1=[C1-MAX_" + list[i] + "] c2=[C2-MAX_" + list[i] + "]");