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

graph TD A["Previous code"] --> Loop{"Check condition"} Loop --> |Condition is valid| RepeatChunk("Code chunk to be repeated") RepeatChunk --> Loop Loop --> |Condition is not valid| NextChunk("Next code to run")

Figure


In a control flow statement a piece of code is repeated (loop) as long as a specific condition is valid.



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


Show activity for:

ImageJ Macro, loop structure

// Before the loop
print ("Starting the process");


// We use for loop to print the processing status of 10 images
for (i = 0; i < 10 ; i++) {
    // we are using string concatenation to make this message
    print ("Index: "+i);
}

// After processing
print("Process completed");


// Self referencing variable
counter = 1;
print("counter " + counter);
counter = counter + 1;
print("counter " + counter);
// is equivalent to
counter = 1;
print("counter " + counter);
counter++;
print("counter " + counter);

// You can also have a loop in a loop

for (j = 0; j < 10 ; j++) {

    for (i = 0; i < 10 ; i++) {
        // we are using string concatenation to make this message
        print ("Index big loop "+j + "; index small loop " + i);
    }
}

ImageJ Macro, example no loop

/*
 * Measure distance of all labels to the first label 
 * 
 * Requirements: 
 * - IJPB-plugins update site
 */
 
// This is what we would do when recording a macro

run("Close All");
open("https://github.com/NEUBIAS/training-resources/raw/master/image_data/xy_16bit_labels__nuclei.tif");
rename("labels");
run("Duplicate...", "title=binary");
run("Manual Threshold...", "min=1 max=1");
run("Convert to Mask");
run("Invert");
run("Chamfer Distance Map", "distances=[Chessknight (5,7,11)] output=[16 bits] normalize");
run("Intensity Measurements 2D/3D", "input=binary-dist labels=labels mean max min");
Table.rename("binary-dist-intensity-measurements", "dist_label"+labelID);

ImageJ Macro, example with loop

/*
 * Measure distance of all labels to the all labels
 * 
 * Requirements: 
 * - IJPB-plugins update site
 */
// Macro to measure closest, furthest and mean distance of labels to each other
// This is a version with a loop
run("Close All");
open("https://github.com/NEUBIAS/training-resources/raw/master/image_data/xy_16bit_labels__nuclei.tif");
rename("labels");
// Explain how to find maximal value of loop
getRawStatistics(nPixels, mean, min, max, std, histogram);

for (i = 0; i < max; i++) {
	run("Duplicate...", "title=binary");
	labelID = i+1;
	run("Manual Threshold...", "min="+labelID+ " max="+ labelID);
	run("Convert to Mask");
	run("Invert");
	run("Chamfer Distance Map", "distances=[Chessknight (5,7,11)] output=[16 bits] normalize");
	run("Intensity Measurements 2D/3D", "input=binary-dist labels=labels mean max min");
	close("binary");
	close("binary-dist");
	Table.rename("binary-dist-intensity-measurements", "dist_label"+labelID);
}

Exercises

Multiple erosion

Show exercise/solution for:

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.

  1. Create a variables maxErode that sets the number of erode operations
  2. Create a for loop to perform maxErode operations, change the name of the image accordingly
  3. (Advanced) Create a second for loop that uses maxErode as counter. Vary maxErode from 1 to 50

A solution can be found in script_for_loop_erodeband_withloop.ijm

Assessment


Follow-up material

Recommended follow-up modules:

Learn more: