RigidITK#

class medicalimageanalysis.utils.rigid.simpleitk.RigidITK(reference_image=None, moving_image=None, reference_mask=None, moving_mask=None)[source]

Bases: object

Rigid registration between a reference (fixed) and moving image, with optional masks.

This is intentionally smaller than the deformable helper: one main registration method covers the common rigid use cases, while a couple of utility methods convert the result to a resampled image or displacement field.

Parameters:
  • reference_image (SimpleITK.Image, optional) – Fixed image. Its grid defines the registration domain.

  • moving_image (SimpleITK.Image, optional) – Image to be registered onto the reference.

  • reference_mask (SimpleITK.Image, optional) – Region of interest on the reference image. Any nonzero voxel is treated as inside.

  • moving_mask (SimpleITK.Image, optional) – Region of interest on the moving image. Any nonzero voxel is treated as inside.

Examples

>>> import numpy as np
>>> fixed = np.zeros((16, 32, 32), dtype=np.float32)
>>> fixed[4:12, 8:24, 8:24] = 100
>>> helper = RigidITK()
>>> _ = helper.create_sitk_image(fixed, (0, 0, 0), (1, 1, 2), np.eye(3))
>>> _ = helper.create_sitk_image(np.roll(fixed, 2, axis=2), (0, 0, 0), (1, 1, 2), np.eye(3), reference=False)
>>> helper.reference_image.GetSize()
(32, 32, 16)
static distance_map(mask, band=None)[source]

Signed Euclidean distance map of a binary mask, in physical units.

Negative inside, positive outside, zero on the boundary. Clamping to band keeps far-away voxels from dominating the metric while still giving a smooth gradient everywhere within band of the surface.

Parameters:
  • mask (SimpleITK.Image) – Binary mask (nonzero = inside).

  • band (float, optional) – Clamp distances to [-band, band] (mm). None leaves them unclamped.

Returns:

Float32 signed distance map on the mask grid.

Return type:

SimpleITK.Image

Examples

>>> import numpy as np
>>> import SimpleITK as sitk
>>> array = np.zeros((16, 32, 32), dtype=np.uint8)
>>> array[4:12, 8:24, 8:24] = 1
>>> distance = RigidITK.distance_map(sitk.GetImageFromArray(array), band=5)
>>> values = sitk.GetArrayViewFromImage(distance)
>>> float(values.min()), float(values.max()), bool(values[8, 16, 16] < 0)
(-3.0, 5.0, True)
static landmark_error(transform, reference_points, moving_points)[source]

Distance between transformed reference landmarks and their moving partners.

On landmarks used in landmark() this is the fiducial registration error; on landmarks left out of the fit (or for a transform from rigid() / rigid_mask()) it is the target registration error.

Parameters:
  • transform (SimpleITK.Transform) – Transform mapping reference points to the moving image.

  • reference_points ((N, D) array_like) – Paired physical points in (x, y, z) order.

  • moving_points ((N, D) array_like) – Paired physical points in (x, y, z) order.

Returns:

Euclidean error per landmark, in physical units.

Return type:

(N,) ndarray

Examples

>>> import SimpleITK as sitk
>>> transform = sitk.Euler3DTransform((0, 0, 0), 0, 0, 0, (1, 0, 0))
>>> RigidITK.landmark_error(transform, [[0, 0, 0], [5, 5, 5]], [[1, 0, 0], [6, 5, 8]]).tolist()
[0.0, 3.0]
create_sitk_image(array, origin, spacing, direction, reference=True, mask=False)[source]

Convert a NumPy array to a SimpleITK image and store it as the reference/moving image or mask.

Parameters:
  • array (numpy.ndarray) – Volume indexed (z, y, x).

  • origin (sequence of float) – Physical position of voxel (0, 0, 0), in (x, y, z) order.

  • spacing (sequence of float) – Voxel size in (x, y, z) order.

  • direction (numpy.ndarray) – 3x3 direction cosine matrix whose columns are the x, y, z axis directions.

  • reference (bool, default True) – Store as reference (True) or moving (False).

  • mask (bool, default False) – Store as a mask. Masks are binarized (nonzero = inside) and cast to sitkUInt8.

Returns:

The created (and stored) image.

Return type:

SimpleITK.Image

Examples

>>> import numpy as np
>>> helper = RigidITK()
>>> image = helper.create_sitk_image(np.zeros((16, 32, 32), dtype=np.float32), (0, 0, 0), (1, 1, 2), np.eye(3))
>>> image.GetSize(), image.GetSpacing()
((32, 32, 16), (1.0, 1.0, 2.0))
>>> mask = helper.create_sitk_image(np.ones((16, 32, 32)), (0, 0, 0), (1, 1, 2), np.eye(3), mask=True)
>>> mask.GetPixelIDTypeAsString()
'8-bit unsigned integer'
cross_modality_correction(image)[source]

Return the gradient magnitude of an image to reduce intensity differences between modalities.

For multimodal rigid registration, prefer metric='MI' or metric='JointMI' in rigid(); this is mainly useful when rigid alignment still benefits from edge-based matching. A recursive Gaussian version is used so the gradients are less noise-sensitive than a plain voxelwise gradient magnitude.

Parameters:

image (SimpleITK.Image) – Input image.

Returns:

Float32 gradient magnitude image.

Return type:

SimpleITK.Image

Examples

>>> import SimpleITK as sitk
>>> helper = RigidITK()
>>> gradient = helper.cross_modality_correction(sitk.Image(32, 32, 16, sitk.sitkFloat32))
>>> gradient.GetPixelIDTypeAsString()
'32-bit float'
index_to_physical(indices, reference=True)[source]

Convert (z, y, x) voxel indices to physical (x, y, z) points using the reference or moving image.

Continuous (fractional) indices are allowed, so sub-voxel landmark positions are kept.

Parameters:
  • indices ((N, D) array_like) – Voxel indices in NumPy (z, y, x) order.

  • reference (bool, default True) – Use the reference image geometry (True) or the moving image geometry (False).

Returns:

Physical points in (x, y, z) order.

Return type:

(N, D) ndarray

Examples

>>> import numpy as np
>>> helper = RigidITK()
>>> _ = helper.create_sitk_image(np.zeros((16, 32, 32), dtype=np.float32), (10, 0, 0), (1, 1, 2), np.eye(3))
>>> helper.index_to_physical([[3, 2, 1]]).tolist()
[[11.0, 2.0, 6.0]]
landmark(reference_points, moving_points, transform='Euler', weights=None, return_info=False)[source]

Closed-form rigid registration from paired landmarks (weighted Kabsch / Horn).

No images are needed. Each row of reference_points is paired with the same row of moving_points, and the least-squares rotation and translation are solved with an SVD, with the reflection case removed so the result is always a proper rotation. The result can be used directly or passed as initial_transform to rigid() or rigid_mask().

Parameters:
  • reference_points ((N, D) array_like) – Physical landmark positions in the reference image, (x, y, z) order.

  • moving_points ((N, D) array_like) – Matching physical landmark positions in the moving image, same order as reference_points.

  • transform ({'Euler', 'Versor'}, default 'Euler') – Rigid transform family of the returned transform.

  • weights ((N,) array_like, optional) – Non-negative per-landmark weights, e.g. lower for landmarks that are hard to localize. None weights all landmarks equally.

  • return_info (bool, default False) – Return a diagnostics dictionary along with the transform.

Returns:

Rigid transform mapping reference points to moving points (the same convention as rigid()), centered on the weighted reference centroid. If return_info=True, returns (transform, info) where info holds the fiducial registration error: 'fre_rms', 'fre_max' and the per-point 'residuals'.

Return type:

SimpleITK.Transform or tuple

Raises:

ValueError – If the point arrays do not match, there are too few points, or the reference points are collinear (the rotation about that line is undetermined).

Notes

The fiducial registration error (FRE) measures how well the landmarks used in the fit agree with each other. It is not an accuracy estimate for the rest of the anatomy; use landmark_error() on landmarks that were left out of the fit (target registration error) for that.

Examples

>>> import numpy as np
>>> rng = np.random.default_rng(0)
>>> reference = rng.uniform(0, 100, (6, 3))
>>> angle = np.radians(10)
>>> rotation = np.array([[np.cos(angle), -np.sin(angle), 0], [np.sin(angle), np.cos(angle), 0], [0, 0, 1]])
>>> moving = reference @ rotation.T + (5, -3, 2)
>>> helper = RigidITK()
>>> transform, info = helper.landmark(reference, moving, return_info=True)
>>> np.allclose(transform.TransformPoint(reference[0].tolist()), moving[0])
True
>>> info['fre_rms'] < 1e-6
True
resample(image, reference, mask=False, transform=None, default_value=None)[source]

Resample an image onto the grid of a reference image.

Parameters:
  • image (SimpleITK.Image) – Image to resample.

  • reference (SimpleITK.Image) – Image defining the output grid.

  • mask (bool, default False) – Use nearest-neighbor interpolation and return a binary sitkUInt8 image.

  • transform (SimpleITK.Transform, optional) – Transform from the reference grid to image. None uses the identity transform.

  • default_value (float, optional) – Fill value outside the moving image domain. None uses 0 for masks and the image minimum otherwise.

Returns:

Resampled image on the reference grid.

Return type:

SimpleITK.Image

Examples

>>> import SimpleITK as sitk
>>> helper = RigidITK()
>>> reference = sitk.Image(32, 32, 16, sitk.sitkFloat32)
>>> moving = sitk.Image(64, 64, 32, sitk.sitkFloat32)
>>> moving.SetSpacing((0.5, 0.5, 0.5))
>>> helper.resample(moving, reference).GetSize()
(32, 32, 16)
resample_moving(transform, interpolator='linear', default_value=None)[source]

Resample the moving image onto the reference grid with a rigid transform.

Parameters:
  • transform (SimpleITK.Transform) – Transform mapping reference points to the moving image.

  • interpolator ({'linear', 'nearest'}, default 'linear') – Interpolation used for the moving image.

  • default_value (float, optional) – Fill value outside the moving image domain. None uses the moving-image minimum.

Returns:

Moving image resampled onto the reference grid.

Return type:

SimpleITK.Image

Examples

>>> import numpy as np
>>> helper = RigidITK()
>>> fixed = np.zeros((16, 32, 32), dtype=np.float32)
>>> fixed[4:12, 8:24, 8:24] = 1
>>> _ = helper.create_sitk_image(fixed, (0, 0, 0), (1, 1, 2), np.eye(3))
>>> _ = helper.create_sitk_image(np.roll(fixed, 2, axis=2), (0, 0, 0), (1, 1, 2), np.eye(3), reference=False)
>>> transform = helper.rigid(sampling=1.0, iterations=50)
>>> aligned = helper.resample_moving(transform)
>>> aligned.GetSize()
(32, 32, 16)
rigid(transform='Euler', initializer='Geometry', metric='Intensity', bins=32, radius=2, sampling=0.1, iterations=200, learning_rate=2.0, min_step=0.0001, relaxation=0.5, shrink_factors=(4, 2, 1), smoothing_sigmas=(2, 1, 0), cross_modality=False, normalize=False, histogram_match=False, initial_transform=None, return_info=False)[source]

Rigid registration with sitk.ImageRegistrationMethod.

This method stays intentionally opinionated: the transform is rigid, the optimizer is regular-step gradient descent, and the main choices exposed are the metric, initializer and multi-resolution settings.

