Transform Tools

Coordinate transformation and image warping utilities.

Module Reference

Tools for transforming and manipulating ITK transforms.

This module provides the ProcessTransforms class with utilities for working with ITK transforms, including transforming images and contours, generating deformation fields, interpolating between transforms, and detecting spatial folding artifacts.

The tools support various transform operations needed for medical image analysis, particularly in the context of 4D cardiac imaging where transforms are used to track anatomical motion over time.

class monai_physio.process_transforms.ProcessTransforms(log_level=20)[source]

Utilities for transforming and manipulating ITK transforms.

This class provides a comprehensive set of tools for working with ITK transforms in medical image analysis. It supports transforming various data types (images, contours), generating visualization aids, and performing advanced operations like transform interpolation and spatial folding detection.

The class is particularly useful for 4D cardiac imaging workflows where transforms are used to track anatomical motion over time, requiring operations like transform chaining, interpolation, and quality control.

Key capabilities: - Transform PyVista contours and ITK images - Generate deformation fields from transforms - Interpolate between transforms temporally - Smooth transforms to reduce noise - Detect spatial folding - Generate visualization grids

Example

>>> transform_tools = ProcessTransforms()
>>> # Transform a contour mesh
>>> transformed_contour = transform_tools.transform_pvcontour(
...     contour, transform, with_deformation_magnitude=True
... )
>>> # Generate deformation field
>>> field = transform_tools.generate_field(transform, reference_image)
__init__(log_level=20)[source]

Initialize the ProcessTransforms class.

Parameters:

log_level (int | str) – Logging level (default: logging.INFO)

combine_displacement_field_transforms(tfm1, tfm2, reference_image, tfm1_weight=1.0, tfm2_weight=1.0, mode='compose', tfm1_blur_sigma=0.0, tfm2_blur_sigma=0.0)[source]

Compose two displacement field transforms.

In add mode, returns a single displacement field transform with weighted summed vectors. In compose mode, returns a composite transform containing both weighted displacement field transforms.

compose follows ITK’s CompositeTransform convention, where the last-added transform is applied first: the result evaluates tfm1(tfm2(x)), so tfm2 is the stage that runs first.

In compose mode at unit weights with no blurring there is nothing to apply to the fields, so the inputs are chained as they are and no field is rasterized at all. See the comment on that branch below for what that saves.

Return type:

Transform

convert_transform_to_displacement_field(tfm, reference_image, np_component_type=<class 'numpy.float64'>, use_reference_image_as_mask=False)[source]

Generate a dense deformation field from an ITK transform.

Converts any ITK transform into a dense displacement field that explicitly stores the displacement vector at each voxel. This is useful for visualization, analysis, and storage of transforms.

Parameters:
  • tfm (itk.Transform) – Input transform to convert. Can be any ITK transform type (Affine, BSpline, DisplacementField, etc.)

  • reference_image (itk.image) – Defines the spatial grid for the output deformation field (spacing, size, origin, direction)

  • use_reference_image_as_mask (bool) – If True, applies the reference image as a mask to zero out displacement vectors outside the image domain

Returns:

Vector image where each voxel contains a displacement

vector [dx, dy, dz] in physical coordinates

Return type:

itk.image

Example

>>> # Generate deformation field for visualization
>>> field = transform_tools.generate_field(registration_transform,
    reference_ct)
>>> # Use as mask to limit field to anatomical regions
>>> masked_field = transform_tools.generate_field(
...     transform, reference_ct, use_reference_image_as_mask=True
... )
convert_transform_to_displacement_field_transform(tfm, reference_image)[source]

Convert an ITK transform to a displacement field transform.

Return type:

DisplacementFieldTransform

invert_displacement_field_transform(tfm, max_iterations=20, max_error_tolerance=0.05, mean_error_tolerance=0.0005)[source]

Invert a displacement field transform.

