A gradient magnitude filter in ITK

AdvancedMedical image analysisMedical imaging

Goal: Applying an ITK filter to a 3D image through its functional Python API.

Python — example.py
import itk, numpy as np

arr = np.zeros((40, 40, 40), dtype=np.float32)
arr[10:30, 10:30, 10:30] = 100.0
image = itk.image_view_from_array(arr)
grad = itk.gradient_magnitude_recursive_gaussian_image_filter(image, sigma=1.0)
g = itk.array_from_image(grad)
print("Output shape:", g.shape)
print(f"Maximum value (at the edges): {g.max():.2f}")
print(f"Value at the centre of the cube: {g[20, 20, 20]:.4f}")

Code explanation

ITK provides thousands of filters and registration algorithms. Here we convert a NumPy array to an ITK image and apply a gradient magnitude filter with Gaussian smoothing, so high values appear only on the edges of the cube.

Requirements

Shell
pip install itk numpy

How to run

Save the code in a file example.py then run it:

Shell
python example.py

Output recorded during testing

Output shape: (40, 40, 40)
Maximum value (at the edges): 36.57
Value at the centre of the cube: 0.0001

This example was actually run and tested on 21 November 2026 on a CPU — itk 5.4.8, numpy 2.5.5, python 3.13.18

Libraries used

Related examples