confusius.registration¶
registration ¶
Registration module for fUSI data.
Modules:
-
affines–Affine matrix decomposition and composition utilities.
-
bspline–B-spline transform helpers for fUSI registration.
-
motion–Motion parameter estimation and framewise displacement computation.
-
resampling–Volume resampling utilities for fUSI data.
-
volume–Volume-to-volume registration for fUSI data.
-
volumewise–Volumewise registration for fUSI data.
Classes:
-
RegistrationProgressPlotter–Plot registration progress in real time.
Functions:
-
compose_affine–Compose translations, rotations, zooms, and shears into an affine matrix.
-
compute_framewise_displacement–Compute framewise displacement from affine transforms.
-
create_motion_dataframe–Create a DataFrame with motion parameters and framewise displacement.
-
decompose_affine–Decompose a 4x4 homogeneous affine into translation, rotation, zoom, shear.
-
extract_motion_parameters–Extract motion parameters from affine matrices.
-
register_volume–Register a single 2D or 3D volume to a fixed reference.
-
register_volumewise–Register all volumes in a fUSI recording to a reference volume.
-
resample_like–Resample a volume onto the grid of a reference DataArray.
-
resample_volume–Resample a volume onto an explicit output grid using a pre-computed transform.
RegistrationProgressPlotter ¶
Plot registration progress in real time.
Displays an optimizer metric curve, a composite fixed/moving overlay, or both, updated at every iteration. Works in both a Jupyter notebook and an interactive matplotlib backend (e.g. Qt).
Parameters:
-
(registration_method¶ImageRegistrationMethod) –The registration method whose progress to monitor.
-
(fixed_img¶Image) –The fixed (reference) image, used to resample the composite view.
-
(moving_img¶Image) –The moving image, used to resample the composite view.
-
(plot_metric¶bool, default:True) –Whether to display the optimizer metric over iterations.
-
(plot_composite¶bool, default:True) –Whether to display a blended fixed/moving composite at each iteration. Requires an additional
sitk.Resamplecall per iteration.
Methods:
-
close–Finalize the plot when registration ends.
-
update–Update the plot with the current iteration's data.
Attributes:
-
figure(Figure) –The matplotlib figure used for plotting.
-
metric_values(list[float]) –Optimizer metric value recorded at each iteration.
figure
property
¶
figure: Figure
The matplotlib figure used for plotting.
Returns:
-
Figure–The figure instance owned by this monitor.
metric_values
property
¶
Optimizer metric value recorded at each iteration.
Returns:
-
list of float–Copy of the internal metric value buffer.
update ¶
Update the plot with the current iteration's data.
Called at every sitkIterationEvent.
compose_affine ¶
compose_affine(
T: NDArray[float64],
R: NDArray[float64],
Z: NDArray[float64],
S: NDArray[float64] | None = None,
) -> NDArray[float64]
Compose translations, rotations, zooms, and shears into an affine matrix.
Parameters:
-
(T¶(N,) numpy.ndarray) –Translation vector, where
Nis usually 3 (3D case). -
(R¶(N, N) numpy.ndarray) –Rotation matrix, where
Nis usually 3 (3D case). -
(Z¶(N,) numpy.ndarray) –Zoom (scale) vector, where
Nis usually 3 (3D case). -
(S¶(P,) numpy.ndarray, default:None) –Shear vector filling the upper triangle above the diagonal of the shear matrix.
Pis the(N-2)-th triangular number (3 for the 3D case). IfNone, no shear is applied.
Returns:
-
(N+1, N+1) numpy.ndarray–Homogeneous affine transformation matrix.
Notes
Adapted from transforms3d.affines.compose by Matthew Brett et al.
(BSD-2-Clause License). See the NOTICE and LICENSE-BSD-2-Clause
files for details.
Source: https://github.com/matthew-brett/transforms3d
compute_framewise_displacement ¶
compute_framewise_displacement(
affines: Sequence[NDArray[float64] | None],
reference: DataArray,
mask: NDArray[bool_] | None = None,
) -> dict[str, NDArray[floating]]
Compute framewise displacement from affine transforms.
Framewise displacement measures how much voxels move between consecutive frames after registration. For each voxel, we compute the Euclidean distance between its position at frame t and frame t+1 after applying the affine transforms.
Parameters:
-
(affines¶list[ndarray | None]) –List of affine matrices, one per frame.
Noneentries are treated as identity transforms. -
(reference¶DataArray) –Spatial DataArray defining the physical grid (spacing and origin derived from its coordinates).
-
(mask¶ndarray, default:None) –Boolean mask indicating which voxels to include. If not provided, uses all voxels.
Returns:
-
dict–Dictionary with keys:
"mean_fd": Mean framewise displacement per frame."max_fd": Maximum framewise displacement per frame."rms_fd": RMS framewise displacement per frame.
create_motion_dataframe ¶
create_motion_dataframe(
affines: Sequence[NDArray[float64] | None],
reference: DataArray,
mask: NDArray[bool_] | None = None,
time_coords: NDArray[floating] | None = None,
) -> DataFrame
Create a DataFrame with motion parameters and framewise displacement.
Parameters:
-
(affines¶list[ndarray | None]) –List of affine matrices from registration.
Noneentries (e.g. from B-spline transforms) are treated as identity. -
(reference¶DataArray) –Spatial DataArray defining the physical grid for framewise displacement computation.
-
(mask¶ndarray, default:None) –Boolean mask for FD computation.
-
(time_coords¶ndarray, default:None) –Time coordinates for each frame.
Returns:
-
DataFrame–DataFrame with columns:
For 2D:
rotation: Rotation angle in radians.trans_x: Translation in x (mm).trans_y: Translation in y (mm).
For 3D:
rot_x, rot_y, rot_z: Rotation angles in radians.trans_x, trans_y, trans_z: Translations (mm).
Both: -
mean_fd: Mean framewise displacement (mm). -max_fd: Maximum framewise displacement (mm). -rms_fd: RMS framewise displacement (mm).
decompose_affine ¶
decompose_affine(
A44: NDArray[float64],
) -> tuple[
NDArray[float64],
NDArray[float64],
NDArray[float64],
NDArray[float64],
]
Decompose a 4x4 homogeneous affine into translation, rotation, zoom, shear.
Decomposes A44 into T, R, Z, S such that::
Smat = np.array([[1, S[0], S[1]],
[0, 1, S[2]],
[0, 0, 1]])
RZS = R @ np.diag(Z) @ Smat
A44[:3, :3] = RZS
A44[:3, 3] = T
Parameters:
-
(A44¶(4, 4) numpy.ndarray) –Homogeneous affine matrix.
Returns:
-
T((3,) numpy.ndarray) –Translation vector.
-
R((3, 3) numpy.ndarray) –Rotation matrix.
-
Z((3,) numpy.ndarray) –Zoom (scale) vector. May have one negative zoom to avoid a negative determinant in
R. -
S((3,) numpy.ndarray) –Shear vector
[sxy, sxz, syz]filling the upper triangle of the shear matrix. Zero for pure rotation/zoom affines.
Notes
Adapted from transforms3d.affines.decompose44 by Matthew Brett et al.
(BSD-2-Clause License). See the NOTICE and LICENSE-BSD-2-Clause
files for details.
Source: https://github.com/matthew-brett/transforms3d
See also: Spencer W. Thomas, "Decomposing a matrix into simple transformations", pp 320-323 in Graphics Gems II, James Arvo (ed.), Academic Press, 1991.
extract_motion_parameters ¶
Extract motion parameters from affine matrices.
Decomposes each (N+1, N+1) homogeneous affine into translation and
rotation parameters.
For 2D transforms, extracts: [rotation, translation_x, translation_y].
For 3D transforms, extracts:
[rot_x, rot_y, rot_z, trans_x, trans_y, trans_z].
Parameters:
-
(affines¶list[ndarray | None]) –List of affine matrices from registration.
Noneentries (e.g. from B-spline transforms) are treated as identity transforms.
Returns:
-
(n_frames, n_params) numpy.ndarray–Motion parameters array.
- For 2D:
n_params = 3 (rotation, tx, ty). - For 3D:
n_params = 6 (rot_x, rot_y, rot_z, trans_x, trans_y, trans_z).
- For 2D:
Raises:
-
ValueError–If any affine does not have shape
(3, 3)(2D) or(4, 4)(3D).
register_volume ¶
register_volume(
moving: DataArray,
fixed: DataArray,
*,
transform: Literal["translation", "rigid", "affine"],
metric: Literal["correlation", "mattes_mi"] = ...,
number_of_histogram_bins: int = ...,
learning_rate: float | Literal["auto"] = ...,
number_of_iterations: int = ...,
convergence_minimum_value: float = ...,
convergence_window_size: int = ...,
initialization: Literal[
"geometry", "moments", "none"
] = ...,
optimizer_weights: list[float] | None = ...,
initial_transform: NDArray[float64] | None = ...,
mesh_size: tuple[int, int, int] = ...,
use_multi_resolution: bool = ...,
shrink_factors: Sequence[int] = ...,
smoothing_sigmas: Sequence[int] = ...,
resample: bool = ...,
resample_interpolation: Literal[
"linear", "bspline"
] = ...,
sitk_threads: int = ...,
show_progress: bool = ...,
plot_metric: bool = ...,
plot_composite: bool = ...,
) -> tuple[DataArray, NDArray[float64]]
register_volume(
moving: DataArray,
fixed: DataArray,
*,
transform: Literal["bspline"],
metric: Literal["correlation", "mattes_mi"] = ...,
number_of_histogram_bins: int = ...,
learning_rate: float | Literal["auto"] = ...,
number_of_iterations: int = ...,
convergence_minimum_value: float = ...,
convergence_window_size: int = ...,
initialization: Literal[
"geometry", "moments", "none"
] = ...,
optimizer_weights: list[float] | None = ...,
initial_transform: NDArray[float64] | None = ...,
mesh_size: tuple[int, int, int] = ...,
use_multi_resolution: bool = ...,
shrink_factors: Sequence[int] = ...,
smoothing_sigmas: Sequence[int] = ...,
resample: bool = ...,
resample_interpolation: Literal[
"linear", "bspline"
] = ...,
sitk_threads: int = ...,
show_progress: bool = ...,
plot_metric: bool = ...,
plot_composite: bool = ...,
) -> tuple[DataArray, DataArray]
register_volume(
moving: DataArray,
fixed: DataArray,
*,
metric: Literal["correlation", "mattes_mi"] = ...,
number_of_histogram_bins: int = ...,
learning_rate: float | Literal["auto"] = ...,
number_of_iterations: int = ...,
convergence_minimum_value: float = ...,
convergence_window_size: int = ...,
initialization: Literal[
"geometry", "moments", "none"
] = ...,
optimizer_weights: list[float] | None = ...,
initial_transform: NDArray[float64] | None = ...,
mesh_size: tuple[int, int, int] = ...,
use_multi_resolution: bool = ...,
shrink_factors: Sequence[int] = ...,
smoothing_sigmas: Sequence[int] = ...,
resample: bool = ...,
resample_interpolation: Literal[
"linear", "bspline"
] = ...,
sitk_threads: int = ...,
show_progress: bool = ...,
plot_metric: bool = ...,
plot_composite: bool = ...,
) -> tuple[DataArray, NDArray[float64]]
register_volume(
moving: DataArray,
fixed: DataArray,
*,
transform: Literal[
"translation", "rigid", "affine", "bspline"
] = "rigid",
metric: Literal[
"correlation", "mattes_mi"
] = "correlation",
number_of_histogram_bins: int = 50,
learning_rate: float | Literal["auto"] = "auto",
number_of_iterations: int = 100,
convergence_minimum_value: float = 1e-06,
convergence_window_size: int = 10,
initialization: Literal[
"geometry", "moments", "none"
] = "geometry",
optimizer_weights: list[float] | None = None,
initial_transform: NDArray[float64] | None = None,
mesh_size: tuple[int, int, int] = (10, 10, 10),
use_multi_resolution: bool = False,
shrink_factors: Sequence[int] = (6, 2, 1),
smoothing_sigmas: Sequence[int] = (6, 2, 1),
resample: bool = False,
resample_interpolation: Literal[
"linear", "bspline"
] = "linear",
sitk_threads: int = -1,
show_progress: bool = False,
plot_metric: bool = True,
plot_composite: bool = True,
) -> tuple[DataArray, NDArray[float64] | DataArray]
Register a single 2D or 3D volume to a fixed reference.
Voxel spacing and origin are automatically extracted from the DataArray coordinates.
Both inputs must be spatial-only (no time dimension).
Parameters:
-
(moving¶DataArray) –Volume to register to
fixed. Must be 2D or 3D. -
(fixed¶DataArray) –Reference volume. Must be 2D or 3D. Need not have the same shape as
moving. -
(transform¶(translation, rigid, affine, bspline), default:"translation") –Transform model to use during registration.
"translation"allows only shifts."rigid"adds rotation."affine"adds scaling and shearing."bspline"fits a non-linear deformable transform (seemesh_size). -
(metric¶(correlation, mattes_mi), default:"correlation") –Similarity metric.
"correlation"(normalized cross-correlation) is appropriate for same-modality registration."mattes_mi"(Mattes mutual information) is better suited for multi-modal registration or when the intensity relationship between images is non-linear. -
(number_of_histogram_bins¶int, default:50) –Number of histogram bins used by Mattes mutual information. Only relevant when using
"mattes_mi"metric. -
(learning_rate¶float or auto, default:"auto") –Optimizer step size in normalized units.
"auto"re-estimates the rate at every iteration. A float uses that value directly; if registration diverges or fails to converge, reduce it. -
(number_of_iterations¶int, default:100) –Maximum number of optimizer iterations.
-
(convergence_minimum_value¶float, default:1e-6) –Value used for convergence checking in conjunction with the energy profile of the similarity metric that is estimated in the given window size.
-
(convergence_window_size¶int, default:10) –Number of values of the similarity metric which are used to estimate the energy profile of the similarity metric.
-
(initialization¶(geometry, moments, none), default:"geometry") –Transform initializer applied before optimization.
"geometry"aligns the image centers (safe default, no assumptions about content)."moments"aligns centers of mass (better when images are offset but share the same content)."none"uses the identity transform. Ignored fortransform="bspline". -
(optimizer_weights¶list of float or None, default:None) –Per-parameter weights applied on top of the auto-estimated physical shift scales.
Noneuses identity weights (all ones). A list is passed directly to SimpleITK'sSetOptimizerWeights; its length must match the number of transform parameters (3 for 2D rigid, 6 for 3D rigid, 6 for 2D affine, 12 for 3D affine). The weight for each parameter is multiplied into the effective step size:0freezes a parameter entirely, values in(0, 1)slow it down, and1leaves it unchanged. For the 3D Euler transform the parameter order is[angleX, angleY, angleZ, tx, ty, tz]; to disable rotations around x and y set weights to[0, 0, 1, 1, 1, 1]. -
(initial_transform¶(N+1, N+1) numpy.ndarray or None, default:None) –Pre-computed affine matrix (pull/inverse convention, as returned by a previous call to
register_volume) used as a warm-start before optimisation. When provided the child transform (transform) is composed on top of this pre-alignment. Primarily useful for the affine → B-spline composition workflow: run an affine registration first, then pass its result here together withtransform="bspline"to refine the deformation. WhenNone(the default) the existinginitializationbehaviour is unchanged. -
(mesh_size¶tuple of int, default:(10, 10, 10)) –Number of B-spline mesh nodes along each spatial dimension. Only used when
transform="bspline". -
(use_multi_resolution¶bool, default:False) –Whether to use a multi-resolution pyramid during registration. When
True, registration proceeds from a coarse downsampled version of the images to the full resolution, which improves convergence for large displacements and reduces the risk of local minima. -
(shrink_factors¶sequence of int, default:(6, 2, 1)) –Downsampling factor at each pyramid level, from coarsest to finest. Must have the same length as
smoothing_sigmas. Only used whenuse_multi_resolution=True. -
(smoothing_sigmas¶sequence of int, default:(6, 2, 1)) –Gaussian smoothing sigma (in voxels) applied at each pyramid level, from coarsest to finest. Must have the same length as
shrink_factors. Only used whenuse_multi_resolution=True. -
(resample¶bool, default:False) –Whether to resample the moving volume onto the fixed grid after estimating the transform. When
True, the output is resampled onto the fixed grid and its coordinates matchfixed. WhenFalse(the default), only the transform is computed and the moving volume is returned unchanged with its original coordinates. -
(resample_interpolation¶(linear, bspline), default:"linear") –Interpolator used when resampling the moving volume onto the fixed grid.
"linear"is fast and appropriate for most cases."bspline"(3rd-order B-spline) produces smoother results and reduces ringing, useful for atlas registration. Only used whenresample=True. -
(sitk_threads¶int, default:-1) –Number of threads SimpleITK may use internally. Negative values resolve to
max(1, os.cpu_count() + 1 + sitk_threads), so-1means all CPUs,-2means all minus one, and so on. You may want to set this to a lower value or1when running multiple registrations in parallel (e.g. with joblib) to avoid over-subscribing the CPU. -
(show_progress¶bool, default:False) –Whether to display a live progress plot during registration. The plot is shown in a Jupyter notebook or in an interactive matplotlib window depending on the active backend.
-
(plot_metric¶bool, default:True) –Whether to include the optimizer metric curve in the progress plot. Ignored when
show_progress=False. -
(plot_composite¶bool, default:True) –Whether to include a fixed/moving composite overlay in the progress plot. Requires resampling the moving image at every iteration. Ignored when
show_progress=False.
Returns:
-
registered(DataArray) –When
resample=True, the moving volume resampled onto the fixed grid with coordinates matchingfixed. Whenresample=False, the original moving volume with aregistrationattribute added to its metadata. -
transform((N+1, N+1) numpy.ndarray or xarray.DataArray or None) –Estimated registration transform. For linear transforms (
"translation","rigid","affine"), returns a homogeneous affine matrix of shape(N+1, N+1)in physical space, whereNis the spatial dimensionality (2 or 3). Follows SimpleITK's pull/inverse convention: the matrix maps fixed-space coordinates to moving-space coordinates. Fortransform="bspline", returns a DataArray encoding the B-spline control-point grid (see [confusius.registration.bspline][] for the DataArray schema). Wheninitial_transformwas also supplied, the DataArray includesattrs["affines"]["bspline_initialization"]so that the full composite (pre-affine + B-spline) can be reconstructed for resampling.
Raises:
-
ValueError–If either input contains a
timedimension or is not 2D or 3D. -
ValueError–If
transform,metric,initialization, orresample_interpolationis not a recognised value. -
ValueError–If
learning_rateis not a positive finite float or"auto". -
ValueError–If
number_of_iterations,convergence_window_size, ornumber_of_histogram_binsis not a positive integer. -
ValueError–If
shrink_factorsandsmoothing_sigmashave different lengths. -
ValueError–If
initial_transformis provided and its shape does not match the image dimensionality.
register_volumewise ¶
register_volumewise(
data: DataArray,
*,
reference_time: int = 0,
n_jobs: int = -1,
transform: Literal[
"translation", "rigid", "affine"
] = "rigid",
metric: Literal[
"correlation", "mattes_mi"
] = "correlation",
number_of_histogram_bins: int = 50,
learning_rate: float | Literal["auto"] = "auto",
number_of_iterations: int = 100,
convergence_minimum_value: float = 1e-06,
convergence_window_size: int = 10,
initialization: Literal[
"geometry", "moments", "none"
] = "geometry",
optimizer_weights: list[float] | None = None,
use_multi_resolution: bool = False,
shrink_factors: Sequence[int] = (6, 2, 1),
smoothing_sigmas: Sequence[int] = (6, 2, 1),
resample_interpolation: Literal[
"linear", "bspline"
] = "linear",
) -> DataArray
Register all volumes in a fUSI recording to a reference volume.
Parameters:
-
(data¶DataArray) –Input data to register.
-
(reference_time¶int, default:0) –Index of the time point to use as registration target.
-
(n_jobs¶int, default:-1) –Number of parallel jobs. Negative values resolve to
max(1, os.cpu_count() + 1 + n_jobs), so-1means all CPUs,-2means all minus one, and so on. Use1for serial processing. -
(transform¶(translation, rigid, affine), default:"translation") –Transform model to use during registration.
"translation"allows only shifts."rigid"adds rotation."affine"adds scaling and shearing. B-spline is not available for motion correction. -
(metric¶(correlation, mattes_mi), default:"correlation") –Similarity metric.
"correlation"(normalized cross-correlation) is appropriate for same-modality registration."mattes_mi"(Mattes mutual information) is better suited for multi-modal registration or when the intensity relationship between images is non-linear. -
(number_of_histogram_bins¶int, default:50) –Number of histogram bins used by Mattes mutual information. Only relevant when
metric="mattes_mi". -
(learning_rate¶float or auto, default:"auto") –Optimizer step size in normalised units (after
SetOptimizerScalesFromPhysicalShift)."auto"re-estimates the rate at every iteration. A float uses that value directly; if registration diverges or fails to converge, reduce it. -
(number_of_iterations¶int, default:100) –Maximum number of optimizer iterations.
-
(convergence_minimum_value¶float, default:1e-6) –Convergence threshold. Optimization stops early when the estimated energy profile falls below this value.
-
(convergence_window_size¶int, default:10) –Number of recent metric values used to estimate the energy profile for convergence checking.
-
(initialization¶(geometry, moments, none), default:"geometry") –Transform initializer applied before optimization.
"geometry"aligns the image centers (safe default, no assumptions about content)."moments"aligns centers of mass (better when images are offset but share the same content)."none"uses the identity transform. -
(optimizer_weights¶list of float or None, default:None) –Per-parameter weights applied on top of the auto-estimated physical shift scales.
Noneuses identity weights (all ones). A list is passed directly to SimpleITK'sSetOptimizerWeights; its length must match the number of transform parameters (3 for 2D rigid, 6 for 3D rigid, 6 for 2D affine, 12 for 3D affine). The weight for each parameter is multiplied into the effective step size:0freezes a parameter entirely, values in(0, 1)slow it down, and1leaves it unchanged. For the 3D Euler transform the parameter order is[angleX, angleY, angleZ, tx, ty, tz]; to disable rotations around x and y set weights to[0, 0, 1, 1, 1, 1]. -
(use_multi_resolution¶bool, default:False) –Whether to use a multi-resolution pyramid during registration. When
True, registration proceeds from a coarse downsampled version of the images to the full resolution, which improves convergence for large displacements and reduces the risk of local minima. -
(shrink_factors¶sequence of int, default:(6, 2, 1)) –Downsampling factor at each pyramid level, from coarsest to finest. Must have the same length as
smoothing_sigmas. Only used whenuse_multi_resolution=True. -
(smoothing_sigmas¶sequence of int, default:(6, 2, 1)) –Gaussian smoothing sigma (in voxels) applied at each pyramid level, from coarsest to finest. Must have the same length as
shrink_factors. Only used whenuse_multi_resolution=True. -
(resample_interpolation¶(linear, bspline), default:"linear") –Interpolator used when resampling each volume onto the reference grid.
"linear"is fast and appropriate for motion correction."bspline"(3rd-order B-spline) produces smoother results at the cost of speed.
Returns:
-
DataArray–Registered data with same coordinates and attributes as input.
resample_like ¶
resample_like(
moving: DataArray,
reference: DataArray,
transform: NDArray[float64] | DataArray,
interpolation: Literal["linear", "bspline"] = "linear",
default_value: float = 0.0,
sitk_threads: int = -1,
) -> DataArray
Resample a volume onto the grid of a reference DataArray.
Convenience wrapper around
resample_volume that extracts the output
grid (shape, spacing, origin) from reference's coordinates.
Parameters:
-
(moving¶DataArray) –2D or 3D spatial DataArray to resample, or 3D+t DataArray with a time dimension. If a time dimension is present, the same transform is applied to all time points.
-
(reference¶DataArray) –DataArray defining the output grid. Must be 2D or 3D spatial (no time dimension).
-
(transform¶(N+1, N+1) numpy.ndarray or xarray.DataArray) –Registration transform, as returned by
register_volume. Maps points from the reference physical space to moving physical space (pull/inverse convention).- Affine (
numpy.ndarray): homogeneous matrix. - B-spline (
xarray.DataArray): control-point DataArray.
- Affine (
-
(interpolation¶(linear, bspline), default:"linear") –Interpolation method used during resampling.
-
(default_value¶float, default:0.0) –Value assigned to voxels that fall outside the moving image's field of view after resampling.
-
(sitk_threads¶int, default:os.cpu_count() or 1) –Number of threads SimpleITK may use for the
Resamplecall. Defaults to all available CPUs.
Returns:
-
DataArray–Resampled volume on the grid of
reference, withreference's coordinates and dimensions andmoving's attributes. Ifmovinghad a time dimension, the output will also have a time dimension.
Raises:
-
ValueError–If
referencecontains atimedimension or is not 2D or 3D.
resample_volume ¶
resample_volume(
moving: DataArray,
transform: NDArray[float64] | DataArray,
*,
shape: Sequence[int],
spacing: Sequence[float],
origin: Sequence[float],
dims: Sequence[str],
interpolation: Literal["linear", "bspline"] = "linear",
default_value: float = 0.0,
sitk_threads: int = -1,
) -> DataArray
Resample a volume onto an explicit output grid using a pre-computed transform.
Low-level resampling primitive. For the common case of resampling onto the grid of
another DataArray, use resample_like
instead.
Parameters:
-
(moving¶DataArray) –2D or 3D spatial DataArray to resample, or 3D+t or 2D+t DataArray with a time dimension. If a time dimension is present, the same transform is applied to all time points.
-
(transform¶(N+1, N+1) numpy.ndarray or xarray.DataArray) –Registration transform, as returned by
register_volume.- Affine (
numpy.ndarray): homogeneous matrix of shape(N+1, N+1)mapping output (fixed) physical coordinates to moving physical coordinates (pull/inverse convention). - B-spline (
xarray.DataArray): control-point DataArray as returned byregister_volume(transform="bspline").
- Affine (
-
(shape¶sequence of int) –Number of voxels along each output axis, in DataArray dimension order.
-
(spacing¶sequence of float) –Voxel spacing along each output axis, in DataArray dimension order.
-
(origin¶sequence of float) –Physical origin (first voxel centre) along each output axis, in DataArray dimension order.
-
(dims¶sequence of str) –Dimension names of the output DataArray.
-
(interpolation¶(linear, bspline), default:"linear") –Interpolation method used during resampling.
-
(default_value¶float, default:0.0) –Value assigned to voxels that fall outside the moving image's field of view after resampling.
-
(sitk_threads¶int, default:-1) –Number of threads SimpleITK may use internally. Negative values resolve to
max(1, os.cpu_count() + 1 + sitk_threads), so-1means all CPUs,-2means all minus one, and so on. You may want to set this to a lower value or1when running multiple registrations in parallel (e.g. with joblib) to avoid over-subscribing the CPU.
Returns:
-
DataArray–Resampled volume on the specified grid with
moving's attributes. If the input had a time dimension, the output will also have a time dimension.
Raises:
-
ValueError–If
movingis not 2D, 3D+t, 3D, or 3D+t. -
ValueError–If
transformis a numpy array whose shape does not match the spatial image dimensionality.