FRET macro improving for z stack projection

Hello
I would like to adapt the macro from Manel Bosch and Elena Kardash https://experiments.springernature.com/articles/10.1007/978-1-4939-9686-5_13
for z projection in neurons.
The problem is that this macro I need to press one by one the file with the name FRET and then will recognize the CFP file with the same number and I would like to do it in batch mode.

Furthermore, I would like to add an instruction to make a projection of my .lsm file (z stack) at the beginning so everything can be in that batch.

Finally, the macro show and save the histogram with the analysis but I would like to have a way to draw an ROI and save in a csv file all the files.

Sample image and/or macro code

This is the original macro:

//Create the dialog box asking for ratio values
Dialog.create("FRETRatioAnalysis");
Dialog.addNumber("Minimum value for the ratio", 0.0);
Dialog.addNumber("Maximum value for the ratio", 2.5);
Dialog.show;
minRatio = Dialog.getNumber();
maxRatio = Dialog.getNumber();

//Open FRET image, collect data and open its corresponding CFP image
showMessage("Open a FRET image when asked");
open();
title = getTitle();
fretID = getImageID();
input = File.directory;
experiment = substring(title, 0, lengthOf(title)-8);//Removing FRET and file extension
cellType = substring(title, lengthOf(title)-8, lengthOf(title)-4);//Looking for FRET word
extension = substring(title, lengthOf(title)-4);//Looking for file extension
getDimensions(width, height, channels, slices, frames);
if(cellType=="FRET"){
	open(experiment + "CFP" + extension);//Pair of FRET image previously open
	cfpID = getImageID();
}else{
	exit("There is no FRET image open");
}

//Rename images
selectImage(fretID);
rename("FRET");
selectImage(cfpID);
rename("CFP");

//Crop the cell of interest
selectImage(fretID);
waitForUser("Draw a ROI around the cell to analyze");
roiManager("Add");
run("Crop");
selectImage(cfpID);
roiManager("Select", 0);
run("Crop");
selectWindow("ROI Manager");
run("Close");

//Process images
selectImage(fretID);
run("Subtract Background...", "rolling=300 stack");
selectImage(cfpID);
run("Subtract Background...", "rolling=300 stack");
run("MultiStackReg", "stack_1=CFP action_1=[Use as Reference] file_1=[] stack_2=FRET action_2=[Align to First Stack] file_2=[] transformation=[Rigid Body]");
selectImage(fretID);
run("32-bit");
run("Smooth", "stack");
selectImage(cfpID);
run("32-bit");
run("Smooth", "stack");

//Segment FRET image
selectImage(fretID);
run("Threshold...");
call("ij.plugin.frame.ThresholdAdjuster.setMode", "Over/Under");
waitForUser("Apply Threshold y click OK");
selectImage(cfpID);
run("Threshold...");
call("ij.plugin.frame.ThresholdAdjuster.setMode", "Over/Under");
waitForUser("Apply Threshold y click OK");

//Calculate the ratio
run("Ratio Plus", "image1=[FRET] image2=[CFP] background1=0 clipping_value1=0 background2=0 clipping_value2=0 multiplication=1");
ratioID = getImageID();
setMinAndMax(minRatio, maxRatio);

//Add a calibration bar
selectImage(ratioID);
run("metamorph");
run("Duplicate...", "title=copy duplicate");
resizeImage();
run("Calibration Bar...", "location=[Upper Right] fill=Black label=White number=3 decimal=1 font=14 zoom=1.5 overlay");
run("Flatten", "stack");
calBarID = getImageID();

//Obtain histogram
selectImage(ratioID);
rename("Ratio");
if(slices>1){
	stackHistogram();
}else{
	run("Histogram", "bins=100 x_min=" + minRatio + " x_max=" + maxRatio + " y_max=Auto");
}

//Create Results folder inside the input folder
output = input + "Results" + File.separator;
File.makeDirectory(output);
if(!File.exists(output)){
	exit("Unable to create the folder");
}

//Save images and histogram
selectImage(calBarID);
saveAs("Tiff", output + experiment + " Ratio_RGB");
selectImage(ratioID);
saveAs("Tiff", output + experiment + " Ratio");
selectWindow("Histogram of Ratio");
saveAs("Tiff", output + experiment + " Ratio_Histogram");
selectImage(fretID);
saveAs("Tiff", output + experiment + " FRETYFP");
selectImage(cfpID);
saveAs("Tiff", output + experiment + " CFP");
if(isOpen("copy")){
	selectWindow("copy");
	close();
}

/**********
* Functions
**********/
//Function to resize an image and increase its canvas by 100px width
function resizeImage(){
	if(width<400){
		run("Size...", "width=400 height=400 constrain average interpolation=None");
		height = getHeight();
	}
	width = getWidth() + 100;
	run("Canvas Size...", "width="+width+" height="+height+" position=Center-Left zero");
}

