How to convert IJMacro to Python code?

I have the following IJ-Macro code.

function action( input, filename) {
    open(input + filename);
    run("Smooth");
    run("Sharpen");
    resetThreshold();
    setAutoThreshold("MaxEntropy");
    run("Convert to Mask");
    run("Convert to Mask");
    run("Convert to Mask");
    run("Make Binary");
    run("Analyze Particles...", "display summarize");
    close();
}



input="/Users/pdubois-macmini-ifrec/Desktop/FIJI_test/"
list = getFileList(input);
for (i = 0; i < list.length; i++)
	action(input, list[i]);

What’s the Python equivalent?

In Python, function definitions work with the def keyword, so this will become:

def action(folder, filename):

Note: I changed the first parameter to folder because input is a reserved word in python.


Whereas in the IJ1 macro language you always rely on the current active image, in all scripting languages you should assign a variable whenever possible, so this becomes:

imp = IJ.openImage(folder + filename)

or, using Python’s os module, making it safer to join paths:

imp = IJ.openImage(os.path.join(folder,filename))

This imp variable can be used by all commands that change the image in the following.


For all these, you can use the macro recorder in JavaScript or BeanShell mode and just leave away the semicolons (;) at the end of each line. Note that you have quite some unnecessary commands in your macro, as some of them are duplicates or their effect gets overridden by a subsequent command. So after simplification, you get:

IJ.run(imp, "Smooth", "")
IJ.run(imp, "Sharpen", "")
IJ.setAutoThreshold(imp, "MaxEntropy")
Prefs.blackBackground = False # here I needed to change 'false' to 'False' in Python
IJ.run(imp, "Convert to Mask", "")
IJ.run(imp, "Analyze Particles...", "display summarize")

For looping through a list of files, you can again use the os python module:

for filename in os.listdir(folder):
    action(folder, filename)

or, if you just want the files and not the folders:

for root, folders, files in os.walk(folder):
        break  # we just want to get the current folder, no subfolders
for filename in files:
    action(folder, filename)

Taken together and after adding the necessary imports, this gives:

import os
from ij import IJ, Prefs

def action(folder, filename):
    imp = IJ.openImage(os.path.join(folder,filename))
    IJ.run(imp, "Smooth", "")
    IJ.run(imp, "Sharpen", "")
    IJ.setAutoThreshold(imp, "MaxEntropy")
    Prefs.blackBackground = False
    IJ.run(imp, "Convert to Mask", "")
    IJ.run(imp, "Analyze Particles...", "display summarize")

folder = "/Users/pdubois-macmini-ifrec/Desktop/FIJI_test/"
for filename in os.listdir(folder):
    action(folder, filename)
6 Likes