Uses SimpleITK’s fixed-point iterative inversion on the input field’s own grid. The defaults are tighter than SimpleITK’s own (10 iterations, 0.1 mm max error) because the fields produced here are not smooth everywhere and converge slowly near their support boundary.

Parameters:
  • tfm (Transform) – Displacement field transform to invert.

  • max_iterations (int) – Fixed-point iterations per voxel.

  • max_error_tolerance (float) – Convergence threshold on the maximum error, in the field’s units.

  • mean_error_tolerance (float) – Convergence threshold on the mean error.

Return type:

Transform

Returns:

The inverted displacement field transform.

invert_transform(tfm, reference_image)[source]

Invert any transform, analytically when the type supports it.

Prefers ITK’s analytic inverse (available for translation, rigid, affine and composites of them) and falls back to rasterizing a displacement field over reference_image and inverting that numerically.

The analytic inverse is preferred because the fallback is only defined on reference_image’s grid: outside it the field is zero, so the inverse silently degrades to the identity there.

Parameters:
  • tfm (itk.Transform) – Transform to invert.

  • reference_image (itk.Image) – Grid used by the displacement-field fallback.

Returns:

The inverse transform.

Return type:

itk.Transform

transform_pvcontour(contour, tfm, with_deformation_magnitude=False)[source]

Transform PyVista contour meshes using an ITK transform.

Applies an ITK transform to all points in a PyVista PolyData mesh, useful for deforming anatomical contours according to computed registration transforms. Optionally computes deformation magnitude at each point.

Parameters:
  • contour (pv.PolyData) – The input contour mesh to transform

  • tfm (itk.Transform) – ITK transform to apply. Can be a single transform or a list/array containing one transform

  • with_deformation_magnitude (bool) – If True, adds a “DeformationMagnitude” point data array containing the Euclidean distance each point moved

Returns:

The transformed contour mesh with updated point

coordinates and optionally deformation magnitude data

Return type:

pv.PolyData

Example

>>> # Transform cardiac contour with deformation tracking
>>> transformed_heart = transform_tools.transform_pvcontour(
...     heart_contour, cardiac_transform, with_deformation_magnitude=True
... )
>>> # Access deformation magnitudes
>>> deformation = transformed_heart['DeformationMagnitude']
transform_dataset(mesh, tfm, with_deformation_magnitude=False)[source]

Transform a PyVista dataset while preserving mesh topology and data arrays.

Applies an ITK point transform to every point in the input dataset and returns a deep copy with the original cells, cell data, and point data preserved. This is appropriate for non-contour datasets such as UnstructuredGrid inputs where casting to PolyData would lose topology.

A displacement field, alone or inside a composite, keeps its edge displacement beyond its extent. ITK’s own TransformPoint moves such points by nothing, which tears a mesh that runs past the edge of the image the field was registered on - a heart cut by the scan’s field of view, say - and inverts the elements across the tear.

Return type:

DataSet

transform_image(image, transform, reference_image, interpolation_method='linear', background_value=0.0)[source]

Transform an ITK image using a specified transform and interpolation.

Resamples an image according to a geometric transform, using the reference image to define the output grid properties. Different interpolation methods are available depending on data type and quality requirements.

Parameters:
  • image (itk.image) – The input image to transform

  • transform (itk.Transform) – The ITK transform to apply

  • reference_image (itk.image) – Defines output spacing, size, origin, and direction for the transformed image

  • interpolation_method (str) – Interpolation method. Options: - “linear”: Linear interpolation (default, good for CT/MR) - “nearest”: Nearest neighbor (preserves discrete values) - “sinc”: Sinc interpolation (highest quality, slower)

  • background_value (float) – Value written where the reference grid samples outside the input image. Default 0.0, which is right for labelmaps and masks; intensity images need the value that means “no tissue” in their own units – for CT that is -1000 HU (air), not 0 HU (water).

Returns:

The transformed image resampled to reference grid

Return type:

itk.image

Raises:

