## Prerequisites

Before starting this lesson, you should be familiar with:

## Learning Objectives

After completing this lesson, learners should be able to:
• Avoid code duplication using functions.

• Understand the skeleton of a function.

• Make the script more efficient.

## Motivation

When a series of steps(i.e. algorithm) that has to be performed on an image or a set of images should be executed more than once, or when the script gets too long and repetitive, it is more efficient to write this series as modules called “functions”. This essentially means that you can reuse parts of code instead of rewriting it. A function is a block that has a specific name and can be called with inputs and can return values.

## Concept map

graph TD IV("Input values") --> F("Function") F -->|generates| OV("Output values") F -->|contains| RC("Reusable code")

## Activities

• Open an image stack
• Enter the slice numbers for which you want to calculate mean intensity.
• Run a function to extract the specified slices, display them and calculate their mean intensity.
• Display the mean intensity value for each specified slice.

Show activity for:

## Exercises

Show exercise/solution for:

## Exercise1 - ImageJ Macro

Use “function_display_slice.ijm”: and display mean intensity values of slices without returning any values from the function.

1. Select two different slice indices of your choice .
2. Modify the function “calculateSliceMeanIntensity” in such a way that it returns nothing and displays mean intensity of each individual slice.

## Solution

``````run("Close All"); // close all opened windows
run("MRI Stack"); // load the example MRI image stack
imageName = getTitle(); //get the image title

//select first slice,calculate its mean intensity and display it
selectWindow(imageName);
sliceNumber = 5;
calculateSliceMeanIntensity(sliceNumber);

//select last slice,calculate its mean intensity and display it
selectWindow(imageName);
sliceNumber = 10;
calculateSliceMeanIntensity(sliceNumber);

// a function that calculates mean intensity of a specified slice in a stack and displays it
function calculateSliceMeanIntensity(sliceNumber)
{
setSlice(sliceNumber);
run("Duplicate...", "title=slice"+sliceNumber);
sliceName = "slice"+sliceNumber;
selectWindow(sliceName);
run("8-bit");
getStatistics(area, mean);
print("Slice#"+ sliceNumber + " has mean intensity: " + mean);
}
``````

## Exercise2 - ImageJ Macro

Use “cc_counting_after_closing.ijm”: and do the following tasks:

1. Figure out the repetitive part of the code, and
2. Apply a function to perform the repetitive task.

## Assessment

### True or False

• The variables defined within the function can be used outside of the function.
• Same function can be called multiple times within a script.

## Solution

• It cannot be used unless the variable is returned by this function. False
• True

## Follow-up material

Recommended follow-up modules: