DeformableITK#

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

Bases: object

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

All image-based methods share the same preprocessing path (_prepare()): the moving image and masks are resampled onto the reference grid, then optionally converted to gradient magnitude, intensity normalized, histogram matched, mask blended (Demons family only) and cropped to the union of both masks.

Parameters:
  • reference_image (SimpleITK.Image, optional) – Fixed image. Its grid defines the output displacement field.

  • 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
>>> from medicalimageanalysis.utils.deformable.simpleitk import DeformableITK
>>> fixed = np.zeros((16, 32, 32), dtype=np.float32)
>>> fixed[4:12, 8:24, 8:24] = 100
>>> helper = DeformableITK()
>>> _ = 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)
blur_mask(mask, sigma=2)[source]

Return a Gaussian-smoothed mask normalized to [0, 1], used as a soft blending weight.

Parameters:
  • mask (SimpleITK.Image) – Binary mask.

  • sigma (float, default 2) – Gaussian standard deviation in mm.

Returns:

Float32 weight image in [0, 1]. An empty or uniform mask is returned unchanged (as float).

Return type:

SimpleITK.Image

Examples

>>> import numpy as np
>>> import SimpleITK as sitk
>>> helper = DeformableITK()
>>> array = np.zeros((16, 32, 32), dtype=np.uint8)
>>> array[4:12, 8:24, 8:24] = 1
>>> weight = helper.blur_mask(sitk.GetImageFromArray(array), sigma=2)
>>> float(sitk.GetArrayViewFromImage(weight).max()), weight.GetPixelIDTypeAsString()
(1.0, '32-bit float')
bspline(control_spacing=(20, 20, 20), scale_factors=(1, 2, 4), shrink_factors=(4, 2, 1), smoothing_sigmas=(2, 1, 0), iterations=100, accuracy=1e-05, metric='Intensity', bins=32, radius=2, sampling=0.1, crop=10, cross_modality=False)[source]

Multi-resolution B-spline registration with control-grid refinement (ImageRegistrationMethod + LBFGS2).

The control grid starts coarse and is refined by scale_factors at each pyramid level, so large deformations are captured first and local detail last.

Parameters:
  • control_spacing (sequence of float, default (20, 20, 20)) – Final control point spacing in mm, (x, y, z). The first level uses control_spacing * max(scale_factors).

  • scale_factors (sequence of int, default (1, 2, 4)) – Control grid refinement per level; must have the same length as shrink_factors.

  • 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.

  • iterations (int, default 100) – Maximum LBFGS2 iterations per level.

  • accuracy (float, default 1e-5) – LBFGS2 solution accuracy (convergence tolerance on the gradient norm).

  • metric ({'Intensity', 'Correlation', 'ANTS', 'MI', 'JointMI'}, default 'Intensity') – ‘Intensity’ = mean squares (same modality, fastest). ‘ANTS’ = ANTS neighborhood correlation (robust for CT-CT/MR-MR with intensity drift). ‘MI’/’JointMI’ = Mattes / joint histogram mutual information (multimodal).

  • 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.

  • crop (float, default 10) – Mask-union crop margin in mm (0 disables).

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

Returns:

sitkVectorFloat32 displacement field (fixed -> moving) on the full reference grid.

Return type:

SimpleITK.Image

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 = DeformableITK()
>>> _ = 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)
>>> dvf = helper.bspline(control_spacing=(8, 8, 8), sampling=1.0)
>>> dvf.GetSize(), dvf.GetPixelIDTypeAsString()
((32, 32, 16), 'vector of 32-bit float')
>>> round(float(sitk.GetArrayViewFromImage(dvf)[8, 16, 16, 0]))
2
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, i.e. the slice spacing is the last entry.

  • 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 = DeformableITK()
>>> 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 registration, prefer metric='MI' in bspline(), displacement_field() or elastix(); this is mainly useful for the Demons family, which assumes matching intensities.

Parameters:

image (SimpleITK.Image) – Input image.

Returns:

Float32 gradient magnitude image.

Return type:

SimpleITK.Image

Examples

>>> import SimpleITK as sitk
>>> helper = DeformableITK()
>>> gradient = helper.cross_modality_correction(sitk.Image(32, 32, 16, sitk.sitkFloat32))
>>> gradient.GetPixelIDTypeAsString()
'32-bit float'
demons(std=1.5, iterations=100, intensity_threshold=0.001, shrink_factors=(4, 2, 1), smoothing_sigmas=(2, 1, 0), crop=10, cross_modality=False, normalize=True, histogram_match=True, blend_sigma=2)[source]

Classic (Thirion) Demons registration, multi-resolution.

Parameters:
  • std (float, default 1.5) – Gaussian regularization of the displacement field, in voxels.

  • iterations (int, default 100) – Iterations per resolution level.

  • intensity_threshold (float, default 0.001) – Intensity differences below this are treated as matched (normalized [0, 1] units when normalize).

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

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

  • crop (float, default 10) – Mask-union crop margin in mm (0 disables).

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

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

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

  • blend_sigma (float, default 2) – Blur (mm) of the mask-union edge used to blend the outside region; 0 uses a hard edge.

Returns:

sitkVectorFloat32 displacement field (fixed -> moving) on the full reference grid.

Return type:

SimpleITK.Image

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 = DeformableITK()
>>> _ = 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)
>>> dvf = helper.demons()
>>> dvf.GetSize()
(32, 32, 16)
diffeomorphic(std=1.5, iterations=100, intensity_threshold=0.001, step=0.5, shrink_factors=(4, 2, 1), smoothing_sigmas=(2, 1, 0), crop=10, cross_modality=False, normalize=True, histogram_match=True, blend_sigma=2)[source]

Diffeomorphic Demons registration (invertible, fold-free fields), multi-resolution.

Parameters:
  • std (float, default 1.5) – Gaussian regularization of the displacement field, in voxels.

  • iterations (int, default 100) – Iterations per resolution level.

  • intensity_threshold (float, default 0.001) – Intensity differences below this are treated as matched (normalized [0, 1] units when normalize).

  • step (float, default 0.5) – Maximum update step length per iteration, in voxels. Kept at the ITK default because large steps can break the diffeomorphic update.

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

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

  • crop (float, default 10) – Mask-union crop margin in mm (0 disables).

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

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

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

  • blend_sigma (float, default 2) – Blur (mm) of the mask-union edge used to blend the outside region; 0 uses a hard edge.

Returns:

sitkVectorFloat32 displacement field (fixed -> moving) on the full reference grid.

Return type:

SimpleITK.Image

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 = DeformableITK()
>>> _ = 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)
>>> dvf = helper.diffeomorphic()
>>> dvf.GetSize()
(32, 32, 16)
displacement_field(metric='Demons', bins=32, radius=2, iterations=200, learning_rate=1.0, update_variance=0.0, total_variance=3.0, shrink_factors=(4, 2, 1), smoothing_sigmas=(2, 1, 0), crop=10, cross_modality=False, normalize=True)[source]

Dense displacement field registration (ImageRegistrationMethod + gradient descent).

Every voxel has its own displacement, regularized by Gaussian smoothing of the update and/or total field. Unlike the Demons family, any metric can be used and the masks restrict the metric natively. Slower than Demons, but the most flexible dense option. ITK’s gradient descent converges slowly on smooth anatomy, so use it for moderate deformations or as a refinement, and raise iterations for ‘ANTS’/’MI’.

Parameters:
  • metric ({'Demons', 'ANTS', 'Intensity', 'Correlation', 'MI', 'JointMI'}, default 'Demons') – Similarity metric. ‘Demons’ converges fastest for same modality. ‘ANTS’ (neighborhood correlation) is more robust to local intensity changes but needs more iterations. ‘MI’/’JointMI’ for multimodal.

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

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

  • iterations (int, default 200) – Maximum gradient descent iterations per level.

  • learning_rate (float, default 1.0) – Gradient descent step; scaled per voxel by SetOptimizerScalesFromPhysicalShift.

  • update_variance (float, default 0.0) – Gaussian variance (voxels^2) applied to each update (fluid-like regularization). 0 disables.

  • total_variance (float, default 3.0) – Gaussian variance (voxels^2) applied to the total field (elastic-like regularization). Larger is smoother but recovers less of large deformations.

  • 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.

  • crop (float, default 10) – Mask-union crop margin in mm (0 disables).

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

  • normalize (bool, default True) – Percentile-normalize both images to [0, 1] (see _prepare()); keeps the step size and the ‘Demons’/’Intensity’ metrics on a consistent scale.

Returns:

sitkVectorFloat32 displacement field (fixed -> moving) on the full reference grid.

Return type:

SimpleITK.Image

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 = DeformableITK()
>>> _ = 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)
>>> dvf = helper.displacement_field(iterations=50)
>>> dvf.GetSize()
(32, 32, 16)
elastix(transform='BSpline', metric='Intensity', bins=32, resolution=4, spacing=10, iterations=500, order=3, bending_weight=0.0, reference_points=None, moving_points=None, points_weight=0.1, parameter=None, crop=10, cross_modality=False)[source]

Nonrigid registration with Elastix; the deformation field is computed with Transformix.

Assumes the images are already rigidly/affinely aligned. Requires a SimpleITK build with Elastix (SimpleITK-SimpleElastix on PyPI).

Parameters:
  • transform ({'BSpline', 'RecursiveBSpline', 'SplineKernel'}, default 'BSpline') – ‘RecursiveBSpline’ gives the same result as ‘BSpline’ but is faster. ‘SplineKernel’ is a thin-plate spline through the landmarks; it requires reference_points and moving_points and refines their positions with the intensity metric.

  • metric ({'Intensity', 'MI'}, default 'Intensity') – AdvancedMeanSquares or AdvancedMattesMutualInformation.

  • bins (int, default 32) – Histogram bins (mutual information only).

  • resolution (int, default 4) – Number of pyramid levels.

  • spacing (float, default 10) – Final B-spline grid spacing in mm (B-spline transforms only).

  • iterations (int, default 500) – Maximum iterations per level.

  • order (int, default 3) – B-spline order (B-spline transforms only).

  • bending_weight (float, default 0.0) – Weight of TransformBendingEnergyPenalty, which penalizes non-smooth deformations. 0 disables. The right value depends on the metric scale; start around 0.01-1.

  • reference_points (array_like, shape (N, 3), optional) – Corresponding points, physical (x, y, z) in mm. With a B-spline transform they add a CorrespondingPointsEuclideanDistanceMetric term; with ‘SplineKernel’ they are the spline landmarks.

  • moving_points (array_like, shape (N, 3), optional) – Corresponding points, physical (x, y, z) in mm. With a B-spline transform they add a CorrespondingPointsEuclideanDistanceMetric term; with ‘SplineKernel’ they are the spline landmarks.

  • points_weight (float, default 0.1) – Weight of the corresponding-points term relative to the intensity metric (weight 1.0).

  • parameter (SimpleITK.ParameterMap, optional) – Full Elastix parameter map. When given, all settings above except the points are ignored.

  • crop (float, default 10) – Mask-union crop margin in mm (0 disables).

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

Returns:

sitkVectorFloat32 displacement field (fixed -> moving) on the full reference grid.

Return type:

SimpleITK.Image

Examples

>>> import numpy as np
>>> z, y, x = np.mgrid[:32, :64, :64]
>>> fixed = (100 * np.exp(-((x - 32) ** 2 + (y - 32) ** 2) / 160 - (z - 16) ** 2 / 40)).astype(np.float32)
>>> helper = DeformableITK()
>>> _ = 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)
>>> dvf = helper.elastix(transform='RecursiveBSpline', resolution=2, iterations=100)
>>> dvf.GetSize()
(64, 64, 32)
elastix_groupwise(images, resolution=4, spacing=10, iterations=500)[source]

Groupwise Elastix registration of several images to their implicit mean (BSplineStackTransform).

No image is the reference: all images are deformed towards a common mean space. Useful for building atlases or longitudinal series without biasing toward one scan. Independent of the stored images/masks.

Parameters:
  • images (list of SimpleITK.Image) – Two or more 3D images, already rigidly aligned. All are resampled onto the grid of images[0].

  • resolution (int, default 4) – Number of pyramid levels.

  • spacing (float, default 10) – Final B-spline grid spacing in mm.

  • iterations (int, default 500) – Maximum iterations per level.