ValueError – If interpolation_method is not one of the supported options

Example

>>> # Transform CT image with linear interpolation
>>> warped_ct = transform_tools.transform_image(
...     ct_image, deformation_transform, reference_ct
... )
>>> # Transform label map preserving discrete values
>>> warped_labels = transform_tools.transform_image(
...     labelmap, transform, reference, interpolation_method='nearest'
... )
convert_vtk_matrix_to_itk_transform(vtk_mat)[source]

Convert a VTK matrix to an ITK transform.

Converts a VTK matrix object into an equivalent ITK transform. This is useful for interoperability between VTK-based processing (e.g., mesh manipulation) and ITK-based image processing and registration.

Parameters:

vtk_mat (itk.vtkMatrix) – The input VTK transform to convert

Returns:

The equivalent ITK transform

Return type:

itk.Transform

Example

>>> # Convert VTK transform from mesh processing
>>> itk_transform = transform_tools.get_itk_transform_from_vtk_transform
    vtk_transform)
smooth_transform(tfm, sigma, reference_image)[source]

Smooth a transform using Gaussian filtering to reduce noise.

Applies Gaussian smoothing to the displacement field representation of a transform to reduce noise and create more regularized deformations. This is useful for improving transform quality and reducing artifacts.

Parameters:
  • tfm (itk.Transform) – Input transform to smooth

  • sigma (float) – Standard deviation of Gaussian smoothing kernel in physical units (millimeters). Larger values create more smoothing

  • reference_image (itk.image) – Defines spatial grid for field generation and smoothing

Returns:

DisplacementFieldTransform with smoothed

deformation field

Return type:

itk.Transform

Example

>>> # Smooth noisy registration transform
>>> smooth_transform = transform_tools.smooth_transform(
...     noisy_transform, sigma=2.0, reference_ct
... )
>>> # Light smoothing for artifact reduction
>>> refined_transform = transform_tools.smooth_transform(
...     transform, sigma=0.5, reference_image
... )
smooth_deformation_field_transform(field, sigma, weight_image=None)[source]

Spread a sparsely sampled deformation field into a continuous one.

field is treated as a weighted set of displacement samples rather than as an image: the weighted samples and their weights are each Gaussian-smoothed by sigma (physical millimeters) and then divided, which is a Gaussian-weighted average of the nearby samples. A thin surface shell therefore becomes a continuous deformation that keeps the displacement magnitude the samples carried, instead of being diluted by the empty voxels a plain blur would average in. Far from every sample the smoothed weight vanishes and the field decays to zero.

This spread is isotropic and carries the whole displacement vector outward. To restrict that spread to an organ’s surface normal beyond a mask – e.g. so a slip interface such as the pleura or the pericardium does not drag surrounding tissue along tangentially – smooth first with this method, then pass the result to restrict_deformation_field_to_normal_falloff_outside_mask().

Parameters:
  • field (itk.Image) – Input vector deformation field, sampled where weight_image is non-zero.

  • sigma (float) – Standard deviation of the Gaussian smoothing kernel in physical units (millimeters).

  • weight_image (Optional[itk.Image]) – Per-voxel sample weight, such as the vertex count WorkflowInferMovement.create_deformation_field() returns. Omit to weight every voxel holding a non-zero displacement equally, which cannot tell an empty voxel from a genuinely zero-displacement one.

Returns:

Smoothed field transform.

Return type:

itk.DisplacementFieldTransform

Raises:

ValueError – If the field holds no non-zero samples to spread.

static displaced_voxel_mask(field, threshold_mm=0.01)[source]

Mark the voxels a deformation field moves by more than threshold_mm.

restrict_deformation_field_to_normal_falloff_outside_mask() ends by averaging the field outside its mask over about one voxel, so its displacement does not stop exactly where its fade does but decays over about one more voxel. threshold_mm sets where that decay is cut, so a mask of a restricted field reaches about one voxel past the fade. Combine the masks of several stages and pass the union to interior_distance_map().

