Color threshold batch processing of images

Hi all,

I have a lot of images to analyze and I’m trying to write a macro for doing it by batch, the idea is simple,

I want to create a mask of my image and save it in a new folder using color threshold.

I have copy pasted the color threshold macro code in my macro for batch analysis but it seems that it is looping on the second picture…

Can anyone help me finding where does the problem come from?

Here is my macro:

source_dir = getDirectory("Choose an input Directory ");  // window to select the input directory
dest_dir = getDirectory("Choose an output Directory ");  // window to select the output directory
list = getFileList(source_dir);  // list files in it

setBatchMode(true); // activate batch process
for (i=0; i<list.length; i++) { // loop over files
    	showProgress(i, list.length); // update progressbar
	file_name = list[i];
	if (endsWith(file_name, ".tif")) {
		file_path = source_dir + file_name; 
		new_path = dest_dir + file_name; 
		open(file_path);//Color threshold macro
		min=newArray(3);
		max=newArray(3);
		filter=newArray(3);
		a=getTitle();
		run("HSB Stack");
		run("Convert Stack to Images");
		selectWindow("Hue");
		rename("0");
		selectWindow("Saturation");
		rename("1");
		selectWindow("Brightness");
		rename("2");
		min[0]=0;
		max[0]=255;
		filter[0]="pass";
		min[1]=0;
		max[1]=255;
		filter[1]="pass";
		min[2]=135;
		max[2]=255;
		filter[2]="pass";
		for (i=0;i<3;i++){
		  selectWindow(""+i);
		  setThreshold(min[i], max[i]);
		  run("Convert to Mask");
		  if (filter[i]=="stop")  run("Invert");
		}
		imageCalculator("AND create", "0","1");
		imageCalculator("AND create", "Result of 0","2");
		for (i=0;i<3;i++){
		  selectWindow(""+i);
		  close();
		}
		selectWindow("Result of 0");
		close();
		selectWindow("Result of Result of 0");
		rename(a);//end of color threshold macro
		close(a)
		save(new_path);
		close();
	}
}

Many thanks!

Hi @Norbert_Bollier welcome to the forum.

You’ll note that you use the variable i for both your file loop and your channel loop:

Simply use a different variable name like j for your second loop which should fix the problem. You may consider using something more descriptive like fileLoop and channelLoop for your counting variables which will also make your code easier to understand for others.

Hope that helps!

1 Like