ITK (Insight Toolkit) Core
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
-
ModuleNotFoundError: No module named 'itk_core'
cause Attempting to import the Python module using the PyPI package name `itk_core`.fixThe correct import for ITK core functionality is `import itk`, regardless of whether `itk-core` or `itk` was installed via pip. -
itk.Exception: Image dimension mismatch
cause Applying an ITK filter or operation that expects a specific image dimension (e.g., 3D) to an image of a different dimension (e.g., 2D), or mismatching dimensions in image processing pipelines.fixEnsure that your input images and chosen filters operate on consistent dimensions. Explicitly define `ImageType` using `itk.Image[itk.F, N_DIMENSIONS]` where `N_DIMENSIONS` matches your image data. -
MemoryError: Unable to allocate XXXXX bytes
cause Attempting to load or process an image that exceeds available system memory, often with large 3D/4D datasets or when copying images to/from NumPy arrays.fixReduce image size, process in smaller regions, use memory-efficient data types (e.g., `itk.UC` for `unsigned char`), or upgrade system RAM. Be mindful when converting between `itk.Image` and `numpy.ndarray` as this can temporarily duplicate data.
Warnings
- breaking ITK 6.0 (currently in beta) requires C++17. While pre-compiled Python wheels usually handle this, users compiling ITK from source or in specific environments may need to ensure a C++17 compliant compiler is available.
- gotcha The `itk` PyPI package is a metapackage that installs `itk-core` along with other common ITK modules (e.g., `itk-io`, `itk-filtering`). While `pip install itk-core` works for core functionality, `pip install itk` is generally recommended for a complete ITK Python experience.
- gotcha ITK operates on N-dimensional images, and memory consumption can be significant for large 3D or 4D datasets. Unmanaged memory usage can quickly lead to `MemoryError` or system slowdowns.
Install
-
pip install itk-core
Imports
- itk
import itk_core
import itk
- ImageFileReader
from itk.io import ImageFileReader
import itk reader = itk.ImageFileReader[itk.Image[itk.F, 3]].New()
Quickstart
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.")