Returns:

One sitkVectorFloat32 displacement field per image, on the grid of images[0]. Field i maps a point in the mean space to image i (pull-back), so warping image i with it moves it to the mean.

Return type:

list of SimpleITK.Image

Examples

>>> import numpy as np
>>> import SimpleITK as sitk
>>> z, y, x = np.mgrid[:32, :64, :64]
>>> base = (100 * np.exp(-((x - 32) ** 2 + (y - 32) ** 2) / 160 - (z - 16) ** 2 / 40)).astype(np.float32)
>>> images = [sitk.GetImageFromArray(np.roll(base, shift, axis=2)) for shift in (-2, 0, 2)]
>>> dvfs = DeformableITK().elastix_groupwise(images, resolution=2, iterations=100)
>>> len(dvfs), dvfs[0].GetSize()
(3, (64, 64, 32))
fast_demons(std=1.5, iterations=100, intensity_threshold=0.001, step=1.0, shrink_factors=(4, 2, 1), smoothing_sigmas=(2, 1, 0), crop=10, cross_modality=False, normalize=True, histogram_match=True, blend_sigma=2)[source]

Fast Symmetric Forces Demons registration, multi-resolution.

Parameters:
  • std (float, default 1.5) – Gaussian regularization of the displacement field, in voxels.

  • iterations (int, default 100) – Iterations per resolution level.

  • intensity_threshold (float, default 0.001) – Intensity differences below this are treated as matched (normalized [0, 1] units when normalize).

  • step (float, default 1.0) – Maximum update step length per iteration, in voxels (ITK default 0.5; larger converges faster but is less stable).

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

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

  • crop (float, default 10) – Mask-union crop margin in mm (0 disables).

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

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

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

  • blend_sigma (float, default 2) – Blur (mm) of the mask-union edge used to blend the outside region; 0 uses a hard edge.

Returns:

sitkVectorFloat32 displacement field (fixed -> moving) on the full reference grid.

Return type:

SimpleITK.Image

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 = DeformableITK()
>>> _ = 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)
>>> dvf = helper.fast_demons()
>>> round(float(sitk.GetArrayViewFromImage(dvf)[8, 16, 16, 0]))
2
landmark(reference_points, moving_points, control_points=8, order=3)[source]

Fit a B-spline displacement field to corresponding point pairs (no image intensities used).

Useful for turning a surface correspondence (e.g. from a mesh registration) into a volumetric DVF. Only the reference image grid is needed; the moving image is not used.

Parameters:
  • reference_points (array_like, shape (N, 3)) – Points on the reference, physical (x, y, z) in mm.

  • moving_points (array_like, shape (N, 3)) – Corresponding points on the moving image, same order and convention.

  • control_points (int, default 8) – Number of B-spline control points per axis (must be greater than order). More points follow the landmarks more closely but extrapolate less smoothly away from them.

  • order (int, default 3) – B-spline order.

Returns:

sitkVectorFloat32 displacement field (fixed -> moving) on the full reference grid.

Return type:

SimpleITK.Image

Examples

>>> import numpy as np
>>> import SimpleITK as sitk
>>> helper = DeformableITK(reference_image=sitk.Image(32, 32, 16, sitk.sitkFloat32))
>>> reference_points = np.random.default_rng(0).uniform(4, 14, size=(50, 3))
>>> moving_points = reference_points + [2, 0, 0]
>>> dvf = helper.landmark(reference_points, moving_points)
>>> round(float(sitk.GetArrayViewFromImage(dvf)[8, 8, 8, 0]))
2
level_set_motion(std=1.5, iterations=200, intensity_threshold=0.001, alpha=0.01, gradient_std=1.0, max_rms_error=0.0, shrink_factors=(4, 2, 1), smoothing_sigmas=(2, 1, 0), crop=10, cross_modality=False, normalize=True, histogram_match=True, blend_sigma=2)[source]

Level Set Motion registration, multi-resolution.

Moves voxels along the image gradient like a level-set front; more robust than Thirion Demons to large intensity differences, but each step is small, so it needs more iterations than the Demons methods.

