Thresholding with macro


hi everyone, this is Sneha,

I am new to the ImageJ software and have no idea about macros. I tried usind macros for analysis of microscopic images of a foam sample and Thresholding or Color thresholding seems to not work in my case.
I manually solved the picture and the results are what I desired and when I run the MAcros program to it its a different evry single time.
Manual procedures are -

  1. Open image
  2. change type to 8-bit
  3. set scale
  4. invert image
  5. give thresold values as 235-255
  6. analyze particles- measure from 10,000-infinity
  7. calculate diameter of each cell from mean area.
    for color thresholding-
  8. open image
  9. calibrate image
  10. invert
  11. color threshold - 235,255
  12. analyze particles
  13. calcuate diameter
    when i record a macros program with all these steps in both cases it doesnt work
    I also tried recording two different programs from opening image to invert and one for just applying threshold and analyzing.
    manula case and these seperate cases give different results.
    I hope you understood my problem and help me in getting a suitable macros program



I am not entirely clear on what your problem is. Is your macro not performing adequately on the same image when run manually vs. automatically? Or is your macro not outputting all of the measurements that you want it to?



Manually it is working… I have problem with its automatic function. It’s just processing part of my image


Did you create your macro by starting the Macro Recorder and putting the result of the manual steps in a text file?
If you then open the text file and Debug the Macro step by step, (cmd-D, then cmd-E repeatedly), can you discover which step differs from manual processing?
If you ‘calculate the diameter’ it always helps (me) to have all results in variables, so you can inspect their values using the Debug window.


I didnt get you. can you please elaborate the matter


If you grab the text from the Recorder window and put macro “mymacro”{ above the text and a } below the text, then often macros don’t work as expected straight away, or it needs a bit of polishing. Recording merely makes sure your syntax is OK.

To see what goes wrong, you can execute your recorded macro line by line and inspect the consequences of each command.
This is called Debugging. You can execute each line of the macro by Step-ping through the text of the macro with help of the macro Debug function.

Are you with me so far?


yes i got you now. can you please tell me how to run the debug option for the created macro program?


Copy the text from the Recorder window (assuming you have started to record your manual steps and these are present in the Recorder window). Then
Plugins>New>Macro and paste in your recorded text.
As long as this window is open and frontmost (!), you will find that the last item in the ImageJ menu bar has changed to Debug. (I’m using ImageJ 1.51u for reference).
The macro will work on the last image you had frontmost. Make it a habit of having inputImage=getWindowID(); as first line of your macro, this allows you to reference it by selectImage(inputImage); so your macro code acts upon this image.
In the Debug menu, choose the Debug Macro item, this prepares debugging and should open a window named Debug, which displays values of variables in use and some extra info. It also highlights the first line of the macro text.
Then repeatedly choose Debug>Step or press the key combo listed behind it, to execute the highlighted line of your macro.
Still with me?


can some one send me the automatic macros program for the above mentioned picture so i can compare with mine.


This is my page right now and i Am using imageJ 1.51r. I see no debug option on menu bar as of now


You are using Fiji. Contrary to popular belief, Fiji is not just ImageJ :wink:
Download ImageJ from trusted sources and you will find the Debug functionality.
If you DO need to use Fiji, once your macro is debugged, you can deploy it in Fiji all right.


Since you said I downloaded the 1.51u version and started debugging and found out that my threshold is going on to the boundaries instead of to the areas inside the boundaries. When i do it manually it’s working but here the condition is reversed. Can you help me with this please.


Good for Debugging!
Did you try setOption(“BlackBackground”, “true”);?
Otherwise a rough description of the road ahead: If you manage to have close(d) boundaries around cells, make them binary (in a new image), thin the boundaroes to their skeleton. Then invert so you have blobs separated by a 1-pixel wide trench. Analyse Particles with Add to ROI Manager checked, this gives you probably what you want already. If not, then in a loop pick a roi from the Manager, Edit>Selection>Enlarge… by -1 and you have the inset boundary.


no that doenst seem to work. no happy results :frowning:
my above program seems to work. i just need some simple trick to shift the threshold from boundaries to mass inside.


I guess you want to change the threshold values a bit after the auto thresholding.
Would it help to use the commands

getThreshold(lower, upper);

after the line where you perform setAutoThreshold?


makeLine(1314, 1115, 1550, 1115);
run(“Set Scale…”, “known=500 unit=micrometers”);
//setThreshold(235, 255);
setOption(“BlackBackground”, false);
run(“Convert to Mask”);
run(“Analyze Particles…”, “size=9580.76-Infinity pixel show=Outlines display exclude clear”);

copy of the macro program


no. this doesnt seem to work. the only error is with the threshold rest all is fine. threshold must be diverted from boundaries to matter inside the boundaries as that is my goal to approachh.


Hey, I tried to write the macro myself.
I had the same problems some time ago but I got some code working, so I’m happy to share:

//macro imageJ-forum - hope this helps

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

for (i=0; i<list.length; i++) { 
			title = getTitle();
			//you can add every measurement here that you are interested in, just use the macro recorder
			run("Set Measurements...", "area feret's redirect=None decimal=3");

			waitForUser("Draw a line that is exactly your scalebar");
			run("Set Scale...", "known=500 pixel=1 unit=um global");
			setThreshold(235, 255);
			setOption("BlackBackground", false);
			run("Convert to Mask");
			//***********I added this because I found it suitable, but there is no need to use it, you didn't want it in the first place***********
			run("Fill Holes"); 

			run("Analyze Particles...", "size=10000-Infinity pixel summarize add");

				if (isOpen("ROI Manager")) {
     					selectWindow("ROI Manager");
						roicount = roiManager("Count");
						for (n=0;n<roicount;n++){

			//saves all measurements as an excel file, not needed though
				if(isOpen("Results")) {	selectWindow("Results"); 
										saveAs("results", path + title + "_all_data.xls");
				if(isOpen(title)){selectWindow(title); close();}
				if(isOpen("ROI Manager")) {selectWindow("ROI Manager"); run("Close");}


//finish everything and calculation
if(isOpen("Summary")) {selectWindow("Summary");

number = nResults;

for (j=0; j<number; j++) {
		area = getResult("Average Size");
		radius = sqrt(area/3.14159);
		diameter = radius * 2;
		setResult("MEAN Diameter", j, diameter);

I dont know if you need all this.

Basically, it asks you for a folder where your pictures are located. It opens the file, analyses it as you asked and saves all measurements as a separate excel file. If you want to have more information, you can modiy the “Set Measurements” command in one of the first lines.

I didnt really know how to calculate the diameter from the area. Are you assuming that they are circular? if yes, everything in the final calculations is fine.
If not, I included the Ferret-Diameter, which is the maximum diameter that a particle has.

You will get a “Results”-table in which you have a lot of data, the last one being “Mean Diameter” as calculated from the mean area per picture assuming that the cells are circular objects.

Keep in mind that there might be better ways to calculate different types of shapes, but that is surely beyond this thread :slight_smile:

Also, you need to draw the scalebar every time. I also have a workaround for this, but this would take me some minutes to implement. But if you need it I could provide :slight_smile:

Please tell me if there are some problems, I’m happy to help.