Vous êtes sur la page 1sur 30

3D/4Dimage reconstruction

using ImageJ /Fiji


/ Fiji

http://rsb.info.nih.gov/ij

WayneRasband

OpenSource
Open
Source
Runseverywhere(Windows,Mac,Linux,32,64bit)
Verysupportiveusercommunity
Manyplugins available
Possibilitytocreatenewfunctionalitywithmacros/plugins

115

Fiji IsJustImageJ
http://fiji.sc/wiki/index.php/Main_Page
DistributionofImageJ,
focusedonmicroscopy
Bundlesmicroscopyplugins
Regularautomatedupdates
Coherentmenustruture
Coherent menu struture

116

Mainwindow
Menubar
Toolbar
Statusbar

ImageJ Website(http://rsb.info.nih.gov/ij/)

Brightness/Contrast

117

Stitching Images

S.Preibisch,S.Saalfeld,P.Tomancak (2009)
Bioinformatics, 25(11):14631465.
http://fiji.sc/wiki/index.php/Stitching_2D/3D

e.g.chooseunknown
configurationandthe
plugin takesallimages
thatarelocatedina
givendirectoryand
triestoalignthem
withoutanyknowledge
ofthetile
configuration.

Stitching Images

MosaicJ

Thepurposeofthisplugin istofacilitatetheassemblyofamosaicofoverlappingindividualimages,or
tiles.Itprovidesasemiautomatedsolutionwheretheinitialroughpositioningofthetilesmustbe
performedbytheuser,andwherethefinaldelicateadjustmentsareperformedbytheplugin.

118

Pastecontrol

Very useful to overlay


RGB images manually.
RGBimages

GFP

Overlay manually,you can move


the overlaid channel easily with
mouse or arrow keys.

dsRed

Processing3D/4D
data sets
Image5D
Adataformatandacollection
ofplugins tohandleuptofive
dimensionaldata(timeseries
of3Dmultichanneldata).

119

Processing3D/4D
data sets

Hyperstacks haveSlices(zdimension),Time
f
frames(tdimension),Channels(cdimension),
(t di
i ) Ch
l ( di
i )
WidthandHeight.UsetheChannelsToolto
navigatebetweenchannels.
Convenientwaytohandle4Dimagedata.

Correcting xy drifts

http://bigwww.epfl.ch/thevenaz/stackreg/

120

Correcting xy drifts

Timeseries before alignment

Afteralignment

Labelstacks /movies

Use color picker


from toolbar to
choose
foreground color

121

3Dviewer

http://3dviewer neurofly de/


http://3dviewer.neurofly.de/
SchmidB,SchindelinJ,CardonaA,Longair M,
HeisenbergM. BMCBioinformatics 2010,11:274.
Thisplugin offershardwareaccelerated
visualizationpossibilitiesforimagestacks.
Stackscanbedisplayedastexturebased
volume renderings surfaces or orthoslices
volumerenderings,surfacesororthoslices.

3Dviewer

122

Workshop manual
FIJI / ImageJ Macro Scripting

NCMLS, Cellbiology
Louis Wolf, oktober 2011

123

Introduction..................................................................................................................................... 3

Programming basics ........................................................................................................................ 3

2.1

Variables and typing ................................................................................................................ 3

2.2

Conditional statements; IF, ELSE ............................................................................................. 4

2.3

Loops ....................................................................................................................................... 5

2.4

Arrays....................................................................................................................................... 6

2.5

Scope ....................................................................................................................................... 8

2.6

Commenting ............................................................................................................................ 9

2.7

Coding style ........................................................................................................................... 10

FIJI .................................................................................................................................................. 10
3.1

FIJI Updates ........................................................................................................................... 10

3.2

Macro development environment ........................................................................................ 11

3.3

Your first macro ..................................................................................................................... 11

3.4

Installing macros................................................................................................................... 11

3.5

The Macro Recorder .............................................................................................................. 12

3.6

Debugging.............................................................................................................................. 12

3.7

The Macro Language ............................................................................................................. 13

3.7.1

Run................................................................................................................................. 13

3.7.2

User Interface ................................................................................................................ 13

3.7.3

File handling .................................................................................................................. 14

3.7.4

Saving results ................................................................................................................. 17

Macro Language Reference ........................................................................................................... 17

124

1 Introduction
There are several reasons to start using FIJI macros:
- Save time on boring stuff
- Reduce errors
- Easily share protocols
FIJI has two concepts for automation: macros and plugins. Basically, macros
utilize existing functionality in an automated fashion. Compared with macros,
plugins are a low-level approach to an imaging problem. Plugins often add new
functionality. To create a plugin youll require some programming knowledge.
Many of the concepts explained here apply to programming in general. The
way the concepts are implemented throughout various programming
languages may differ (the syntax differs). In this manual well stick to the FIJI
macro language.
The underlying programming concepts are discussed in chapter 2. If youd like
to dive into writing macros directly, have a look at paragraphs 3.3, 3.4 and 3.7.
Refer back to chapter 2 for explanation of the programming concepts used.

2 Programming basics
2.1 Variables and typing
Variables are a fundamental concept in programming; a variable is a named
entity which has a value assigned to it. An example:
hello = "Hello";
name = "Dr. Strangelove";

Programming languages such as JAVA and C++ differentiate between types of


variables such as integers (numbers) and Strings (text). The macro language is
untyped, so Strings and integers are regarded as the same thing. This enables
you, for instance, to add (concatenate) Strings and integers. It is good however,
to keep the difference in mind.
You can do stuff with variables, such as subtractions etc.
An example in FIJI:

125

message = hello + name;


print(message);

// Prints Hello Dr. Strangelove

2.2 Conditional statements; IF, ELSE


FIJI:
if (message == "Dr. Strangelove") {
print(message);
} else {
message = hello + name;
}

In the example message == Hello Dr. Strangelove is the condition, which


should always evaluate to a boolean (TRUE or FALSE). In the condition == is the
operator. There are more operators, for instance:
==
!=
<
>
<=
>=

Is equal to
Is not equal to
Is smaller than
Is greater than
Is equal or smaller than
Is equal or greater than

126

2.3 Loops
A way to do repetitive tasks without repeating code is to use loops. Below you
see an example of a for-loop:
for (i = 0; i < 10; i++) {
print(message);
}

Theres a lot going on here. The for loop consists of four parts:
1)
2)
3)
4)