Parameters:
  • field (itk.Image) – Vector deformation field, in millimeters.

  • threshold_mm (float) – Displacement magnitude, in millimeters, a voxel must exceed to be marked.

Returns:

Binary mask (1 = displaced) on field’s grid.

Return type:

itk.Image

static interior_distance_map(mask)[source]

Distance, in millimeters, from each voxel of mask to the mask’s edge.

ITK’s signed Maurer distance map, inside positive and clipped at zero: the mask voxels on its edge and every voxel outside it are zero. It is the same map restrict_deformation_field_to_normal_falloff_outside_mask() measures distance beyond its own mask with, so both measure to the same edge.

Used with that method’s zero_displacement_distance_map: built from the union of the voxels every stage displaces (displaced_voxel_mask()), it gives each stage the same boundary at which displacement reaches zero.

Parameters:

mask (itk.Image) – Binary or label image; any non-zero value is inside.

Returns:

Float distance map on mask’s grid.

Return type:

itk.Image

Raises:

ValueError – If mask marks no voxel, or every voxel, which leaves no edge to measure to.

restrict_deformation_field_to_normal_falloff_outside_mask(field, mask, *, slip_layer_mm=2.0, normal_fade_ratio=2.0, zero_displacement_distance_map=None)[source]

Restrict a dense field to its normal component and fade it outside a mask.

Inside mask the field passes through unchanged, so an organ’s own contents still follow its surface. Beyond it, only the component of the displacement along the surface normal is kept – the expansion and contraction, not the tangential sliding – which is how a slip interface such as the pleura or the pericardium behaves: surrounding tissue is pushed and pulled by the organ without being dragged along it.

Across a slip layer just outside the mask the tangential motion fades to zero, so the field stays continuous at the organ’s surface. The layer is slip_layer_mm thick, but at least two voxels along the local surface normal, so that on a coarse grid the sliding still fades over more than a single voxel step. The normal is the mask’s own: the gradient of its signed distance map, smoothed over a voxel, at the mask voxel nearest each outside voxel. The normal component is kept whole across that layer and then fades to zero over normal_fade_ratio times the normal displacement of the nearest surface point (at least one voxel), so the push reaches only about as far as the organ moves.

The fade is a smoothstep, whose steepest slope is 1.5 times its mean. A flat push faded over normal_fade_ratio times its own size therefore changes the thickness of a tissue layer by up to 1.5 / normal_fade_ratio: the smallest Jacobian determinant is about 1 - 1.5 / normal_fade_ratio. The default 2 keeps at least a quarter of every layer while keeping the push local; a ratio of 1.5 crushes a layer to nothing, and a smaller one folds the field.

With zero_displacement_distance_map the normal fade instead ends on a boundary shared by every stage of a time series: the edge of the union of the voxels each stage displaces under the rule above (see displaced_voxel_mask() and interior_distance_map()). At an outside voxel s millimeters past the slip layer and D millimeters inside that boundary, the normal component is weighted by 1 - smoothstep(s / (s + D)): whole at the slip layer and zero from the boundary on, including any part of the slip layer that lies beyond it. Each stage then fades over the same region, however far it moves itself. Build the map with the same mask frame, grid and slip layer as this call; WorkflowInferMovement.process_time_series() does so itself when given shared_fade_boundary=True.

Outside the mask the field is built from the mask boundary alone: each voxel takes the displacement of its nearest mask voxel, drops its tangential component across the slip layer, and fades the remaining normal component with its distance beyond it. field is therefore read only on and inside the mask, never in the far tail of a spread field, where a sparse Gaussian spread is least reliable. That outside field is then averaged over one voxel along each axis, from outside voxels only, so that neighbors taking their displacement from distant parts of a concave boundary do not step against each other. The averaging also lets a small tail of displacement, a few percent of the push, reach about one voxel past where the fade itself ends.

