SimpleITK is a simplified interface to the Insight Toolkit (ITK) for image registration and segmentation
—
Quality
Pending
Does it follow best practices?
Impact
Pending
No eval scenarios have been run
Utility functions and classes for version information, image display, logging, event handling, and global configuration of SimpleITK behavior.
Query SimpleITK and ITK version information.
class Version:
"""Static class providing version information."""
@staticmethod
def MajorVersion() -> int:
"""Get SimpleITK major version number."""
@staticmethod
def MinorVersion() -> int:
"""Get SimpleITK minor version number."""
@staticmethod
def PatchVersion() -> int:
"""Get SimpleITK patch version number."""
@staticmethod
def TweakVersion() -> int:
"""Get SimpleITK tweak version number."""
@staticmethod
def VersionString() -> str:
"""Get full SimpleITK version string (e.g., '2.5.3')."""
@staticmethod
def BuildDate() -> str:
"""Get build date string."""
@staticmethod
def ITKMajorVersion() -> int:
"""Get underlying ITK major version."""
@staticmethod
def ITKMinorVersion() -> int:
"""Get underlying ITK minor version."""
@staticmethod
def ITKPatchVersion() -> int:
"""Get underlying ITK patch version."""
@staticmethod
def ITKVersionString() -> str:
"""Get ITK version string."""
@staticmethod
def ITKModulesEnabled() -> tuple[str, ...]:
"""Get list of enabled ITK modules."""
@staticmethod
def ExtendedVersionString() -> str:
"""Get detailed version information including build info and enabled modules."""Usage example:
import SimpleITK as sitk
print(f"SimpleITK version: {sitk.Version.VersionString()}")
print(f"ITK version: {sitk.Version.ITKVersionString()}")
print(f"Build date: {sitk.Version.BuildDate()}")
print(f"\nExtended info:\n{sitk.Version.ExtendedVersionString()}")Display images in external viewer applications for visualization.
def Show(image, title: str = "", debugOn: bool = False):
"""
Display image in external viewer.
By default, uses Fiji/ImageJ if available. The viewer application can be
configured via environment variables or ImageViewer settings.
Args:
image: Image to display
title: Window title for the viewer
debugOn: Enable debug output showing viewer command
Raises:
RuntimeError: If no suitable viewer is found
"""
class ImageViewer:
"""Configure external image viewer application."""
@staticmethod
def SetApplication(app: str, arguments: str = ""):
"""
Set viewer application and arguments.
Args:
app: Path to viewer executable
arguments: Command-line arguments (use %a for image placeholder)
"""
@staticmethod
def GetApplication() -> str:
"""Get configured viewer application path."""
@staticmethod
def SetTitle(title: str):
"""Set default window title for viewer."""
@staticmethod
def GetTitle() -> str:
"""Get default window title."""
@staticmethod
def SetFileExtension(ext: str):
"""Set file extension for temporary files (e.g., '.png', '.nii')."""
@staticmethod
def GetFileExtension() -> str:
"""Get file extension for temporary files."""Usage example:
import SimpleITK as sitk
# Configure viewer
sitk.ImageViewer.SetApplication('/usr/bin/itksnap')
# Display image
image = sitk.ReadImage('brain.nii')
sitk.Show(image, title='Brain MRI')Cast images between pixel types.
class CastImageFilter:
"""Cast image to specified pixel type."""
def SetOutputPixelType(self, pixelID: int) -> None:
"""
Set target pixel type.
Args:
pixelID: Target pixel type (sitkUInt8, sitkFloat32, etc.)
"""
def GetOutputPixelType(self) -> int:
"""Get target pixel type."""
def Execute(self, image):
"""
Cast image.
Args:
image: Input image
Returns:
Image with specified pixel type
"""
def Cast(image, pixelID: int):
"""
Cast image to specified pixel type (procedural interface).
Args:
image: Input image
pixelID: Target pixel type (sitkUInt8, sitkFloat32, etc.)
Returns:
Casted image
"""Usage example:
import SimpleITK as sitk
# Read image
image = sitk.ReadImage('input.dcm') # May be Int16
print(f"Original type: {image.GetPixelIDTypeAsString()}")
# Cast to unsigned 8-bit for PNG export
image_uint8 = sitk.Cast(image, sitk.sitkUInt8)
print(f"New type: {image_uint8.GetPixelIDTypeAsString()}")
sitk.WriteImage(image_uint8, 'output.png')Control multi-threading behavior for all filters.
def SetGlobalDefaultNumberOfThreads(n: int):
"""
Set default number of threads for filter execution.
Args:
n: Number of threads (0 = auto-detect from hardware)
"""
def GetGlobalDefaultNumberOfThreads() -> int:
"""
Get default number of threads.
Returns:
Number of threads
"""
def SetGlobalDefaultThreader(threader: str):
"""
Set threading implementation.
Args:
threader: Threading backend ('POOL', 'TBB', or 'PLATFORM')
"""
def GetGlobalDefaultThreader() -> str:
"""
Get threading implementation.
Returns:
Threading backend name
"""Usage example:
import SimpleITK as sitk
# Use 4 threads for all operations
sitk.SetGlobalDefaultNumberOfThreads(4)
print(f"Using {sitk.GetGlobalDefaultNumberOfThreads()} threads")
# Run computationally intensive filter
image = sitk.ReadImage('large_volume.nii')
smoothed = sitk.SmoothingRecursiveGaussian(image, sigma=[2.0, 2.0, 2.0])Configure geometric tolerance for image comparisons.
def SetGlobalDefaultCoordinateTolerance(tolerance: float):
"""
Set tolerance for coordinate comparisons.
Used when checking if images have matching origins, spacing, etc.
Args:
tolerance: Coordinate tolerance in physical units
"""
def GetGlobalDefaultCoordinateTolerance() -> float:
"""
Get coordinate tolerance.
Returns:
Coordinate tolerance
"""
def SetGlobalDefaultDirectionTolerance(tolerance: float):
"""
Set tolerance for direction cosine comparisons.
Used when checking if images have matching orientations.
Args:
tolerance: Direction tolerance (angle difference)
"""
def GetGlobalDefaultDirectionTolerance() -> float:
"""
Get direction tolerance.
Returns:
Direction tolerance
"""Control debug output for all filters.
# These methods are available on any ProcessObject (filter base class)
def DebugOn():
"""Enable debug output for this filter instance."""
def DebugOff():
"""Disable debug output for this filter instance."""
def GetDebug() -> bool:
"""Get debug state for this filter instance."""
def SetDebug(debug: bool):
"""Set debug state for this filter instance."""
def GlobalDefaultDebugOn():
"""Enable debug output globally for all filters."""
def GlobalDefaultDebugOff():
"""Disable debug output globally for all filters."""
def GetGlobalDefaultDebug() -> bool:
"""Get global debug state."""
def SetGlobalDefaultDebug(debug: bool):
"""Set global debug state."""
def GlobalWarningDisplayOn():
"""Enable warning display globally."""
def GlobalWarningDisplayOff():
"""Disable warning display globally."""
def GetGlobalWarningDisplay() -> bool:
"""Get global warning display state."""
def SetGlobalWarningDisplay(display: bool):
"""Set global warning display state."""Usage example:
import SimpleITK as sitk
# Enable debug for specific filter
gaussian = sitk.DiscreteGaussianImageFilter()
gaussian.DebugOn()
result = gaussian.Execute(image)
# Enable debug globally
sitk.ProcessObject.GlobalDefaultDebugOn()Monitor filter execution with callbacks.
class Command:
"""
Base class for filter callbacks.
Subclass this to create custom commands that respond to filter events.
"""
def Execute(self):
"""Called when registered event occurs."""
class FunctionCommand(Command):
"""
Command that calls a Python function.
Automatically created when passing a function to AddCommand().
"""
# Available on all ProcessObject subclasses (filters)
def AddCommand(event: int, command):
"""
Register callback for filter events.
Args:
event: Event type (sitkProgressEvent, sitkIterationEvent, etc.)
command: Command object or Python callable
Returns:
Command ID for later removal
"""
def RemoveAllCommands():
"""Remove all registered event callbacks."""
def HasCommand(event: int) -> bool:
"""
Check if filter has commands registered for event type.
Args:
event: Event type to check
Returns:
True if commands are registered
"""
def GetProgress() -> float:
"""
Get current progress (0.0 to 1.0).
Only valid during filter execution, typically called from progress callback.
Returns:
Progress fraction
"""Usage example:
import SimpleITK as sitk
def progress_callback():
print(f"Progress: {gaussian.GetProgress() * 100:.1f}%")
def iteration_callback():
print(f"Iteration {reg_method.GetOptimizerIteration()}: "
f"Metric = {reg_method.GetMetricValue():.4f}")
# Monitor filter progress
gaussian = sitk.SmoothingRecursiveGaussianImageFilter()
gaussian.AddCommand(sitk.sitkProgressEvent, progress_callback)
result = gaussian.Execute(large_image)
# Monitor registration iterations
reg_method = sitk.ImageRegistrationMethod()
reg_method.AddCommand(sitk.sitkIterationEvent, iteration_callback)
transform = reg_method.Execute(fixed_image, moving_image)Redirect ITK/SimpleITK output to Python logging.
class LoggerBase:
"""Base class for logger implementations."""
def SetAsGlobalITKLogger(self):
"""Set this logger as the global ITK output handler."""
def SetPriorityLevel(self, level: int):
"""
Set minimum log level.
Args:
level: Priority level (0=DEBUG, 1=INFO, 2=WARNING, 3=ERROR, 4=CRITICAL)
"""
def GetPriorityLevel() -> int:
"""Get current priority level."""
class ITKLogger(LoggerBase):
"""
Logger that captures ITK output window messages.
Redirects ITK warnings and errors to SimpleITK logging system.
"""
def __init__(self):
"""Create ITK logger."""Usage example:
import SimpleITK as sitk
# Redirect ITK output
logger = sitk.ITKLogger()
logger.SetPriorityLevel(2) # WARNING and above
logger.SetAsGlobalITKLogger()
# Now ITK warnings/errors are captured
image = sitk.ReadImage('input.dcm')Compute cryptographic hash of image for verification.
class HashImageFilter:
"""Compute hash of image data."""
def SetHashFunction(self, function: int):
"""
Set hash function.
Args:
function: Hash function enum (default is SHA-1)
"""
def Execute(self, image):
"""
Compute hash.
Args:
image: Input image
"""
def GetHashValue(self) -> str:
"""
Get computed hash string.
Returns:
Hexadecimal hash string
"""
def Hash(image, hashFunction: int = 0) -> str:
"""
Compute image hash (procedural interface).
Args:
image: Input image
hashFunction: Hash function enum
Returns:
Hexadecimal hash string
"""Usage example:
import SimpleITK as sitk
# Compute hash for verification
image = sitk.ReadImage('image.nii')
hash_value = sitk.Hash(image)
print(f"Image hash: {hash_value}")
# Verify after processing
processed = sitk.GaussianBlur(image, sigma=1.0)
processed_hash = sitk.Hash(processed)
print(f"Changed: {hash_value != processed_hash}")Install with Tessl CLI
npx tessl i tessl/pypi-simpleitk