The initializer
The condition
The incrementer
The code block

[i=0]
[ i < 10 ]
[ i++ ]
[ print(variable); ]

The following things happen when the code is executed:


- The condition is checked (is i below 10?)
- The code block is executed (the message is printed)
- The incrementor is executed (i++, which is the same as i = i + 1, so 0 + 1 )
- The whole process starts over until the condition is met, which will be
the case after 10 iterations.
Notice we start counting at 0. This is a common practice in programming; the
first item is always 0.
So in effect, the result of the loop will be:
Hello Dr. Strangelove
Hello Dr. Strangelove
Hello Dr. Strangelove
Hello Dr. Strangelove
Hello Dr. Strangelove
Hello Dr. Strangelove
Hello Dr. Strangelove
Hello Dr. Strangelove
Hello Dr. Strangelove
Hello Dr. Strangelove
A different type of loop is the WHILE loop. It does the same thing as a for loop,
but it is a bit less abstract. On the other hand, it takes a few more lines of code:

127

i = 0;
while (i < 10) {
print(message);
i++;
}

2.4 Arrays
Arrays act as a container for several variables. In FIJI you can declare an array
with:
listOfNames = newArray( "Dr. Strangelove",
"Muffley",
"Ripper",
"Turgidson",
"Major Kong" );

In combination with loops, arrays provide a powerful way to do a lot of work in


