Stitching¶
Multi-station image stitching for combining overlapping field-of-view acquisitions into a single volume.
Stitching¶
TPTBox.stitching.stitching
¶
get_rotation_and_spacing_from_affine
¶
Decompose a NIfTI affine into its rotation matrix and voxel spacing.
Adapted from nibabel.orientations.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
affine
|
ndarray
|
4x4 affine transformation matrix. |
required |
Returns:
| Type | Description |
|---|---|
ndarray
|
A 2-tuple of |
ndarray
|
orthonormal matrix and |
Source code in TPTBox/stitching/stitching.py
get_ras_affine
¶
Build a RAS affine matrix from rotation, voxel spacing, and image origin.
Adapted from TorchIO's IO utilities.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
rotation
|
ndarray
|
3x3 orthonormal rotation matrix. |
required |
spacing
|
ndarray
|
1-D array of three voxel spacings (mm). |
required |
origin
|
ndarray
|
1-D array giving the index-space origin coordinates. |
required |
Returns:
| Type | Description |
|---|---|
ndarray
|
A 4x4 RAS affine matrix. |
Source code in TPTBox/stitching/stitching.py
get_all_corner_points
¶
Compute the eight world-space corner points of a voxel volume.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
affine
|
ndarray
|
4x4 affine mapping voxel indices to world coordinates. |
required |
shape
|
tuple[int, ...]
|
Volume shape (X, Y, Z). |
required |
Returns:
| Type | Description |
|---|---|
ndarray
|
Array of shape (8, 3) with the world-space coordinates of all eight |
ndarray
|
corners of the bounding box. |
Source code in TPTBox/stitching/stitching.py
get_array
¶
Extract the voxel data from a NIfTI image as a writable NumPy array.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
nii
|
Nifti1Image
|
Source NIfTI image. |
required |
Returns:
| Type | Description |
|---|---|
ndarray
|
A copy of the image data array with the original dtype preserved. |
Source code in TPTBox/stitching/stitching.py
set_array
¶
Return a new NIfTI image with the given array, preserving header and affine.
If the dtype of arr differs from the existing image, the header dtype is
updated accordingly.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
nii
|
Nifti1Image
|
Source NIfTI image whose header and affine are reused. |
required |
arr
|
ndarray
|
Replacement voxel data array. |
required |
Returns:
| Type | Description |
|---|---|
Nifti1Image
|
A new :class: |
Source code in TPTBox/stitching/stitching.py
argmin
¶
Return the index of the minimum element in a list.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
lst
|
list
|
Input list of comparable elements. |
required |
Returns:
| Type | Description |
|---|---|
int
|
Zero-based index of the smallest element. |
get_max_affine_and_shape
¶
get_max_affine_and_shape(points: ndarray, affines: list[ndarray], min_spacing: float | None = None, dtype: type = float, verbose: bool = False) -> Nifti1Image
Determine the optimal output affine and shape that encloses all input volumes.
Iterates over all input affines and selects the rotation that minimises the
bounding-box volume of the convex hull of points. The finest (minimum)
voxel spacing across all inputs is used, optionally clipped from below by
min_spacing.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
points
|
ndarray
|
World-space corner coordinates of all input volumes, shape (N, 3). |
required |
affines
|
list[ndarray]
|
List of 4x4 affine matrices, one per input volume. |
required |
min_spacing
|
float | None
|
Optional lower-bound on the output voxel spacing (mm). |
None
|
dtype
|
type
|
NumPy dtype for the output image data. |
float
|
verbose
|
bool
|
If True, prints chosen spacing, shape, origin, and optimal rotation to stdout. |
False
|
Returns:
| Type | Description |
|---|---|
Nifti1Image
|
A zeroed :class: |
Nifti1Image
|
to be used as a resampling target. |
Raises:
| Type | Description |
|---|---|
ValueError
|
If no valid rotation could be determined from |
Source code in TPTBox/stitching/stitching.py
121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 | |
compute_crop_slice
¶
Computes the minimum slice that removes unused space from the image and returns the corresponding slice tuple along with the origin shift required for centroids.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
minimum
|
int
|
The minimum value of the array (0 for MRI, -1024 for CT). Default value is 0. |
0
|
dist
|
int
|
The amount of padding to be added to the cropped image. Default value is 0. |
0
|
other_crop
|
tuple[slice, ...]
|
A tuple of slice objects representing the slice of an other image to be combined with the current slice. Default value is None. |
required |
Returns:
| Name | Type | Description |
|---|---|---|
ex_slice |
slice
|
A tuple of slice objects that need to be applied to crop the image. |
origin_shift |
slice
|
A tuple of integers representing the shift required to obtain the centroids of the cropped image. |
Note
- The computed slice removes the unused space from the image based on the minimum value.
- The padding is added to the computed slice.
- If the computed slice reduces the array size to zero, a ValueError is raised.
- If other_crop is not None, the computed slice is combined with the slice of another image to obtain a common region of interest.
- Only None slice is supported for combining slices.
Source code in TPTBox/stitching/stitching.py
dilate_msk
¶
Dilate each label in a segmentation mask by a fixed number of voxels.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
msk_i_data
|
ndarray
|
Integer-valued 3-D segmentation array. Label 0 is background. |
required |
mm
|
int
|
Number of dilation iterations to apply per label. |
5
|
connectivity
|
int
|
Structuring-element connectivity (1 = face-connected, 3 = fully-connected including diagonals). |
3
|
Returns:
| Type | Description |
|---|---|
ndarray
|
A dilated |
Source code in TPTBox/stitching/stitching.py
n4_bias_field_correction
¶
n4_bias_field_correction(nib: Nifti1Image, mask: ndarray | None = None, threshold: int = 60, shrink_factor: int = 4, convergence: dict | None = None, spline_param: int = 150, verbose: bool = False, weight_mask: ndarray | None = None, crop: bool = False) -> Nifti1Image
Apply N4 bias-field correction to a NIfTI image using ANTsPy.
A binary mask is derived automatically from voxels above threshold
and dilated by 3 voxels before correction is applied.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
nib
|
Nifti1Image
|
Input NIfTI image to correct. |
required |
mask
|
ndarray | None
|
Optional pre-computed binary mask passed to ANTsPy. Overridden
when |
None
|
threshold
|
int
|
Voxel intensity threshold for automatic mask generation. Set to 0 to disable automatic masking. |
60
|
shrink_factor
|
int
|
Image downsampling factor used inside ANTsPy to speed up computation. |
4
|
convergence
|
dict | None
|
ANTsPy convergence dict with keys |
None
|
spline_param
|
int
|
B-spline control point spacing for the bias field model. |
150
|
verbose
|
bool
|
If True, ANTsPy prints progress information. |
False
|
weight_mask
|
ndarray | None
|
Optional spatial weight mask passed to ANTsPy. |
None
|
crop
|
bool
|
If True, crops the corrected image to the region where the bias field differed from the input. |
False
|
Returns:
| Type | Description |
|---|---|
Nifti1Image
|
The bias-field-corrected NIfTI image. |
Raises:
| Type | Description |
|---|---|
ModuleNotFoundError
|
If |
Source code in TPTBox/stitching/stitching.py
270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 | |
buffer_reference
¶
buffer_reference(path: str | Path, bias_field: bool, crop: bool = False) -> np.ndarray | Nifti1Image
Load (and optionally bias-correct) a NIfTI file, caching the result.
Subsequent calls with the same path return the cached result without
re-reading or re-correcting the file.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
path
|
str | Path
|
File path of the NIfTI image. |
required |
bias_field
|
bool
|
If True, applies N4 bias-field correction before caching. |
required |
crop
|
bool
|
Passed to :func: |
False
|
Returns:
| Type | Description |
|---|---|
ndarray | Nifti1Image
|
The image data array (if |
ndarray | Nifti1Image
|
class: |
Source code in TPTBox/stitching/stitching.py
main
¶
main(images: list[str] | list[Path] | list[Nifti1Image], output: str | None, match_histogram: bool = False, store_ramp: bool = False, verbose: bool = False, min_value: float = 0, bias_field: bool = True, crop_to_bias_field: bool = False, crop_empty: bool = False, histogram: str | None = None, ramp_edge_min_value: int = 5, min_spacing: int | None = None, kick_out_fully_integrated_images: bool = False, is_segmentation: bool = False, dtype: type | str = float, save: bool = True, ramp_path=None) -> tuple[Nifti1Image | None, Nifti1Image | None]
Stitch multiple overlapping NIfTI volumes into a single output volume.
The algorithm:
- Optionally applies N4 bias-field correction and histogram matching to each input volume.
- Finds the minimum bounding-box affine that encloses all inputs.
- Resamples every volume into that common space.
- Computes per-voxel blending weights using distance-transform-based ramps in overlap regions.
- Combines all resampled volumes with those weights and saves the result.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
images
|
list[str] | list[Path] | list[Nifti1Image]
|
Input volumes as file paths or pre-loaded :class: |
required |
output
|
str | None
|
Output file path ( |
required |
match_histogram
|
bool
|
If True, matches the histogram of each volume to the previous one before stitching. |
False
|
store_ramp
|
bool
|
If True, also saves the per-volume blend weights as a 4-D NIfTI alongside the stitched output. |
False
|
verbose
|
bool
|
If True, prints progress messages to stdout. |
False
|
min_value
|
float
|
Background value (0 for MRI, -1024 for CT). Voxels at or below this value are replaced by it in the output. |
0
|
bias_field
|
bool
|
If True, applies N4 bias-field correction to each input before stitching. Forced to False for segmentations. |
True
|
crop_to_bias_field
|
bool
|
If True, crops each bias-corrected volume to the region affected by the correction. |
False
|
crop_empty
|
bool
|
If True, crops the final output to its non-background bounding box. |
False
|
histogram
|
str | None
|
Path or index string used as the histogram reference for
|
None
|
ramp_edge_min_value
|
int
|
Minimum thickness (voxels) of non-overlapping regions used when computing distance-transform ramps. |
5
|
min_spacing
|
int | None
|
Minimum allowed output voxel spacing (mm). Overrides the finest input spacing when specified. |
None
|
kick_out_fully_integrated_images
|
bool
|
If True, recursively removes volumes that are fully enclosed within another volume. |
False
|
is_segmentation
|
bool
|
If True, disables bias field, histogram matching, and uses nearest-neighbour resampling with integer dtype selection. |
False
|
dtype
|
type | str
|
Output data type. Accepts a Python type (e.g. |
float
|
save
|
bool
|
If True, writes the stitched image to |
True
|
Returns:
| Type | Description |
|---|---|
Nifti1Image | None
|
A 2-tuple |
Nifti1Image | None
|
unless |
tuple[Nifti1Image | None, Nifti1Image | None]
|
than two images are supplied. |
Source code in TPTBox/stitching/stitching.py
433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 | |
Stitching Tools¶
TPTBox.stitching.stitching_tools
¶
stitching
¶
stitching(bids_files: list[BIDS_FILE | NII | str | Path] | list, out: BIDS_FILE | str | Path, is_seg: bool = False, is_ct: bool = False, verbose_stitching: bool = False, bias_field: bool = False, kick_out_fully_integrated_images: bool = True, verbose: bool = True, dtype: type = float, match_histogram: bool = False, store_ramp: bool = False, ramp_path=None) -> tuple
Stitch a list of BIDS/NII volumes into a single output NIfTI file.
Convenience wrapper around :func:stitching_raw that accepts BIDS_FILE
objects, NII instances, or raw file paths and resolves the output path from
a BIDS_FILE if necessary.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
bids_files
|
list[BIDS_FILE | NII | str | Path] | list
|
Input volumes to stitch. Accepts any mix of
:class: |
required |
out
|
BIDS_FILE | str | Path
|
Destination path for the stitched volume. When a
:class: |
required |
is_seg
|
bool
|
If True, treats the inputs as segmentation images (disables bias field and histogram matching, uses integer dtypes). |
False
|
is_ct
|
bool
|
If True, sets the background |
False
|
verbose_stitching
|
bool
|
If True, forwards verbose output from the low-level stitching routine. |
False
|
bias_field
|
bool
|
If True, applies N4 bias-field correction to each input. |
False
|
kick_out_fully_integrated_images
|
bool
|
If True, removes volumes that are fully contained within another volume before stitching. |
True
|
verbose
|
bool
|
If True, logs the output path before stitching. |
True
|
dtype
|
type
|
NumPy dtype for the output array. |
float
|
match_histogram
|
bool
|
If True, matches histograms between consecutive inputs. |
False
|
store_ramp
|
bool
|
If True, also returns the per-volume blending weight array. |
False
|
Returns:
| Type | Description |
|---|---|
tuple
|
A 2-tuple |
tuple
|
func: |
Source code in TPTBox/stitching/stitching_tools.py
GNC_stitch_T2w
¶
GNC_stitch_T2w(HWS: Image_Reference, BWS: Image_Reference, LWS: Image_Reference, n4_after_stitch: bool = False) -> NII
Apply N4 bias correction to each chunk, stitch them, then apply N4 again.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
HWS
|
NII | str | Path
|
Cervical region |
required |
BWS
|
NII | str | Path
|
Thoracic region |
required |
LWS
|
NII | str | Path
|
Lumbar region |
required |
n4_after_stitch
|
bool
|
where to do n4 correction after stitching again |
False
|
Returns: NII: Stitched and n4 corrected nifty
Source code in TPTBox/stitching/stitching_tools.py
n4_bias
¶
n4_bias(nii: NII, threshold: int = 70, spline_param: int = 200, dtype2nii: bool = False, norm: int = -1) -> tuple[NII, NII]
Apply N4 bias-field correction to a NII image with automatic mask generation.
Voxels below threshold are excluded from the bias estimation via a
dilated binary mask.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
nii
|
NII
|
Input image to correct. |
required |
threshold
|
int
|
Intensity threshold below which voxels are excluded from the bias estimation mask. |
70
|
spline_param
|
int
|
B-spline control point spacing for the bias field model. |
200
|
dtype2nii
|
bool
|
If True, casts the corrected image back to the original
dtype of |
False
|
norm
|
int
|
If != -1, normalizes the corrected image so its maximum equals
|
-1
|
Returns:
| Type | Description |
|---|---|
NII
|
A 2-tuple |
NII
|
dilated binary mask used during correction. |