Segmentation¶
Integration with external segmentation pipelines: SPINEPS (spine segmentation) and VibeSeg / nnU-Net (general deep learning inference).
SPINEPS¶
TPTBox.segmentation.spineps
¶
get_outpaths_spineps
¶
get_outpaths_spineps(file_path: str | Path | BIDS_FILE, dataset: str | Path | None = None, derivative_name: str = 'derivative', ignore_bids_filter: bool = True) -> dict[Literal['out_spine', 'out_spine_raw', 'out_vert', 'out_vert_raw', 'out_unc', 'out_logits', 'out_snap', 'out_ctD', 'out_snap2', 'out_debug', 'out_raw'], Path]
Return the expected output paths for a SPINEPS segmentation run.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
file_path
|
str | Path | BIDS_FILE
|
Path to the input NIfTI image, or a |
required |
dataset
|
str | Path | None
|
Optional dataset root directory. Required when file_path is a
plain |
None
|
derivative_name
|
str
|
Name of the derivatives sub-folder used by SPINEPS. |
'derivative'
|
ignore_bids_filter
|
bool
|
If True, disable strict BIDS filename filtering. |
True
|
Returns:
| Type | Description |
|---|---|
dict[Literal['out_spine', 'out_spine_raw', 'out_vert', 'out_vert_raw', 'out_unc', 'out_logits', 'out_snap', 'out_ctD', 'out_snap2', 'out_debug', 'out_raw'], Path]
|
Dictionary mapping output keys (e.g. |
dict[Literal['out_spine', 'out_spine_raw', 'out_vert', 'out_vert_raw', 'out_unc', 'out_logits', 'out_snap', 'out_ctD', 'out_snap2', 'out_debug', 'out_raw'], Path]
|
the corresponding |
Source code in TPTBox/segmentation/spineps.py
run_spineps
¶
run_spineps(file_path: str | Path | BIDS_FILE, dataset: str | Path | None = None, model_semantic: str | Path = 't2w', model_instance: str | Path = 'instance', model_labeling: str | None = 't2w_labeling', derivative_name: str = 'derivative', override_semantic: bool = False, override_instance: bool = False, lambda_semantic=None, save_debug_data: bool = False, verbose: bool = False, save_raw: bool = False, ignore_compatibility_issues: bool = False, use_cpu: bool = False, **args) -> dict
Run the SPINEPS spine segmentation pipeline on a single image.
Handles model loading, BIDS path resolution, and delegates to SPINEPS'
process_img_nii function.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
file_path
|
str | Path | BIDS_FILE
|
Path to the input NIfTI image, or a |
required |
dataset
|
str | Path | None
|
Optional dataset root directory (used when file_path is a plain path and a BIDS root is required). |
None
|
model_semantic
|
str | Path
|
Semantic segmentation model name (e.g. |
't2w'
|
model_instance
|
str | Path
|
Instance segmentation model name or explicit path. |
'instance'
|
model_labeling
|
str | None
|
Labeling model name, or |
't2w_labeling'
|
derivative_name
|
str
|
Name of the derivatives sub-folder for outputs. |
'derivative'
|
override_semantic
|
bool
|
If True, recompute the semantic segmentation even when a cached result exists. |
False
|
override_instance
|
bool
|
If True, recompute the instance segmentation even when a cached result exists. |
False
|
lambda_semantic
|
Optional callable to post-process the semantic output. |
None
|
|
save_debug_data
|
bool
|
If True, save intermediate debug files. |
False
|
verbose
|
bool
|
If True, enable verbose logging. |
False
|
save_raw
|
bool
|
If True, also save unprocessed (raw) model outputs. |
False
|
ignore_compatibility_issues
|
bool
|
If True, suppress BIDS compatibility checks and model/image compatibility warnings. |
False
|
use_cpu
|
bool
|
If True, force CPU inference even if a GPU is available. |
False
|
**args
|
Additional keyword arguments forwarded to |
{}
|
Returns:
| Type | Description |
|---|---|
dict
|
The output paths dictionary returned by SPINEPS' |
Source code in TPTBox/segmentation/spineps.py
61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 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 | |
VibeSeg¶
TPTBox.segmentation.VibeSeg.vibeseg
¶
run_nnunet
¶
run_nnunet(i: list[Image_Reference], out_seg: str | Path, *, override: bool = False, gpu: int = 0, ddevice: Literal['cpu', 'cuda', 'mps'] = 'cuda', dataset_id: int = 80, model_path: str | Path | None = None, auto_download=False, keep_size=False, fill_holes=False, logits=False, mapping=None, crop=False, max_folds=None, mode='nearest', padd: int = 0, key_ResEnc='__nnUNet*ResEnc', **args) -> None
Run an nnU-Net model on a list of images (multi-channel) and save the segmentation.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
i
|
list[Image_Reference]
|
List of input image references forming one multi-channel sample. |
required |
out_seg
|
str | Path
|
Destination path for the segmentation output (NIfTI). |
required |
override
|
bool
|
If True, recompute and overwrite an existing output file. |
False
|
gpu
|
int
|
GPU device index to use for inference. |
0
|
ddevice
|
Literal['cpu', 'cuda', 'mps']
|
Compute device: |
'cuda'
|
dataset_id
|
int
|
nnU-Net dataset identifier. |
80
|
**args
|
Additional keyword arguments forwarded to |
{}
|
Source code in TPTBox/segmentation/VibeSeg/vibeseg.py
extract_vertebra_bodies_from_VibeSeg
¶
extract_vertebra_bodies_from_VibeSeg(nii_vibeSeg: Image_Reference, num_thoracic_verts: int = 12, num_lumbar_verts: int = 5, out_path: str | Path | None = None, out_path_poi: str | Path | None = None) -> tuple[NII, POI]
Extracts and labels vertebra bodies from a VibeSeg segmentation NIfTI file.
This function processes a segmentation mask containing vertebrae and intervertebral discs (IVDs). It separates individual vertebra bodies by eroding and splitting the mask at IVD regions, labels the vertebrae from bottom to top (lumbar and thoracic), and optionally saves the labeled mask and point-of-interest (POI) data.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
nii_vibeSeg
|
Image_Reference
|
Path or reference to the NIfTI file containing the VibeSeg segmentation mask. |
required |
num_thoracic_verts
|
int
|
Number of thoracic vertebrae to include. Defaults to 12. |
12
|
num_lumbar_verts
|
int
|
Number of lumbar vertebrae to include. Defaults to 5. |
5
|
out_path
|
str | Path | None
|
Path to save the processed mask data. If None, no files are saved. Defaults to None. |
None
|
out_path_poi
|
str | Path | None
|
Path to save the processed POI data (ending json). If None, no files are saved. Defaults to None. |
None
|
Returns:
| Name | Type | Description |
|---|---|---|
tuple |
tuple[NII, POI]
|
|
Notes
- Labels for the vertebrae follow the naming convention: L1=20 to L5=24 for lumbar and T1=8 to T12=19 for thoracic; T13 = 28.
- Cervical vertebrae and any unclassified regions are excluded (set to 0).
- The output files, if saved, will include the mask and POI data:
- Mask file:
<out_path> - POI file:
<out_path>with_poi.jsonsuffix recommended.
Example
nii_vibeSeg = "/path/to/vibe_segmentation.nii.gz" labeled_mask, centroids = extract_vertebra_bodies_from_nii_vibeSeg(nii_vibeSeg, out_path="output_mask.nii.gz")
Source code in TPTBox/segmentation/VibeSeg/vibeseg.py
183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 | |
nnU-Net Utilities¶
TPTBox.segmentation.nnUnet_utils.inference_api
¶
load_inf_model
¶
load_inf_model(model_folder: str | Path, step_size: float = 0.5, ddevice: str = 'cuda', use_folds: tuple[str | int, ...] | None = None, init_threads: bool = True, allow_non_final: bool = True, inference_augmentation: bool = False, use_gaussian: bool = True, verbose: bool = False, gpu: int | None = None, memory_base: int = 5000, memory_factor: int = 160, memory_max: int = 160000, wait_till_gpu_percent_is_free: float = 0.3) -> nnUNetPredictor
Load and initialise an nnU-Net model predictor from a trained model folder.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
model_folder
|
str | Path
|
Path to the nnU-Net result folder containing |
required |
step_size
|
float
|
Sliding-window step size as a fraction of the patch size. Larger values are faster but may reduce accuracy. Must be in (0, 1]. |
0.5
|
ddevice
|
str
|
Inference device: |
'cuda'
|
use_folds
|
tuple[str | int, ...] | None
|
Tuple of fold indices or fold names to load. Loads all
available folds when |
None
|
init_threads
|
bool
|
If True, configure PyTorch thread counts optimally for the selected device. |
True
|
allow_non_final
|
bool
|
If True, fall back to |
True
|
inference_augmentation
|
bool
|
If True, enable test-time mirroring augmentation. |
False
|
use_gaussian
|
bool
|
If True, apply Gaussian weighting in the sliding window. |
True
|
verbose
|
bool
|
If True, print progress information during model initialisation. |
False
|
gpu
|
int | None
|
GPU device index forwarded to the predictor. |
None
|
memory_base
|
int
|
Base GPU memory reservation in MB (default 5 000 MB = 5 GB). |
5000
|
memory_factor
|
int
|
Per-voxel memory scaling factor. The formula is
|
160
|
memory_max
|
int
|
Maximum GPU memory cap in MB (default 160 000 MB = 160 GB). |
160000
|
wait_till_gpu_percent_is_free
|
float
|
Fraction of GPU memory that must be free before inference is started. |
0.3
|
Returns:
| Type | Description |
|---|---|
nnUNetPredictor
|
Initialised |
Source code in TPTBox/segmentation/nnUnet_utils/inference_api.py
24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 | |
run_inference
¶
run_inference(input_nii: str | NII | list[NII], predictor: nnUNetPredictor, reorient_PIR: bool = False, logits: bool = False, verbose: bool = False) -> tuple[NII, NII | None, np.ndarray | None]
Run nnU-Net inference on a single image or list of images (multi-channel).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
input_nii
|
str | NII | list[NII]
|
Input as a path to a |
required |
predictor
|
nnUNetPredictor
|
Loaded |
required |
reorient_PIR
|
bool
|
If True, reorient each input image to PIR orientation before passing it to the model. |
False
|
logits
|
bool
|
If True, return raw softmax logits. Currently not implemented and
will raise |
False
|
verbose
|
bool
|
Unused; reserved for future logging support. |
False
|
Raises:
| Type | Description |
|---|---|
NotImplementedError
|
If logits is True. |
AssertionError
|
If input_nii is not a supported type, or if the output shape does not match the input shape. |
Returns:
| Type | Description |
|---|---|
tuple[NII, NII | None, ndarray | None]
|
A tuple of (segmentation_NII, uncertainty_map_or_None, softmax_logits_or_None). |
Source code in TPTBox/segmentation/nnUnet_utils/inference_api.py
sliding_nd_slices
¶
Apply fun to an N-D array using a sliding-window strategy with overlap.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
arr
|
ndarray
|
Input array to process. |
required |
patch_size
|
tuple
|
Size of each patch along every dimension. |
required |
overlap
|
int
|
Number of voxels to overlap between adjacent patches (symmetric). |
required |
fun
|
Callable applied to each patch; must return an array with the same shape as its input. |
required |
Returns:
| Type | Description |
|---|---|
ndarray
|
Reconstructed array of the same shape as arr with patch outputs stitched |
ndarray
|
together (overlap regions are overwritten by the most recent patch). |