only a few lines of code:
for (i=0; i<listOfNames.length; i++) {
print("Hello " + listOfNames[i];
}

Functions
Functions (or Methods) are reusable sections of code. This concept is very
useful because it enables you to re-use your code. For readability, functions
should be small and they should be used often!
An example:
function welcome(name) {
return Hello + name;
}

In the above examples name is passed as a parameter to the function and is


used within the function. The function and this isnt always necessary
returns a new String as a variable. These examples dont do anything yet, they
have to be called to do something:
message = welcome(name);
print(message);

// Prints Hello Dr. Strangelove

128

What happens is that the function welcome is executed en returns whatever is


in name with the text Hello prepended. The returned String is assigned to
message, which is then printed.

129

2.5 Scope
This section is a bit technical, but please try to read on. The section ends in
some guidelines to keep your code readable.
In languages such as JAVA, the declaration of IF, ELSE, FOR and functions
(basically anything that lets you define code between curly brackets), also
defines a scope. Variables defined within a certain scope (curly brackets) are
not available outside that scope. For instance in JAVA:
if (variable == "Hello Dr. Strangelove") {
String myQuestion = "How did you learn to stop worrying?";
}
System.out.println(myQuestion);

This code will result in an error.


The variable myQuestion was defined within the scope of the if statement
and can therefore not be accessed outside this statement.
In the macro language this works differently, and counter intuitively if you have
some coding experience:
if (message == "Hello Dr. Strangelove") {
myquestion = "How did you learn to stop worrying?";
}
print(myquestion);

This will work, and even this:


if (message == "Hello Dr. Strangelove") {
myquestion = "How did you learn to stop worrying?";
}
askQuestion();

// How did you learn to stop worrying?

function askQuestion() {
print(myquestion);
}

The above will work, but it looks extremely weird: in the example, the variable
question is defined within the if statement, and is never passed to the
function askQuestion, which is called outside the if statement. Yet, the
function has no problem whatsoever to print the requested variable. Code like
this can be very daunting to debug! Nevertheless, there are many situations in

130

which you do want your variables to be available globally. There might even be
situations in which youll want to define global variables that never change, and
global variables that you do want to change. Use to following guidelines to
make your own life and that of the people trying to read your code easier:
Define global variables that should not change in capitals
Use underscores in global variables that might change
Use camel casing for all other variables
Try to pass all other variables as parameters to functions, so you know
where they came from.
Notice that it doesnt matter where you define and call your functions. Good
practice however is to put your functions at the end of your macro.
The above example, slightly adjusted, might then look like:
WELCOME_MESSAGE = "Hello Dr. Strangelove"
my_question = "How did you become to love the bomb?";
if (variable == WELCOME_MESSAGE) {
my_question = "How did you learn to stop worrying?";
}
askQuestion(my_question);
function askQuestion(myQuestion) {
print(myQuestion);
}

2.6 Commenting
Sometimes you want a reminder or some kind of explanation in your code that
shouldnt be visible to the user. This can be done per line:
// This is a commented line

Or in multiline statements:
/*
This is a multiline
comment block
*/

131

2.7 Coding style


Try and adhere to the following guidelines. They will make your code more
readable, easier to debug and easier to expand and re-use:

Dont repeat yourself


Use indenting for conditional statements, loops and functions
Use function and variable names that clarify your intention
Define your constants at the start of your macro
Use small functions; functions over 10 lines are often too big
Dont use more than 2 parameters
Dont use booleans (i.e. TRUE, FALSE variables) as a parameter

3 FIJI
3.1 FIJI Updates
Between FIJI versions and operating systems (XP, Windows 7, Linux) execution
of macros show slight differences. This can make debugging difficult between
different FIJI installations. Updating FIJI regularly is the only way to limit the
chance of an old version of FIJI causing a bug. FIJI can be configured to update
at startup:
Edit > Options > Configure FIJI Updater > Check at Startup
Updating can be done manually as well:
Help > Update FIJI
For the same reason, your macro (actually this is true for all software) will be
subject to degradation; youll have to update your code once in a while.

132

3.2 Macro development environment


It is possible to develop FIJI macros in a text editor such as notepad or
notepad++, but FIJI itself also offers a limited development environment:
Plugins > New > Macro
Hint: Save your macro under a different name, immediately after youve started creating a
new script. This way youll never overwrite your macro with macro.ijm.

The FIJI development environment gives you some advantages over a regular
text editor such as syntax highlighting.

3.3 Your first macro


In your editor type:
macro "Hello" {
print("Hello Dr. Strangelove");
}

Thats it. Now run the macro by pressing CTRL + R

3.4 Installing macros


Install your macro by doing the following in your Macro editor:
File > Export as .jar
Save the file to any location you like. Now, in FIJI, go to:
Plugins > Install Plugin > Select your .jar file > Ok
Your macro should now be installed.
Alternatively, you can copy the exported JAR directly to the FIJI or ImageJ
plugins folder (i.e. Fiji.app\plugins or ImageJ\plugins). Restart FIJI/ImageJ to
activate the macro.

133

3.5 The Macro Recorder


Development of macros is greatly simplified with the help of the macro
recorder:
Plugins > Macros > Record
If you open the recorder and then, for instance, open an image file with FIJI
youll see that your action is displayed as macro language in the recorder. This
is true for almost any action in FIJI and you can use the commands from the
recorder in your scripts.

3.6 Debugging
FIJI doesnt offer much debugging tools. During this workshop were going to
stick to FIJI, but ImageJ does have a debugger. However, the ImageJ editor
doesnt have syntax highlighting. If youd like to look into the ImageJ debugger,
see the following page:
http://imagej.nih.gov/ij/developer/macro/macros.html#debugger
The only tool you have available in FIJI is the print() function. Basically this is
what debugging is; finding out whats going on at a certain point in your code.
The way to get there is to print the values of your variables.
Once you start writing larger macros, it might be wise to put a debug switch in
your code:
macro "Hello" {
isDebug = false;
limit = 10;
if (isDebug) {
limit = 1;
}

for (i=0; i<limit; i++) {


if (isDebug) {
print(i);
}
print("Hello Dr. Strangelove");
}

134

In the above example, the debug switch is turned off (isDebug = false). When
you change its value to true, the code limits executions of your for loop to 1
iteration and at the same time it prints the value of i to your log window.

3.7 The Macro Language


3.7.1 Run
As you have seen, you can record your FIJI actions with the macro recorder. In
general all plugins can be called using the run() function:
run("Make Binary");

In itself you could have gotten this from the recorder, but in most cases youll
want to include variables in the run statement. For instance, say youd want to
get some measurements out of your image:
run( "Set Measurements...",
"area median redirect=None decimal=3");
run("Measure");

Now say you want to be able to change the decimal value in the above
statement, for instance because in the end you want the user to provide this
value. Then the above statement would change to something like:
valueDecimal = 3;
run( "Set Measurements...",
"area median redirect=None decimal=" + valueDecimal);
run("Measure");

Make sure you notice that the variable valueDecimal is outside the quotes.
Would it be inside the quotes, then valueDecimal would be interpreted as
the actual String valueDecimal and not as the value 3.
3.7.2 User Interface
In the previous section, it was mentioned that the user might provide a certain
value. For this we need to create a user interface:
Dialog.create("Please enter a decimal value");
Dialog.addNumber("Decimal", 3);
Dialog.show();

135

The above will create you a user interface, but you still dont have a way to get
at the number that was provided by the user:
Dialog.getNumber();

Which, in a complete code example looks like:


Dialog.create("Please enter a decimal value");
Dialog.addNumber("Decimal", 3);
Dialog.show();
valueDecimal = Dialog.getNumber();
run( "Set Measurements...",
"area median redirect=None decimal=" + valueDecimal);
run("Measure");

When you add more items to your interface, the order of declaration should
also be the order in which you retrieve your input (fifo; first in, first out):
Dialog.create("Please enter a decimal value");
Dialog.addNumber(Some number, 0);
Dialog.addNumber("Decimal", 3);
Dialog.show();
valueDecimal = Dialog.getNumber();
run( "Set Measurements...",
"area median redirect=None decimal=" + valueDecimal);
run("Measure");

In the above example, the variable valueDecimal will be 0 if the user did not
change the default value in the interface.
3.7.3 File handling
In most cases you wont be hard-coding directory names, but instead youll ask
the user to provide the location of the files you want to process:
sourcePath = getDirectory("Choose a Directory");

The above code opens a file dialog in which the user can choose the path to the
files of interest. When the user confirms his/her choice, the function returns a
String containing the entire directory path. Its possible to list the files and
directories within the chosen directory:

136

fileList = getFileList(sourcePath);

The getFileList() function returns an array of filenames. Directory names will


have a / appended, which enables you to separate files from directories:
for (i=0; i<fileList.length; i++) {
if (endsWith(fileList[i], "/")) {
print(fileList[i] + " is a directory");
} else {
Print(fileList[i] + " is a file");
}
}

In the same fashion its possible to identify files with a certain extension, say
tiff files:
count = 0;
for (i=0; i<fileList.length; i++) {
if (endsWith(fileList[i], ".tif")) {
count++;
}
}
print("Directory contains " + count + " tiff files");

Before we start opening and editing files, well need to know how to create a
new directory so we dont have to overwrite our original files.
Remember; directories are returned with an appending /, so if we want a
directory name, based on the source path, we need to remove that appending
slash:
firstCharacter = 0;
finalCharacter = lengthOf(sourcePath) 1;
cleanSourcePath = substring(sourcePath, firstCharacter,
finalCharacter);

In the above example, we take the substring of the sourcePath from the first
charcter (0) until the last charter minus 1 (the slash):
lengthOf(sourcePath) 1

When we put it all together we can create a new direcory based on our source
directory name:
sourcePath = getDirectory("Choose a Directory");

137

firstCharacter = 0;
finalCharacter = lengthOf(sourcePath) 1;
cleanSourcePath = substring(sourcePath, firstCharacter,
finalCharacter);
goalPath = cleanSourcePath + "_processed";
File.makeDirectory(goalPath);

If youre unsure of what is going on here, try printing (debugging) the variables
sourcePath, cleanSourcePath and goalPath.
Opening files is straightforward now we know how to get the filenames:
fileName = fileList[i];
File.open(sourcePath + fileName);

And saving images:


saveAs("tiff", goalPath + "\\" + fileName);

Now, say we want to have copies of our tiff images, but we want to convert
them from 16-bit images to 8-bit images. For this we need to:
1)
2)
3)
4)
5)
6)

