ITK Filtering
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
-
ModuleNotFoundError: No module named 'itk'
cause The core `itk` package (which includes filtering modules) is not installed in your Python environment. The `itk-filtering` package depends on `itk`.fixEnsure `itk` is installed by running `pip install itk` or `pip install itk-filtering` to get the core library along with the filtering components. -
AttributeError: module 'itk' has no attribute 'SomeFilterName'
cause You are trying to access a filter or function that does not exist or is not exposed directly under the `itk` module, or there's a typo in the name.fixCheck the exact name and capitalization of the filter in the ITK documentation. For templated filters, ensure you are using the correct Pythonic factory function (e.g., `itk.median_image_filter()`) or explicitly templating the class (`itk.MedianImageFilter[ImageType, ImageType].New()`). Sometimes, a filter might be in a less common module that requires a separate `import` (e.g., `import itk.bridge.vtk` for VTK integration), though this is less common for core filtering. -
RuntimeError: Exception thrown in SimpleITK CastImageFilter (or similar filter) ... Input image type is mismatching requested output image type.
cause ITK filters often expect specific input pixel types (e.g., float, unsigned char). If your image's pixel type does not match the filter's expectation or if you're chaining filters with incompatible types, this error occurs.fixUse `itk.CastImageFilter` to explicitly convert your image to the required pixel type before applying the filter. For example, `itk.CastImageFilter[itk.UC, itk.F].New().SetInput(input_image).Update().GetOutput()` converts an unsigned char image to float.
Warnings
- breaking ITK 6.0, currently in beta, will require C++17 and includes significant C++ code modernization and build system changes. While the Python wrappers aim for stability, users should anticipate potential breaking API changes or behavioral differences, especially for advanced use cases or custom C++ extensions, upon the stable release of ITK 6.0.
- gotcha ITK images and filters are templated by pixel type and dimension. Incorrectly specifying these (or relying on implicit types that don't match your data) can lead to runtime errors or unexpected behavior. This is particularly important when instantiating filter types explicitly (e.g., `itk.MedianImageFilter[ImageType, ImageType]`).
- gotcha ITK's memory management for large N-dimensional images can be a concern. Copying large images unnecessarily or processing them in inefficient ways can lead to high memory consumption and slow performance.
Install
-
pip install itk-filtering
Imports
- itk
from itk import some_filter_module
import itk
- Image
image = itk.Image[pixel_type, dimension_count]()
Quickstart
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