ITK (Insight Toolkit) Core

5.4.5 · active · verified Fri Apr 17

ITK is an open-source, cross-platform toolkit for N-dimensional scientific image processing, segmentation, and registration in a spatially-oriented architecture. The `itk-core` package provides the fundamental Python bindings for ITK's C++ core functionalities. It is currently in a 5.4.x maintenance release cycle (5.4.5) with active development on the major 6.0 release.

Common errors

Warnings

Install

Imports

Quickstart

This quickstart demonstrates how to read an N-dimensional image, apply a common filter (Gaussian smoothing), and write the result back to disk using `itk-core`'s Python bindings. It includes setup for creating a dummy image if no input file exists, making it runnable out-of-the-box.

import itk
import numpy as np
import os

# --- Setup: Create a dummy image if 'input.mha' doesn't exist ---
input_file = "input.mha"
output_file = "output_smoothed.mha"

if not os.path.exists(input_file):
    print(f"{input_file} not found, creating a dummy 3D image for demonstration.")
    array_image = np.zeros((64, 64, 64), dtype=np.float32)
    # Add a simple cube to the image
    array_image[10:50, 10:50, 10:50] = 100.0
    dummy_image = itk.image_from_array(array_image)
    # Set metadata (origin, spacing) which is important for ITK images
    dummy_image.SetSpacing([1.0, 1.0, 1.0])
    dummy_image.SetOrigin([0.0, 0.0, 0.0])
    itk.imwrite(dummy_image, input_file)
    print(f"Created {input_file}")

# --- Core ITK Usage: Read, Process, Write ---

# 1. Define the image type (e.g., 3D float image)
ImageType = itk.Image[itk.F, 3] # itk.F for float, 3 for 3 dimensions

# 2. Read an image
print(f"Reading image from {input_file}...")
image = itk.imread(input_file, ImageType)
print(f"Original image size: {image.GetLargestPossibleRegion().GetSize()}")

# 3. Apply a filter (e.g., Gaussian smoothing)
print("Applying Gaussian filter...")
gaussian_filter = itk.GaussianImageFilter[ImageType, ImageType].New()
gaussian_filter.SetInput(image)
gaussian_filter.SetSigma(2.0) # Set the standard deviation for the Gaussian kernel
gaussian_filter.Update() # Execute the filter
smoothed_image = gaussian_filter.GetOutput()

# 4. Write the processed image
print(f"Writing smoothed image to {output_file}...")
itk.imwrite(smoothed_image, output_file)
print(f"Smoothed image size: {smoothed_image.GetLargestPossibleRegion().GetSize()}")
print("Image processing complete.")

view raw JSON →