Memory error Coloc2 macro

I have been trying to create a macro for Coloc2. I have previous macros that split channels and crop images, so my new macro loads those images/corresponding ROI (& re-centers the ROI) and runs Coloc2 on them. I pilot tested the macro on 4 images and finally got it working properly. When I scaled up to a larger amount of images I got a memory error around 10 images into the analysis. I first tried adding memory as the error message suggested I do. I assume this is due to the Coloc2 window that opens during the analysis. I could not figure out how to close that window. From googling and looking here it seems that window is troublesome and getting it to close is difficult. I noted there are recommendations on here for using a groovy script or the ImageJ Ops but am not familiar with either of these options. I wanted to check to see if there was something I was missing for closing that image and being able to process larger data sets with my existing script. I am not a programmer so if this is not an ideal script please let me know how it could be improved.

I also tried running in batch mode the colocalization test (which worked for my whole data set) which I have commented out below. However those Pearson’s R values are slightly different from those provided by Coloc2. In general which platform does everyone prefer for getting a Pearson’s Correlation Value?

Thanks in advance!


_RootFolder = getDirectory("Choose a Directory");

// Creating a directory where the files are saved

outputfolder = _RootFolder + "/coloc2_output";

outputfolderROIs = _RootFolder + "/coloc2_output/ROIs";