//Function to create a stack of histograms obtained from each slice in a stack
function stackHistogram(){
	setBatchMode(true);
	for(i=1; i<=slices; i++){
		selectImage(ratioID);
		setSlice(i);
		run("Histogram", "bins=100 x_min=" + minRatio + " x_max=" + maxRatio + " y_max=Auto");
		rename("frame " + i);
	}
	run("Images to Stack", "name=histoStack title=frame use");
	rename("Histogram of Ratio");
	setBatchMode(false);
	
}
run("Close All");

`

  1. I want to integrate at the beginning this macro (z stack projection) that I run separately.

`

macro "split" {

  path    = getDirectory("Choose a Directory");
  list    = getFileList(path);
  length  = list.length;

  File.makeDirectory(path + "Ratio/");

  //Split for analysis

  for (i=0; i<length; i++) {
             
    n=i+1;
    open(path+list[i]);
    img = File.nameWithoutExtension();
    selectWindow(img+".lsm");

run("Split Channels"); 
selectWindow("C3-" + list[ i ]);
run("Z Project...", "projection=[Sum Slices]");
rename("FarRED");
saveAs("Tiff", path+"Ratio/" + IJ.pad(i,1)+ "FarRED");
selectWindow("C2-" + list[ i ]);
run("Z Project...", "projection=[Sum Slices]");
rename("FRET");
saveAs("Tiff", path +"Ratio/" + IJ.pad(i,1)+ "FRET");
selectWindow("C1-" + list[ i ]);
run("Z Project...", "projection=[Sum Slices]");
rename("CFP");
saveAs("Tiff", path+"Ratio/" + IJ.pad(i,1)+ "CFP");
close();
    run("Close All");
}`
  1. finally, I would like to draw and ROI and save information.
    Similar to this
`run("ROI Manager...");
    waitForUser("add ROI, Draw ROI, then hit OK");
    roiManager("Add");
    roiManager("Show All");
    roiManager("Multi Measure");
    selectWindow("Results");
    saveAs("Results",path + "FRET/roi" + i+".csv");
    run("Close");  
    selectWindow("ROI Manager"); 
    run("Close"); `

Analysis goals

  1. I want to analyze in batch mode, transform .lsm file into separate z projection with the name
    0FRET
    0CFP
    1FRET
    1CFP …etc
  2. in batch the FRET ratiometric macro analyzing every FRET and CFP z projection tiff file.
  3. add roi and create a csv file for statistic

Challenges

Merge 3 macros in one batch mode

I hope someone can guide me with this challenge.
Thanks in advance
Pablo

Hi @Pablo_M,

A few guides :slight_smile: : Did you already perform a search in the forum for loop formation (processFolder comes to mind as a search term), for naming-with-numbers and prefixes, (where similar and prefix look ideal search terms), for z-projecting (with sum?) and for ‘save as text’, possibly combined with ‘csv’ or ‘excel’, and the latter: did you search the function list both for the commands File.open and File.append, and did you find e.g. saveAs("Text", (including comma) as a search term?

Where did you get stuck?

When you post code, please the </> tool button in the forum editor so your code remains intact; currently there is a load of curly quotes and ellipses, which chokes the macro interpreter. And for lengthy code, there is a Hide Details under the cog wheel. Select the code and use that to create a concise message.

Thank you for the advice. I already checked all the function list that is why I have the third macro with the fuctionlist saveas.
My problem is to add the second macro at the beginning of the first one. I used the three macro separate but I want to merge the three but I have been trying and I cannot combine them in a right way.
THe third macro to measure and ROI and save it as cvs I would like to add it next to this line:

//Calculate the ratio
run("Ratio Plus", "image1=[FRET] image2=[CFP] background1=0 clipping_value1=0 background2=0 clipping_value2=0 multiplication=1");
ratioID = getImageID();
setMinAndMax(minRatio, maxRatio);

Any guide or help to do it I would really appreaciatte it.

Hi, @Pablo_M

If you simply z-project a Ratio image (RGB) such as FRET, the resulting image will change from the original color and it will be difficult to think of the meaning of that color.
In order to solve this problem, we have improved our plugin and developed a plugin for z-projection of ratio images.
If you need them, I can ask my boss for permission to upload this new version.

hwada

Thank you, that would be great. I am trying to analyse several images, that is why I am trying to use a macro that can do it in batch mode. Since I have z stack projection I used sum slice for the FRET channel and CFP channel then use ratio plus for the radiometric. However, with that macro I have to open the files one by one. SO I am trying to solve that problem.

What exactly do you mean with “I have to open the files one by one”? Can’t you loop over the files found in a folder (Or over the lines of a file that contains the file names you want to process) and just ignore the ones you can’t find? And how about changing the macros into functions which you call with the ID of the open image? I do not completely understand all details of your three macros but also I do not see any prohibitive circumstances to cast them in functions.

Batch processing is nice but with a for-loop you can more tightly control what will happen.
And the lsm files, can’t you automatically extract all subfiles with Bioformats Importer? I used that before with the ‘only metadata’ option, then distill what is in the file by analysing the text window that opens up. But that may not be where your question is.

the original macro from Bosch and Kurdish. asks you to open a file with the name FRET and then you follow the instructions, at the end it close and save your images and histograms. After that you have to press “run” again in the macro and do it with the next FRET file and so on. SO if you have 100 images you will have to press 100 time run and go to your folder clicking in the FRET files.

So my first macro is to convert my LSM file into tiff and rename it as 1FRET, 2 FRET, 1CFP, 2CFP ,etc
So then when I press 1FRET the macro call the file1CFP and start to do the calculation.

I am trying to find the way to loop it

Assuming you have an lsm file and you start the macro recorder, what appears in the Recorder window when you open the lsm file and save the files found in the lsm to your liking? What is the name scheme of the lsm files? Is there any pattern? Do you want the FRET file to inherit that lsm naming pattern? Do you really need to rename them FRET or could you alter the macro to use whatever name you find in the lsm?

Simplest start would be to ask for the source folder. In the forum, look for processFolder and processFile, there are many examples on how that works. Once you have the source folder, harvest the names of the files inside the source folder and with processFolder, do your loop (how, we can discuss later).

Thank you, I will look for process folder option and come back with screenshot. Thanks again

A list of filenames (a dozen at max) is easier than a screenshot. With filenames we can test macro codes by using them as dummies. With a screenshot we need to type out those names and call it lazyness, but there is a better way to pass time :wink:
Also you might want to have a look at this post that holds an example of file name manipulation.

So far, I could solve the ROI challenge so far :slight_smile , I added this lines to the original macro

//Calculate the ratio
run("Ratio Plus", "image1=[FRET] image2=[CFP] background1=0 clipping_value1=0 background2=0 clipping_value2=0 multiplication=1");
ratioID = getImageID();
setMinAndMax(minRatio, maxRatio);
selectImage(ratioID);
run("metamorph");
run("Duplicate...", "ratioroi");
 run("ROI Manager...");
    waitForUser("add ROI, Draw ROI, then hit OK");
    roiManager("Add");
    roiManager("Show All");
    roiManager("Multi Measure");
    selectWindow("Results");
    saveAs("Results",output + experiment + "ROI.csv");
    selectWindow("Results");
    run("Close");  
    roiManager("Save", output + experiment + "ROI.zip");
    selectWindow("ROI Manager");
    roiManager("Select", 0);
    roiManager("Delete");
    run("Close");
    roiID = getImageID();

here are 3 lsm file with the type of file that I am trying to analyze.


any help for the looping is appreciated
Thank you

Hi @Pablo_M,
That is an easy naming schedule :wink:
There are enough contributions in the forum about the processFolder routine which opens a folder, gets its list of files and processFile() each of them. You would put in aFile and processFolder tmp+"neuron test/"

This is a for loop construction that would show you every part of your image:

close("*");
tmp=getDirectory("temp");//place your files in a folder named "neuron test" in here
tmp = tmp +  "neuron test"+File.separator;
aFile  ="1.lsm";
run("Bio-Formats", "open=["+tmp+aFile+"] color_mode=Default view=Hyperstack stack_order=XYCZT use_virtual_stack");
getDimensions(width, height, channels, slices, frames);
for(slice = 1; slice < slices+1; slice++){
	for(frame = 0; frame < frames; frame++){
		for(channel = 1; channel < channels+1; channel++){
			Stack.setPosition(channel, slice, frame);
			//do your thing, e.g.
			wait(100);//ms
		}
	}
}

Thank you very much. I will try this before the calculation in the macro.
Now my challenge is just to create a single table with the row results per file instead having single files separate per each image.
Thanks again for all your guide

Add a few variables, per image update these variables and per channel, frame or slice save the results. As my example for loop only deals with one lsm file (is that what you mean with results per file?) save the summary results in a table (setResult(“Column”, row, value) after the example loops, but inside the loop you are going to make using the processFolder principle, that encloses the example loops. After having set the summary outcome variables into the Results table, you can re-initialise them to zero and repeat with the next (lsm?) file.

Thanks, I will add it and see the results then I will come back to you with the full macro so others can use it too.
Thanks again

@Pablo_M

It’s late, but I’ve tried it with your sample image.
First, load these images as an image sequence.
I changed it to HyperStack (c2, z1, t2) and did it with the previously mentioned plugin.
This plug-in calculates all images for 2 channel stack images.
If you need a histogram, you can get it from the created image.

Resize_FRETratio_CalcNo4_min0.1_max0.9.tif (1.5 MB)

hwada

thank you very much, I will have a look on this analysis