Resampling an image reads it at x + u(x), so a field pointing outward makes the organ shrink in the warped image and compresses the tissue the fade spans. A slip much larger than the slip layer, or a normal_fade_ratio of 1.5 or less, can fold the field near the boundary; a warning giving the number of folded voxels is logged when it does.

Parameters:
  • field (itk.Image) – Dense vector deformation field, e.g. the output of smooth_deformation_field_transform() (.GetDisplacementField()).

  • mask (itk.Image) – Binary or label image on field’s grid; any non-zero value marks the organ’s interior.

  • slip_layer_mm (float) – Thickness, in millimeters, of the slip layer outside the mask across which the tangential motion fades out: about 2 mm for the pleura or the pericardium. Widened to two voxels along the local normal where the grid is coarser than that.

  • normal_fade_ratio (float) – Length of the normal fade beyond the slip layer, per millimeter of the nearest surface point’s normal displacement; no displacement remains past it. A flat push keeps a Jacobian determinant of about 1 - 1.5 / normal_fade_ratio. Ignored when zero_displacement_distance_map is given.

  • zero_displacement_distance_map (Optional[itk.Image]) – Distance, in millimeters, from each voxel to the boundary at which the normal displacement reaches zero, positive inside it and zero outside, on field’s grid: interior_distance_map() of the union of every stage’s displaced_voxel_mask(). Omit to fade with normal_fade_ratio instead.

Returns:

The restricted field transform.

Return type:

itk.DisplacementFieldTransform

Raises:

ValueError – If mask or zero_displacement_distance_map does not lie on field’s grid (size, spacing, origin, direction), if slip_layer_mm or normal_fade_ratio is not a finite value greater than zero, or if mask is empty.

compute_jacobian_determinant_from_field(field)[source]

Compute Jacobian determinant of a displacement field.

Calculates the Jacobian determinant at each voxel of a displacement field, which indicates local volume change. Values less than 0 indicate spatial folding, values between 0-1 indicate compression, and values greater than 1 indicate expansion.

Parameters:

field (itk.Image) – Vector displacement field image

Returns:

Scalar image containing Jacobian determinant values

Return type:

itk.Image

Example

>>> jacobian = transform_tools.compute_jacobian_determinant_from_field(
        deformation_field
    )
detect_folding_in_field(jacobian_det, threshold=0.1)[source]

Detect spatial folding in a transform.

Checks for spatial folding by examining the minimum Jacobian determinant value. Folding occurs when the Jacobian determinant becomes negative or very small, indicating non-invertible regions.

Parameters:
  • jacobian_det (itk.Image) – Jacobian determinant image

  • threshold (float) – Threshold below which folding is detected

Returns:

True if folding is detected, False otherwise

Return type:

bool

Example

>>> if transform_tools.detect_folding_in_field(jacobian, 0.1):
...     print('Spatial folding detected - transform needs correction')
generate_grid_image(reference_image, grid_size=60, line_width=3)[source]

Generate a grid image.

Return type:

image

convert_field_to_grid_visualization(tfm, reference_image, grid_size=60, line_width=3)[source]

Generate a visual deformation grid for transform visualization.

Creates a regular grid pattern in the reference image space, then applies the transform to visualize the deformation. The resulting warped grid shows how the transform deforms space and can reveal areas of compression, expansion, or folding.

Parameters:
  • tfm (itk.Transform) – Transform to visualize

  • reference_image (itk.image) – Defines spatial domain and grid properties

  • grid_size (int) – Number of grid lines in each dimension

Returns:

Binary image containing the transformed grid pattern

Return type:

itk.image

Example

>>> # Create deformation visualization grid
>>> grid = transform_tools.convert_field_to_grid_visualization(
...     cardiac_transform, reference_ct, grid_size=20
... )
>>> # Overlay on original image for visualization

Navigation

Image Tools | Utility Modules | Surface Mesh Tools