Parameters:
  • transform ({'Euler', 'Versor'}, default 'Euler') – Rigid transform family. ‘Versor’ is available only for 3D images.

  • initializer ({'Geometry', 'Moments'}, default 'Geometry') – How the initial transform center and translation are estimated. ‘Moments’ is intensity-weighted and can be unreliable on raw CT because large air regions dominate the moment calculation. Ignored when initial_transform is given.

  • metric ({'Intensity', 'Correlation', 'ANTS', 'MI', 'JointMI'}, default 'Intensity') – Similarity metric. ‘Intensity’ = mean squares, ‘Correlation’ = global correlation, ‘ANTS’ = local neighborhood correlation, ‘MI’/’JointMI’ = mutual information for multimodal cases.

  • bins (int, default 32) – Histogram bins for ‘MI’ and ‘JointMI’.

  • radius (int, default 2) – Neighborhood radius in voxels for ‘ANTS’.

  • sampling (float, default 0.1) – Fraction of voxels randomly sampled for the metric. 1.0 uses every voxel. With very small masks, a larger value may be needed because only samples inside the mask contribute to the metric.

  • iterations (int, default 200) – Maximum regular-step gradient descent iterations.

  • learning_rate (float, default 2.0) – Initial optimizer step size, in physical units.

  • min_step (float, default 1e-4) – Smallest optimizer step before convergence is declared.

  • relaxation (float, default 0.5) – Factor used to reduce the step size when the optimizer changes direction.

  • shrink_factors (sequence of int, default (4, 2, 1)) – Image downsampling per level.

  • smoothing_sigmas (sequence of float, default (2, 1, 0)) – Gaussian image smoothing per level, in mm.

  • cross_modality (bool, default False) – Register gradient magnitude images instead of raw intensities.

  • normalize (bool, default False) – Percentile-normalize both images to [0, 1] (see _prepare()).

  • histogram_match (bool, default False) – Histogram-match the moving image to the reference before optimization.

  • initial_transform (SimpleITK.Transform, optional) – Rigid starting transform, e.g. the result of landmark() or rigid_mask(). It is copied, so the object passed in is not modified.

  • return_info (bool, default False) – Return a small diagnostics dictionary along with the transform.

Returns:

Rigid transform mapping points from the reference image to the moving image. If return_info=True, returns (transform, info) where info contains the final metric value, stop condition and number of iterations.

Return type:

SimpleITK.Transform or tuple

Examples

>>> import numpy as np
>>> z, y, x = np.mgrid[:16, :32, :32]
>>> fixed = (100 * np.exp(-((x - 16) ** 2 + (y - 16) ** 2) / 40 - (z - 8) ** 2 / 10)).astype(np.float32)
>>> helper = RigidITK()
>>> _ = helper.create_sitk_image(fixed, (0, 0, 0), (1, 1, 2), np.eye(3))
>>> _ = helper.create_sitk_image(np.roll(fixed, 2, axis=2), (0, 0, 0), (1, 1, 2), np.eye(3), reference=False)
>>> transform = helper.rigid(sampling=1.0, iterations=50)
>>> round(float(transform.GetTranslation()[0]))
2
rigid_mask(transform='Euler', initializer='Moments', band=20.0, sampling=0.25, iterations=200, learning_rate=2.0, min_step=0.0001, relaxation=0.5, shrink_factors=(4, 2, 1), smoothing_sigmas=(2, 1, 0), reference_mask=None, moving_mask=None, initial_transform=None, return_info=False)[source]

Rigid registration of two binary masks through their signed distance maps.

The images are not used, only the shapes, so this works across modalities (CT, CBCT, MR) and is a robust way to align one structure (a bone, the liver) before an intensity refinement with rigid(). Distance maps give the optimizer a smooth, nearly quadratic metric that converges from much further away than raw binary masks. Each mask is converted in its own native grid, so no pre-resampling is needed.