ask for a source path


create a goal path
open each tiff file from the source path
convert the tiff images to 8-bit images
save the resulting files
close the files

138

sourcePath = getDirectory("Choose a Directory");


firstChar = 0;
finalChar = lengthOf(sourcePath) 1;
cleanSourcePath = substring(sourcePath, firstChar, finalChar);
goalPath = cleanSourcePath + "_processed";
File.makeDirectory(goalPath);

//
//
//
//
//
//

1
2
2
2
2
2

fileList = getFileList(sourcePath);

// 3

for(i=0; i<fileList.length; i++) {


if (endsWith(fileList[i], ".tif")) {
fileName = fileList[i];
File.open(sourcePath + fileName);
run("8-bit");
saveAs("tiff", goalPath + "\\" + fileName);
close();
}

// 3
//
//
//
//
//

3.7.4 Saving results


Some actions in FIJI generate a text window. These values of this window can
be saved to a text file:
selectWindow("Results");
saveAs("Results", goalPath + "\\" + "my_results.xls");

The various text windows require various ways of saving the file. Just use the
macro recorder to find out how you should save your results.
Notice that in the above example; the results are saved as an Excel file. This is
not what is actually happening; the resulting file is a regular text file with an
Excel extension. Excel will therefore complain when you try to open this file,
but will be able to open it nevertheless.

4 Macro Language Reference


http://imagej.nih.gov/ij/developer/macro/functions.html

139

3
3
4
5
6

Workshop manual
Image segmentation and quantification

Cindy Dieteren

140

Protocol image segmentation pipeline: Analysis of GFP and PI staining (Using Fiji)
1)
2)

