Loops
Learning Objectives
After completing this lesson, learners should be able to:
Use for loops to repeat operations multiple times
Running a script for multiple files
Motivation
In an imaging processing workflow you often apply the same operation to several images, several labels, etc. In order to avoid repeating the same code many times we can use control flow statements such as a for
loop. Loops together with if
clauses represent extremely useful tools when programming.
Concept map
Figure
For loop
A for
loop occurs by iterating over a loop variable defined in a loop header. You use for
loops when you know the number of iterations to execute.
While loop
While loop does not have a fixed number of iterations. Typically the header contains a condition that is computed within the body of the loop. TODO.
Activities
- Open a script editor.
- Open and run a script that contains several repeated operations and explain that you would like to write this part of code in a more simple way.
- Explain the different elements of a numeric
for
loop:- The loop header, the loop counter/variable, and body
- The initial and end condition
- How the counter is iterated (e.g.
i++
).
- Using a print command show how the iterator changes
- Take the starting script and modify it using a
for
loop
Show activity for:
ImageJ Macro, loop structure
ImageJ Macro, example no loop
ImageJ Macro, example with loop
Python, for loop
Python, advanced for loop
Exercises
Multiple erosion
- Open the binary image xy_8bit_binary__nuclei.tif
- Create a macro (or use a pre-defined one) to erode and find boundary of the binary objects
- Modify the macro so that you can perform an arbitrary number of erosions and find their boundary
ImageJ Macro, Multiple erosion
Download the script script_for_loop_erodeband_noloop.ijm. The goal is to perform a series of binary-erosions and compute the outline of these objects.
- Create a variables
maxErode
that sets the number of erode operations- Create a
for
loop to performmaxErode
operations, change the name of the image accordingly- (Advanced) Create a second
for
loop that usesmaxErode
as counter. VarymaxErode
from 1 to 50A solution can be found in script_for_loop_erodeband_withloop.ijm
Assessment
Follow-up material
Recommended follow-up modules:
Learn more: