ImageJ Macro Language Quick-notes. This is a very simplified version of the ImageJ macro language manual. It should be enough to get you started. For more information visit http://rsb.info.nih.gov/ij/developer/macro/macros.html. Creating or opening macros To open the macro editor go to Plugins/New or Plugins/Edit if you want to open an existing macro (in this case you can actually just drag and drop the macro in ImageJ). To run the macro, in the macro window press Macros/Run Macro. Comments You can add comments in the macro by using //, the text after will be ignored. Variables A variable can contain a number, a word or phrase (string) or a group of variables of the same type (array). In fact, the same variable can be any of these at different times. A variable can have any name as long as it is not started by a number or is not a word already used by the language like if (wish is a statement) or nimages (wish is a function). a = 1.23; //The variable a contains the number 1.23 b = "a string"; //The variable b contains the string a string An array is a special type of of variable that can contain multiple variables of the same type inside. Operators c = newarray("welcome", "to", "EMBO"); //In this case c[0] will contain the string Welcome, c[1] the string to and c[2] the string EMBO. //To create an array we must use a function called newarray(elements...), see the functions chapter. = assign a value to a variable + addition or string concatenation d = 1+1; //d contains the number 2. e = d+1; //e contains the sum of d plus 1, in this case 3. f = "Welcome " + "to " + "EMBO " + 2007; //Notice that when adding a string to a number, the number will be automatically converted into a string. - subtraction * multiplication / division ++ increment g=1; g++; //g contains the number 2. -- decrement h=1; h--; //h contains the number 0.
Comparative Operators (use this with the if, else, for, while statements) <, <= less than, less than or equal i=2; i<2; //this is false i<=2; //this is true >, >= greater than, greater than or equal ==,!= equal, not equal The if Statement The if statement conditionally executes other statements depending on the value of a boolean expression. It has the form: if (condition) { statement(s) Example: j = 3; if (j == 3) { j++; //if j is equal to 3 then add 1, j now has the value of 4. The for Statement for (initialization; condition; increment) { statement(s) Example: for (i=0; i<10; i++) { j = 10*i; print(j);
Functions Functions can execute actions and/or return information. n=nimages(); //the n variable will get the count of open images returned by the nimages() function selectimage(1); //this will select the first open image image1=gettitle(); //the image1 variable will get the title string of the currently selected image. Some of the commonly used functions close() Closes the active image. This function has the advantage of not closing the "Log" or "Results" window when you meant to close the active image. selectwindow("name") Activates the image window with the title "name". Also activates non-image windows. getdirectory(title) Returns the path to a specified directory. If title is "startup", returns the path to the directory that ImageJ was launched from (usually the ImageJ directory). If it is "plugins" or "macros", returns the path to the plugins or macros folder. If it is "image", returns the path to the directory that the active image was loaded from. If it is "home", returns the path to users home directory. If it is "temp", returns the path to the /tmp directory. Otherwise, displays a dialog (with title as the title), and returns the path to the directory selected by the user. Note that the path returned by getdirectory() ends with a file separator, either "\" (Windows) or "/". Returns an empty string if the specified directory is not found or aborts the macro if the user cancels the dialog box. For examples, see the GetDirectoryDemo and ListFilesRecursively macros. getfilelist(directory) Returns an array containing the names of the files in the specified directory path. The names of subdirectories have a "/" appended. getstring("prompt", "default") Displays a dialog box and returns the string entered by the user. The first argument is the prompting message and the second is the initial string value. Exits the macro if the user clicks on "Cancel" or enters an empty string. getnumber("prompt", defaultvalue) Displays a dialog box and returns the number entered by the user. The first argument is the prompting message and the second is the value initially displayed in the dialog. Exits the macro if the user clicks on "Cancel" in the dialog. Returns defaultvalue if the user enters an invalid number. getslicenumber() Returns the number of the currently displayed stack slice, an integer between 1 and nslices(). Returns 1 if the active image is not a stack. gettitle() Returns the title of the current image. isopen("title") Returns true if the window with the specified title is open. newarray(size) Returns a new array containing size elements. You can also create arrays by listing the elements, for example newarray(1,4,7) or newarray("a","b","c"). nimages
Returns number of open images. The parentheses "()" are optional. nslices Returns the number of slices in the current stack. Returns 1 if the current image is not a stack. The parentheses "()" are optional. open(path) Opens and displays a tiff, dicom, fits, pgm, jpeg, bmp, gif, lut, roi, or text file. Displays an error message and aborts the macro if the specified file is not in one of the supported formats, or if the file is not found. Displays a file open dialog box if path is an empty string or if there is no argument. Use the File>Open command with the command recorder running to generate calls to this function. print(string) Outputs a string to the "Log" window. Numeric arguments are automatically converted to strings. Starting with ImageJ v1.34b, print() accepts multiple arguments. For example, you can use print(x,y,width, height) instead of print(x+" "+y+" "+width+" "+height). If the first argument is a file handle returned by File.open(path), then the second is saved in the refered file. File.open(path) - Creates a new text file and returns a file variable that refers to it. To write to the file, pass the file variable to the print function. Displays a file save dialog box if path is an empty string. The file is closed when the macro exits. File.close(f) - Closes the specified file, which must have been opened using File.open(). rename(name) Changes the title of the active image to the string name. run("command"[, "options"]) Executes an ImageJ menu command. The optional second argument contains values that are automatically entered into dialog boxes (must be GenericDialog or OpenDialog). Use the Command Recorder (Plugins>Macros>Record) to generate run() function calls. Use string concatentation to pass a variable as an argument. For examples, see the ArgumentPassingDemo macro. save(path) Saves an image, lookup table, selection or text window to the specified file path. The path must end in ".tif", ".jpg", ".gif", ".zip", ".raw", ".avi", ".bmp", ".fits", ".png", ".pgm", ".lut", ".roi" or ".txt". saveas(format, path) Saves the active image, lookup table, selection, measurement results, selection XY coordinates or text window to the specified file path. The format argument must be "tiff", "jpeg", "gif", "zip", "raw", "avi", "bmp", "fits", "png", "pgm", "text image", "lut", "selection", "measurements", "xy Coordinates" or "text". Use saveas(format) to have a "Save As" dialog displayed. selectimage(id) Activates the image with the specified ID (a negative number). If id is greater than zero, activates the idth image listed in the Window menu. With ImageJ 1.33n and later, id can be an image title (a string). selectwindow("name") Activates the image window with the title "name". Also activates non-image windows in v1.30n or later. setslice(n) Displays the nth slice of the active stack. Does nothing if the active image is not a stack. showmessage("title", "message") Displays "message" in a dialog box using "title" as the the dialog box title.
From the macro recorder to a macro... Most of the macros that one needs to create typically represent a list of commands that need to be repeated several times. The Command Recorder is very useful to start up creating a macro. Using the Command Recorder to Generate Macros Simple macros can be generated using the command recorder (Plugins/Macros/Record). For example, the following macro, which measures and labels a selection, run("measure"); run("label"); is generated when you use the Analyze/Measure and Analyze/Label commands with the recorder running. When you have finished recording, press the "Create" button in the recorder and edit the macro. Save the macro in the plugins folder, or a subfolder, as "The_Macro_Name.txt", restart ImageJ and there will be a new "The Macro Name" command in the Plugins menu. Lets do an example... Here's an example where we start from a color image, separate the channels and automatically measure the nucleus area stained by DAPI. Note that we use an example image already existing in ImageJ. While you do this keep an eye in the command recorder to get a feeling of what is happening. Open a sample image (File/Open Samples/Fluorescent Cells). Start the command recorder (Plugins/Macros/Record). Split the color image into the 3 red, green, blue channels (Image/Color/RGB split) Select the "FluorescentCells.jpg (green)" channel and close it. Do the same for the "FluorescentCells.jpg (red)". Now go to (Analyse/Set Measuments...) and make sure you have the "Area" selected. Adjust the threshold (Image/Adjust/Threshold...) to make sure only the nucleus are selected, on the threshold window that will appear don't click on the apply button. Now run the Analyse Particles function (Analyse/Analyse Particles...), make sure the "Size (pixel^2)" has the value '0-Infinity', the "Circularity" has the value '0.00-1.00', "Show" is set to 'Outlines' and make sure the "Display Results" setting is active, press OK. Now the command recorder should have the text: run("rgb Split"); run("set Measurements...", "area redirect=none decimal=3"); setautothreshold(); //run("threshold..."); run("analyze Particles...", "size=0-infinity circularity=0.00-1.00 show=outlines display"); Lets play around with the code, first press "Create" command recorder and start editing the text in new window. But before close every open window except the ImageJ main window and the new macro window (just to make things a bit less confusing).
Lets edit the text... You don't actually need to write the comments (what is after the // in each line). title = gettitle(); //Lets store the image title in the title variable to later use it. run("rgb Split"); selectimage(title+" (red)"); //This is to make sure we have the right image selected before closing it //since title contains the string 'Fluorescent Cells.jpg', doing title+" (red)" will result in the string //'Fluorescent Cells.jpg (red)'. selectimage(title+" (green)"); selectimage(title+" (blue)"); //To make sure we are going to analyze the wright image. setautothreshold(); //Notice that the program tries to automatically set a threshold. //run("threshold..."); //You can safely delete this line since it's commented, if uncommented it would make the "Threshold" //dialog appear. run("analyze Particles...", "size=0-infinity circularity=0.00-1.00 show=outlines display"); Try it out, open the image again, go to the macro window, in that window do "Run Macro" (Macros/Run Macro). Excellent, you have your first macro... What next? Check out the ImageJ macro manual at http://rsb.info.nih.gov/ij/developer/macro/macros.html, it's quite more extensive and still easy to understand, also start looking at other macros code to see how they work. In the end you'll realize that most repetitive task in ImageJ can be improved with the help of a macro and it will make you speed up (a lot!!) your image analysis. By Ricardo Henriques <ricardohenriquespt@gmail.com> May 31st, 2007.