ITK-IO
ITK-IO provides core input/output capabilities for the Insight Toolkit (ITK), an open-source, cross-platform toolkit for n-dimensional scientific image analysis. It enables reading and writing various image file formats. Currently at version 5.4.5, it follows ITK's maintenance release cadence, with major version 6.0 in beta, focusing on bug fixes, performance improvements, and C++ modernization.
Common errors
-
ModuleNotFoundError: No module named 'itk_io'
cause Attempted to import directly from 'itk_io' instead of the unified 'itk' namespace.fixUse `import itk` to access all ITK functionality, including IO functions like `itk.imread`. -
AttributeError: module 'itk' has no attribute 'imread'
cause The installed `itk` package (or its sub-packages) does not include the IO components required for `imread`/`imwrite`. This can happen if only a minimal `itk` version without IO support was installed, or if the `itk-io` component is missing.fixEnsure you have `itk-io` installed (`pip install itk-io`) or install the full ITK package (`pip install itk` or `pip install itk-full`). -
RuntimeError: itk::ImageIOBaseException (0x...): Could not read image file "path/to/image.dcm"
cause Generic error indicating ITK failed to read the image file. This could be due to the file not existing, corrupted data, an unsupported file format, or missing optional backend libraries (e.g., GDCM for DICOM, HDF5, etc.) required by ITK.fixVerify the file path and existence. Check if the file is valid and not corrupted. If reading a specialized format like DICOM, ensure `itk-full` is installed (`pip install itk-full`) as it includes more IO backends. For custom builds, ensure relevant ITK modules are enabled. -
TypeError: in method 'ImageFileReader_SetFileName', argument 2 of type 'char const *'
cause You are passing an object of an incorrect type (e.g., `pathlib.Path` object) to an ITK C++ binding method that specifically expects a Python string (which maps to `char const *` in C++).fixConvert the path object to a string before passing it: `reader.SetFileName(str(my_path_object))`.
Warnings
- breaking ITK 6.0 (currently in beta) requires C++17. If you are building ITK from source, developing custom C++ ITK modules, or using specific compiler versions, this C++ standard update may cause compilation failures or require environment adjustments.
- gotcha The `itk-io` Python package does not expose its functionality via `from itk_io import ...`. All ITK Python functionality, including IO, is consolidated under the main `itk` namespace. Attempting to import directly from `itk_io` will result in a `ModuleNotFoundError`.
- gotcha ITK has a complex C++ backend with many optional components (e.g., for specific file formats like DICOM, HDF5, JPEG2000). While `pip install itk-io` provides core IO, you might need `pip install itk` or `pip install itk-full` to get full support for all desired image formats and features, especially for medical imaging.
- gotcha ITK Python bindings often expect plain Python strings for file paths and other string arguments, especially when interacting directly with underlying C++ ITK objects (e.g., `itk.ImageFileReader.SetFileName`). Passing `pathlib.Path` objects directly can sometimes lead to `TypeError`.
Install
-
pip install itk-io -
pip install itk -
pip install itk-full
Imports
- itk
from itk_io import imread
import itk
- imread
itk.imread
- imwrite
itk.imwrite
- ImageFileReader
itk.ImageFileReader
Quickstart
import itk
import numpy as np
import os
# 1. Create a dummy NumPy array (e.g., 3D unsigned char)
image_array = np.arange(64*64*64, dtype=np.uint8).reshape((64, 64, 64))
# 2. Convert NumPy array to ITK image object
itk_image = itk.image_from_array(image_array)
# Define a temporary file name for the image
output_filename = os.path.join(os.getcwd(), "itk_dummy_image.mha") # .mha is a common ITK format
# 3. Write the ITK image to a file using itk.imwrite
print(f"Writing image to {output_filename}")
itk.imwrite(itk_image, output_filename)
print("Image written successfully.")
# 4. Read the image back from the file using itk.imread
print(f"Reading image from {output_filename}")
read_itk_image = itk.imread(output_filename) # itk.imread infers pixel type if not specified
print("Image read successfully.")
# 5. Verify properties of the read image
print(f"Read image dimensions: {read_itk_image.GetImageDimension()}")
print(f"Read image size: {read_itk_image.GetLargestPossibleRegion().GetSize()}")
print(f"Read image pixel type: {read_itk_image.GetPixelIDTypeAsString()}")
# 6. (Optional) Convert the read ITK image back to a NumPy array for verification
read_array = itk.array_from_image(read_itk_image)
print(f"Read array shape: {read_array.shape}, dtype: {read_array.dtype}")
print(f"Arrays are equal: {np.array_equal(image_array, read_array)}")
# Clean up the dummy file
if os.path.exists(output_filename):
os.remove(output_filename)
print(f"Cleaned up {output_filename}")