Professional Documents
Culture Documents
session 12
run("Duplicate...", "title=newimage.tif");
ml@life.ku.dk
Part I
Macro basics
ImageJ Macros
Text output
Generalizing macros
open("myimage.tif");
imageCalculator("Add create", "myimage1.tif", "myimage2.tif");
selectWindow("myimage.tif");
close();
Verify that you have the correct lines by running the macro!
Add comment lines stating which exercise this is (and
other comments as needed).
// Exercise 2-15
// part (a)
run("Duplicate...", "title=newimage.tif"); // run on duplicate image
run("Duplicate...", "title=newimage.tif");
run("Smooth");
run("Convolve...", "text1=[0 0 0 1 0 0 0 0 0] normalize");
run("Add...", "value=25");
selectWindow("myimage.tif");
or with:
selectImage("myimage.tif");
selectWindow is recordable and works even for
non-image windows.
mode).
You can obtain the image title of the current image with the
call getTitle().
Image analysis 2010 Session 12 Slide 8/87
Image IDs work not only with selectImage but also with
other functions normally taking image titles as arguments,
e.g. imageCalculator.
It is always safer to use the image ID than other forms of
identification, because:
Using getImageID()
getImageID().
Invoking macros
Persistent variables
runMacro("filename","arguments");
(full path or relative to the ImageJ macros folder).
Macro sets
In this case there must be only two arguments and the first
must be the window name in square brackets.
The \n means new line (not automatically added when
not printing to log).
To open a new text window with a specific name:
run("New... ", "name=[MyWindow.txt] type=Text");
run("Duplicate...", "title=background");
run("Maximum...", "radius=15");
run("Minimum...", "radius=15");
run("Gaussian Blur...", "sigma=15");
run("Subtract...", "value=207");
imageCalculator("Subtract",
"Cell_Colony.tif", "background");
selectWindow("background");
close();
To generalize macro: Parameterize, i.e. replace constants
with variables.
Histogram of
Cell_Colony.tif
background
background
run("Duplicate...", "title=background");
run("Maximum...", "radius=15");
run("Minimum...", "radius=15");
run("Gaussian Blur...", "sigma=15");
run("Histogram");
close();
run("Subtract...", "value=207");
imageCalculator("Subtract", "Cell_Colony.tif", "background");
selectWindow("background");
close();
Image analysis 2010 Session 12 Slide 18/87
im = getImageID();
run("Duplicate...", "title=background");
bgim = getImageID();
run("Maximum...", "radius=15");
run("Minimum...", "radius=15");
run("Gaussian Blur...", "sigma=15");
run("Subtract...", "value=207");
imageCalculator("Subtract", im, bgim);
selectImage(bgim);
close();
selectImage(im);
We know how to make a macro robust with image IDs...
But some constants remain, embedded in strings.
Image analysis 2010 Session 12 Slide 20/87
String concatenation
rad = 15;
..
.
run("Maximum...", "radius="+rad);
run("Minimum...", "radius="+rad);
run("Gaussian Blur...", "sigma="+rad);
Part II
Strings
Arrays
Macro variables
x = 7;
x = "a string";
x = newArray(7, 9, 13);
Example: y = x<<4;
The single equals sign = assigns a value to a variable.
The example also shows the three types of values in the
macro language: numbers (floating point), strings and
arrays.
Image analysis 2010 Session 12 Slide 26/87
f = parseFloat(s);
or simply:
f = 0+s;
Extracting substrings:
indexOf(haystack, needle)
startsWith(haystack, needle)
endsWith(haystack, needle)
lengthOf(string)
replace(string, pattern, substitution)
Strings
Arrays
Square brackets are used around the index, e.g. x[3] for
element number 3 of the array x.
Array operations
x = newArray(7, 9, 13);
y = newArray("some", "string", "values");
z = newArray(10); // array of length 10 containing all zeros
print(x[1]);
// prints 9
print(y[2]);
// prints "values"
print(z[8]);
// prints 0
x[1] = 17;
print(x[1]);
// now prints 17
print(x.length); // prints 3 (number of elements in x)
x[1] = "a";
// converts x to an array of strings...
Part III
Control structures
10
for loops
while and do...while loops
11
Example if . . . else
==
!=
<
>
<=
>=
equal to
not equal to
less than
greater than
less than or equal to
greater than or equal to
Example: if (x != 0) ...
Logical operators: ! (not), && (and), || (or).
Conditional execution: if
if ( condition )
statement 1
else
if ( condition )
statement 2
statement
Example if
if( bitDepth() != 32 ) {
convert = getBoolean("Do you wish to convert to 32 bit?");
if(convert) run("32-bit");
}
The loop above executes its body 100 times, with i=1, 2,
. . . , 100.
for loops
body
body
Example: Repeating an operation a number of times.
iter = getNumber("Iterations", 1);
for(i=1; i<=iter; i++)
run("Median...", "radius=1.5");
The loop above runs the radius 1.5 median filter iter
times.
Note: i++ is shorthand for i=i+1, i.e. increment i.
Image analysis 2010 Session 12 Slide 42/87
Loops: while
A while loops while a specified condition is true:
while ( condition )
body
Example while
while ( condition )
body
while (nImages()>0) {
selectImage(nImages());
close();
}
After the loop, modei contains the number of the bin with
the highest count, i.e. the most common pixel value.
Image analysis 2010 Session 12 Slide 46/87
Part IV
Loops: do . . . while
A do . . . while execues the loop body at least once:
do
body
while ( condition );
12
Pixels
13
14
15
16
Batch Mode
Example do . . . while
do
body
while ( condition );
getHistogram(0, hist, 256);
run("Options...", "iterations=1 count=5");
do {
numzero = hist[0];
run("Erode");
getHistogram(0, hist, 256);
} while( numzero != hist[0] );
cx = getWidth()/2;
cy = getHeight()/2;
for (x=cx-2; x<=cx+2; x++)
for (y=cy-2; y<=cy+2; y++) {
v = getPixel(x, y);
setPixel(x, y, 255-v);
}
Note: Extensive pixel manipulation (e.g. filtering) is much
more efficient with a plug-in.
h = getHeight();
w = getWidth();
for (x=0; x<w; x++)
for (y=0; y<h; y++) {
v = getPixel(x, y);
r = v>>16;
g = (v>>8)&255;
b = v&255;
g = g*2;
if (g>255) g = 255;
setPixel(x, y, (r<<16)+(g<<8)+b);
}
1243791
000100101111101010001111
18
250
143
nResults()
getResult(colLabel,row)
setResult(colLabel,row,value)
updateResults()
print("[Results]", text)
v
r
g
b
=
=
=
=
getPixel(x, y);
v>>16;
(v>>8)&255;
v&255;
String.copyResults()
run("Clear Results")
(Recall: & is binary AND, << and >> shift bit patterns.)
Image analysis 2010 Session 12 Slide 54/87
Selections (I)
b 2
Selections (I)
getSelectionBounds(x,y,w,h)
getSelectionCoordinates(x,y)
makeOval(x,y,w,h)
makePolygon(x1,y1,x2,y2,...)
makeLine(x1,y1,x2,y2)
makePoint(x,y,x,y)
makeSelection(type,x,y)
run("Select All")
run("Select None")
setForegroundColor(r,g,b)
run("Draw")
run("Fill")
cmd
"Draw"
"Fill"
"Count"
"Index"
Meaning
Draws the ROIs which are currently selected
in the ROI manager. Draws all ROIs if none
are selected.
Fills the ROIs which are currently selected in
the ROI manager. Fills all ROIs if none are
selected.
roiManager("Count") returns the number of
ROIs in the ROI manager.
roiManager("Index") returns the index number
of the currently selected ROI in the manager;
-1 if none or more than one.
cmd
"Add"
"Add & Draw"
"Delete"
"Reset"
"Select"
"Deselect"
Meaning
Adds current selection as new ROI.
Add current selection and draw its outline.
Deletes the currently selected ROIs from the
manager.
Remove all selections from the manager.
roiManager("Select",i) marks ROI number i
as selected (first ROI is number 0).
Makes no ROIs selected in the manager.
setBatchMode(true);
Batch mode can be exited with:
setBatchMode(false);
To exit batch mode and display created images in new
windows:
Part V
Batch mode
Macros may run in batch mode, which may be (much)
faster than normal mode.
User dialogs
17
18
Special dialogs
Dialog.create("Translate Right");
Dialog.addNumber("X translation", 1, 0, 3, "pixels");
Dialog.addCheckbox("New image",false);
Dialog.show();
xoff=Dialog.getNumber();
asNew=Dialog.getCheckbox();
Display the dialog and have the user interact with it:
Dialog.create("Translate Right");
Dialog.addNumber("X translation", 1, 0, 3, "pixels");
Dialog.addCheckbox("New image",false);
Dialog.show();
xoff=Dialog.getNumber();
asNew=Dialog.getCheckbox();
Dialog.create("Translate Right");
Dialog.addNumber("X translation", 1, 0, 3, "pixels");
Dialog.addCheckbox("New image",false);
Dialog.show();
xoff=Dialog.getNumber();
asNew=Dialog.getCheckbox();
Dialog.create("Translate Right");
Dialog.addNumber("X translation", 1, 0, 3, "pixels");
Dialog.addCheckbox("New image",false);
Dialog.show();
xoff=Dialog.getNumber();
asNew=Dialog.getCheckbox();
Dialog.addString(label, default)
Dialog.getString()
Dialog.addNumber(label, default)
Dialog.addNumber(label, default,
decimalPlaces, columns, units)
Dialog.getNumber()
Dialog.addCheckbox(label, default)
Dialog.getCheckbox()
Dialog.addChoice(label, items)
Dialog.addChoice(label, items,
default)
Dialog.getChoice()
// Possible directions:
dirs = newArray("left","right","up","down");
Dialog.create("Translate Right");
Dialog.addNumber("X translation", 1, 0, 3, "pixels");
Dialog.addCheckbox("New image",false);
Dialog.show();
xoff=Dialog.getNumber();
asNew=Dialog.getCheckbox();
if (asNew) run("Duplicate...", "title=Translated");
for (i=1 ; i<=xoff ; i=i+1)
run("Convolve...", "text1=[1 0 0\n]");
Specialized dialogs
showMessage(message)
showMessageWithCancel(message)
showStatus(message)
x = getNumber(prompt, default)
s = getString(prompt, default)
b = getBoolean(prompt)
path = File.openDialog(title)
dir = getDirectory(title)
Part VI
Return value
A function may return a value:
function setY(x) { y = x; }
y = 1;
setY(2);
print(y); // Will print 1
function setVals(x, a) {
x = 7;
a[0] = 9;
}
y = 13;
b = newArray(1, 2, 3);
setVals(y, b);
print(y, b[0]); // Will print 13 9
function setY(x) { y = x; }
var y = 1;
setY(2);
print(y); // Will print 2
Image analysis 2010 Session 12 Slide 85/87