ITK Filtering

5.4.5 · active · verified Fri Apr 17

ITK (Insight Toolkit) is an open-source, cross-platform toolkit for N-dimensional scientific image analysis, including processing, segmentation, and registration. The `itk-filtering` package bundles Python bindings for many ITK filtering modules. The current stable version is 5.4.5, with frequent maintenance releases for the 5.x series and active beta development for the upcoming 6.0 major version.

Common errors

Warnings

Install

Imports

Quickstart

This example demonstrates how to create a simple ITK image programmatically, apply a 2D Median filter, and inspect the output. It highlights the templated nature of ITK images and filters, and shows how to convert between ITK image objects and NumPy arrays for interoperability.

import itk
import numpy as np

# Create a simple 2D image (e.g., a square)
size = itk.Size[2]()
size.SetElement(0, 100)
size.SetElement(1, 100)

start = itk.Index[2]()
start.Fill(0)

region = itk.ImageRegion[2]()
region.SetSize(size)
region.SetIndex(start)

# Instantiate an ITK image with unsigned char pixels (UC) and 2 dimensions
image = itk.Image[itk.UC, 2].New()
image.SetRegions(region)
image.Allocate()
image.FillBuffer(0)

# Draw a white square on a black background
for x in range(20, 80):
    for y in range(20, 80):
        idx = itk.Index[2]()
        idx.SetElement(0, x)
        idx.SetElement(1, y)
        image.SetPixel(idx, 255)

# Apply a Median filter. The filter type is templated based on the input image type.
median_filter = itk.MedianImageFilter[type(image), type(image)].New()
median_filter.SetInput(image)
median_filter.SetRadius(2) # Radius of 2x2 neighborhood
median_filter.Update()

output_image = median_filter.GetOutput()

# Convert ITK image to NumPy array for display/further processing (optional)
output_array = itk.GetArrayFromImage(output_image)

print(f"Original image size: {image.GetLargestPossibleRegion().GetSize()}")
print(f"Output image size: {output_image.GetLargestPossibleRegion().GetSize()}")
print(f"Non-zero pixels in original: {np.sum(itk.GetArrayFromImage(image) > 0)}")
print(f"Non-zero pixels in filtered: {np.sum(output_array > 0)}")

# For real image processing, you'd typically read/write files like this:
# try:
#     itk.imwrite(output_image, "filtered_image.png")
#     print("Filtered image saved as filtered_image.png")
# except Exception as e:
#     print(f"Could not save image: {e}. Ensure image format is supported and path is valid.")
# read_image = itk.imread("input.mha", itk.F) # Read a medical image as float type

view raw JSON →