Segmentation registration API¶
neuroreg.segreg.register¶
High-level segmentation-based registration APIs.
This layer ties together centroid extraction, bundled target resources, label
presets, and point-set solvers to expose one public segreg workflow that
returns a transform plus the metadata needed for LTA writing.
- class neuroreg.segreg.register.RegistrationResult(r2r, labels, target_name, target_geometry, target_affine, target_shape)[source]¶
Result returned by
segreg().- Attributes:
- r2rnp.ndarray
Recovered 4×4 RAS-to-RAS transform mapping moving space into the chosen target space.
- labelslist[int]
Label IDs that participated in the final fit.
- target_namestr
Human-readable identifier for the target geometry written into output LTAs.
- target_geometryAny or None
Geometry object describing the target space. This may be a nibabel image, a header-like dictionary loaded from a centroid target file, or
Nonewhen the target geometry is unknown.- target_affinenp.ndarray or None
Target voxel-to-RAS affine when explicit target geometry is available.
- target_shapetuple[int, int, int] or None
Target spatial shape when explicit target geometry is available.
- Parameters:
r2r (ndarray)
labels (list[int])
target_name (str)
target_geometry (Any)
target_affine (ndarray | None)
target_shape (tuple[int, int, int] | None)
- neuroreg.segreg.register.segreg(seg, target_seg=None, *, centroids=None, dof=6, labels=None, label_set=None, min_common_labels=None, flipped=False, midslice=None)[source]¶
Register a moving segmentation to another target via label centroids.
- Parameters:
- segImageLike
Moving segmentation image. This may be a path or a nibabel-like image.
- target_segImageLike or None, optional
Target segmentation image for segmentation-to-segmentation registration.
- centroidsstr or Path or None, optional
Path to a centroid target JSON file or the name of a bundled centroid target such as
"fsaverage".- dof{3, 6, 7, 9, 12}, default=6
Degrees of freedom for the closed-form fit.
3selects translation-only,6rigid,7rigid plus global scale,9rigid plus anisotropic scaling without shear, and12affine registration.- labelslist[int] or None, optional
Explicit label subset override.
- label_set{‘all_shared’, ‘target_centroids’, ‘cortex_lr_pairs’} or None, optional
Named label preset. Mode-specific defaults are used when omitted.
- min_common_labelsint or None, optional
Minimum number of matched labels required to proceed. When omitted, the default is
1for translation-only,3for rigid/similarity, and4for anisotropic-scale or affine registration.- flippedbool, default=False
If
True, ignore external targets and register the moving segmentation to a left-right flipped self target for upright or midspace use cases.- midslicefloat or None, optional
Explicit sagittal mid-slice used only with
flipped=True. When omitted, the geometric center of the moving image is used.
- Returns:
- RegistrationResult
Result object containing the recovered RAS transform, participating labels, and target geometry metadata.
- Raises:
- ValueError
If the arguments define no valid target, define multiple targets, or do not provide enough matched labels for the requested fit.
- Parameters:
seg (str | Path | Any)
target_seg (str | Path | Any | None)
centroids (str | Path | None)
dof (int)
labels (list[int] | None)
label_set (Literal['all_shared', 'target_centroids', 'cortex_lr_pairs'] | None)
min_common_labels (int | None)
flipped (bool)
midslice (float | None)
- Return type:
- neuroreg.segreg.register.export_segmentation_target(seg, out_path, *, geometry=None, labels=None)[source]¶
Compute segmentation centroids and write a centroid target JSON file.
- Parameters:
- segImageLike
Segmentation image or path used to compute scanner-RAS centroids.
- out_pathstr or Path
Output JSON path.
- geometryImageLike or None, optional
Optional image or path whose geometry metadata should be embedded in the target file. When omitted, the segmentation geometry is embedded.
- labelslist[int] or None, optional
Optional label subset to export. When omitted, all non-zero labels are written.
- Returns:
- None
Writes the selected centroid target payload to
out_path.
- Parameters:
seg (str | Path | Any)
out_path (str | Path)
geometry (str | Path | Any | None)
labels (list[int] | None)
- Return type:
None
neuroreg.segreg.points¶
Closed-form point-set registration helpers.
This module implements the small family of transform models used by
segreg: translation-only, rigid, similarity, anisotropic no-shear, and
full affine fits between paired 3-D point sets.
- neuroreg.segreg.points.find_rotation(p_mov, p_dst)[source]¶
Estimate the best-fit proper rotation between centered point sets.
- Parameters:
- p_mov, p_dstarray-like
Mean-centered moving and destination point arrays with matching shape.
- Returns:
- np.ndarray
(3, 3)proper rotation matrix minimizing the least-squares error.
- Parameters:
p_mov (ArrayLike)
p_dst (ArrayLike)
- Return type:
NDArray[float64]
Notes
The solution uses the Kabsch SVD update and flips the final singular vector when necessary to enforce a positive determinant.
- neuroreg.segreg.points.find_translation(p_mov, p_dst)[source]¶
Fit a translation-only transform between paired 3-D point sets.
- Parameters:
- p_mov, p_dstarray-like
Paired moving and destination points with shape
(N, 3).
- Returns:
- np.ndarray
(4, 4)homogeneous transform with identity linear part and a translation equal to the centroid offset between the point sets.
- Raises:
- ValueError
If no point correspondences are provided.
- Parameters:
p_mov (ArrayLike)
p_dst (ArrayLike)
- Return type:
NDArray[float64]
- neuroreg.segreg.points.find_rigid(p_mov, p_dst)[source]¶
Fit a rigid transform between paired 3-D point sets.
- Parameters:
- p_mov, p_dstarray-like
Paired moving and destination points with shape
(N, 3).
- Returns:
- np.ndarray
(4, 4)homogeneous rigid transform mapping moving points to destination points.
- Raises:
- ValueError
If fewer than three correspondences are provided or if the points are degenerate/collinear.
- Parameters:
p_mov (ArrayLike)
p_dst (ArrayLike)
- Return type:
NDArray[float64]
- neuroreg.segreg.points.find_similarity(p_mov, p_dst)[source]¶
Fit a similarity transform with one global scale factor.
- Parameters:
- p_mov, p_dstarray-like
Paired moving and destination points with shape
(N, 3).
- Returns:
- np.ndarray
(4, 4)homogeneous similarity transform.
- Raises:
- ValueError
If the correspondences are insufficient, degenerate, or imply a non-positive isotropic scale.
- Parameters:
p_mov (ArrayLike)
p_dst (ArrayLike)
- Return type:
NDArray[float64]
- neuroreg.segreg.points.find_rigid_anisotropic_scale(p_mov, p_dst, *, max_iter=64, tol=1e-10)[source]¶
Fit a rotation-plus-anisotropic-scale transform without shear.
- Parameters:
- p_mov, p_dstarray-like
Paired moving and destination points with shape
(N, 3).- max_iterint, default=64
Maximum number of alternating updates for the rotation and scale terms.
- tolfloat, default=1e-10
Convergence tolerance on the change in axis scales.
- Returns:
- np.ndarray
(4, 4)homogeneous transform whose linear part is constrained toR @ diag(s).
- Raises:
- ValueError
If fewer than four correspondences are provided, if the points do not span 3-D space, or if the fitted axis scales become non-positive.
- Parameters:
p_mov (ArrayLike)
p_dst (ArrayLike)
max_iter (int)
tol (float)
- Return type:
NDArray[float64]
Notes
The solver alternates exact updates for
Randdiag(s)while always rebuilding one constrained linear transform instead of composing incremental updates that would accumulate shear.
- neuroreg.segreg.points.find_affine(p_mov, p_dst)[source]¶
Fit a full affine transform between paired 3-D point sets.
- Parameters:
- p_mov, p_dstarray-like
Paired moving and destination points with shape
(N, 3).
- Returns:
- np.ndarray
(4, 4)least-squares affine transform.
- Raises:
- ValueError
If fewer than four correspondences are provided or if the points do not span affine 3-D space.
- Parameters:
p_mov (ArrayLike)
p_dst (ArrayLike)
- Return type:
NDArray[float64]
- neuroreg.segreg.points.register_points(p_mov, p_dst, dof=6)[source]¶
Dispatch to the closed-form point-set solver for a requested DoF.
- Parameters:
- p_mov, p_dstarray-like
Paired moving and destination points with shape
(N, 3).- dof{3, 6, 7, 9, 12}, default=6
Requested transform family.
- Returns:
- np.ndarray
(4, 4)homogeneous transform returned by the selected solver.
- Raises:
- ValueError
If
dofis not one of the supported closed-form solvers.
- Parameters:
p_mov (ArrayLike)
p_dst (ArrayLike)
dof (int)
- Return type:
NDArray[float64]
neuroreg.segreg.centroids¶
Centroid extraction and matching helpers for label images.
These utilities keep image loading, centroid computation, and shared-label assembly in one place so higher-level registration code can focus on transform estimation rather than segmentation bookkeeping.
- neuroreg.segreg.centroids.compute_voxel_centroids_from_seg(seg_img, label_ids=None)[source]¶
Compute voxel-space centroids for labels in a segmentation image.
- Parameters:
- seg_imgImageLike
Segmentation image or path.
- label_idslist[int] or None, optional
Explicit label subset to evaluate. When omitted, all non-zero labels in the segmentation are used.
- Returns:
- dict[int, np.ndarray or None]
Mapping from label ID to centroid in voxel coordinates. Labels with no matching voxels are assigned
None.
- Parameters:
seg_img (str | Path | Any)
label_ids (list[int] | None)
- Return type:
dict[int, NDArray[float64] | None]
- neuroreg.segreg.centroids.compute_ras_centroids_from_seg(seg_img, label_ids=None)[source]¶
Compute scanner-RAS centroids for labels in a segmentation image.
- Parameters:
- seg_imgImageLike
Segmentation image or path.
- label_idslist[int] or None, optional
Explicit label subset to evaluate. When omitted, all non-zero labels in the segmentation are used.
- Returns:
- dict[int, np.ndarray or None]
Mapping from label ID to centroid in scanner-RAS coordinates. Labels with no matching voxels are assigned
None.
- Parameters:
seg_img (str | Path | Any)
label_ids (list[int] | None)
- Return type:
dict[int, NDArray[float64] | None]
- neuroreg.segreg.centroids.collect_joint_centroids(mov_centroids, ref_centroids, *, min_common_labels)[source]¶
Collect matched centroid arrays for labels present in both inputs.
- Parameters:
- mov_centroidsdict[int, np.ndarray or None]
Moving-image centroid mapping.
- ref_centroidsdict[int, np.ndarray or None]
Reference or atlas centroid mapping.
- min_common_labelsint
Minimum number of shared labels required to continue.
- Returns:
- mov_pointsnp.ndarray
(N, 3)moving centroid array.- ref_pointsnp.ndarray
(N, 3)reference centroid array.- labelslist[int]
Sorted shared labels used to build the paired arrays.
- Raises:
- ValueError
If fewer than
min_common_labelsvalid correspondences are found.
- Parameters:
mov_centroids (dict[int, NDArray[float64] | None])
ref_centroids (dict[int, NDArray[float64]] | dict[int, NDArray[float64] | None])
min_common_labels (int)
- Return type:
tuple[NDArray[float64], NDArray[float64], list[int]]
- neuroreg.segreg.centroids.build_flipped_centroid_targets(voxel_centroids, lr_pairs, *, mid_slice, min_common_labels)[source]¶
Build paired voxel centroids for left-right flipped self-registration.
- Parameters:
- voxel_centroidsdict[int, np.ndarray or None]
Moving-image centroid mapping in voxel coordinates.
- lr_pairstuple[tuple[int, int], …]
Left/right label pairs defining the mirrored correspondences.
- mid_slicefloat
Sagittal mid-slice about which the x coordinate is mirrored.
- min_common_labelsint
Minimum number of participating labels required to continue.
- Returns:
- source_pointsnp.ndarray
(N, 3)source centroid array in voxel coordinates.- target_pointsnp.ndarray
(N, 3)mirrored target centroid array in voxel coordinates.- labelslist[int]
Flattened label list matching the returned point order.
- Raises:
- ValueError
If fewer than
min_common_labelsmirrored correspondences are found.
- Parameters:
voxel_centroids (dict[int, NDArray[float64] | None])
lr_pairs (tuple[tuple[int, int], ...])
mid_slice (float)
min_common_labels (int)
- Return type:
tuple[NDArray[float64], NDArray[float64], list[int]]
neuroreg.segreg.io¶
JSON I/O helpers for centroid target files.
The on-disk target format stores required label centroids plus optional geometry metadata used for LTA destination volume info. These helpers also accept the legacy centroid-only JSON shape where the top-level object is the label-to-point mapping itself.
- class neuroreg.segreg.io.GeometryDict[source]¶
Minimal geometry metadata needed for LTA destination volume info.
- class neuroreg.segreg.io.TargetFile(centroids, geometry=None)[source]¶
Centroid target payload loaded from or written to JSON.
- Parameters:
centroids (dict[int, NDArray[float64]])
geometry (GeometryDict | None)
- neuroreg.segreg.io.convert_numpy_to_json_serializable(obj)[source]¶
Convert nested NumPy-backed objects into JSON-safe Python values.
- Parameters:
- objobject
Object tree that may contain dictionaries, lists, tuples, NumPy arrays, or NumPy scalar types.
- Returns:
- object
Equivalent structure composed only of JSON-serializable Python values.
- Parameters:
obj (object)
- Return type:
object
- neuroreg.segreg.io.geometry_from_image(image)[source]¶
Extract LTA-relevant geometry metadata from an image or path.
- Parameters:
- imageAny
Image-like object or path accepted by
neuroreg.transforms.lta._header_info.
- Returns:
- GeometryDict
Geometry metadata compatible with bundled atlas targets and LTA writing.
- Parameters:
image (Any)
- Return type:
- neuroreg.segreg.io.read_target_json(path)[source]¶
Read a centroid target JSON file.
- Parameters:
- pathstr or Path
Path to a target JSON file.
- Returns:
- TargetFile
Target payload with required centroids and optional geometry.
- Parameters:
path (str | Path)
- Return type:
- neuroreg.segreg.io.write_target_json(path, centroids, *, geometry=None)[source]¶
Write a centroid target JSON file.
- Parameters:
- pathstr or Path
Output JSON path.
- centroidsdict[int, array-like or None]
Label-to-centroid mapping. Entries with value
Noneare skipped.- geometryGeometryDict or None, optional
Optional geometry metadata to embed alongside the centroid coordinates.
- Returns:
- None
Writes the target payload to
path.
- Parameters:
path (str | Path)
centroids (dict[int, ArrayLike | None])
geometry (GeometryDict | None)
- Return type:
None
neuroreg.segreg.atlas¶
Bundled centroid target resources for segmentation-based registration.
- neuroreg.segreg.atlas.available_atlases()[source]¶
Return the names of bundled centroid targets.
- Return type:
tuple[str, …]
- neuroreg.segreg.atlas.load_atlas_target(name)[source]¶
Load a supported bundled centroid target.
- Parameters:
name (str)
- Return type:
- neuroreg.segreg.atlas.load_fsaverage_centroids()[source]¶
Load bundled fsaverage centroid coordinates.
- Return type:
dict[int, NDArray[float64]]
- neuroreg.segreg.atlas.load_fsaverage_data()[source]¶
Load bundled fsaverage geometry metadata.
- Return type:
tuple[NDArray[float64], GeometryDict]
- neuroreg.segreg.atlas.load_atlas_centroids(name)[source]¶
Load centroid coordinates for a supported bundled target.
- Parameters:
name (str)
- Return type:
dict[int, NDArray[float64]]
- neuroreg.segreg.atlas.load_atlas_data(name)[source]¶
Load geometry metadata for a supported bundled target.
- Parameters:
name (str)
- Return type:
tuple[NDArray[float64], GeometryDict]
- neuroreg.segreg.atlas.affine_from_header(header)[source]¶
Reconstruct a voxel-to-RAS affine from header-like geometry metadata.
- Parameters:
header (GeometryDict)
- Return type:
NDArray[float64]
neuroreg.segreg.labels¶
Label presets and left/right cortical pairing tables for segreg.
The helpers in this module provide stable label subsets for centroid-based registration modes, especially the left/right pairing used by upright/self-flip registration.