Parameters:
  • transform ({'Euler', 'Versor'}, default 'Euler') – Rigid transform family. ‘Versor’ is available only for 3D.

  • initializer ({'Moments', 'Geometry'}, default 'Moments') – Applied to the binary masks. ‘Moments’ aligns the mask centroids, which is reliable here because a binary mask has no background intensity to bias it. Ignored when initial_transform is given.

  • band (float, default 20.0) – Distances are clamped to [-band, band] mm and the metric is evaluated only where the reference distance is inside the band. This roughly sets the capture range beyond the initializer, so raise it for large initial offsets.

  • sampling (float, default 0.25) – Fraction of voxels randomly sampled (only samples inside the reference band contribute).

  • iterations – Optimizer and multi-resolution settings, as in rigid().

  • learning_rate – Optimizer and multi-resolution settings, as in rigid().

  • min_step – Optimizer and multi-resolution settings, as in rigid().

  • relaxation – Optimizer and multi-resolution settings, as in rigid().

  • shrink_factors – Optimizer and multi-resolution settings, as in rigid().

  • smoothing_sigmas – Optimizer and multi-resolution settings, as in rigid().

  • reference_mask (SimpleITK.Image, optional) – Masks to register. None uses the stored self.reference_mask / self.moving_mask. Passing them here lets the shapes differ from the ROI masks used by rigid().

  • moving_mask (SimpleITK.Image, optional) – Masks to register. None uses the stored self.reference_mask / self.moving_mask. Passing them here lets the shapes differ from the ROI masks used by rigid().

  • initial_transform (SimpleITK.Transform, optional) – Rigid starting transform, e.g. from landmark(). It is copied, not modified.

  • return_info (bool, default False) – Return a diagnostics dictionary along with the transform. metric_value is the mean squared distance difference in mm², so its square root is a rough RMS surface mismatch.

Returns:

Rigid transform mapping reference points to the moving image (same convention as rigid()).

Return type:

SimpleITK.Transform or tuple

Raises:

ValueError – If either mask is missing or empty, or the masks have different dimensions.

Examples

>>> import numpy as np
>>> fixed = np.zeros((24, 48, 48), dtype=np.uint8)
>>> fixed[6:18, 10:30, 14:34] = 1
>>> fixed[6:18, 10:20, 34:40] = 1
>>> helper = RigidITK()
>>> _ = helper.create_sitk_image(fixed, (0, 0, 0), (1, 1, 2), np.eye(3), mask=True)
>>> _ = helper.create_sitk_image(np.roll(fixed, (3, 2), axis=(2, 1)), (0, 0, 0), (1, 1, 2), np.eye(3),
...                              reference=False, mask=True)
>>> transform = helper.rigid_mask(sampling=1.0)
>>> (np.round(transform.TransformPoint((0, 0, 0)), 1) + 0.0).tolist()
[3.0, 2.0, 0.0]
transform_to_displacement_field(transform)[source]

Convert a rigid transform to a displacement field on the reference image grid.

Parameters:

transform (SimpleITK.Transform) – Transform mapping reference points to the moving image.

Returns:

sitkVectorFloat32 displacement field on the full reference grid.

Return type:

SimpleITK.Image

Examples

>>> import numpy as np
>>> import SimpleITK as sitk
>>> helper = RigidITK()
>>> fixed = np.zeros((16, 32, 32), dtype=np.float32)
>>> fixed[4:12, 8:24, 8:24] = 1
>>> _ = helper.create_sitk_image(fixed, (0, 0, 0), (1, 1, 2), np.eye(3))
>>> _ = helper.create_sitk_image(np.roll(fixed, 2, axis=2), (0, 0, 0), (1, 1, 2), np.eye(3), reference=False)
>>> field = helper.transform_to_displacement_field(helper.rigid(sampling=1.0, iterations=50))
>>> field.GetPixelIDTypeAsString(), field.GetSize()
('vector of 32-bit float', (32, 32, 16))