Source code for monai_physio.process_transforms
"""
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.
"""
import logging
from typing import Optional, Union, cast
import itk
import numpy as np
import pyvista as pv
import SimpleITK as sitk
import vtk
from scipy.ndimage import distance_transform_edt, map_coordinates
from .monai_physio_base import MONAIPhysioBase
from .process_images import ProcessImages
[docs]
class ProcessTransforms(MONAIPhysioBase):
"""
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)
"""
[docs]
def __init__(self, log_level: int | str = logging.INFO):
"""Initialize the ProcessTransforms class.
Args:
log_level: Logging level (default: logging.INFO)
"""
super().__init__(class_name=self.__class__.__name__, log_level=log_level)
[docs]
def combine_displacement_field_transforms(
self,
tfm1: itk.Transform,
tfm2: itk.Transform,
reference_image: itk.Image,
tfm1_weight: float = 1.0,
tfm2_weight: float = 1.0,
mode: str = "compose",
tfm1_blur_sigma: float = 0.0,
tfm2_blur_sigma: float = 0.0,
) -> itk.Transform:
"""
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.
"""
assert mode in ["add", "compose"], "Invalid mode"
if (
mode == "compose"
and tfm1_weight == 1.0
and tfm2_weight == 1.0
and tfm1_blur_sigma == 0.0
and tfm2_blur_sigma == 0.0
):
# A CompositeTransform chains its members lazily, so rasterizing
# them first only reproduces what it would compute anyway -- less
# accurately, because sampling onto *reference_image* and
# interpolating back introduces error that evaluating the originals
# does not.
#
# It is also what dominates memory here. The distance-map caller
# composes on a grid padded to 2.5 * mask_dilation_mm per side; on
# the lung chest CT that is 758 x 758 x 664, where one
# ``Vector<double, 3>`` field is 9.2 GB. Rasterizing both sides of
# both directions retained 36.6 GB and peaked far above that, to
# hold an affine and a 175-cubed field that together are under
# 130 MB.
#
# Weighting or blurring a transform genuinely needs its field, so
# those keep the path below.
passthrough_tfm = itk.CompositeTransform[itk.D, 3].New()
passthrough_tfm.AddTransform(tfm1)
passthrough_tfm.AddTransform(tfm2)
return passthrough_tfm
dtfm1 = self.convert_transform_to_displacement_field_transform(
tfm1, reference_image
)
dtfm2 = self.convert_transform_to_displacement_field_transform(
tfm2, reference_image
)
dfield1 = dtfm1.GetDisplacementField()
dfield2 = dtfm2.GetDisplacementField()
dfield1_arr = itk.array_from_image(dfield1)
dfield2_arr = itk.array_from_image(dfield2)
if tfm1_blur_sigma > 0.0:
for dim in range(dfield1.GetNumberOfComponentsPerPixel()):
tmp_field = dfield1_arr[:, :, :, dim]
tmp_image = itk.image_from_array(tmp_field)
tmp_image.CopyInformation(dfield1)
tmp_image = itk.smoothing_recursive_gaussian_image_filter(
tmp_image, Sigma=tfm1_blur_sigma
)
tmp_field = itk.array_from_image(tmp_image)
dfield1_arr[:, :, :, dim] = tmp_field
if tfm2_blur_sigma > 0.0:
for dim in range(dfield2.GetNumberOfComponentsPerPixel()):
tmp_field = dfield2_arr[:, :, :, dim]
tmp_image = itk.image_from_array(tmp_field)
tmp_image.CopyInformation(dfield2)
tmp_image = itk.smoothing_recursive_gaussian_image_filter(
tmp_image, Sigma=tfm2_blur_sigma
)
tmp_field = itk.array_from_image(tmp_image)
dfield2_arr[:, :, :, dim] = tmp_field
if mode == "add":
dfield_composed_arr = tfm1_weight * dfield1_arr + tfm2_weight * dfield2_arr
image_tools = ProcessImages()
dfield_composed = image_tools.convert_array_to_image_of_vectors(
dfield_composed_arr,
ptype=itk.D,
reference_image=dfield1,
)
new_tfm = itk.DisplacementFieldTransform[itk.D, 3].New()
new_tfm.SetDisplacementField(dfield_composed)
return new_tfm
# compose
image_tools = ProcessImages()
dfield1_arr = tfm1_weight * dfield1_arr
dfield2_arr = tfm2_weight * dfield2_arr
new_dfield1 = image_tools.convert_array_to_image_of_vectors(
dfield1_arr,
ptype=itk.D,
reference_image=dfield1,
)
new_dfield2 = image_tools.convert_array_to_image_of_vectors(
dfield2_arr,
ptype=itk.D,
reference_image=dfield2,
)
new_tfm1 = itk.DisplacementFieldTransform[itk.D, 3].New()
new_tfm1.SetDisplacementField(new_dfield1)
new_tfm2 = itk.DisplacementFieldTransform[itk.D, 3].New()
new_tfm2.SetDisplacementField(new_dfield2)
composite_tfm = itk.CompositeTransform[itk.D, 3].New()
composite_tfm.AddTransform(new_tfm1)
composite_tfm.AddTransform(new_tfm2)
return composite_tfm
[docs]
def convert_transform_to_displacement_field(
self,
tfm: itk.Transform,
reference_image: itk.image,
np_component_type: type[np.float32] | type[np.float64] = np.float64,
use_reference_image_as_mask: bool = False,
) -> itk.image:
"""
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.
Args:
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:
itk.image: Vector image where each voxel contains a displacement
vector [dx, dy, dz] in physical coordinates
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
... )
"""
# Handle case where tfm is a list (e.g., from itk.transformread)
if isinstance(tfm, (list, tuple)):
if len(tfm) == 1:
tfm = tfm[0]
else:
raise ValueError(
f"Expected single transform, got list with {len(tfm)} transforms"
)
TfmPrecision = itk.template(tfm)[1][0]
# Create and configure filter
field = None
if "DisplacementFieldTransform" not in str(type(tfm)):
field_filter = itk.TransformToDisplacementFieldFilter[
itk.Image[itk.Vector[itk.F, 3], 3], TfmPrecision
].New()
field_filter.SetTransform(tfm)
field_filter.SetReferenceImage(reference_image)
field_filter.SetUseReferenceImage(True)
field_filter.Update()
field = field_filter.GetOutput()
else:
field = tfm.GetDisplacementField()
field_arr = itk.array_view_from_image(tfm.GetDisplacementField())
reference_image_arr = itk.array_view_from_image(reference_image)
if field_arr.shape[:3] != reference_image_arr.shape:
field_filter = itk.TransformToDisplacementFieldFilter[
itk.Image[itk.Vector[itk.F, 3], 3], TfmPrecision
].New()
field_filter.SetTransform(tfm)
field_filter.SetReferenceImage(reference_image)
field_filter.SetUseReferenceImage(True)
field_filter.Update()
field = field_filter.GetOutput()
field_arr = itk.array_from_image(field)
field_arr = field_arr.astype(np_component_type)
image_tools = ProcessImages()
field = image_tools.convert_array_to_image_of_vectors(
field_arr,
ptype=np_component_type,
reference_image=reference_image,
)
if use_reference_image_as_mask:
mask = reference_image
field = itk.MaskImageFilter(field, mask)
return field
[docs]
def convert_transform_to_displacement_field_transform(
self, tfm: itk.Transform, reference_image: itk.Image
) -> itk.DisplacementFieldTransform:
"""
Convert an ITK transform to a displacement field transform.
"""
# TransformToDisplacementFieldFilter only supports float precision
# so we need to cast the transform to float and then convert
# to double since most other transform filters require double precision
field = self.convert_transform_to_displacement_field(
tfm, reference_image, np_component_type=np.float64
)
new_tfm = itk.DisplacementFieldTransform[itk.D, 3].New()
new_tfm.SetDisplacementField(field)
return new_tfm
[docs]
def invert_displacement_field_transform(
self,
tfm: itk.Transform,
max_iterations: int = 20,
max_error_tolerance: float = 0.05,
mean_error_tolerance: float = 0.0005,
) -> itk.Transform:
"""
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.
Args:
tfm: Displacement field transform to invert.
max_iterations: Fixed-point iterations per voxel.
max_error_tolerance: Convergence threshold on the maximum error, in
the field's units.
mean_error_tolerance: Convergence threshold on the mean error.
Returns:
The inverted displacement field transform.
"""
assert "DisplacementFieldTransform" in str(type(tfm)), (
"Input transform must be a displacement field transform"
)
image_tools = ProcessImages()
field_itk = tfm.GetDisplacementField()
field_sitk = image_tools.convert_itk_image_to_sitk(field_itk)
field_sitk_inv = sitk.InvertDisplacementField(
field_sitk,
maximumNumberOfIterations=max_iterations,
maxErrorToleranceThreshold=max_error_tolerance,
meanErrorToleranceThreshold=mean_error_tolerance,
)
field_itk_inv = image_tools.convert_sitk_image_to_itk(field_sitk_inv)
new_tfm = itk.DisplacementFieldTransform[itk.D, 3].New()
new_tfm.SetDisplacementField(field_itk_inv)
return new_tfm
[docs]
def invert_transform(
self, tfm: itk.Transform, reference_image: itk.Image
) -> itk.Transform:
"""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.
Args:
tfm (itk.Transform): Transform to invert.
reference_image (itk.Image): Grid used by the displacement-field
fallback.
Returns:
itk.Transform: The inverse transform.
"""
try:
analytic = tfm.GetInverseTransform()
except Exception: # noqa: BLE001 # pragma: no cover - transform type dependent
analytic = None
if analytic is not None:
return cast(itk.Transform, analytic)
return self.invert_displacement_field_transform(
self.convert_transform_to_displacement_field_transform(tfm, reference_image)
)
[docs]
def transform_pvcontour(
self,
contour: pv.PolyData,
tfm: itk.Transform,
with_deformation_magnitude: bool = False,
) -> pv.PolyData:
"""
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.
Args:
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:
pv.PolyData: The transformed contour mesh with updated point
coordinates and optionally deformation magnitude data
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']
"""
return cast(
pv.PolyData,
self.transform_dataset(
contour,
tfm,
with_deformation_magnitude=with_deformation_magnitude,
),
)
[docs]
def transform_dataset(
self,
mesh: pv.DataSet,
tfm: itk.Transform,
with_deformation_magnitude: bool = False,
) -> pv.DataSet:
"""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.
"""
new_mesh = mesh.copy(deep=True)
pnts = np.array(new_mesh.points, dtype=float)
# Handle case where tfm is a list (e.g., from itk.transformread)
if isinstance(tfm, (list, tuple)):
if len(tfm) == 1:
tfm = tfm[0]
else:
raise ValueError(
f"Expected single transform, got list with {len(tfm)} transforms"
)
new_pnts = self._transform_points(pnts, tfm)
new_mesh.points = new_pnts
if with_deformation_magnitude:
new_mesh.point_data["DeformationMagnitude"] = np.linalg.norm(
new_pnts - pnts, axis=1
)
return new_mesh
def _transform_points(self, points: np.ndarray, tfm: itk.Transform) -> np.ndarray:
"""Apply *tfm* to *points*, holding displacement fields at their edge.
Displacement fields are sampled here, with ITK's linear interpolation,
but clamped to their extent; every other transform is applied by ITK.
"""
name = tfm.GetNameOfClass()
precision = itk.template(tfm)[1][0]
if name == "CompositeTransform":
composite = itk.CompositeTransform[precision, 3].cast(tfm)
# ITK applies a composite's last-added transform first.
for index in reversed(range(composite.GetNumberOfTransforms())):
points = self._transform_points(
points, composite.GetNthTransform(index)
)
return points
if name == "DisplacementFieldTransform":
field = (
itk.DisplacementFieldTransform[precision, 3]
.cast(tfm)
.GetDisplacementField()
)
direction = itk.array_from_matrix(field.GetDirection())
# The array starts at the buffered region's index, not at 0.
continuous_index = (
(points - np.asarray(field.GetOrigin()))
[docs]
@ np.linalg.inv(direction).T
/ np.asarray(field.GetSpacing())
) - np.asarray(field.GetBufferedRegion().GetIndex())
# The field's array is indexed (z, y, x); "nearest" clamps.
coordinates = continuous_index[:, ::-1].T
displacement = itk.array_view_from_image(field)
return points + np.stack( # type: ignore[no-any-return]
[
map_coordinates(
displacement[..., axis], coordinates, order=1, mode="nearest"
)
for axis in range(3)
],
axis=1,
)
return np.array(
[tfm.TransformPoint([float(c) for c in point]) for point in points],
dtype=np.float64,
).reshape(-1, 3)
def transform_image(
self,
image: itk.image,
transform: itk.Transform,
reference_image: itk.image,
interpolation_method: str = "linear",
background_value: float = 0.0,
) -> itk.image:
"""
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.
Args:
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:
itk.image: The transformed image resampled to reference grid
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'
... )
"""
# Handle case where transform is a list (e.g., from itk.transformread)
if isinstance(transform, (list, tuple)):
if len(transform) == 1:
transform = transform[0]
else:
raise ValueError(
"Expected single transform or list with one transform, got list"
f"with {len(transform)} transforms"
)
interpolator = None
if interpolation_method == "linear":
interpolator = itk.LinearInterpolateImageFunction.New(image)
elif interpolation_method == "nearest":
interpolator = itk.NearestNeighborInterpolateImageFunction.New(image)
elif interpolation_method == "sinc":
interpolator = itk.WindowedSincInterpolateImageFunction.New(image)
else:
raise ValueError(f"Invalid transform type: {interpolation_method}")
# This shouldn't be needed, but for certain itk.CompositeTransform types,
# the resample_image_filter will silently fail and apply the identity
# transform instead of the one passed.
dftfm = self.convert_transform_to_displacement_field_transform(
transform, reference_image
)
# ITK's wrapping types DefaultPixelValue to the image's pixel type, and
# rejects a Python float for a discrete image.
dtype = itk.GetArrayViewFromImage(image).dtype
default_pixel_value: Union[int, float]
if np.issubdtype(dtype, np.integer) or np.issubdtype(dtype, np.bool_):
default_pixel_value = round(background_value)
low, high = (
(0, 1)
if np.issubdtype(dtype, np.bool_)
else (int(np.iinfo(dtype).min), int(np.iinfo(dtype).max))
)
if not low <= default_pixel_value <= high:
raise ValueError(
f"background_value {background_value} is outside the range "
f"[{low}, {high}] of the image's {dtype} pixel type"
)
else:
default_pixel_value = float(background_value)
img_reg = itk.resample_image_filter(
Input=image,
Transform=dftfm,
Interpolator=interpolator,
ReferenceImage=reference_image,
UseReferenceImage=True,
DefaultPixelValue=default_pixel_value,
)
return img_reg
[docs]
def convert_vtk_matrix_to_itk_transform(
self, vtk_mat: vtk.vtkMatrix4x4
) -> itk.Transform:
"""
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.
Args:
vtk_mat (itk.vtkMatrix): The input VTK transform to convert
Returns:
itk.Transform: The equivalent ITK transform
Example:
>>> # Convert VTK transform from mesh processing
>>> itk_transform = transform_tools.get_itk_transform_from_vtk_transform
vtk_transform)
"""
mat = np.eye(3).astype(np.float64)
vec = itk.Vector[itk.D, 3]()
for i in range(3):
vec[i] = vtk_mat.GetElement(i, 3)
for j in range(3):
mat[i, j] = vtk_mat.GetElement(i, j)
itkmat = itk.Matrix[itk.D, 3, 3](itk.GetVnlMatrixFromArray(mat))
itk_tfm = itk.AffineTransform[itk.D, 3].New()
itk_tfm.SetIdentity()
itk_tfm.SetMatrix(itkmat)
itk_tfm.SetOffset(vec)
return itk_tfm
[docs]
def smooth_transform(
self, tfm: itk.Transform, sigma: float, reference_image: itk.image
) -> itk.Transform:
"""
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.
Args:
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:
itk.Transform: DisplacementFieldTransform with smoothed
deformation field
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
... )
"""
field = self.convert_transform_to_displacement_field(tfm, reference_image)
field_arr = itk.array_from_image(field)
for dim in range(field.GetNumberOfComponentsPerPixel()):
tmp_field_arr = field_arr[:, :, :, dim]
tmp_image = itk.image_from_array(tmp_field_arr)
tmp_image.CopyInformation(field)
tmp_image = itk.smoothing_recursive_gaussian_image_filter(
tmp_image, Sigma=sigma
)
tmp_field_arr = itk.array_from_image(tmp_image)
field_arr[:, :, :, dim] = tmp_field_arr
image_tools = ProcessImages()
field = image_tools.convert_array_to_image_of_vectors(
field_arr,
ptype=itk.D,
reference_image=field,
)
tfm_smooth = itk.DisplacementFieldTransform[
itk.D, field.GetImageDimension()
].New()
tfm_smooth.SetDisplacementField(field)
return tfm_smooth
[docs]
def smooth_deformation_field_transform(
self,
field: itk.Image,
sigma: float,
weight_image: Optional[itk.Image] = None,
) -> itk.DisplacementFieldTransform:
"""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
:meth:`restrict_deformation_field_to_normal_falloff_outside_mask`.
Args:
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
:meth:`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:
itk.DisplacementFieldTransform: Smoothed field transform.
Raises:
ValueError: If the field holds no non-zero samples to spread.
"""
field_arr = itk.array_from_image(field).astype(np.float64)
if weight_image is not None:
weights = itk.array_from_image(weight_image).astype(np.float64)
else:
weights = (np.linalg.norm(field_arr, axis=3) > 0.0).astype(np.float64)
spread = np.zeros_like(field_arr)
for dim in range(field_arr.shape[3]):
spread[:, :, :, dim] = self._smooth_scalar_array(
field_arr[:, :, :, dim] * weights, sigma, field
)
smoothed_weights = self._smooth_scalar_array(weights, sigma, field)
# Add a floor to the denominator rather than clamping to it. ITK's
# recursive Gaussian is an IIR approximation, so far from every
# sample both smoothed arrays ring around zero; clamping a
# denominator that small turns that ringing into displacements
# several times larger than any the samples carried, while adding to
# it lets the quotient fall off to zero there, which is what a field
# with no nearby sample should do.
weight_floor = 1.0e-3 * float(smoothed_weights.max())
if weight_floor <= 0.0:
raise ValueError("Deformation field has no non-zero samples to spread.")
spread /= (np.maximum(smoothed_weights, 0.0) + weight_floor)[..., None]
smoothed_field = ProcessImages().convert_array_to_image_of_vectors(
spread, reference_image=field, ptype=itk.D
)
field_transform = itk.DisplacementFieldTransform[itk.D, 3].New()
field_transform.SetDisplacementField(smoothed_field)
return field_transform
@staticmethod
def _smoothstep(ramp: np.ndarray) -> np.ndarray:
"""Evaluate the cubic smoothstep ``3t^2 - 2t^3`` on ``ramp`` in ``[0, 1]``."""
return cast(np.ndarray, ramp * ramp * (3.0 - 2.0 * ramp))
[docs]
@staticmethod
def displaced_voxel_mask(field: itk.Image, threshold_mm: float = 0.01) -> itk.Image:
"""Mark the voxels a deformation field moves by more than ``threshold_mm``.
:meth:`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
:meth:`interior_distance_map`.
Args:
field (itk.Image): Vector deformation field, in millimeters.
threshold_mm (float): Displacement magnitude, in millimeters, a
voxel must exceed to be marked.
Returns:
itk.Image: Binary mask (1 = displaced) on ``field``'s grid.
"""
displacement = itk.array_from_image(field)
displaced = np.linalg.norm(displacement, axis=3) > threshold_mm
mask = itk.image_from_array(displaced.astype(np.uint8))
mask.CopyInformation(field)
return mask
[docs]
@staticmethod
def interior_distance_map(mask: itk.Image) -> itk.Image:
"""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
:meth:`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
(:meth:`displaced_voxel_mask`), it gives each stage the same boundary
at which displacement reaches zero.
Args:
mask (itk.Image): Binary or label image; any non-zero value is
inside.
Returns:
itk.Image: Float distance map on ``mask``'s grid.
Raises:
ValueError: If ``mask`` marks no voxel, or every voxel, which
leaves no edge to measure to.
"""
inside = itk.array_from_image(mask) > 0
if not inside.any():
raise ValueError("mask must mark at least one voxel.")
if inside.all():
raise ValueError(
"mask covers the whole grid, so it has no edge to measure to; "
"use a grid that extends past it."
)
binary = itk.image_from_array(inside.astype(np.uint8))
binary.CopyInformation(mask)
distance = itk.array_from_image(
itk.signed_maurer_distance_map_image_filter(
binary,
InsideIsPositive=True,
SquaredDistance=False,
UseImageSpacing=True,
)
)
distance_image = itk.image_from_array(
np.maximum(distance, 0.0).astype(np.float32)
)
distance_image.CopyInformation(mask)
return distance_image
[docs]
def restrict_deformation_field_to_normal_falloff_outside_mask(
self,
field: itk.Image,
mask: itk.Image,
*,
slip_layer_mm: float = 2.0,
normal_fade_ratio: float = 2.0,
zero_displacement_distance_map: Optional[itk.Image] = None,
) -> itk.DisplacementFieldTransform:
"""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
:meth:`displaced_voxel_mask` and :meth:`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;
:meth:`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.
Args:
field (itk.Image): Dense vector deformation field, e.g. the output
of :meth:`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: :meth:`interior_distance_map`
of the union of every stage's :meth:`displaced_voxel_mask`.
Omit to fade with ``normal_fade_ratio`` instead.
Returns:
itk.DisplacementFieldTransform: The restricted field transform.
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.
"""
for name, value in (
("slip_layer_mm", slip_layer_mm),
("normal_fade_ratio", normal_fade_ratio),
):
if not (np.isfinite(value) and value > 0.0):
raise ValueError(f"{name} must be finite and > 0, got {value}.")
field_size = field.GetLargestPossibleRegion().GetSize()
grid_images = [("mask", mask)]
if zero_displacement_distance_map is not None:
grid_images.append(
("zero_displacement_distance_map", zero_displacement_distance_map)
)
for name, grid_image in grid_images:
if (
grid_image.GetLargestPossibleRegion().GetSize() != field_size
or grid_image.GetSpacing() != field.GetSpacing()
or grid_image.GetOrigin() != field.GetOrigin()
or grid_image.GetDirection() != field.GetDirection()
):
raise ValueError(
f"{name} must lie on the field's grid (same size, spacing, "
"origin and direction)."
)
field_arr = itk.array_from_image(field).astype(np.float64)
mask_arr = itk.array_from_image(mask).astype(np.float64)
if mask_arr.shape != field_arr.shape[:3]:
raise ValueError(
f"mask {mask_arr.shape} must lie on the field's grid {field_arr.shape}."
)
inside = mask_arr > 0.5
if not inside.any():
raise ValueError("mask must mark at least one voxel.")
interior = itk.image_from_array(inside.astype(np.uint8))
interior.CopyInformation(mask)
outside = ~inside
signed_distance_mm = itk.array_from_image(
itk.signed_maurer_distance_map_image_filter(
interior,
InsideIsPositive=False,
SquaredDistance=False,
UseImageSpacing=True,
)
).astype(np.float64)
distance_mm = signed_distance_mm[outside]
del interior
# The mask voxel each outside voxel takes its displacement from: the
# nearest one, in physical distance.
spacing_mm = np.asarray(mask.GetSpacing(), dtype=np.float64)
nearest = distance_transform_edt(
outside,
sampling=spacing_mm[::-1],
return_distances=False,
return_indices=True,
)
boundary = tuple(axis[outside] for axis in nearest)
del nearest
boundary_field = field_arr[boundary]
# The mask's own outward normal, the gradient of its signed distance
# map, smoothed over a voxel so the voxel staircase does not tilt it.
# The split into normal and tangential motion happens at the mask's
# surface, so it uses that surface's normal rather than one spread
# from a separately fitted mesh.
smoothed_distance = self._smooth_scalar_array(
signed_distance_mm, spacing_mm, mask
)
del signed_distance_mm
# np.gradient returns d/dz, d/dy, d/dx; reversed, they run along the
# image's index axes (x, y, z), in millimeters.
gradient_index = np.stack(
np.gradient(smoothed_distance, *spacing_mm[::-1])[::-1], axis=-1
)
del smoothed_distance
boundary_normals = (
gradient_index[boundary] @ itk.array_from_matrix(mask.GetDirection()).T
)
del gradient_index
# Where the smoothed distance has no slope (a ridge of a thin mask),
# the normal is near zero. The direction from that boundary voxel to
# the outside voxel taking its displacement, in physical space, stands
# in for it.
normal_norm = np.linalg.norm(boundary_normals, axis=1)
unoriented = normal_norm < 1.0e-8
if unoriented.any():
offset_index = np.stack(
[
outside_axis[unoriented] - boundary_axis[unoriented]
for outside_axis, boundary_axis in zip(
np.nonzero(outside), boundary
)
],
axis=1,
)[:, ::-1].astype(np.float64)
direction = itk.array_from_matrix(mask.GetDirection())
boundary_normals[unoriented] = (offset_index * spacing_mm) @ direction.T
normal_norm[unoriented] = np.linalg.norm(
boundary_normals[unoriented], axis=1
)
del boundary
unit_normals = boundary_normals / normal_norm[:, None]
normal_part = (boundary_field * unit_normals).sum(
axis=1, keepdims=True
) * unit_normals
# The slip layer spans at least two grid steps along the normal, the
# step being the distance along the normal that crosses one voxel:
# 1 / |n / spacing|, with n expressed along the image's index axes.
index_normals = unit_normals @ itk.array_from_matrix(mask.GetDirection())
grid_step_mm = 1.0 / np.linalg.norm(index_normals / spacing_mm, axis=1)
slip_mm = np.maximum(slip_layer_mm, 2.0 * grid_step_mm)
del boundary_normals, unit_normals, index_normals, grid_step_mm
tangential_weight = 1.0 - self._smoothstep(
np.clip(distance_mm / slip_mm, 0.0, 1.0)
)
exterior = normal_part + tangential_weight[:, None] * (
boundary_field - normal_part
)
past_slip_mm = np.maximum(distance_mm - slip_mm, 0.0)
if zero_displacement_distance_map is None:
fade_mm = np.maximum(
normal_fade_ratio * np.linalg.norm(normal_part, axis=1),
float(spacing_mm.min()),
)
fade_fraction = np.clip(past_slip_mm / fade_mm, 0.0, 1.0)
else:
# The fraction of the way from the slip layer to the shared
# zero-displacement boundary, s / (s + D). It is 1 wherever D is
# zero -- on the boundary and beyond it, even inside the slip
# layer -- so nothing moves past the boundary.
to_boundary_mm = itk.array_from_image(zero_displacement_distance_map)[
outside
].astype(np.float64)
fade_fraction = np.divide(
past_slip_mm,
past_slip_mm + to_boundary_mm,
out=np.ones_like(past_slip_mm),
where=to_boundary_mm > 0.0,
)
del to_boundary_mm
del boundary_field, normal_part, tangential_weight, past_slip_mm, slip_mm
falloff_weight = 1.0 - self._smoothstep(np.clip(fade_fraction, 0.0, 1.0))
del fade_fraction
restricted = field_arr.copy()
restricted[outside] = falloff_weight[:, None] * exterior
del exterior, falloff_weight
# Neighboring outside voxels can take their displacement from distant
# parts of a concave boundary, a step between them. Averaging the
# outside over a voxel or so, from outside voxels only so the organ's
# own (tangential) motion does not leak out, removes those steps; the
# mask and its contents keep the field as it was.
# One voxel along each axis: a coarse axis keeps the averaging that
# removes those steps, and a fine axis is not blurred over many voxels,
# which would pull the first outside samples away from the restored
# interior and fold the field at the boundary.
sigma_mm = spacing_mm
outside_weight = self._smooth_scalar_array(
outside.astype(np.float64), sigma_mm, mask
)
outside_weight = np.maximum(outside_weight, 1.0e-6)
for axis in range(3):
restricted[..., axis] = (
self._smooth_scalar_array(
np.where(outside, restricted[..., axis], 0.0), sigma_mm, mask
)
/ outside_weight
)
del outside_weight
restricted[inside] = field_arr[inside]
del field_arr
restricted_field = ProcessImages().convert_array_to_image_of_vectors(
restricted, reference_image=field, ptype=itk.D
)
jacobian = itk.array_from_image(
self.compute_jacobian_determinant_from_field(restricted_field)
)
folded_voxels = int(np.count_nonzero(jacobian <= 0.0))
if folded_voxels:
self.log_warning(
"The restricted deformation field folds at %d voxels (minimum "
"Jacobian determinant %.3f); a warped image may show "
"duplicated or torn tissue there.",
folded_voxels,
float(jacobian.min()),
)
del jacobian
field_transform = itk.DisplacementFieldTransform[itk.D, 3].New()
field_transform.SetDisplacementField(restricted_field)
return field_transform
@staticmethod
def _smooth_scalar_array(
array: np.ndarray, sigma: Union[float, np.ndarray], reference_image: itk.Image
) -> np.ndarray:
"""Gaussian-smooth a scalar array on ``reference_image``'s grid.
The array is wrapped with the reference geometry before filtering, so
``sigma`` is in millimeters rather than in voxels: one value, or one per
axis in the image's (x, y, z) order.
"""
image = itk.image_from_array(np.ascontiguousarray(array))
image.CopyInformation(reference_image)
smoothed: np.ndarray = itk.array_from_image(
itk.smoothing_recursive_gaussian_image_filter(
image, SigmaArray=np.broadcast_to(sigma, (3,)).tolist()
)
)
return smoothed
[docs]
def compute_jacobian_determinant_from_field(self, field: itk.Image) -> itk.Image:
"""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.
Args:
field (itk.Image): Vector displacement field image
Returns:
itk.Image: Scalar image containing Jacobian determinant values
Example:
>>> jacobian = transform_tools.compute_jacobian_determinant_from_field(
deformation_field
)
"""
if "VF" not in str(type(field)):
field_arr = itk.array_from_image(field)
field = ProcessImages().convert_array_to_image_of_vectors(
field_arr, field, itk.F
)
jac_filter = itk.DisplacementFieldJacobianDeterminantFilter.New(field)
jac_filter.SetUseImageSpacing(True)
jac_filter.Update()
return jac_filter.GetOutput()
[docs]
def detect_folding_in_field(
self, jacobian_det: itk.Image, threshold: float = 0.1
) -> bool:
"""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.
Args:
jacobian_det (itk.Image): Jacobian determinant image
threshold (float): Threshold below which folding is detected
Returns:
bool: True if folding is detected, False otherwise
Example:
>>> if transform_tools.detect_folding_in_field(jacobian, 0.1):
... print('Spatial folding detected - transform needs correction')
"""
stats = itk.StatisticsImageFilter.New(jacobian_det)
stats.Update()
return float(stats.GetMinimum()) < threshold
[docs]
def generate_grid_image(
self, reference_image: itk.image, grid_size: int = 60, line_width: int = 3
) -> itk.image:
"""
Generate a grid image.
"""
img_arr = itk.array_from_image(reference_image)
img_arr_max = np.max(img_arr)
img_shape = list(img_arr.shape)
grid_spacing = [s / grid_size for s in img_shape]
if line_width <= 0:
line_width = 1
width_min = line_width // 2
width_max = width_min + line_width
for i in range(grid_size):
for j in range(grid_size):
min_idx0 = max(0, int(i * grid_spacing[0]) - width_min)
max_idx0 = min(img_arr.shape[0], int(i * grid_spacing[0]) + width_max)
min_idx1 = max(0, int(j * grid_spacing[1]) - width_min)
max_idx1 = min(img_arr.shape[1], int(j * grid_spacing[1]) + width_max)
if min_idx0 < max_idx0 and min_idx1 < max_idx1:
img_arr[min_idx0:max_idx0, min_idx1:max_idx1, :] = img_arr_max
min_idx2 = max(0, int(j * grid_spacing[2]) - width_min)
max_idx2 = min(img_arr.shape[2], int(j * grid_spacing[2]) + width_max)
if min_idx0 < max_idx0 and min_idx2 < max_idx2:
img_arr[min_idx0:max_idx0, :, min_idx2:max_idx2] = img_arr_max
min_idx1 = max(0, int(i * grid_spacing[1]) - width_min)
max_idx1 = min(img_arr.shape[1], int(i * grid_spacing[1]) + width_max)
if min_idx1 < max_idx1 and min_idx2 < max_idx2:
img_arr[:, min_idx1:max_idx1, min_idx2:max_idx2] = img_arr_max
grid_image = itk.image_from_array(img_arr)
grid_image.CopyInformation(reference_image)
return grid_image
[docs]
def convert_field_to_grid_visualization(
self,
tfm: itk.Transform,
reference_image: itk.image,
grid_size: int = 60,
line_width: int = 3,
) -> itk.image:
"""
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.
Args:
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:
itk.image: Binary image containing the transformed grid pattern
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
"""
grid_image = self.generate_grid_image(reference_image, grid_size, line_width)
grid_image_tfm = self.transform_image(grid_image, tfm, reference_image)
return grid_image_tfm