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
The Image class is the central data structure in SimpleITK, representing n-dimensional images (2D, 3D, or 4D) with comprehensive support for medical and scientific imaging. Each image stores pixel data along with spatial metadata (origin, spacing, direction) that defines the image's position and orientation in physical space.
Create images with specified dimensions and pixel types.
class Image:
"""
Core class for n-dimensional medical and scientific images.
The Image class supports 2D, 3D, and 4D images with various pixel types
including scalar, vector, complex, and label types. Images maintain both
pixel data and spatial metadata for proper physical space representation.
"""
def __init__(self):
"""Create an empty image."""
def __init__(self, width: int, height: int, pixelType: int):
"""
Create a 2D image.
Args:
width: Image width in pixels
height: Image height in pixels
pixelType: Pixel type (sitkUInt8, sitkFloat32, etc.)
"""
def __init__(self, width: int, height: int, depth: int, pixelType: int):
"""
Create a 3D image.
Args:
width: Image width in pixels
height: Image height in pixels
depth: Image depth in pixels
pixelType: Pixel type (sitkUInt8, sitkFloat32, etc.)
"""
def __init__(self, size: list[int], pixelType: int, numberOfComponents: int = 1):
"""
Create an N-dimensional image.
Args:
size: Size in each dimension [width, height, depth, ...]
pixelType: Pixel type
numberOfComponents: Components per pixel (1 for scalar, N for vector)
"""Usage example:
import SimpleITK as sitk
# Create 2D grayscale image
img_2d = sitk.Image(256, 256, sitk.sitkUInt8)
# Create 3D floating-point image
img_3d = sitk.Image(128, 128, 64, sitk.sitkFloat32)
# Create 3D RGB image (3 components per pixel)
img_rgb = sitk.Image([256, 256, 128], sitk.sitkVectorUInt8, 3)
# Create from size list
size = [512, 512, 200]
img = sitk.Image(size, sitk.sitkInt16)Query image dimensions and size.
def GetDimension(self) -> int:
"""
Get number of spatial dimensions.
Returns:
Number of dimensions (2, 3, or 4)
"""
def GetSize(self) -> tuple[int, ...]:
"""
Get image size in each dimension.
Returns:
Tuple of sizes (width, height, [depth, [time]])
"""
def GetWidth(self) -> int:
"""Get image width (size in X dimension)."""
def GetHeight(self) -> int:
"""Get image height (size in Y dimension)."""
def GetDepth(self) -> int:
"""
Get image depth (size in Z dimension).
Returns:
Depth for 3D/4D images, 0 for 2D images
"""
def GetNumberOfPixels(self) -> int:
"""
Get total number of pixels.
Returns:
Product of all dimension sizes
"""Query and describe the pixel data type.
def GetPixelID(self) -> int:
"""
Get pixel type ID (deprecated, use GetPixelIDValue).
Returns:
Pixel type enumeration value
"""
def GetPixelIDValue(self) -> int:
"""
Get pixel type ID.
Returns:
Pixel type (sitkUInt8, sitkFloat32, sitkVectorFloat64, etc.)
"""
def GetPixelIDTypeAsString(self) -> str:
"""
Get pixel type as string description.
Returns:
Human-readable pixel type name (e.g., "8-bit unsigned integer")
"""
def GetNumberOfComponentsPerPixel(self) -> int:
"""
Get number of components per pixel.
Returns:
1 for scalar images, N for vector/RGB images
"""Usage example:
import SimpleITK as sitk
image = sitk.ReadImage('example.nii.gz')
print(f"Dimensions: {image.GetDimension()}D")
print(f"Size: {image.GetSize()}")
print(f"Total pixels: {image.GetNumberOfPixels()}")
print(f"Pixel type: {image.GetPixelIDTypeAsString()}")
print(f"Components per pixel: {image.GetNumberOfComponentsPerPixel()}")Access and modify physical space information.
def GetOrigin(self) -> tuple[float, ...]:
"""
Get physical space origin.
The origin defines the physical coordinates of the image's first pixel
(index [0,0,0]).
Returns:
Origin coordinates in physical space (x, y, [z, [t]])
"""
def SetOrigin(self, origin: tuple[float, ...]) -> None:
"""
Set physical space origin.
Args:
origin: Origin coordinates, must match image dimension
"""
def GetSpacing(self) -> tuple[float, ...]:
"""
Get physical spacing between pixels.
Spacing defines the physical size of each pixel/voxel.
Returns:
Spacing in each dimension (dx, dy, [dz, [dt]])
"""
def SetSpacing(self, spacing: tuple[float, ...]) -> None:
"""
Set physical spacing between pixels.
Args:
spacing: Spacing values, must match image dimension
"""
def GetDirection(self) -> tuple[float, ...]:
"""
Get direction cosine matrix (flattened).
The direction matrix defines the orientation of the image axes in
physical space. For a 3D image, this is a 3x3 matrix flattened to
9 values in row-major order.
Returns:
Direction cosines as flattened tuple
"""
def SetDirection(self, direction: tuple[float, ...]) -> None:
"""
Set direction cosine matrix.
Args:
direction: Direction cosines (flattened matrix, row-major order)
"""
def CopyInformation(self, srcImage) -> None:
"""
Copy spatial metadata from another image.
Copies origin, spacing, and direction from source image. Useful after
processing with NumPy arrays.
Args:
srcImage: Source image to copy metadata from
"""Usage example:
import SimpleITK as sitk
image = sitk.ReadImage('ct_scan.nii')
# Get metadata
print(f"Origin: {image.GetOrigin()}")
print(f"Spacing: {image.GetSpacing()}")
print(f"Direction: {image.GetDirection()}")
# Modify spacing (e.g., resample to isotropic)
image.SetSpacing((1.0, 1.0, 1.0))
# Copy metadata to processed image
processed = sitk.GetImageFromArray(array)
processed.CopyInformation(image)Convert between index space and physical space.
def TransformIndexToPhysicalPoint(self, index: tuple[int, ...]) -> tuple[float, ...]:
"""
Transform pixel index to physical coordinates.
Uses origin, spacing, and direction to compute physical position.
Args:
index: Pixel index (x, y, [z, [t]])
Returns:
Physical coordinates
"""
def TransformPhysicalPointToIndex(self, point: tuple[float, ...]) -> tuple[int, ...]:
"""
Transform physical coordinates to pixel index.
Rounds to nearest integer index.
Args:
point: Physical coordinates
Returns:
Pixel index
"""
def TransformContinuousIndexToPhysicalPoint(self, index: tuple[float, ...]) -> tuple[float, ...]:
"""
Transform continuous (floating-point) index to physical coordinates.
Args:
index: Continuous pixel coordinates
Returns:
Physical coordinates
"""
def TransformPhysicalPointToContinuousIndex(self, point: tuple[float, ...]) -> tuple[float, ...]:
"""
Transform physical coordinates to continuous index.
Returns fractional pixel coordinates (useful for interpolation).
Args:
point: Physical coordinates
Returns:
Continuous index coordinates
"""Usage example:
import SimpleITK as sitk
image = sitk.ReadImage('mri.nii.gz')
# Get physical coordinates of a pixel
index = (64, 64, 32)
physical = image.TransformIndexToPhysicalPoint(index)
print(f"Pixel {index} is at physical location {physical}")
# Find nearest pixel for a physical coordinate
physical_point = (12.5, -8.3, 45.2)
pixel_index = image.TransformPhysicalPointToIndex(physical_point)
print(f"Physical point {physical_point} corresponds to pixel {pixel_index}")Read and write individual pixel values.
def GetPixel(self, *idx: int) -> float | tuple[float, ...]:
"""
Get pixel value at specified index.
For scalar images, returns single value.
For vector images, returns tuple of component values.
Args:
idx: Pixel indices (x, y, [z, [t]])
Returns:
Pixel value or tuple of values
"""
def SetPixel(self, *args) -> None:
"""
Set pixel value at specified index.
For scalar images: SetPixel(x, y, value) or SetPixel(x, y, z, value)
For vector images: SetPixel(x, y, tuple_of_values)
Args:
args: Indices followed by value(s) to set
"""
def __getitem__(self, idx):
"""
Get pixel value using bracket notation.
Args:
idx: Tuple of indices or single index
Returns:
Pixel value(s)
"""
def __setitem__(self, idx, value):
"""
Set pixel value using bracket notation.
Args:
idx: Tuple of indices or single index
value: Value to set
"""Usage example:
import SimpleITK as sitk
# Create and access pixels
image = sitk.Image(100, 100, sitk.sitkFloat32)
# Set pixel using method
image.SetPixel(50, 50, 255.0)
# Get pixel using method
value = image.GetPixel(50, 50)
# Use bracket notation (Python indexing)
image[50, 50] = 128.0
value = image[50, 50]
# For 3D images
image_3d = sitk.Image(100, 100, 50, sitk.sitkUInt16)
image_3d[25, 30, 10] = 1024Control image memory and uniqueness.
def MakeUnique(self) -> None:
"""
Force unique ownership of image buffer.
SimpleITK uses lazy copy-on-write. This method forces a deep copy
if the image buffer is shared. Called automatically before getting
NumPy views.
"""
def GetITKBase(self):
"""
Get underlying ITK image object.
Advanced usage: access the internal ITK image for low-level operations.
Returns:
ITK image pointer (use with caution)
"""Create independent copies of images.
def __copy__(self):
"""
Create shallow copy (shares pixel buffer).
Returns:
New Image object sharing data
"""
def __deepcopy__(self, memo):
"""
Create deep copy (independent pixel buffer).
Returns:
New Image object with copied data
"""Usage example:
import SimpleITK as sitk
import copy
original = sitk.ReadImage('input.png')
# Deep copy - independent data
independent = copy.deepcopy(original)
# Or use filter
independent = sitk.Image(original)Evaluate image intensity at non-integer (sub-pixel) coordinates using interpolation.
def EvaluateAtContinuousIndex(self, index: tuple[float, ...], interpolator: int = sitkLinear) -> float | tuple[float, ...]:
"""
Evaluate image at continuous (non-integer) index using interpolation.
Args:
index: Continuous index coordinates (can be fractional)
interpolator: Interpolation method (sitkLinear, sitkNearestNeighbor, etc.)
Returns:
Interpolated pixel value(s)
"""
def EvaluateAtPhysicalPoint(self, point: tuple[float, ...], interpolator: int = sitkLinear) -> float | tuple[float, ...]:
"""
Evaluate image at physical coordinates using interpolation.
Combines coordinate transformation and interpolation.
Args:
point: Physical coordinates
interpolator: Interpolation method
Returns:
Interpolated pixel value(s)
"""Usage example:
import SimpleITK as sitk
image = sitk.ReadImage('mri.nii')
# Evaluate at fractional pixel location
value = image.EvaluateAtContinuousIndex((64.5, 64.7, 32.3))
# Evaluate at physical coordinate
physical_value = image.EvaluateAtPhysicalPoint((12.5, -8.3, 45.2))Convert between vector and scalar representations.
def ToVectorImage(self) -> 'Image':
"""
Convert scalar image to vector image.
Creates a vector image with one component per pixel.
Returns:
Vector image representation
"""
def ToScalarImage(self) -> 'Image':
"""
Convert vector image to scalar image.
Only valid for single-component vector images.
Returns:
Scalar image representation
Raises:
RuntimeError: If image has more than one component per pixel
"""Compare spatial metadata between images.
def IsCongruentImageGeometry(self, other) -> bool:
"""
Check if two images have matching spatial geometry.
Compares size, origin, spacing, and direction within global tolerances.
Does not compare pixel data or pixel types.
Args:
other: Image to compare against
Returns:
True if geometries match within tolerances
"""Usage example:
import SimpleITK as sitk
fixed = sitk.ReadImage('fixed.nii')
moving = sitk.ReadImage('moving.nii')
if fixed.IsCongruentImageGeometry(moving):
# Images have compatible geometry, can operate directly
difference = fixed - moving
else:
# Need to resample first
print("Images have different geometries")Additional size query methods.
def GetSizeOfPixelComponent(self) -> int:
"""
Get size of each pixel component in bytes.
Returns:
Bytes per component (1 for UInt8, 4 for Float32, etc.)
"""Internal mechanism for efficient in-place operations (used by operators like +=).
def ProxyForInPlaceOperation(self):
"""
Get proxy for in-place operations.
Used internally by compound assignment operators (+=, -=, etc.).
Creates a writable view if the image buffer is shared.
Returns:
Proxy object for in-place modification
"""sitkUInt8 # 8-bit unsigned integer (0-255)
sitkInt8 # 8-bit signed integer (-128 to 127)
sitkUInt16 # 16-bit unsigned integer (0-65535)
sitkInt16 # 16-bit signed integer (-32768 to 32767)
sitkUInt32 # 32-bit unsigned integer
sitkInt32 # 32-bit signed integer
sitkUInt64 # 64-bit unsigned integer
sitkInt64 # 64-bit signed integersitkFloat32 # 32-bit floating point (single precision)
sitkFloat64 # 64-bit floating point (double precision)sitkComplexFloat32 # Complex number with 32-bit real and imaginary parts
sitkComplexFloat64 # Complex number with 64-bit real and imaginary partssitkVectorUInt8 # Vector of 8-bit unsigned integers
sitkVectorInt8 # Vector of 8-bit signed integers
sitkVectorUInt16 # Vector of 16-bit unsigned integers
sitkVectorInt16 # Vector of 16-bit signed integers
sitkVectorUInt32 # Vector of 32-bit unsigned integers
sitkVectorInt32 # Vector of 32-bit signed integers
sitkVectorUInt64 # Vector of 64-bit unsigned integers
sitkVectorInt64 # Vector of 64-bit signed integers
sitkVectorFloat32 # Vector of 32-bit floats (e.g., RGB float images)
sitkVectorFloat64 # Vector of 64-bit floatssitkLabelUInt8 # 8-bit labels (segmentation masks, up to 255 labels)
sitkLabelUInt16 # 16-bit labels (up to 65535 labels)
sitkLabelUInt32 # 32-bit labels
sitkLabelUInt64 # 64-bit labelssitkUnknown = -1 # Unknown or unspecified pixel typeimport SimpleITK as sitk
# Create image with specific metadata
image = sitk.Image([256, 256, 128], sitk.sitkInt16)
image.SetOrigin((-127.5, -127.5, -63.5))
image.SetSpacing((1.0, 1.0, 2.0))
# Identity direction (axial orientation)
image.SetDirection((1, 0, 0, 0, 1, 0, 0, 0, 1))import SimpleITK as sitk
image = sitk.ReadImage('scan.nii')
# Define a region of interest in physical coordinates
roi_center_physical = (50.0, 30.0, 40.0) # mm
roi_radius = 10.0 # mm
# Convert to index space
roi_center_index = image.TransformPhysicalPointToIndex(roi_center_physical)
# Calculate index bounds
spacing = image.GetSpacing()
radius_pixels = [int(roi_radius / s) for s in spacing]import SimpleITK as sitk
import numpy as np
# Read image
original = sitk.ReadImage('input.nii.gz')
# Process with NumPy
array = sitk.GetArrayFromImage(original)
processed_array = array * 2.0 # Some operation
# Create new image and copy metadata
result = sitk.GetImageFromArray(processed_array)
result.CopyInformation(original) # Preserve spatial metadata
sitk.WriteImage(result, 'output.nii.gz')Install with Tessl CLI
npx tessl i tessl/pypi-simpleitk