Insight Toolkit for N-dimensional image processing, segmentation, and registration in medical and scientific applications
—
Helper functions for pipeline management, progress monitoring, image information queries, and introspection.
def output(input):
"""
Extract output from filter or return input unchanged.
If input has GetOutput() method, calls it; otherwise returns input as-is.
Parameters:
- input: itk.Image or ProcessObject
Returns:
itk.Image - Output image
"""def size(image_or_filter):
"""
Return the size of an image or filter output.
Parameters:
- image_or_filter: itk.Image or ProcessObject
Returns:
tuple of int - Size in each dimension
"""
def physical_size(image_or_filter):
"""
Return the physical size (size × spacing) of an image.
Parameters:
- image_or_filter: itk.Image or ProcessObject
Returns:
tuple of float - Physical size in each dimension
"""
def spacing(image_or_filter):
"""
Return the spacing of an image.
Parameters:
- image_or_filter: itk.Image or ProcessObject
Returns:
tuple of float - Spacing in each dimension
"""
def origin(image_or_filter):
"""
Return the origin of an image.
Parameters:
- image_or_filter: itk.Image or ProcessObject
Returns:
tuple of float - Origin coordinates
"""
def index(image_or_filter):
"""
Return the starting index of an image.
Parameters:
- image_or_filter: itk.Image or ProcessObject
Returns:
tuple of int - Starting index in each dimension
"""
def region(image_or_filter):
"""
Return the largest possible region of an image.
Parameters:
- image_or_filter: itk.Image or ProcessObject
Returns:
itk.ImageRegion - Largest possible region
"""
def image_intensity_min_max(image_or_filter):
"""
Return the minimum and maximum pixel values in an image.
Parameters:
- image_or_filter: itk.Image or ProcessObject
Returns:
tuple - (min_value, max_value)
"""def set_nthreads(number_of_threads):
"""
Set the global number of threads for ITK operations.
Parameters:
- number_of_threads: int - Number of threads to use (0 for automatic)
"""
def get_nthreads():
"""
Get the current global number of threads.
Returns:
int - Number of threads
"""def auto_progress(progress_type=1):
"""
Set up automatic progress reporting.
Parameters:
- progress_type: int or bool
- 0 or False: Disable progress reporting
- 1 or True: Terminal progress with special characters
- 2: Simple text progress
"""
class AutoProgressTypes:
"""Enumeration for progress types."""
DISABLE = 0
TERMINAL = 1
SIMPLE = 2
def terminal_progress_callback(name, p):
"""
Display progress with terminal control characters.
Used with itkConfig.ProgressCallback.
Parameters:
- name: str - Filter name
- p: float - Progress (0.0 to 1.0)
"""
def simple_progress_callback(name, p):
"""
Display progress with simple text output.
Parameters:
- name: str - Filter name
- p: float - Progress (0.0 to 1.0)
"""def force_load():
"""
Force ITK to load all submodules immediately.
Useful for introspection and discovering available classes.
By default, ITK uses lazy loading for faster import times.
"""
def auto_not_in_place(v=True):
"""
Force filters to not run in-place.
Parameters:
- v: bool - If True, prevent in-place operations
"""def search(s, case_sensitive=False):
"""
Search for a class name in the itk module.
Parameters:
- s: str - Search string (can be partial)
- case_sensitive: bool - Case-sensitive search
Returns:
list of str - List of matching class names
"""
def down_cast(obj):
"""
Down cast an ITK object to its most specialized type.
Parameters:
- obj: ITK object - Object to down cast
Returns:
ITK object - Object cast to most specialized available type
Note:
Useful when working with base class references to access derived class methods.
"""
def template(cl):
"""
Return template information for a templated class.
Parameters:
- cl: class or object - Templated ITK class or instance
Returns:
tuple - (itkTemplate, template_parameters)
Note:
Useful for introspecting template instantiations and available types.
"""
def class_(obj):
"""
Return the class from an ITK object instance.
Parameters:
- obj: ITK object - Object instance
Returns:
type - The class object (Python type) of the ITK object
"""
def ctype(s):
"""
Get itkCType from a string representation.
Parameters:
- s: str - Type string (e.g., 'float', 'unsigned char', 'UC')
Returns:
itkCType - Corresponding ITK C type
Examples:
itk.ctype('float') → itk.F
itk.ctype('UC') → itk.UC
"""
def python_type(object_ref):
"""
Get Python type name from an ITK object reference.
Parameters:
- object_ref: ITK object - Object or class reference
Returns:
str - Python type name
"""
def echo(obj, f=None):
"""
Print an object to stream.
Uses the object's Print() method if available, otherwise uses repr().
Parameters:
- obj: object - Object to print
- f: file, optional - Output stream (default: sys.stderr)
"""
def set_inputs(new_itk_object, args, kwargs):
"""
Set the inputs of an ITK object from positional and keyword arguments.
Used internally by enhanced New() methods.
Parameters:
- new_itk_object: ITK object - Object to configure
- args: tuple - Positional arguments
- kwargs: dict - Keyword arguments
"""class pipeline:
"""
Convenience class to store references to filters in a pipeline.
Usage:
p = itk.pipeline()
p.connect(filter1)
p.connect(filter2)
p.SetInput(image)
p.Update()
result = p.GetOutput()
"""
def connect(self, filter):
"""
Connect a new filter to the pipeline.
Parameters:
- filter: ProcessObject - Filter to connect
"""
def append(self, filter):
"""
Add a filter without connecting.
Parameters:
- filter: ProcessObject - Filter to add
"""
def clear(self):
"""Clear the filter list."""
def GetOutput(self, index=0):
"""
Get pipeline output.
Parameters:
- index: int - Output index
Returns:
itk.Image
"""
def GetInput(self):
"""Get pipeline input."""
def SetInput(self, input):
"""
Set pipeline input.
Parameters:
- input: itk.Image - Input image
"""
def Update(self):
"""Update the pipeline."""
def UpdateLargestPossibleRegion(self):
"""Update largest possible region."""
def expose(self, name, new_name=None, position=-1):
"""
Expose filter attributes.
Parameters:
- name: str - Attribute name
- new_name: str, optional - New attribute name
- position: int - Filter position in pipeline
"""
class auto_pipeline(pipeline):
"""
Extension of pipeline that automatically tracks filter connections.
"""
@classmethod
def Start(cls):
"""Start automatic pipeline tracking."""
@classmethod
def Stop(cls):
"""Stop automatic pipeline tracking."""
current: 'auto_pipeline' # Currently active auto_pipeline instance
class templated_class:
"""
Decorator class to create custom templated classes mimicking ITK's template behavior.
Allows creation of custom Python classes that can be templated like ITK C++ classes.
Usage:
@itk.templated_class
class CustomClass:
def __init__(self, template_parameters=None):
# Use template_parameters tuple
pass
@staticmethod
def check_template_parameters(parameters):
# Optional: validate template parameters
pass
# Instantiate with template parameters
obj = CustomClass[itk.F, 3].New()
Note:
This is an advanced feature primarily for library developers creating
custom templated classes that integrate with ITK's template system.
"""
def __init__(self, cls):
"""
Initialize templated_class wrapper.
Parameters:
- cls: class - Class to make templated
"""
def __getitem__(self, template_parameters):
"""
Get class instantiation for specific template parameters.
Parameters:
- template_parameters: tuple or single value - Template parameters
Returns:
class - Class configured with template parameters
"""class TemplateTypeError(TypeError):
"""
Exception raised when template type mismatches occur.
Raised when attempting to use incompatible template parameters
or type instantiations.
"""
def __init__(self, template_type, input_type):
"""
Initialize TemplateTypeError with template and input type information.
Parameters:
- template_type: ITK template class - The templated class that was instantiated
- input_type: type or tuple - The input type(s) that were incompatible
Note:
This exception generates a helpful error message showing available types
and suggesting solutions for type incompatibility issues.
"""import itk
image = itk.imread('input.png', itk.F)
# Query image properties
print(f"Size: {itk.size(image)}")
print(f"Spacing: {itk.spacing(image)}")
print(f"Origin: {itk.origin(image)}")
print(f"Physical size: {itk.physical_size(image)}")
# Get intensity range
min_val, max_val = itk.image_intensity_min_max(image)
print(f"Intensity range: [{min_val}, {max_val}]")
# Get region
region = itk.region(image)
print(f"Region size: {region.GetSize()}")
print(f"Region index: {region.GetIndex()}")import itk
# Enable progress reporting
itk.auto_progress(True) # or itk.AutoProgressTypes.TERMINAL
# Run a long operation - progress will be displayed automatically
image = itk.imread('large_image.nii.gz', itk.F)
smoothed = itk.median_image_filter(image, radius=5)
itk.imwrite(smoothed, 'smoothed.nii.gz')
# Disable progress
itk.auto_progress(False)import itk
# Use 8 threads
itk.set_nthreads(8)
# Check current setting
n_threads = itk.get_nthreads()
print(f"Using {n_threads} threads")
# Use all available threads (set to 0)
itk.set_nthreads(0)import itk
# Search for classes
results = itk.search('Median')
print("Median filters:", results)
results = itk.search('Gaussian', case_sensitive=False)
print("Gaussian filters:", results)
# Force load all modules for complete search
itk.force_load()
results = itk.search('Transform')
print(f"Found {len(results)} transform classes")import itk
# Create pipeline
p = itk.pipeline()
# Add filters
p.connect(itk.MedianImageFilter.New())
p.connect(itk.GradientMagnitudeImageFilter.New())
# Configure
p.SetInput(itk.imread('input.png', itk.F))
# Expose filter parameters
p.expose('Radius', position=0) # MedianImageFilter.SetRadius
p.SetRadius(3)
# Execute
p.Update()
result = p.GetOutput()
itk.imwrite(result, 'pipeline_result.png')import itk
# Start automatic pipeline tracking
itk.auto_pipeline.Start()
# Create filters - they're automatically tracked
median = itk.MedianImageFilter.New()
gradient = itk.GradientMagnitudeImageFilter.New()
# Stop tracking
pipeline = itk.auto_pipeline.Stop()
# Use pipeline
pipeline.SetInput(itk.imread('input.png', itk.F))
pipeline.Update()
result = pipeline.GetOutput()import itk
image = itk.imread('input.png', itk.F)
# Print image information
itk.echo(image) # Prints to stderr
# Print filter information
filter = itk.MedianImageFilter.New(image)
itk.echo(filter)Install with Tessl CLI
npx tessl i tessl/pypi-itk@5.4.1docs
guides
reference