Parameters:
  • std (float, default 1.5) – Gaussian regularization of the displacement field, in voxels.

  • iterations (int, default 200) – Iterations per resolution level.

  • intensity_threshold (float, default 0.001) – Intensity differences below this are treated as matched (normalized [0, 1] units when normalize).

  • alpha (float, default 0.01) – Stabilizing constant added to the gradient magnitude (prevents large steps in flat regions). Tuned for normalized [0, 1] intensities; ITK’s default of 0.1 barely moves on normalized images.

  • gradient_std (float, default 1.0) – Gaussian smoothing (voxels) applied to the image before computing gradients.

  • max_rms_error (float, default 0.0) – Stop a level early when the RMS change of the field per iteration falls below this. 0 disables (ITK’s default of 0.02 stops after a few iterations on normalized images).

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

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

  • crop (float, default 10) – Mask-union crop margin in mm (0 disables).

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

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

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

  • blend_sigma (float, default 2) – Blur (mm) of the mask-union edge used to blend the outside region; 0 uses a hard edge.

Returns:

sitkVectorFloat32 displacement field (fixed -> moving) on the full reference grid.

Return type:

SimpleITK.Image

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 = DeformableITK()
>>> _ = 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)
>>> dvf = helper.level_set_motion()
>>> dvf.GetSize()
(32, 32, 16)
mask_crop(images, reference_mask, moving_mask, margin=10)[source]

Crop images to the bounding box of the union of two masks, padded by a margin.

All images must already share the same grid (see resample()).

Parameters:
  • images (list of SimpleITK.Image) – Images (and/or masks) to crop with the same region.

  • reference_mask (SimpleITK.Image) – Binary masks on the shared grid.

  • moving_mask (SimpleITK.Image) – Binary masks on the shared grid.

  • margin (float, default 10) – Padding around the bounding box, in mm (converted per axis so it is isotropic for anisotropic voxels).

Returns:

Cropped images, in the same order. Returned uncropped if both masks are empty.

Return type:

list of SimpleITK.Image

Examples

>>> import numpy as np
>>> import SimpleITK as sitk
>>> helper = DeformableITK()
>>> array = np.zeros((16, 32, 32), dtype=np.uint8)
>>> array[4:12, 8:24, 8:24] = 1
>>> mask = sitk.GetImageFromArray(array)
>>> mask.SetSpacing((1, 1, 2))
>>> cropped = helper.mask_crop([mask], mask, mask, margin=4)
>>> cropped[0].GetSize()
(24, 24, 12)
resample(image, reference, mask=False)[source]

Resample an image onto the grid of a reference image (identity transform).

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

  • reference (SimpleITK.Image) – Image defining the output grid (size, origin, spacing, direction).

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

Returns:

Image on the reference grid. Returned without resampling if the grids already match.

Return type:

SimpleITK.Image

Examples

>>> import SimpleITK as sitk
>>> helper = DeformableITK()
>>> 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)
symmetric_demons(std=1.5, iterations=100, intensity_threshold=0.001, shrink_factors=(4, 2, 1), smoothing_sigmas=(2, 1, 0), crop=10, cross_modality=False, normalize=True, histogram_match=True, blend_sigma=2)[source]

Symmetric Forces Demons registration (forces from both image gradients), multi-resolution.

Older and slower than fast_demons(); mainly useful for comparison.

Parameters:
  • std (float, default 1.5) – Gaussian regularization of the displacement field, in voxels.

  • iterations (int, default 100) – Iterations per resolution level.

  • intensity_threshold (float, default 0.001) – Intensity differences below this are treated as matched (normalized [0, 1] units when normalize).

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

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

  • crop (float, default 10) – Mask-union crop margin in mm (0 disables).

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

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

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

  • blend_sigma (float, default 2) – Blur (mm) of the mask-union edge used to blend the outside region; 0 uses a hard edge.

Returns:

sitkVectorFloat32 displacement field (fixed -> moving) on the full reference grid.

Return type:

SimpleITK.Image

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 = DeformableITK()
>>> _ = 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)
>>> dvf = helper.symmetric_demons()
>>> dvf.GetSize()
(32, 32, 16)