ITK-IO

5.4.5 · active · verified Fri Apr 17

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

Warnings

Install

Imports

Quickstart

This quickstart demonstrates how to create a simple 3D image using NumPy, convert it to an ITK image object, save it to a MetaImage (.mha) file, and then read it back. Finally, it verifies the integrity of the data by converting it back to a NumPy array and comparing it with the original.

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}")

view raw JSON →