Spine¶
Spine-specific utilities: modular 2D snapshot generation and statistical measurements (distances, angles, intervertebral disc POIs).
2D Snapshots¶
TPTBox.spine.snapshot2D.snapshot_modular
¶
Visualization_Type
¶
Bases: Enum
Enum selecting how voxels along a projection axis are reduced to a 2D pixel value.
Source code in TPTBox/spine/snapshot2D/snapshot_modular.py
Snapshot_Frame
dataclass
¶
Dataclass bundling an image, optional segmentation/centroids, and per-frame rendering settings.
Source code in TPTBox/spine/snapshot2D/snapshot_modular.py
sag_cor_curve_projection
¶
sag_cor_curve_projection(ctd_list: POI, img_data: ndarray, ctd_fallback: POI, cor_savgol_filter: bool = False, curve_location: Location = Location.Vertebra_Corpus) -> tuple[np.ndarray, np.ndarray, np.ndarray]
Makes a curve projection (spline interpolation) over the spline through the given centroids.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
ctd_list
|
POI
|
given Centroids |
required |
img_data
|
ndarray
|
given img_data |
required |
cor_savgol_filter
|
bool
|
If true, will perform the savgol filter also in coronal view |
False
|
curve_location
|
Location
|
Location of the curve's centroids to be used. |
Vertebra_Corpus
|
Returns:
| Name | Type | Description |
|---|---|---|
x_ctd |
tuple[ndarray, ndarray, ndarray]
|
ctd x values sorted (nparray), y_cord: interpolated y coords (nparray), z_cord: interpolated z coords (nparray) |
Source code in TPTBox/spine/snapshot2D/snapshot_modular.py
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 | |
curve_projected_slice
¶
curve_projected_slice(x_ctd: ndarray, img_data: ndarray, y_cord: ndarray, z_cord: ndarray, axial_heights: list[float] | None) -> tuple[np.ndarray, np.ndarray, np.ndarray]
Extract sagittal, coronal, and axial slice planes along a curved spinal path.
For each axial position the sagittal slice is taken at the interpolated coronal coordinate and vice versa. Outside the range of the centroids the boundary values are extrapolated.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
x_ctd
|
ndarray
|
Sorted x-indices of the vertebral centroids (integer array). |
required |
img_data
|
ndarray
|
3-D image volume in IPL orientation with shape (X, Y, Z). |
required |
y_cord
|
ndarray
|
Interpolated y (anterior-posterior) coordinates for each x position between the first and last centroid. |
required |
z_cord
|
ndarray
|
Interpolated z (left-right) coordinates for each x position between the first and last centroid. |
required |
axial_heights
|
list[float] | None
|
Heights for the axial fallback planes passed through to
|
required |
Returns:
| Type | Description |
|---|---|
ndarray
|
A tuple |
ndarray
|
2-D numpy array representing the sagittal, coronal, and axial |
ndarray
|
projections respectively. |
Source code in TPTBox/spine/snapshot2D/snapshot_modular.py
curve_projected_mean
¶
curve_projected_mean(img_data: ndarray, zms: tuple[float, float, float], x_ctd: ndarray, y_cord: ndarray, ctd_list: POI, thick_t: tuple[int, int] = (100, 300), axial_heights: list[float] | None = None) -> tuple[np.ndarray, np.ndarray, np.ndarray]
Compute mean-intensity curved-planar projections along the spinal curve.
For each axial position the sagittal mean is computed over all non-zero
voxels in that row, while the coronal mean is computed over a slab of
width thick_t centred on the interpolated y coordinate.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
img_data
|
ndarray
|
3-D image volume in IPL orientation with shape (X, Y, Z). |
required |
zms
|
tuple[float, float, float]
|
Voxel spacing (zoom) in mm for each axis |
required |
x_ctd
|
ndarray
|
Sorted x-indices of the vertebral centroids (integer array). |
required |
y_cord
|
ndarray
|
Interpolated y (anterior-posterior) coordinates for each x position between the first and last centroid. |
required |
ctd_list
|
POI
|
POI object whose region keys are used to adjust slab thickness near the sacrum. |
required |
thick_t
|
tuple[int, int]
|
Anterior and posterior slab half-widths in mm used for the
coronal projection |
(100, 300)
|
axial_heights
|
list[float] | None
|
Heights for the axial fallback planes. |
None
|
Returns:
| Type | Description |
|---|---|
tuple[ndarray, ndarray, ndarray]
|
A tuple |
Source code in TPTBox/spine/snapshot2D/snapshot_modular.py
curve_projected_mip
¶
curve_projected_mip(img_data: ndarray, zms: tuple[float, float, float], x_ctd: ndarray, y_cord: ndarray, ctd_list: POI, thick_t: tuple[int, int] = (100, 300), make_colored_depth: bool = False, axial_heights: list[float] | None = None) -> tuple[np.ndarray, np.ndarray, np.ndarray]
Compute maximum-intensity curved-planar projections along the spinal curve.
A slab of configurable thickness is extracted around the interpolated
spinal curve for each axial position, and the maximum intensity is
projected onto the output plane. Optionally the depth of the maximum is
colour-encoded using the inferno colourmap.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
img_data
|
ndarray
|
3-D image volume in IPL orientation with shape (X, Y, Z). |
required |
zms
|
tuple[float, float, float]
|
Voxel spacing (zoom) in mm for each axis |
required |
x_ctd
|
ndarray
|
Sorted x-indices of the vertebral centroids (integer array). |
required |
y_cord
|
ndarray
|
Interpolated y (anterior-posterior) coordinates for each x position between the first and last centroid. |
required |
ctd_list
|
POI
|
POI object (currently unused, reserved for future thickness adaptation near the sacrum). |
required |
thick_t
|
tuple[int, int]
|
Anterior and posterior slab half-widths in mm
|
(100, 300)
|
make_colored_depth
|
bool
|
If |
False
|
axial_heights
|
list[float] | None
|
Heights for the axial fallback planes. |
None
|
Returns:
| Type | Description |
|---|---|
ndarray
|
A tuple |
ndarray
|
|
ndarray
|
have shape |
Source code in TPTBox/spine/snapshot2D/snapshot_modular.py
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 | |
normalize_image
¶
Linearly rescale an array to the range [0, 1].
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
img
|
ndarray
|
Input array to normalise. |
required |
v_range
|
tuple[float, float] | None
|
Optional |
None
|
Returns:
| Type | Description |
|---|---|
ndarray
|
A float array with values in |
Source code in TPTBox/spine/snapshot2D/snapshot_modular.py
curve_projection_axial_fallback
¶
curve_projection_axial_fallback(img_data: ndarray, x_ctd: ndarray, heights: list[float] | None) -> np.ndarray
Build an axial composite plane for display as a fallback or from explicit heights.
When heights is given each value is interpreted as an absolute slice
index (if |h| >= 1) or as a fraction of the volume depth (if
|h| < 1). The slices are concatenated vertically. When heights
is None three slices centred on the median centroid are concatenated.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
img_data
|
ndarray
|
3-D image volume in IPL orientation with shape (X, Y, Z). |
required |
x_ctd
|
ndarray
|
Sorted x-indices of the vertebral centroids (integer array). |
required |
heights
|
list[float] | None
|
Explicit axial heights to extract, or |
required |
Returns:
| Type | Description |
|---|---|
ndarray
|
A 2-D numpy array representing the composed axial view. |
Source code in TPTBox/spine/snapshot2D/snapshot_modular.py
make_isotropic2d
¶
Resample a 2-D array to isotropic pixel spacing.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
arr2d
|
ndarray
|
Input 2-D array. |
required |
zms2d
|
tuple[float, float]
|
Voxel spacing |
required |
msk
|
bool
|
If |
False
|
Returns:
| Type | Description |
|---|---|
ndarray
|
Resampled 2-D array with isotropic pixel spacing. |
Source code in TPTBox/spine/snapshot2D/snapshot_modular.py
make_isotropic2dpluscolor
¶
make_isotropic2dpluscolor(arr3d: ndarray, zms2d: tuple[float, float], msk: bool = False) -> np.ndarray
Resample a 2-D or 2-D+RGB array to isotropic pixel spacing.
Delegates to :func:make_isotropic2d for scalar images. For colour
images (3rd dimension of size 3) each channel is resampled independently
and the results are stacked.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
arr3d
|
ndarray
|
Input array with shape |
required |
zms2d
|
tuple[float, float]
|
Voxel spacing |
required |
msk
|
bool
|
Passed through to :func: |
False
|
Returns:
| Type | Description |
|---|---|
ndarray
|
Resampled array with the same number of channels as the input. |
Source code in TPTBox/spine/snapshot2D/snapshot_modular.py
get_contrasting_stroke_color
¶
Return "gray" or "black" depending on the perceived luminance of rgb.
A dark foreground colour (luminance < 0.3) gets a "gray" stroke so
that text remains readable on dark backgrounds; all other colours receive
a "black" stroke.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
rgb
|
int | list[float] | tuple[float, ...]
|
Either an integer label index (looked up in the colour map) or an
RGB / RGBA tuple / list of floats in |
required |
Returns:
| Type | Description |
|---|---|
str
|
|
Source code in TPTBox/spine/snapshot2D/snapshot_modular.py
create_figure
¶
Create a matplotlib figure sized to contain all projection planes side by side.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
dpi
|
int
|
Output resolution in dots per inch. |
required |
planes
|
list[ndarray]
|
List of 2-D (or 3-D colour) arrays whose widths determine the column layout of the figure. |
required |
has_title
|
bool
|
When |
True
|
Returns:
| Type | Description |
|---|---|
tuple
|
A |
tuple
|
class: |
tuple
|
class: |
Source code in TPTBox/spine/snapshot2D/snapshot_modular.py
plot_sag_centroids
¶
plot_sag_centroids(axs: Axes, ctd: POI, zms: tuple[float, float, float], poi_labelmap: dict[int, str], hide_centroid_labels: bool, cmap: ListedColormap = cm_itk, curve_location: Location = Location.Vertebra_Corpus, show_these_subreg_poi: list[int | Location] | None = None) -> None
Overlay centroid circles and vertebra labels on a sagittal axis.
Points are drawn as filled circles coloured by vertebra label. Vertebra
names from poi_labelmap are added as bold text next to the circle when
hide_centroid_labels is False. Additional arrows and text
annotations stored in ctd.info["line_segments_sag"] and
ctd.info["text_sag"] are also rendered.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
axs
|
Axes
|
Matplotlib axes on which to draw. |
required |
ctd
|
POI
|
POI object containing centroid coordinates and optional rendering
hints in its |
required |
zms
|
tuple[float, float, float]
|
Voxel spacing |
required |
poi_labelmap
|
dict[int, str]
|
Mapping from vertebra region ID to display name. |
required |
hide_centroid_labels
|
bool
|
When |
required |
cmap
|
ListedColormap
|
Colour map used to assign per-vertebra colours. |
cm_itk
|
curve_location
|
Location
|
Sub-region location whose centroid receives the text label. |
Vertebra_Corpus
|
show_these_subreg_poi
|
list[int | Location] | None
|
If provided, only POIs with these sub-region IDs are plotted. |
None
|
Source code in TPTBox/spine/snapshot2D/snapshot_modular.py
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 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 | |
plot_cor_centroids
¶
plot_cor_centroids(axs: Axes, ctd: POI, zms: tuple[float, float, float], poi_labelmap: dict[int, str], hide_centroid_labels: bool, cmap: ListedColormap = cm_itk, curve_location: Location = Location.Vertebra_Corpus, show_these_subreg_poi: list[int | Location] | None = None) -> None
Overlay centroid circles and vertebra labels on a coronal axis.
Analogous to :func:plot_sag_centroids but uses the z-coordinate for the
horizontal axis instead of the y-coordinate. Additional arrows and text
stored in ctd.info["line_segments_cor"] and ctd.info["text_cor"]
are also rendered.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
axs
|
Axes
|
Matplotlib axes on which to draw. |
required |
ctd
|
POI
|
POI object containing centroid coordinates and optional rendering
hints in its |
required |
zms
|
tuple[float, float, float]
|
Voxel spacing |
required |
poi_labelmap
|
dict[int, str]
|
Mapping from vertebra region ID to display name. |
required |
hide_centroid_labels
|
bool
|
When |
required |
cmap
|
ListedColormap
|
Colour map used to assign per-vertebra colours. |
cm_itk
|
curve_location
|
Location
|
Sub-region location whose centroid receives the text label. |
Vertebra_Corpus
|
show_these_subreg_poi
|
list[int | Location] | None
|
If provided, only POIs with these sub-region IDs are plotted. |
None
|
Source code in TPTBox/spine/snapshot2D/snapshot_modular.py
738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 | |
make_2d_slice
¶
make_2d_slice(img: Image_Reference, ctd: POI, zms: tuple[float, float, float], msk: bool, visualization_type: Visualization_Type, ctd_fallback: POI, cor_savgol_filter: bool = False, to_ax: tuple[str, str, str] = ('I', 'P', 'L'), curve_location: Location = Location.Vertebra_Corpus, rescale_to_iso: bool = True, axial_heights: list[float] | None = None) -> tuple[np.ndarray, np.ndarray, np.ndarray]
Generate 2-D sagittal, coronal, and axial projection images from a volume.
The image is reoriented to to_ax and a spline through the vertebral
centroids is computed. Depending on visualization_type slices,
maximum-intensity projections, depth-coloured MIPs, or mean-intensity
projections are extracted. The result is optionally resampled to
isotropic pixel spacing.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
img
|
Image_Reference
|
Source image volume. |
required |
ctd
|
POI
|
POI object used to compute the spinal curve. |
required |
zms
|
tuple[float, float, float]
|
Voxel spacing |
required |
msk
|
bool
|
When |
required |
visualization_type
|
Visualization_Type
|
One of the :class: |
required |
ctd_fallback
|
POI
|
Fallback POI used when |
required |
cor_savgol_filter
|
bool
|
Whether to apply a Savitzky-Golay filter to the
coronal spline in :func: |
False
|
to_ax
|
tuple[str, str, str]
|
Target orientation axes as a 3-tuple of direction codes. |
('I', 'P', 'L')
|
curve_location
|
Location
|
Anatomical sub-region used for spline fitting. |
Vertebra_Corpus
|
rescale_to_iso
|
bool
|
When |
True
|
axial_heights
|
list[float] | None
|
Optional explicit axial slice heights; passed to
:func: |
None
|
Returns:
| Type | Description |
|---|---|
ndarray
|
A tuple |
ndarray
|
attr: |
ndarray
|
|
tuple[ndarray, ndarray, ndarray]
|
images. |
Source code in TPTBox/spine/snapshot2D/snapshot_modular.py
851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 | |
div0
¶
Divide a by b, replacing divisions by zero with fill.
Source code in TPTBox/spine/snapshot2D/snapshot_modular.py
to_cdt
¶
Load a POI from a reference and return it, or None if it is empty.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
ctd_bids
|
POI_Reference | None
|
A path, BIDS file, or POI object to load. |
required |
Returns:
| Type | Description |
|---|---|
POI | None
|
The loaded :class: |
POI | None
|
otherwise |
Source code in TPTBox/spine/snapshot2D/snapshot_modular.py
create_snapshot
¶
create_snapshot(snp_path: str | Path | list[str | Path] | list[str] | list[Path], frames: list[Snapshot_Frame], crop=False, check=False, to_ax=('I', 'P', 'L'), dpi=96, verbose: bool = False) -> None
Create virtual dx, sagittal, and coronal curved-planar CT snapshots with mask overlay.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
snp_path
|
str
|
Path to the new jpg |
required |
frames
|
List[Snapshot_Frame]
|
List of Images |
required |
crop
|
bool
|
crop output to vertebral masks (seg-vert). Defaults to False. |
False
|
check
|
bool
|
if true, check if snap is present and do not re-create. Defaults to False. |
False
|
to_ax
|
Orientation
|
Sets the Orientation. Can be used for flipping the image or fixing false rotations of the original inputs. |
('I', 'P', 'L')
|
dpi
|
int
|
Set the resolution. |
96
|
Source code in TPTBox/spine/snapshot2D/snapshot_modular.py
1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 | |
Snapshot Templates¶
TPTBox.spine.snapshot2D.snapshot_templates
¶
mip_shot
¶
mip_shot(ct_ref: BIDS_FILE, vert_msk: Image_Reference, subreg_ctd: POI_Reference, subreg_msk: Image_Reference | None = None, out_path: str | Path | None = None) -> None
Save a multi-panel CT snapshot combining slice, mean-intensity, and coloured-depth MIP views.
Three frames are always included:
- Standard CT slice view with vertebra segmentation and centroids (sagittal + coronal).
- Mean-intensity projection of the masked vertebra region only (sagittal + coronal, no segmentation overlay).
- Coloured-depth maximum-intensity projection of the bone above a 100 HU threshold (coronal only).
An optional fourth frame with the subregion mask is appended when
subreg_msk is provided.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
ct_ref
|
BIDS_FILE
|
BIDS file pointing to the CT image. |
required |
vert_msk
|
Image_Reference
|
Vertebra segmentation mask. |
required |
subreg_ctd
|
POI_Reference
|
Subregion centroids (POI reference). |
required |
subreg_msk
|
Image_Reference | None
|
Optional subregion segmentation mask for an extra frame. |
None
|
out_path
|
str | Path | None
|
Output file path. When |
None
|
Source code in TPTBox/spine/snapshot2D/snapshot_templates.py
sacrum_shot
¶
sacrum_shot(ct_ref: BIDS_FILE, vert_msk: Image_Reference, subreg_ctd: POI_Reference, add_ctd: list[POI_Reference] | None = None, mip_c: bool = False, out_path: str | Path | None = None) -> None
Save a CT snapshot focused on the sacrum region.
A primary sagittal + coronal frame is always created. Additional coronal
frames are appended for each extra centroid file in add_ctd. When
mip_c is True a coloured-depth MIP coronal frame is added.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
ct_ref
|
BIDS_FILE
|
BIDS file pointing to the CT image. If an instance of
:class: |
required |
vert_msk
|
Image_Reference
|
Vertebra segmentation mask. |
required |
subreg_ctd
|
POI_Reference
|
Primary subregion centroids (POI reference). |
required |
add_ctd
|
list[POI_Reference] | None
|
Optional list of additional centroid references, each rendered as an extra coronal frame. |
None
|
mip_c
|
bool
|
When |
False
|
out_path
|
str | Path | None
|
Output file path. When |
None
|
Source code in TPTBox/spine/snapshot2D/snapshot_templates.py
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 | |
spline_shot
¶
spline_shot(ct_ref: BIDS_FILE, vert_msk: Image_Reference, subreg_ctd: POI_Reference, spline_nii: NII, add_info: str = '', out_path: str | Path | None = None) -> None
Save a two-frame CT snapshot showing the spinal spline interpolation result.
Frame 1 shows the original vertebra mask overlaid on the CT (sagittal only). Frame 2 shows the spline NIfTI segmentation overlaid on the CT (sagittal + coronal) so that the spline quality can be assessed visually.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
ct_ref
|
BIDS_FILE
|
BIDS file pointing to the CT image. |
required |
vert_msk
|
Image_Reference
|
Vertebra segmentation mask. |
required |
subreg_ctd
|
POI_Reference
|
Subregion centroids (POI reference). |
required |
spline_nii
|
NII
|
NIfTI image containing the fitted spline segmentation. |
required |
add_info
|
str
|
Optional string appended to the |
''
|
out_path
|
str | Path | None
|
Output file path. When |
None
|
Source code in TPTBox/spine/snapshot2D/snapshot_templates.py
snapshot
¶
snapshot(ref: Image_Reference, vert_msk: Image_Reference, subreg_ctd: POI_Reference, subreg_msk: Image_Reference | None = None, out_path: str | Path | list[str | Path] | list[Path] | None = None, mode: str = 'MINMAX', crop: bool = False) -> list[str | Path]
Save a standard vertebra snapshot, auto-detecting CT vs. MRI mode.
Delegates to :func:mri_snapshot after setting mode to "CT" for
BIDS CT files or "MRI" for all other BIDS files.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
ref
|
Image_Reference
|
Source image reference. A :class: |
required |
vert_msk
|
Image_Reference
|
Vertebra segmentation mask. |
required |
subreg_ctd
|
POI_Reference
|
Subregion centroids (POI reference). |
required |
subreg_msk
|
Image_Reference | None
|
Optional subregion segmentation mask for an extra frame. |
None
|
out_path
|
str | Path | list[str | Path] | list[Path] | None
|
Output path(s). |
None
|
mode
|
str
|
Intensity window mode passed to :class: |
'MINMAX'
|
crop
|
bool
|
Whether to crop the output to the segmentation bounding box. |
False
|
Returns:
| Type | Description |
|---|---|
list[str | Path]
|
List of saved output paths. |
Source code in TPTBox/spine/snapshot2D/snapshot_templates.py
mri_snapshot
¶
mri_snapshot(mrt_ref: BIDS_FILE, vert_msk: Image_Reference, subreg_ctd: POI_Reference, subreg_msk: Image_Reference | None = None, out_path: str | Path | list[str | Path] | list[Path] | None = None, mode: str = 'MRI', crop: bool = False) -> list[str | Path]
Save a two-frame (or three-frame) MRI vertebra snapshot.
Frame 1: image with centroids but without segmentation overlay (to
check centroid placement without clutter).
Frame 2: image with both centroids and segmentation overlay.
Frame 3 (optional): image with the subregion mask overlay, added when
subreg_msk is provided.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
mrt_ref
|
BIDS_FILE
|
BIDS file pointing to the MRI image. |
required |
vert_msk
|
Image_Reference
|
Vertebra segmentation mask. |
required |
subreg_ctd
|
POI_Reference
|
Subregion centroids (POI reference). |
required |
subreg_msk
|
Image_Reference | None
|
Optional subregion segmentation mask for an extra frame. |
None
|
out_path
|
str | Path | list[str | Path] | list[Path] | None
|
Output path(s). When |
None
|
mode
|
str
|
Intensity window mode; defaults to |
'MRI'
|
crop
|
bool
|
Whether to crop output frames to the segmentation bounding box. |
False
|
Returns:
| Type | Description |
|---|---|
list[str | Path]
|
List of saved output paths. |
Source code in TPTBox/spine/snapshot2D/snapshot_templates.py
vibe_snapshot
¶
vibe_snapshot(mrt_ref: tuple[BIDS_FILE, BIDS_FILE, BIDS_FILE, BIDS_FILE], vert_msk: Image_Reference | None, subreg_ctd: POI_Reference, subreg_msk: Image_Reference, hide_centroids: bool = False, out_path: str | Path | None = None, verbose: bool = False) -> str | Path
Save a VIBE multi-contrast MRI snapshot with four Dixon phases.
Creates one sagittal frame for each of the four VIBE contrast phases in
mrt_ref, all with the subregion mask overlay. An optional fifth
frame shows the first phase in sagittal + coronal with the vertebra mask.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
mrt_ref
|
tuple[BIDS_FILE, BIDS_FILE, BIDS_FILE, BIDS_FILE]
|
Four-tuple of BIDS files corresponding to the VIBE Dixon phases (e.g. in-phase, opposed-phase, water, fat). |
required |
vert_msk
|
Image_Reference | None
|
Optional vertebra segmentation mask used for an extra
sagittal + coronal frame. Skipped when |
required |
subreg_ctd
|
POI_Reference
|
Subregion centroids (POI reference). |
required |
subreg_msk
|
Image_Reference
|
Subregion segmentation mask overlaid on all four phases. |
required |
hide_centroids
|
bool
|
When |
False
|
out_path
|
str | Path | None
|
Output file path. When |
None
|
verbose
|
bool
|
When |
False
|
Returns:
| Type | Description |
|---|---|
str | Path
|
Path to the saved snapshot image. |
Source code in TPTBox/spine/snapshot2D/snapshot_templates.py
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 441 442 443 444 445 446 447 448 449 | |
ct_mri_snapshot
¶
ct_mri_snapshot(mrt_ref: Image_Reference, ct_ref: Image_Reference, vert_msk_mrt: Image_Reference | None = None, subreg_ctd_mrt: POI_Reference | None = None, vert_msk_ct: Image_Reference | None = None, subreg_ctd_ct: POI_Reference | None = None, out_path: str | Path | None = None, return_frames: bool = False) -> list | str | Path
Save a two-frame snapshot comparing an MRI and a CT side by side.
Frame 1: MRI in "MRI" mode with optional vertebra mask and centroids.
Frame 2: CT in "CT" mode with optional vertebra mask and centroids.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
mrt_ref
|
Image_Reference
|
MRI image reference. |
required |
ct_ref
|
Image_Reference
|
CT image reference. |
required |
vert_msk_mrt
|
Image_Reference | None
|
Optional vertebra segmentation for the MRI frame. |
None
|
subreg_ctd_mrt
|
POI_Reference | None
|
Optional subregion centroids for the MRI frame. |
None
|
vert_msk_ct
|
Image_Reference | None
|
Optional vertebra segmentation for the CT frame. |
None
|
subreg_ctd_ct
|
POI_Reference | None
|
Optional subregion centroids for the CT frame. |
None
|
out_path
|
str | Path | None
|
Output file path. When |
None
|
return_frames
|
bool
|
When |
False
|
Returns:
| Type | Description |
|---|---|
list | str | Path
|
The list of :class: |
list | str | Path
|
is |
Source code in TPTBox/spine/snapshot2D/snapshot_templates.py
poi_snapshot
¶
poi_snapshot(ct_nii: BIDS_FILE, vert_msk: Image_Reference | None, subreg_ctd: POI_Reference, out_path: str | Path | None = None) -> None
Save a multi-frame CT snapshot visualising ligament attachment-point POIs.
The POIs are partitioned into lateral groups (dorsal _D, sinister
_S, median) and ligament groups (ALL, PLL, FL). Seven frames are
produced covering different sagittal and coronal views of these groups.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
ct_nii
|
BIDS_FILE
|
BIDS file pointing to the CT image. |
required |
vert_msk
|
Image_Reference | None
|
Optional vertebra segmentation mask. |
required |
subreg_ctd
|
POI_Reference
|
POI reference containing the ligament attachment points. |
required |
out_path
|
str | Path | None
|
Output file path. When |
None
|
Source code in TPTBox/spine/snapshot2D/snapshot_templates.py
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 | |
make_snap
¶
Generate a POI snapshot for the given file if it matches the expected subject index.
Source code in TPTBox/spine/snapshot2D/snapshot_templates.py
Distances¶
TPTBox.spine.spinestats.distances
¶
compute_all_distances
¶
compute_all_distances(poi: POI, vert: Image_Reference | None = None, subreg: Image_Reference | None = None, all_pois_computed: bool = False, recompute: bool = False) -> POI
Compute all registered anatomical distances and store them in poi.info.
Iterates over :data:distances_funs and calls :func:_compute_distance
for each entry. Results are accumulated in the returned POI object under
the corresponding key in poi.info.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
poi
|
POI
|
POI object to compute distances for and to store results in. |
required |
vert
|
Image_Reference | None
|
Vertebra segmentation image required when POIs have not been
pre-computed. May be |
None
|
subreg
|
Image_Reference | None
|
Subregion segmentation image required when POIs have not been
pre-computed. May be |
None
|
all_pois_computed
|
bool
|
When |
False
|
recompute
|
bool
|
When |
False
|
Returns:
| Type | Description |
|---|---|
POI
|
The updated :class: |
POI
|
stored under the keys defined in :data: |
Source code in TPTBox/spine/spinestats/distances.py
Angles¶
TPTBox.spine.spinestats.angles
¶
MoveTo
¶
Bases: Enum
Enum selecting which endplate or centre point of a vertebra is used as the measurement anchor.
Source code in TPTBox/spine/spinestats/angles.py
has_point
¶
Check if the given vertebra has a specific POI at the current MoveTo position.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
v
|
Vertebra_Instance | int
|
The vertebra instance or its ID. |
required |
poi
|
POI
|
The point of interest data structure. |
required |
Returns:
| Name | Type | Description |
|---|---|---|
bool |
bool
|
True if the POI exists for the specified MoveTo position, otherwise False. |
Source code in TPTBox/spine/spinestats/angles.py
get_location
¶
Determine the anatomical POI coordinates for the current MoveTo position in a vertebra.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
v
|
Vertebra_Instance | int
|
The vertebra instance or its ID. |
required |
poi
|
POI
|
The point of interest data structure. |
required |
Returns:
| Name | Type | Description |
|---|---|---|
tuple |
tuple
|
The location tuple that defines the position within the vertebra. |
Source code in TPTBox/spine/spinestats/angles.py
get_point
¶
Retrieve the 3D coordinates of a POI in a vertebra at the current MoveTo position.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
v
|
Vertebra_Instance | int
|
The vertebra instance or its ID. |
required |
poi
|
POI
|
The point of interest data structure. |
required |
Returns:
| Type | Description |
|---|---|
ndarray
|
np.ndarray: The 3D coordinates of the specified POI. |
Raises:
| Type | Description |
|---|---|
NotImplementedError
|
If the POI cannot be determined. |
Source code in TPTBox/spine/spinestats/angles.py
unit_vector
¶
Return the unit vector of the input vector.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
vector
|
ndarray
|
Any non-zero numeric array. |
required |
Returns:
| Type | Description |
|---|---|
ndarray
|
Array with the same direction as |
Source code in TPTBox/spine/spinestats/angles.py
angle_between
¶
Calculates the angle in radians between two vectors.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
v1
|
tuple
|
The first vector. |
required |
v2
|
tuple
|
The second vector. |
required |
Returns:
| Name | Type | Description |
|---|---|---|
float |
float
|
The angle in radians between vectors 'v1' and 'v2'. |
Examples:
>>> 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 TPTBox/spine/spinestats/angles.py
get_to_space
¶
Compute forward and inverse transformation matrices for the space defined by three orthogonal vectors.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
a
|
ndarray
|
First orthogonal vector. |
required |
b
|
ndarray
|
Second orthogonal vector. |
required |
c
|
ndarray
|
Third orthogonal vector. |
required |
Returns:
| Name | Type | Description |
|---|---|---|
tuple |
tuple[ndarray, ndarray]
|
A tuple containing two matrices (to_space, from_space): - to_space (np.ndarray): Transformation matrix to the canonical space. - from_space (np.ndarray): Transformation matrix from the canonical space. |
Source code in TPTBox/spine/spinestats/angles.py
cosine_distance
¶
Computes the cosine distance between two vectors.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
a
|
ndarray
|
The first vector. |
required |
b
|
ndarray
|
The second vector. |
required |
Returns:
| Name | Type | Description |
|---|---|---|
float |
float
|
The cosine distance between vectors 'a' and 'b'. |
Source code in TPTBox/spine/spinestats/angles.py
compute_angel_between_two_points_
¶
compute_angel_between_two_points_(poi: POI, vert_id1: Vertebra_Instance | int | None, vert_id2: Vertebra_Instance | int | None, direction: DIRECTIONS, vert_id1_mv: MoveTo = MoveTo.CENTER, vert_id2_mv: MoveTo = MoveTo.CENTER, project_2D=False, use_ivd_direction=False) -> float | None
Compute the 2D or 3D angle between two anatomical landmarks.
Useful for calculating coplanar angles, lordosis, and kyphosis depending on the direction specified.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
poi
|
POI
|
An object representing a point of interest that supports indexing
with point IDs and returns 3D coordinates. Must have methods |
required |
vert_id1
|
Vertebra_Instance | int | None
|
The identifier for the first point of interest. |
required |
vert_id2
|
Vertebra_Instance | int | None
|
The identifier for the second point of interest. |
required |
direction
|
DIRECTIONS
|
The direction in which to compute the angle. Possible values are: - "P" for Posterior, used for calculating lordosis and kyphosis. - "A" for Anterior. - "R" for Right, used for calculating coplanar angles. - "L" for Left. - "S" for Superior. - "I" for Inferior. |
required |
vert_id1_mv
|
MoveTo
|
MoveTo instance indicating the position to consider for the first vertebra. Defaults to MoveTo.CENTER. |
CENTER
|
vert_id2_mv
|
MoveTo
|
MoveTo instance indicating the position to consider for the second vertebra. Defaults to MoveTo.CENTER. |
CENTER
|
project_2d
|
bool
|
If True, computes the 2D projection of the angle. Defaults to False. |
required |
Returns:
| Type | Description |
|---|---|
float | None
|
float | None: The computed angle in degrees. Returns None if either vertebra ID is invalid. |
Raises:
| Type | Description |
|---|---|
NotImplementedError
|
If the direction |
Example
To compute the coplanar angle between two vertebrae with IDs 20 and 21:
compute_angel_between_two_points_(poi, 20, 21, "R")
To compute the lordosis angle between two vertebrae with IDs 20 and 21:
compute_angel_between_two_points_(poi, 20, 21, "P")
Source code in TPTBox/spine/spinestats/angles.py
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 | |
compute_lordosis_and_kyphosis
¶
Calculates the angles of cervical lordosis, thoracic kyphosis, and lumbar lordosis based on the given points of interest (POI).
This function determines the angles formed by specific vertebrae along the spine, which are indicative of spinal curvatures. The angles are calculated for three key regions: cervical, thoracic, and lumbar, representing lordosis and kyphosis.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
poi
|
POI
|
The points of interest object containing 3D coordinates for various vertebrae. It must include the vertebra direction information for proper calculation. (Location.Vertebra_Direction_Posterior) |
required |
project_2d
|
bool
|
If True, the calculation is done in 2D projection; otherwise, in 3D. Defaults to False. |
required |
Returns:
| Name | Type | Description |
|---|---|---|
dict |
dict[str, float | None]
|
A dictionary containing the following key-value pairs: - "cervical_lordosis": The angle of cervical lordosis, calculated between C2 and C7. - "thoracic_kyphosis": The angle of thoracic kyphosis, calculated between T1 and the last thoracic vertebra. - "lumbar_lordosis": The angle of lumbar lordosis, calculated between L1 and the last lumbar vertebra. |
Raises:
| Type | Description |
|---|---|
AssertionError
|
If the required vertebra direction information is not present in the POI. |
Notes
- It is essential that the
poicontains the posterior vertebra direction for accurate angle calculations. - Thoracic kyphosis is calculated from T1 to the last thoracic vertebra identified in the POI.
- Lumbar lordosis is calculated from L1 to the last lumbar vertebra identified in the POI.
Example
To compute the spinal angles for a given POI object:
angles = compute_lordosis_and_kyphosis(poi, project_2d=True) print(angles)
Source code in TPTBox/spine/spinestats/angles.py
compute_max_cobb_angle
¶
compute_max_cobb_angle(poi: POI, vertebrae_list=None, vert_id1_mv: MoveTo = MoveTo.TOP, vert_id2_mv: MoveTo = MoveTo.BOTTOM, project_2D=True, use_ivd_direction=False) -> tuple[float, int | None, int | None, int | None]
Calculates the maximum Cobb angle from a list of vertebrae using the points of interest (POI).
The Cobb angle is a measure commonly used to quantify the degree of spinal curvature, particularly for scoliosis. This function identifies the maximum Cobb angle by comparing angles between pairs of vertebrae in the specified list. You must compute have computed pois in the following structures: Version 1: poi = calc_poi_from_subreg_vert(nii, nii_subreg, subreg_id=[Location.Vertebra_Corpus,Location.Vertebra_Direction_Right]) ivd position will be interpolated. Version 2: poi = calc_poi_from_subreg_vert(nii, nii_subreg, subreg_id=[Location.Vertebra_Corpus,Location.Vertebra_Direction_Right,Location.Vertebra_Disc]) ivd (Vertebra_Disc) will be computed by the segmentation Version 3 (best): poi = calc_poi_from_subreg_vert(nii, nii_subreg, subreg_id=[Location.Vertebra_Corpus,Location.Vertebra_Direction_Right,Location.Vertebra_Disc,Location.Vertebra_Disc_Superior]) ivd (Vertebra_Disc) will be computed by the segmentation + use_ivd_direction = True will use the disc direction and will note if there is a large shift between vertebra without rotation.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
poi
|
POI
|
The points of interest object containing 3D coordinates for various vertebrae. |
required |
vertebrae_list
|
list
|
A list of vertebra instances to consider for Cobb angle calculation. If not provided, defaults to all cervical, thoracic, and lumbar vertebrae. |
None
|
vert_id1_mv
|
MoveTo
|
Enum indicating the move direction for the first vertebra (default is MoveTo.TOP). |
TOP
|
vert_id2_mv
|
MoveTo
|
Enum indicating the move direction for the second vertebra (default is MoveTo.BOTTOM). |
BOTTOM
|
project_2d
|
bool
|
If True, the calculation is done in 2D projection; otherwise, in 3D. Defaults to False. |
required |
Returns:
| Name | Type | Description |
|---|---|---|
tuple |
tuple[float, int | None, int | None, int | None]
|
A tuple containing the following elements: - max_angle (float): The maximum Cobb angle identified between any pair of vertebrae. - from_vert (int or None): The vertebra ID at which the maximum angle originates. - to_vert (int or None): The vertebra ID at which the maximum angle terminates. - apex (int or None): The vertebra ID that is the apex of the maximum Cobb angle curvature. |
Raises:
| Type | Description |
|---|---|
AssertionError
|
If the necessary direction data for computation is not present in the POI. |
Notes
- The function iterates through pairs of vertebrae to calculate the angles between them.
- It uses the
compute_angel_between_two_points_function to determine the angle between two vertebrae. - The apex is determined by finding the vertebra with the largest cosine distance to the calculated apex vector.
- Ensure that the vertebrae are provided in a correct anatomical order to avoid inaccurate results.
Example
To compute the maximum Cobb angle for a given POI object:
max_angle, from_vert, to_vert, apex = compute_max_cobb_angle(poi, project_2d=True) print(f"Max Angle: {max_angle}, From: {from_vert}, To: {to_vert}, Apex: {apex}") Max Angle: 35.6, From: 3, To: 12, Apex: 7
Source code in TPTBox/spine/spinestats/angles.py
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 532 533 | |
compute_max_cobb_angle_multi
¶
compute_max_cobb_angle_multi(poi: POI, vertebrae_list=None, threshold_deg=10, out_list=None, vert_id1_mv: MoveTo = MoveTo.TOP, vert_id2_mv: MoveTo = MoveTo.BOTTOM, use_ivd_direction=False, project_2D=True) -> list[tuple[float, int, int, int | None]]
Identifies multiple Cobb angles along the spine that exceed a given threshold.
This function calculates Cobb angles for a list of vertebrae and recursively finds multiple spinal curvatures that are large enough, as determined by a threshold angle. It is useful for detecting and evaluating scoliosis or other spinal deformities with multiple curves. You must compute have computed pois in the following structures: Version 1: poi = calc_poi_from_subreg_vert(nii, nii_subreg, subreg_id=[Location.Vertebra_Corpus,Location.Vertebra_Direction_Right]) ivd position will be interpolated. Version 2: poi = calc_poi_from_subreg_vert(nii, nii_subreg, subreg_id=[Location.Vertebra_Corpus,Location.Vertebra_Direction_Right,Location.Vertebra_Disc]) ivd (Vertebra_Disc) will be computed by the segmentation Version 3 (best): poi = calc_poi_from_subreg_vert(nii, nii_subreg, subreg_id=[Location.Vertebra_Corpus,Location.Vertebra_Direction_Right,Location.Vertebra_Disc,Location.Vertebra_Disc_Inferior]) ivd (Vertebra_Disc) will be computed by the segmentation + use_ivd_direction = True will use the disc direction and will note if there is a large shift between vertebra without rotation.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
poi
|
POI
|
The points of interest object containing 3D coordinates for various vertebrae. |
required |
vertebrae_list
|
list
|
A list of vertebra instances to consider for Cobb angle calculation. If not provided, defaults to all cervical, thoracic, and lumbar vertebrae. |
None
|
threshold_deg
|
float
|
The angle threshold in degrees. Only curves with angles greater than this value will be recorded. |
10
|
out_list
|
list
|
A list to store the results of the identified Cobb angles. If not provided, an empty list will be created and used. |
None
|
vert_id1_mv
|
MoveTo
|
Enum indicating the move direction for the first vertebra (default is MoveTo.TOP). |
TOP
|
vert_id2_mv
|
MoveTo
|
Enum indicating the move direction for the second vertebra (default is MoveTo.BOTTOM). |
BOTTOM
|
use_ivd_direction
|
Uses the IVD direction instead of the Vertebra direction for Lumbar and Thorax region. |
False
|
Returns:
| Name | Type | Description |
|---|---|---|
list |
list[tuple[float, int, int, int | None]]
|
A list of tuples, each containing: - max_angle (float): The Cobb angle identified between two vertebrae that exceeds the threshold. - from_vert (int): The vertebra ID at which the angle originates. - to_vert (int): The vertebra ID at which the angle terminates. - apex (int or None): The vertebra ID that is the apex of the curvature. |
Notes
- The function splits the list of vertebrae and recursively calculates Cobb angles for sublists.
- Only angles that are above the specified threshold are added to the output list.
- It uses
compute_max_cobb_angleto find the maximum Cobb angle within a given set of vertebrae.
Example
To compute multiple Cobb angles for a given POI object with a threshold of 15 degrees:
curves = compute_max_cobb_angle_multi(poi, threshold_deg=15) for curve in curves: print(f"Angle: {curve[0]}, From: {curve[1]}, To: {curve[2]}, Apex: {curve[3]}") Angle: 18.2, From: 2, To: 6, Apex: 4 Angle: 12.4, From: 7, To: 10, Apex: 8
Source code in TPTBox/spine/spinestats/angles.py
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 | |
plot_compute_lordosis_and_kyphosis
¶
plot_compute_lordosis_and_kyphosis(img_path: str | Path | None, poi: POI, img: Image_Reference, seg: Image_Reference | None = None, line_len=100, project_2D=True) -> tuple[dict[str, float | None], Snapshot_Frame]
Plots and computes the angles of lordosis and kyphosis on a spinal image.
This function calculates cervical lordosis, thoracic kyphosis, and lumbar lordosis angles based on the provided Points of Interest (POI) object. It visualizes these angles on the specified image by drawing line segments corresponding to vertebra orientations, and adds annotations for the calculated angles.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
img_path
|
str | Path | None
|
Path to save the generated image. If None, the image is not saved. |
required |
poi
|
POI
|
The points of interest object containing 3D coordinates for various vertebrae. |
required |
img
|
Image_Reference
|
The reference image on which to plot the angles and lines. |
required |
seg
|
Image_Reference | None
|
The segmentation image reference. Optional, can be None. |
None
|
line_len
|
int
|
The length of the lines representing the vertebrae directions (default is 100). |
100
|
Returns:
| Name | Type | Description |
|---|---|---|
tuple |
tuple[dict[str, float | None], Snapshot_Frame]
|
A tuple containing: - out2 (dict): A dictionary with the calculated angles of lordosis and kyphosis, including: - "cervical_lordosis" (float): Angle of cervical lordosis. - "thoracic_kyphosis" (float): Angle of thoracic kyphosis. - "lumbar_lordosis" (float): Angle of lumbar lordosis. - snap (Snapshot_Frame): A Snapshot_Frame object containing the plotted image data. |
Notes
- Artificial intervertebral discs (IVD) in not present like for CT.
- The lines drawn indicate vertebra orientations with specified lengths and directions.
- The function also generates text annotations for each computed angle, positioned at the midpoint between the respective vertebrae.
- If an image path is provided, the snapshot is saved as an image file.
Example
To compute and visualize lordosis and kyphosis angles on a given image with a POI:
angles, snapshot = plot_compute_lordosis_and_kyphosis("output_path.png", poi, img, seg) print(angles)
Source code in TPTBox/spine/spinestats/angles.py
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 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 | |
plot_cobb_angle
¶
plot_cobb_angle(img_path: str | Path | None, poi: POI, img: Image_Reference, seg: Image_Reference | None = None, line_len=100, threshold_deg=10, vert_id1_mv: MoveTo = MoveTo.TOP, vert_id2_mv: MoveTo = MoveTo.BOTTOM, use_ivd_direction=False, project_2D=True) -> tuple[list[tuple[float, int, int, int | None]], Snapshot_Frame]
Visualize Cobb angles on a spinal image by plotting the maximum angles across the spine.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
img_path
|
str | Path | None
|
The file path where the output image with plotted angles should be saved. If None, the image is not saved. |
required |
poi
|
POI
|
An object representing a point of interest that supports indexing with vertebra identifiers and returns 3D coordinates. |
required |
img
|
Image_Reference
|
The image to plot the cobb angles on. |
required |
seg
|
Image_Reference | None
|
Optional segmentation image to be used in conjunction with the main image. |
None
|
line_len
|
int
|
The length of the line segments used to visualize the direction of cobb angles. |
100
|
threshold_deg
|
int
|
The angle threshold in degrees above which cobb angles are considered for plotting. |
10
|
vert_id1_mv
|
MoveTo
|
The MoveTo option for the first vertebra in each angle calculation. |
TOP
|
vert_id2_mv
|
MoveTo
|
The MoveTo option for the second vertebra in each angle calculation. |
BOTTOM
|
Returns:
| Name | Type | Description |
|---|---|---|
tuple |
tuple[list[tuple[float, int, int, int | None]], Snapshot_Frame]
|
A tuple containing: - List of angle data and segments for plotting. - Snapshot_Frame object containing the final image with cobb angles plotted. |
Notes
- The function uses the maximum cobb angle algorithm to find angles and plots them on the sagittal view.
- It assumes vertebrae are labeled using a standard convention (e.g., C1, T1, L1, etc.).
- Only angles exceeding the specified threshold are plotted.
Example
To plot the cobb angles and save the output image:
plot_cobb_angle("output.png", poi, img, seg, line_len=100, threshold_deg=10)
Source code in TPTBox/spine/spinestats/angles.py
747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 | |
plot_cobb_and_lordosis_and_kyphosis
¶
plot_cobb_and_lordosis_and_kyphosis(img_path: str | Path | None, poi: POI, img: Image_Reference, seg: Image_Reference | None = None, line_len=100, threshold_deg=10, project_2D=True) -> tuple[list, dict[str, float | None], list[Snapshot_Frame]]
Plots Cobb angles and lordosis/kyphosis angles on a spinal image.
This function calculates and visualizes both the Cobb angles for spinal curvature and the angles of cervical lordosis, thoracic kyphosis, and lumbar lordosis. It overlays these visualizations on the provided spinal image and can save the resulting image to a specified path.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
img_path
|
str | Path | None
|
Path to save the generated image. If None, the image is not saved. |
required |
poi
|
POI
|
The points of interest object containing 3D coordinates for various vertebrae. |
required |
img
|
Image_Reference
|
The reference image on which to plot the angles and lines. |
required |
seg
|
Image_Reference | None
|
The segmentation image reference. Optional, can be None. |
None
|
line_len
|
int
|
The length of the lines representing the vertebrae directions (default is 100). |
100
|
threshold_deg
|
int
|
The threshold angle in degrees to identify significant Cobb angles (default is 10). |
10
|
Returns:
| Name | Type | Description |
|---|---|---|
tuple |
tuple[list, dict[str, float | None], list[Snapshot_Frame]]
|
A tuple containing:
- out_cobb (list): A list of tuples for each significant Cobb angle found, each with:
- max_angle (float): The maximum Cobb angle in the segment.
- from_vert (int): The vertebra ID at the start of the Cobb angle measurement.
- to_vert (int): The vertebra ID at the end of the Cobb angle measurement.
- apex (int | None): The vertebra ID of the apex of the curvature.
- out_lak (dict): A dictionary with the calculated angles of lordosis and kyphosis, including:
- "cervical_lordosis" (float): Angle of cervical lordosis.
- "thoracic_kyphosis" (float): Angle of thoracic kyphosis.
- "lumbar_lordosis" (float): Angle of lumbar lordosis.
- frames (list): A list containing the generated |
Notes
- This function internally calls
plot_cobb_angleandplot_compute_lordosis_and_kyphosisto generate the respective plots. - The function combines both visualizations into a single output image if a path is specified.
- It effectively allows for simultaneous assessment of scoliosis (via Cobb angles) and sagittal plane curvatures (lordosis and kyphosis).
Example
To visualize and save both Cobb angles and lordosis/kyphosis angles:
cobb_angles, lordosis_kyphosis, frames = plot_cobb_and_lordosis_and_kyphosis( ... "output_path.png", poi, img, seg, line_len=150, threshold_deg=15 ... ) print(cobb_angles) [(22.3, 3, 12, 7), (18.5, 13, 17, 15)] print(lordosis_kyphosis)
Source code in TPTBox/spine/spinestats/angles.py
IVD POIs¶
TPTBox.spine.spinestats.ivd_pois
¶
strategy_calculate_up_vector
¶
strategy_calculate_up_vector(poi: POI, current_vert: NII, vert_id: int, bb: tuple, log: object = _log) -> POI
Compute IVD superior and inferior extreme points via PCA-based normal estimation.
Fits a principal component axis through the IVD label (vert_id + 100)
to determine the superior–inferior direction of the disc, then ray-casts to
the extreme points along that axis. The results are stored as
:attr:~TPTBox.Location.Vertebra_Disc_Inferior and
:attr:~TPTBox.Location.Vertebra_Disc_Superior in poi.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
poi
|
POI
|
POI object that already contains the IVD centroid for |
required |
current_vert
|
NII
|
Cropped vertebra NIfTI used for PCA and ray casting. |
required |
vert_id
|
int
|
Integer vertebra region ID whose IVD label is |
required |
bb
|
tuple
|
Bounding-box slices (as returned by
:meth: |
required |
log
|
object
|
Logger instance used for progress / warning messages. |
_log
|
Returns:
| Type | Description |
|---|---|
POI
|
The updated :class: |
Source code in TPTBox/spine/spinestats/ivd_pois.py
compute_fake_ivd
¶
Add synthetic intervertebral disc (IVD) labels to the vertebra segmentation.
For every adjacent vertebra pair a synthetic IVD mask is computed using
morphological operations on the subregion labels. The disc for vertebra
i is assigned label 100 + i in the output. The computation is
parallelised over vertebrae using a :class:~concurrent.futures.ProcessPoolExecutor.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
vert_full
|
NII
|
Vertebra segmentation NIfTI; each vertebra has a unique integer label. Modified in place and returned. |
required |
subreg_full
|
NII
|
Subregion segmentation NIfTI containing spine body labels (e.g. 49, 50). |
required |
poi
|
POI
|
POI object used to ensure that
:attr: |
required |
dilate
|
int
|
Morphological dilation radius applied when building the IVD hull mask. |
1
|
Returns:
| Type | Description |
|---|---|
NII
|
The updated |
Source code in TPTBox/spine/spinestats/ivd_pois.py
calculate_IVD_POI
¶
calculate_IVD_POI(vert: NII, subreg: NII, poi: POI, ivd_location: set[Location] | None = None) -> POI
Compute IVD-related Points of Interest and add them to poi.
If the subregion image does not yet contain IVD labels (label 100),
:func:compute_fake_ivd is called first to synthesise them. Centroid
POIs at label 100 are then computed for all vertebrae and optionally
extended with superior / inferior extreme disc points via
:func:strategy_calculate_up_vector.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
vert
|
NII
|
Vertebra segmentation NIfTI. |
required |
subreg
|
NII
|
Subregion segmentation NIfTI; updated in place when IVD labels are synthesised. |
required |
poi
|
POI
|
POI object to extend. Updated in place and returned. |
required |
ivd_location
|
set[Location] | None
|
Set of :class: |
None
|
Returns:
| Type | Description |
|---|---|
POI
|
The updated :class: |
POI
|
added. |