list = getFileList( _RootFolder + "/channel1/cells/" ); 
for ( i=0; i<list.length; i++ ) { 

    //create image ID
    fileName = list[i]; 
    imageName = replace(fileName,"\\.tif$", "");

	//open channel 1
	open(_RootFolder + "/channel1/cells/" + imageName + ".tif");
	//run("Z Project...", "projection=[Max Intensity]");
	saveAs("Tiff", _RootFolder + "/channel1/" + "channel1.tif");

	//open channel 2
	open(_RootFolder + "/channel2/cells/" + imageName + ".tif"); 
	//run("Z Project...", "projection=[Max Intensity]");
	saveAs("Tiff", _RootFolder + "/channel2/" + "channel2.tif");

	//open ROI
	run("ROI Manager...");
	roiManager("Associate", "false");
	roiManager("Centered", "false");
	roiManager("UseNames", "true");
	roiManager("Open",_RootFolder + "/channel1/ROIs/" + imageName + ".roi");
	roiManager("Select", 0);

	//Adjust location of ROI to center of image
	Roi.getBounds(x, y, width, height);	
	// saveAs("Text", outputfolder + "/" + imageName + "ROIcoord.txt");
	Roi.move((1500 - width) / 2, (1500 - height) / 2);

	//Add new ROI and delete old ROI
	roiManager("Select", 1);
	roiManager("Save selected", _RootFolder + "/coloc2_output/ROIs/" + imageName + ".roi");
	roiManager("Select", 0);

	//Run Coloc 2 and reset 
	run("Coloc 2", "channel_1=channel1.tif channel_2=channel2.tif roi_or_mask=[ROI Manager] threshold_regression=Bisection psf=3 costes_randomisations=10");
	saveAs("Text", outputfolder + "/" + imageName + ".txt");
	//run("Colocalization Test", "channel_1=channel1.tif channel_2=channel2.tif roi=[ROI in channel 2] randomization=[Costes approximation (smoothed noise)] show_all_r_values randomize pixel=1.000 channel_2_wavelength=520 na=1.40 iterations=0 use_manual_psf psf_radius=10");
	//selectWindow("Random R values");
	//saveAs("Text", outputfolder + "/" + imageName + ".txt");
	run("Close All");	


What exactly do you wish to measure in your colocalization analysis? How much of the output from Coloc2 do you need? Because of the way the plugin was designed… there is no way to do any of the calculations easily without going through the GUI, which is why we provide a few scripting alternatives - as you mentioned - to try to make the data-grab a bit more customizable and ‘easy’. I’m assuming you read through this older forum post:

Don’t worry - you don’t have to know Groovy already before using it in ImageJ/Fiji… We tried to provide enough examples to get users moving forward quickly.

All you have to do is open the Script Editor (File > New > Script…) and then go to Templates > Examples > Colocalisation (Groovy) (see script below - to copy/paste directly) - that example should work if you run it on two images. To do this via batching… you can modify the other Batch example code in Templates > ImageJ 1.x > Batch > Process Folder (Groovy) so two images are opened and then analysis run, etc (also see script below - to copy/paste directly).

Colocalisation.groovy script (with just an update to the Script Parameter syntax):

#@ImagePlus imp1
#@ImagePlus imp2

// Colocalisation.groovy
// This script demonstrates programmatic usage of Fiji's Coloc 2 plugin,
// including how to extract quantitative measurements after execution.

import sc.fiji.coloc.Coloc_2
coloc2 = new Coloc_2()

indexMask = 0
indexRegr = 0
autoSavePdf = false
displayImages = false
displayShuffledCostes = false
useLiCh1 = true
useLiCh2 = true
useLiICQ = true
useSpearmanRank = true
useManders = true
useKendallTau = true
useScatterplot = true
useCostes = true
psf = 3
nrCostesRandomisations = 10


img1 = coloc2.img1
img2 = coloc2.img2
box = coloc2.masks[0].roi
mask = coloc2.masks[0].mask

// NB: Passing a different bounding box and/or mask here
// may work, but is (as of this writing) UNTESTED.
results = coloc2.colocalise(img1, img2, box, mask, null)
for (v in results.values()) {
  println( + " = " + (v.isNumber ? v.number : v.value))
println("I also have histograms:")
for (h in results.histograms()) {
	println("\t" + h)

Process_Folder.groovy script:

#@ File    (label = "Input directory", style = "directory") srcFile
#@ File    (label = "Output directory", style = "directory") dstFile
#@ String  (label = "File extension", value=".tif") ext
#@ String  (label = "File name contains", value = "") containString
#@ Boolean (label = "Keep directory structure when saving", value = true) keepDirectories

import ij.IJ

def main() {
	srcFile.eachFileRecurse {
		name = it.getName()
		if (name.endsWith(ext) && name.contains(containString)) {
			process(it, srcFile, dstFile, keepDirectories)

def process(file, src, dst, keep) {
	println "Processing $file"

	// Opening the image
	imp = IJ.openImage(file.getAbsolutePath())

	// Put your processing steps here

	// Saving the result
	relativePath = keep ?
			: "" // no relative path
	saveDir = new File(dst.toPath().toString(), relativePath)
	if (!saveDir.exists()) saveDir.mkdirs()
	saveFile = new File(saveDir, file.getName()) // customize name if needed
	IJ.saveAs(imp, "Tiff", saveFile.getAbsolutePath());

	// Clean up


If you provide a bit more details of your analysis and how you have for image files organized/named, etc. … we can provide a bit more targeted help. I’m not sure if using such scripts will help with the memory issue - but depending on what you need for outputs… might be worth at least trying as a first step.

Currently I use R to extract the pearsons info from the text file.

I nest my folders like this

I think I found a workaround:

The plugin clicks the mouse at a specific xy coordinate.

I modified the end of my code like this after installing autoclicker and ran it on my folder; no memory errors and processed the whole set!

//Run Coloc 2 and reset 
	run("Coloc 2", "channel_1=channel1.tif channel_2=channel2.tif roi_or_mask=[ROI Manager] threshold_regression=Bisection psf=3 costes_randomisations=10");
	saveAs("Text", outputfolder + "/" + imageName + ".txt");
	run("AutoClickerJ GUI 1.0.7", "order=LeftClick x_point=278 y_point=181 delay=100 clickandkeywrite=[]");
	run("AutoClickerJ GUI 1.0.7", "order=LeftClick x_point=14 y_point=33 delay=100 clickandkeywrite=[]");
	run("Close All");	
1 Like