Open the BG and FF corrected GFP and PI image in Fiji


Go to Process Image calculator (See Fig. 1 for example)
Image 1: GFP image
Operation: Add
Image 2: PI image
OK

Figure 1: Example of Image calculator window Fiji

3)

Go to Image Adjust Threshold set 0 / 160 OKApply (see Fig.2 for example). Close Threshold
window.

Figure 2: Example of
thresholded image

141

4)

Go to Process Binary Convert to mask. See Fig. 3 for example result

Figure 3: Example of mask

5)

Go to Process Filters Median 3.0 pixels. See Fig. 4 for example result

Figure 4: Example of median filtered mask

6)

Go to Process Binary Watershed

7)

Go to Analyze set measurements select area and integrated density OK

8)

Go to Analyze Analyze particles select Add to manager and Exclude on Edges (see Fig. 5) OK

Figure 5: Example of Analyze


particles window

142

9)

The Rois appear into the mask (see Fig. 6)

Figure 6: Example of ROIS in mask

6)

10)

Open BG and FF corrected GFP image again

11)

Click on window ROI manager

12)

Deselect show all and select again. Then ROIS should appear on top of the BG and FF corrected image
(See Fig. 7)

Figure 7: Example of ROIS in original BG


and FF corrected GFP image

13)
14)
15)
16)
17)
18)
19)

Select ROI manager window Measure


Save results, go to File save as
Close results window
close BG and FF corrected GFP image
Open BG and FF PI image
Click on window ROI manager
Deselect show all and select again. Then ROIS should appear on top of the BG and FF PI corrected
image (See Fig. 8)

143

Figure 8: Example of ROIS in original BG


and FF corrected PI image

20)
21)
22)
23)

Select ROI manager window Measure


Save results, go to File save as
Close all windows
Repeat the same procedure with other GFP/PI image pairs

144

Vous aimerez peut-être aussi