Models¶
Model discovery/loading and the segmentation/labeling model classes.
spineps.get_models¶
spineps.get_models
¶
Discovery, lookup and instantiation of SPINEPS segmentation and labeling models from disk or remote URLs.
get_semantic_model
¶
Finds and returns a semantic (subregion) model by name.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
model_name
|
str
|
Id of the semantic model to load (case-insensitive). |
required |
**kwargs
|
Extra keyword arguments forwarded to the model constructor. |
{}
|
Returns:
| Name | Type | Description |
|---|---|---|
Segmentation_Model |
Segmentation_Model
|
The instantiated semantic model. |
Raises:
| Type | Description |
|---|---|
KeyError
|
If no model with the given name is available. |
Source code in spineps/get_models.py
get_instance_model
¶
Finds and returns an instance (vertebra) model by name.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
model_name
|
str
|
Id of the instance model to load (case-insensitive). |
required |
**kwargs
|
Extra keyword arguments forwarded to the model constructor. |
{}
|
Returns:
| Name | Type | Description |
|---|---|---|
Segmentation_Model |
Segmentation_Model
|
The instantiated instance model. |
Raises:
| Type | Description |
|---|---|
KeyError
|
If no model with the given name is available. |
Source code in spineps/get_models.py
get_labeling_model
¶
Finds and returns a vertebra-labeling model by name.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
model_name
|
str
|
Id of the labeling model to load (case-insensitive). |
required |
**kwargs
|
Extra keyword arguments forwarded to the model constructor. |
{}
|
Returns:
| Name | Type | Description |
|---|---|---|
VertLabelingClassifier |
VertLabelingClassifier
|
The instantiated labeling classifier. |
Raises:
| Type | Description |
|---|---|
KeyError
|
If no model with the given name is available. |
Source code in spineps/get_models.py
modelid2folder_semantic
¶
Returns the dictionary mapping semantic model ids to their corresponding path.
Uses the cached mapping if available, otherwise scans the configured models directory.
Returns:
| Type | Description |
|---|---|
dict[str, Path | str]
|
dict[str, Path | str]: Mapping from semantic model id to its folder path or download URL. |
Source code in spineps/get_models.py
modelid2folder_instance
¶
Returns the dictionary mapping instance model ids to their corresponding path.
Uses the cached mapping if available, otherwise scans the configured models directory.
Returns:
| Type | Description |
|---|---|
dict[str, Path | str]
|
dict[str, Path | str]: Mapping from instance model id to its folder path or download URL. |
Source code in spineps/get_models.py
modelid2folder_labeling
¶
Returns the dictionary mapping labeling model ids to their corresponding path.
Uses the cached mapping if available, otherwise scans the configured models directory.
Returns:
| Type | Description |
|---|---|
dict[str, Path | str]
|
dict[str, Path | str]: Mapping from labeling model id to its folder path or download URL. |
Source code in spineps/get_models.py
check_available_models
¶
check_available_models(
models_folder: str | Path, verbose: bool = False
) -> tuple[
dict[str, Path | str],
dict[str, Path | str],
dict[str, Path | str],
]
Searches the given directory for models and sorts them into semantic, instance and labeling id-to-folder maps.
Recursively finds all inference_config.json files, loads each config and assigns the model to the labeling map (classifier), the instance map (segmentation input modality) or the semantic map (everything else). The results are cached in module-level globals. Models whose config fails to load are skipped.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
models_folder
|
str | Path
|
The folder to be analyzed for models. |
required |
verbose
|
bool
|
If true, logs models that were skipped because their config could not be loaded. Defaults to False. |
False
|
Returns:
| Type | Description |
|---|---|
tuple[dict[str, Path | str], dict[str, Path | str], dict[str, Path | str]]
|
tuple[dict[str, Path | str], dict[str, Path | str], dict[str, Path | str]]: The semantic, instance and labeling id-to-folder maps. |
Raises:
| Type | Description |
|---|---|
AssertionError
|
If models_folder does not exist. |
Source code in spineps/get_models.py
modeltype2class
¶
Maps a ModelType to the corresponding model class.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
modeltype
|
ModelType
|
The model type from the inference config. |
required |
Raises:
| Type | Description |
|---|---|
NotImplementedError
|
If the model type is not supported. |
Returns:
| Name | Type | Description |
|---|---|---|
type |
type
|
The class to instantiate (Segmentation_Model_NNunet, Segmentation_Model_Unet3D or VertLabelingClassifier). |
Source code in spineps/get_models.py
get_actual_model
¶
get_actual_model(
in_config: str | Path, use_cpu: bool = False, **kwargs
) -> Segmentation_Model | VertLabelingClassifier
Creates and returns the appropriate model from a given inference config path.
Accepts either a path to an inference_config.json file or a folder containing exactly one such file (searched recursively). Loads the config, picks the matching model class and instantiates it.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
in_config
|
str | Path
|
Path to the model's inference config file, or to a folder containing it. |
required |
use_cpu
|
bool
|
If true, runs inference on CPU instead of GPU. Defaults to False. |
False
|
**kwargs
|
Extra keyword arguments forwarded to the model constructor. |
{}
|
Returns:
| Type | Description |
|---|---|
Segmentation_Model | VertLabelingClassifier
|
Segmentation_Model | VertLabelingClassifier: The instantiated model. |
Raises:
| Type | Description |
|---|---|
FileNotFoundError
|
If no inference_config.json is found in the given folder. |
AssertionError
|
If more than one inference_config.json is found in the given folder. |
Source code in spineps/get_models.py
spineps.seg_model¶
spineps.seg_model
¶
Segmentation model abstractions: the abstract Segmentation_Model and its nnU-Net and Unet3D subclasses.
Segmentation_Model
¶
Bases: ABC
Abstract base class wrapping a segmentation network together with its inference configuration.
Subclasses implement load() and run() for a concrete backend (e.g. nnU-Net or Unet3D). The class handles input preparation (reorientation, rescaling to the recommended zoom, padding), running the model and mapping the output back into the input space.
Attributes:
| Name | Type | Description |
|---|---|---|
name |
str
|
Optional human-readable model name. |
logger |
No_Logger
|
Logger used for all model output. |
use_cpu |
bool
|
If true, runs inference on CPU instead of GPU. |
inference_config |
Segmentation_Inference_Config
|
Configuration describing expected inputs, resolution range and labels. |
default_verbose |
bool
|
Default verbosity for printing. |
default_allow_tqdm |
bool
|
Whether a progress bar is shown during segmentation by default. |
model_folder |
str
|
Path to the model's folder on disk. |
predictor |
The loaded backend predictor, or None until load() is called. |
Source code in spineps/seg_model.py
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 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 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 265 266 267 268 269 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 | |
__init__
¶
__init__(
model_folder: str | Path,
inference_config: Segmentation_Inference_Config
| None = None,
use_cpu: bool = False,
default_verbose: bool = False,
default_allow_tqdm: bool = True,
)
Initializes the segmentation model, finding and loading the corresponding inference config for that model.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
model_folder
|
str | Path
|
Path to that model's folder. |
required |
inference_config
|
Segmentation_Inference_Config | None
|
Inference config to use; if None, loads "inference_config.json" from the model folder. Defaults to None. |
None
|
use_cpu
|
bool
|
If true, runs inference on CPU instead of GPU. Defaults to False. |
False
|
default_verbose
|
bool
|
If true, prints more information when used. Defaults to False. |
False
|
default_allow_tqdm
|
bool
|
If true, shows a progress bar while segmenting. Defaults to True. |
True
|
Raises:
| Type | Description |
|---|---|
AssertionError
|
If model_folder does not exist. |
Source code in spineps/seg_model.py
load
abstractmethod
¶
Loads the model weights from disk.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
folds
|
tuple[str, ...] | None
|
Which folds to load; if None, uses the folds from the inference config. Defaults to None. |
None
|
Returns:
| Name | Type | Description |
|---|---|---|
Self |
Self
|
This model with its predictor loaded. |
Source code in spineps/seg_model.py
calc_recommended_resampling_zoom
¶
Calculates the resolution a corresponding input should be resampled to for this model.
If the inference config defines a (min, max) resolution range, each axis of the input zoom is clamped into that range; otherwise the fixed configured resolution is returned.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
input_zoom
|
ZOOMS
|
Voxel spacing (mm) of the input image, per axis. |
required |
Returns:
| Name | Type | Description |
|---|---|---|
ZOOMS |
ZOOMS
|
Recommended voxel spacing (mm) to resample the input to before inference. |
Source code in spineps/seg_model.py
same_modelzoom_as_model
¶
Checks whether another model would resample a given input to the same resolution as this model.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
model
|
Self
|
The other segmentation model to compare against. |
required |
input_zoom
|
ZOOMS
|
Voxel spacing (mm) of the input image, per axis. |
required |
Returns:
| Name | Type | Description |
|---|---|---|
bool |
bool
|
True if both models' recommended resampling zooms agree on every axis within ZOOM_MATCH_TOLERANCE. |
Source code in spineps/seg_model.py
segment_scan
¶
segment_scan(
input_image: Image_Reference
| dict[InputType, Image_Reference],
pad_size: int = 0,
step_size: float | None = None,
resample_to_recommended: bool = True,
resample_output_to_input_space: bool = True,
verbose: bool = False,
) -> dict[OutputType, NII | None]
Segments a given input with this model.
Prepares each expected input (optional padding, reorientation to the model orientation and rescaling to the recommended zoom), runs the model and maps the outputs back into the input space.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
input_image
|
Image_Reference | dict[InputType, Image_Reference]
|
A single image, or a mapping from InputType to image for multi-input models. |
required |
pad_size
|
int
|
Padding added in each dimension (this many extra voxels on each side per axis), removed again from the output. Defaults to 0. |
0
|
step_size
|
float | None
|
Sliding-window tile step size; if None, uses the config default. Defaults to None. |
None
|
resample_to_recommended
|
bool
|
If true, rescales each input to the model's recommended zoom. Defaults to True. |
True
|
resample_output_to_input_space
|
bool
|
If true, resamples and pads the outputs back to the original input space. Defaults to True. |
True
|
verbose
|
bool
|
If true, prints verbose information. Defaults to False. |
False
|
Returns:
| Type | Description |
|---|---|
dict[OutputType, NII | None]
|
dict[OutputType, NII | None]: Mapping of output type to result NII (e.g. the segmentation mask, optionally softmax logits). |
Source code in spineps/seg_model.py
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 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 | |
modalities
¶
Returns the modalities this model supports.
Returns:
| Type | Description |
|---|---|
list[Modality]
|
list[Modality]: Modalities the model was trained for, as listed in its inference config. |
acquisition
¶
Returns the acquisition this model supports.
Returns:
| Name | Type | Description |
|---|---|---|
Acquisition |
Acquisition
|
Acquisition plane/type the model expects, as listed in its inference config. |
run
abstractmethod
¶
Runs the backend predictor on the prepared inputs.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
input_nii
|
list[NII]
|
Inputs already reoriented and rescaled to the model's expectation, in the configured order. |
required |
verbose
|
bool
|
If true, prints verbose information. Defaults to False. |
False
|
Returns:
| Type | Description |
|---|---|
dict[OutputType, NII | None]
|
dict[OutputType, NII | None]: Mapping of output type to result NII produced by the model. |
Source code in spineps/seg_model.py
print
¶
Logs text via the model's logger.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
*text
|
object
|
Items to print. |
()
|
verbose
|
bool | None
|
Overrides the default verbosity; if None, uses default_verbose. Defaults to None. |
None
|
Source code in spineps/seg_model.py
print_self
¶
modelid
¶
Returns an identifier string for this model.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
include_log_name
|
bool
|
If true and a name is set, appends the config log name. Defaults to False. |
False
|
Returns:
| Name | Type | Description |
|---|---|---|
str |
str
|
The model name, or the inference config's log name if no name is set. |
Source code in spineps/seg_model.py
dict_representation
¶
Builds a summary dictionary describing this model.
Returns:
| Type | Description |
|---|---|
dict[str, str]
|
dict[str, str]: Model id, model path, modalities, acquisition and resolution range as strings. |
Source code in spineps/seg_model.py
__str__
¶
Returns the model id together with its inference config representation.
Returns:
| Name | Type | Description |
|---|---|---|
str |
str
|
Human-readable description of the model. |
Source code in spineps/seg_model.py
__repr__
¶
Returns the same representation as str.
Returns:
| Name | Type | Description |
|---|---|---|
str |
str
|
Human-readable description of the model. |
Segmentation_Model_NNunet
¶
Bases: Segmentation_Model
Segmentation_Model backed by an nnU-Net predictor.
Source code in spineps/seg_model.py
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 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 | |
__init__
¶
__init__(
model_folder: str | Path,
inference_config: Segmentation_Inference_Config
| None = None,
use_cpu: bool = False,
default_verbose: bool = False,
default_allow_tqdm: bool = True,
)
Initializes an nnU-Net-backed segmentation model.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
model_folder
|
str | Path
|
Path to the nnU-Net model folder. |
required |
inference_config
|
Segmentation_Inference_Config | None
|
Inference config; if None, loads it from the model folder. Defaults to None. |
None
|
use_cpu
|
bool
|
If true, runs inference on CPU instead of GPU. Defaults to False. |
False
|
default_verbose
|
bool
|
If true, prints more information when used. Defaults to False. |
False
|
default_allow_tqdm
|
bool
|
If true, shows a progress bar while segmenting. Defaults to True. |
True
|
Source code in spineps/seg_model.py
load
¶
Loads the nnU-Net predictor and its ensemble folds from the model folder.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
folds
|
tuple[str, ...] | None
|
Folds to load; if None, uses the folds from the inference config. Defaults to None. |
None
|
Returns:
| Name | Type | Description |
|---|---|---|
Self |
Self
|
This model with its nnU-Net predictor loaded. |
Source code in spineps/seg_model.py
run
¶
Runs nnU-Net inference on the prepared inputs.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
input_nii
|
list[NII]
|
Inputs in the model's expected orientation and resolution, in the configured order. |
required |
verbose
|
bool
|
If true, prints verbose information. Defaults to False. |
False
|
Returns:
| Type | Description |
|---|---|
dict[OutputType, NII | None]
|
dict[OutputType, NII | None]: The segmentation mask under OutputType.seg and the softmax logits under OutputType.softmax_logits. |
Source code in spineps/seg_model.py
Segmentation_Model_Unet3D
¶
Bases: Segmentation_Model
Segmentation_Model backed by a single-input 3D U-Net (PyTorch Lightning PLNet).
Used as the instance (vertebra) model: it takes a segmentation mask as input and refines it into the vertebra instance output. Supports both the current multi-channel network and a legacy single-channel network.
Source code in spineps/seg_model.py
423 424 425 426 427 428 429 430 431 432 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 | |
__init__
¶
__init__(
model_folder: str | Path,
inference_config: Segmentation_Inference_Config
| None = None,
use_cpu: bool = False,
default_verbose: bool = False,
default_allow_tqdm: bool = True,
)
Initializes a 3D U-Net-backed segmentation model.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
model_folder
|
str | Path
|
Path to the model folder containing the checkpoint. |
required |
inference_config
|
Segmentation_Inference_Config | None
|
Inference config; if None, loads it from the model folder. Defaults to None. |
None
|
use_cpu
|
bool
|
If true, runs inference on CPU instead of GPU. Defaults to False. |
False
|
default_verbose
|
bool
|
If true, prints more information when used. Defaults to False. |
False
|
default_allow_tqdm
|
bool
|
If true, shows a progress bar while segmenting. Defaults to True. |
True
|
Raises:
| Type | Description |
|---|---|
AssertionError
|
If the inference config expects more than one input. |
Source code in spineps/seg_model.py
load
¶
Loads the 3D U-Net checkpoint, trying the current then the legacy PLNet implementation.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
folds
|
tuple[str, ...] | None
|
Unused; present for interface compatibility. Defaults to None. |
None
|
Returns:
| Name | Type | Description |
|---|---|---|
Self |
Self
|
This model with its 3D U-Net predictor loaded and moved to the selected device. |
Raises:
| Type | Description |
|---|---|
AssertionError
|
If exactly one checkpoint file is not found in the model folder. |
Source code in spineps/seg_model.py
run
¶
Runs the 3D U-Net on a single input segmentation mask.
Converts the input mask to a network tensor (one-hot encoded for the multi-channel network, or intensity-normalized for the legacy single-channel network), runs the forward pass and returns the per-voxel argmax class as a mask.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
input_nii
|
list[NII]
|
A single-element list containing the input segmentation mask. |
required |
verbose
|
bool
|
If true, prints verbose information. Defaults to False. |
False
|
Returns:
| Type | Description |
|---|---|
dict[OutputType, NII | None]
|
dict[OutputType, NII | None]: The predicted segmentation mask under OutputType.seg. |
Raises:
| Type | Description |
|---|---|
AssertionError
|
If more than one input is provided. |
Source code in spineps/seg_model.py
spineps.lab_model¶
spineps.lab_model
¶
Vertebra-labeling classifier: crops vertebra patches and predicts their anatomical labels.
VertLabelingClassifier
¶
Bases: Segmentation_Model
Classifier that assigns anatomical labels to individual vertebrae.
For each vertebra a patch is cropped around its center of mass, optionally rotated to align with the spine axis, normalized and center-cropped to a fixed size, then passed through a DenseNet (PLClassifier) that outputs per-head softmax predictions. Although it subclasses Segmentation_Model to reuse config loading, it does not perform voxel segmentation (run/segment_scan are not implemented).
Attributes:
| Name | Type | Description |
|---|---|---|
device |
device
|
Device the classifier runs on. |
final_size |
tuple[int, int, int]
|
Spatial size (voxels) the cropped patch is reduced to before inference. |
cutout_size |
tuple[int, int, int]
|
Patch size used when cutting out a vertebra, set from the loaded model. |
totensor |
ToTensor
|
Transform converting numpy arrays to tensors. |
transform |
Compose
|
Intensity normalization and center-crop transform applied to each patch. |
Source code in spineps/lab_model.py
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 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 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 265 266 267 268 269 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 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 | |
__init__
¶
__init__(
model_folder: str | Path,
inference_config: Segmentation_Inference_Config
| None = None,
use_cpu: bool = False,
default_verbose: bool = False,
default_allow_tqdm: bool = True,
)
Initializes the vertebra-labeling classifier and its preprocessing transforms.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
model_folder
|
str | Path
|
Path to the classifier's model folder. |
required |
inference_config
|
Segmentation_Inference_Config | None
|
Inference config; if None, loads it from the model folder. Defaults to None. |
None
|
use_cpu
|
bool
|
If true, runs inference on CPU instead of GPU. Defaults to False. |
False
|
default_verbose
|
bool
|
If true, prints more information when used. Defaults to False. |
False
|
default_allow_tqdm
|
bool
|
If true, shows a progress bar while predicting. Defaults to True. |
True
|
Raises:
| Type | Description |
|---|---|
AssertionError
|
If the inference config expects more than one input. |
Source code in spineps/lab_model.py
load
¶
Loads the classifier checkpoint and updates the preprocessing transform to the model's input size.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
folds
|
tuple[str, ...] | None
|
Unused; present for interface compatibility. Defaults to None. |
None
|
Returns:
| Name | Type | Description |
|---|---|---|
Self |
Self
|
This classifier with its predictor loaded and moved to the selected device. |
Raises:
| Type | Description |
|---|---|
AssertionError
|
If no matching checkpoint file is found in the model folder. |
Source code in spineps/lab_model.py
run
¶
Not implemented: the classifier does not perform voxel segmentation.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
input_nii
|
list[NII]
|
Unused. |
required |
verbose
|
bool
|
Unused. Defaults to False. |
False
|
Raises:
| Type | Description |
|---|---|
NotImplementedError
|
Always, since running it as a segmentation model is not meaningful. |
Source code in spineps/lab_model.py
segment_scan
¶
Not implemented: the classifier does not perform voxel segmentation.
Raises:
| Type | Description |
|---|---|
NotImplementedError
|
Always, since segmenting with this model is not meaningful. |
Source code in spineps/lab_model.py
from_modelfolder
classmethod
¶
Not implemented: construction directly from a model folder.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
model_folder
|
str | Path
|
Path to the model folder. |
required |
Raises:
| Type | Description |
|---|---|
NotImplementedError
|
Always; use from_checkpoint_path instead. |
Source code in spineps/lab_model.py
from_checkpoint_path
classmethod
¶
Constructs a classifier from a checkpoint file path.
Resolves the model folder as the grandparent of the checkpoint file and instantiates the classifier from it.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
checkpoint_path
|
str | Path
|
Path to the checkpoint (.ckpt) file. |
required |
Returns:
| Name | Type | Description |
|---|---|---|
VertLabelingClassifier |
VertLabelingClassifier
|
The constructed classifier. |
Raises:
| Type | Description |
|---|---|
AssertionError
|
If the checkpoint path does not exist. |
Source code in spineps/lab_model.py
run_all_position_instances
¶
run_all_position_instances(
img: NII, com_list: list[tuple[int, int, int]]
) -> dict[int, dict[str, np.ndarray]]
Runs the classifier on patches cropped around a list of center-of-mass positions.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
img
|
NII
|
The intensity image (reoriented in place to the default orientation). |
required |
com_list
|
list[tuple[int, int, int]]
|
Center-of-mass voxel positions, ordered top-to-bottom, one per vertebra. |
required |
Returns:
| Type | Description |
|---|---|
dict[int, dict[str, ndarray]]
|
dict[int, dict[str, np.ndarray]]: Mapping from list index to a dict with "soft" (softmax outputs) and "pred" (argmax class) per classifier head. |
Source code in spineps/lab_model.py
run_all_seg_instances
¶
Runs the classifier on every vertebra instance present in a segmentation mask.
For each label in the mask, computes the patch rotation angle from the neighbouring vertebra centers of mass (to align with the spine axis) and runs the classifier on the corresponding patch.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
img
|
NII
|
The intensity image. |
required |
seg
|
NII
|
The vertebra instance segmentation mask. |
required |
Returns:
| Type | Description |
|---|---|
dict[int, dict[str, ndarray]]
|
dict[int, dict[str, np.ndarray]]: Mapping from vertebra label to a dict with "soft" (softmax outputs) and "pred" (argmax class) per classifier head. |
Source code in spineps/lab_model.py
run_given_seg_pos
¶
run_given_seg_pos(
img: NII,
seg: NII,
vert_label: int | None = None,
angle: float | None = None,
) -> tuple[dict[str, np.ndarray], dict[str, np.ndarray]]
Runs the classifier on the patch centered on a single vertebra defined by a segmentation.
Selects the given vertebra label (or binarizes the mask if multiple labels are present), computes the center of its bounding box and runs the classifier there.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
img
|
NII
|
The intensity image. |
required |
seg
|
NII
|
The segmentation mask defining the vertebra location. |
required |
vert_label
|
int | None
|
Label of the vertebra to use; if None, the whole mask is used. Defaults to None. |
None
|
angle
|
float | None
|
Rotation angle (degrees) to align the patch with the spine axis. Defaults to None. |
None
|
Returns:
| Type | Description |
|---|---|
tuple[dict[str, ndarray], dict[str, ndarray]]
|
tuple[dict, dict]: The softmax outputs and argmax class predictions per classifier head. |
Source code in spineps/lab_model.py
run_given_center_pos
¶
run_given_center_pos(
img: NII,
seg: NII,
center_pos: tuple[int, int, int],
angle: float | None = None,
) -> tuple[dict[str, np.ndarray], dict[str, np.ndarray]]
Crops image and segmentation patches around a center point, optionally rotates them, and runs the classifier.
Cuts out a patch larger than the final size (with extra padding for rotation), reorients to (I, P, L), optionally rotates sagittally by the given angle, crops back to the cutout size and runs the classifier on the patch.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
img
|
NII
|
The intensity image (or a raw array). |
required |
seg
|
NII
|
The segmentation mask used as the second channel. |
required |
center_pos
|
tuple[int, int, int]
|
Voxel position to center the patch on. |
required |
angle
|
float | None
|
Rotation angle (degrees) to align the patch with the spine axis; no rotation if None or 0. Defaults to None. |
None
|
Returns:
| Type | Description |
|---|---|
tuple[dict[str, ndarray], dict[str, ndarray]]
|
tuple[dict, dict]: The softmax outputs and argmax class predictions per classifier head. |
Source code in spineps/lab_model.py
run_all_arrays
¶
Runs the classifier on a set of pre-cut image patches.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
img_arrays
|
dict[int, ndarray]
|
Mapping from vertebra id to its 3D image patch. |
required |
Returns:
| Type | Description |
|---|---|
dict[int, dict[str, ndarray]]
|
dict[int, dict[str, np.ndarray]]: Mapping from vertebra id to a dict with "soft" (softmax outputs) and "pred" (argmax class) per classifier head. |
Source code in spineps/lab_model.py
unit_vector
¶
angle_between
¶
Returns the angle in radians between vectors 'v1' and 'v2'::
angle_between((1, 0, 0), (0, 1, 0)) 1.5707963267948966 angle_between((1, 0, 0), (1, 0, 0)) 0.0 angle_between((1, 0, 0), (-1, 0, 0)) 3.141592653589793
Source code in spineps/lab_model.py
rotate_patch_sagitally
¶
rotate_patch_sagitally(
patch: ndarray,
angle: float,
msk: bool = False,
cval: int = 0,
) -> np.ndarray
Rotates a patch sagittally by a given angle (assuming the patch is in (I, P, L) orientation).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
patch
|
ndarray
|
A numpy array in (I, P, L) orientation. |
required |
angle
|
float
|
Angle of rotation in degrees. |
required |
msk
|
bool
|
If true, treats the patch as a mask and uses nearest-neighbour interpolation (order 0); otherwise uses cubic interpolation (order 3). Defaults to False. |
False
|
cval
|
int
|
Constant value used to fill regions outside the rotated patch. Defaults to 0. |
0
|
Returns:
| Type | Description |
|---|---|
ndarray
|
np.ndarray: The rotated patch with the same shape as the input. |