Loaders API
pictologics.loader
Image Loading Module
This module handles the loading of medical images from various formats (NIfTI, DICOM)
into a standardized Image class. It abstracts away file format differences to provide
a consistent interface for the rest of the library.
Key Features:
- Unified Image Class: Stores 3D data, spacing, origin, direction, and modality.
- Format Support:
- NIfTI (.nii, .nii.gz) via
nibabel. - NRRD (.nrrd, .nhdr, .seg.nrrd) and MetaImage (.mha, .mhd), with the readers of
pictologics.loaders. - DICOM Series (directory of DICOM files) via
pydicom. - Single DICOM files.
- NIfTI (.nii, .nii.gz) via
- Automatic Detection:
load_imageautomatically detects format and dimensionality. - Robust DICOM Sorting: Sorts slices based on spatial position and orientation.
Axis Conventions:
All image arrays are stored in (X, Y, Z) order to match ITK/SimpleITK conventions:
- X (axis 0): Left-Right direction (columns in DICOM terminology)
- Y (axis 1): Anterior-Posterior direction (rows in DICOM terminology)
- Z (axis 2): Superior-Inferior direction (slices)
This differs from raw DICOM and matplotlib conventions:
- DICOM pixel_array: Returns (Rows, Columns) = (Y, X) for 2D slices
- Matplotlib imshow: Expects (height, width) = (Y, X)
The loaders handle the necessary axis transformations automatically. The visualization
utilities (visualize_slices(), save_slices()) transpose the slices for display.
World Coordinate Frame:
Origin and direction metadata are in the LPS+ world frame (Left, Posterior, Superior) for every format, as in DICOM and ITK/SimpleITK:
- DICOM (series, single files, SEG): as defined by
ImagePositionPatient/ImageOrientationPatient. - NIfTI: the affine of the file is in RAS+ (Right, Anterior, Superior), so the loader changes the sign of its X and Y rows, as SimpleITK does.
So an image and its masks can come from different formats. A mask that holds the
grid of its reference_image in another voxel order (axes flipped or swapped,
as some converters write NIfTI files) is turned to the voxel order of the
reference image when it loads.
Image
dataclass
A standardized container for 3D medical image data and metadata.
This class serves as the common interface for all image processing operations in the library, abstracting away the differences between file formats like DICOM and NIfTI.
Note
origin and direction are in the LPS+ world frame for every source
format (the NIfTI loader converts the RAS+ affine) — see the module
docstring ("World Coordinate Frame"). Equality (==) compares object
identity: element-wise comparison of the array fields would be ambiguous,
so dataclass-generated equality is disabled.
Attributes:
| Name | Type | Description |
|---|---|---|
array |
NDArray[floating[Any]]
|
The 3D image data with shape (x, y, z). |
spacing |
tuple[float, float, float]
|
Voxel spacing in millimeters (mm) along the (x, y, z) axes. |
origin |
tuple[float, float, float]
|
World coordinates of the image origin (center of the first voxel) in millimeters (mm). |
direction |
Optional[NDArray[floating[Any]]]
|
3x3 direction cosine matrix defining the orientation of the image axes in world space. Defaults to identity matrix. |
modality |
str
|
The imaging modality (e.g., 'CT', 'MR', 'PT'). Defaults to 'Unknown'. |
source_mask |
Optional[NDArray[bool_]]
|
Optional boolean mask indicating which voxels contain valid source data (True) vs sentinel/invalid values (False). When set, preprocessing operations like resampling and filtering will exclude invalid voxels from interpolation/convolution to prevent sentinel value contamination. If None, all voxels are assumed to contain valid data (traditional behavior). |
frame_of_reference_uid |
Optional[str]
|
The DICOM FrameOfReferenceUID of the scan (DICOM images, SEG and RTSTRUCT masks); None for other formats. A mask that loads onto a reference image with another UID gives a warning. |
Example
Source code in pictologics/loader.py
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 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 | |
has_source_mask
property
Whether this image has a source validity mask (sentinel values are excluded).
with_source_mask(mask, copy=True)
Return a copy of this image with a source validity mask applied.
The source mask indicates which voxels contain valid data (True) vs sentinel/invalid values (False). When set, spatial operations like resampling and filtering will exclude invalid voxels.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
mask
|
'npt.NDArray[np.bool_] | npt.NDArray[np.integer[Any]] | Image'
|
Boolean array, integer array (>0 = valid), or Image object. Must have the same shape as the image array. |
required |
copy
|
bool
|
Copy the image array (the default). With False, the new image shares the array of this image: no copy of the voxels (419 MB for a 512 x 512 x 200 CT). A change to one array then shows in the other. Pictologics does not write into the array of an image. |
True
|
Returns:
| Type | Description |
|---|---|
'Image'
|
New Image with source_mask set. |
Raises:
| Type | Description |
|---|---|
ValueError
|
If mask shape or physical geometry doesn't match image geometry. |
Example
from pictologics.loader import load_image
image = load_image("image_with_sentinel.nii.gz")
roi_mask = load_image("roi_mask.nii.gz")
# Use ROI mask as source validity mask
image_with_source = image.with_source_mask(roi_mask)
# Now resampling will exclude sentinel voxels
from pictologics.preprocessing import resample_image
resampled = resample_image(image_with_source, new_spacing=(1, 1, 1))
Source code in pictologics/loader.py
load_image(path, dataset_index=0, recursive=False, reference_image=None, transpose_axes=None, fill_value=0.0, apply_rescale=True, subvoxel_tolerance=0.5, subvoxel_warning_threshold=0.01, min_overlap_fraction=0.5, series_uid=None, suv=None, stored_type=False)
Load a medical image from a file path or directory.
This is the main entry point for loading data. It automatically detects whether
the input is a NIfTI file, DICOM directory/file (single DICOM or series), or
a DICOM Segmentation (SEG) object and standardizes it into an Image object.
The resulting image array is always 3D with dimensions (x, y, z).
Note
For DICOM SEG files, this function uses pictologics.loaders.load_seg()
internally. For more control over segment extraction (e.g., selecting specific
segments or extracting them separately), use load_seg() directly.
dataset_index and fill_value do not apply to SEG files and are
ignored with a UserWarning if set to non-default values.
Note
Every format gives its geometry in the LPS+ world frame (the NIfTI loader converts the RAS+ affine), so an image and its masks can come from different formats. See the module docstring ("World Coordinate Frame").
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
path
|
str | Path | list | DicomPhaseInfo
|
The absolute or relative path to the
image file (e.g., .nii.gz, .dcm or file with no extension) or the directory
containing DICOM files. It can also be the DICOM files of one series: a list
of file paths, or a |
required |
dataset_index
|
int
|
For multi-volume datasets, specifies which volume to extract (0-indexed). This works for:
Defaults to 0 (the first volume/phase). |
0
|
recursive
|
bool
|
If True and |
False
|
reference_image
|
Optional[Image]
|
If provided and the loaded image has different dimensions than the reference, it will be repositioned into the reference coordinate space using spatial metadata (origin, spacing). This is useful for loading cropped segmentation masks that need to match a full-sized image. A loaded image whose axes are the reference axes in another order or with other signs (the same grid in another voxel order) is first turned to the voxel order of the reference. |
None
|
transpose_axes
|
tuple[int, int, int] | None
|
Optional axis transposition to apply before repositioning. Use this if the mask's axis order differs from the reference. E.g., (0, 2, 1) swaps Y and Z axes. Only used when reference_image is provided; when set, repositioning is performed even if the loaded shape already matches the reference. |
None
|
fill_value
|
float
|
Fill value for regions outside the loaded image when repositioning (default: 0.0). Only used when reference_image is provided. |
0.0
|
apply_rescale
|
bool
|
If True (default), apply RescaleSlope and RescaleIntercept transformation for DICOM files to convert stored pixel values to real-world values (e.g., Hounsfield Units for CT). The DICOM image is then float64, also without rescale tags, like a NIfTI image (nibabel's get_fdata()). Set to False if you need raw stored values. |
True
|
subvoxel_tolerance
|
float
|
Maximum permitted fractional-voxel offset when
repositioning (default: 0.5). Only used when reference_image is provided.
See |
0.5
|
subvoxel_warning_threshold
|
float
|
Fractional-voxel drift above which a
|
0.01
|
min_overlap_fraction
|
float
|
Minimum fraction of the mask volume that must intersect with the reference image space (default: 0.5). Only used when reference_image is provided. |
0.5
|
series_uid
|
str | None
|
The SeriesInstanceUID of the series to load when a DICOM folder holds more than one image series (for example two reconstructions of one scan). Without it, such a folder raises an error that lists the series. Only used for DICOM folders. |
None
|
suv
|
str | None
|
Convert a DICOM PET image (Modality PT) to its standardized
uptake value: |
None
|
stored_type
|
bool
|
Keep the stored type of a NIfTI file that has an integer type (int8, uint8, int16, uint16, int32, uint32), native byte order and no scaling (slope 1, intercept 0), for a mask or a label map: the array is then that type instead of float64. Any other NIfTI file, and every other format, loads as without the keyword. The pipeline loads its masks and label maps with it. Default False. |
False
|
Returns:
| Name | Type | Description |
|---|---|---|
Image |
Image
|
An |
Raises:
| Type | Description |
|---|---|
ValueError
|
If the path does not exist, the file format is not supported,
the file is corrupt/unreadable, a DICOM folder holds more than one
image series and |
Example
Loading a NIfTI file:
from pictologics.loader import load_image
# Load a standard brain scan
img = load_image("data/brain.nii.gz")
print(f"Image shape: {img.array.shape}")
# Output: Image shape: (256, 256, 128)
Loading a DICOM series:
# Load a CT scan from a folder of DICOM files
img_ct = load_image("data/patients/001/CT_scan/")
print(f"Voxel spacing: {img_ct.spacing}")
# Output: Voxel spacing: (0.97, 0.97, 2.5)
Loading a single DICOM file:
# Load a single DICOM file (even without .dcm extension)
img_slice = load_image("data/slice_001")
print(f"Modality: {img_slice.modality}")
Recursive DICOM loading:
# Finds the deep subfolder with actual DICOM files
img = load_image("data/patients/001/", recursive=True)
Loading a specific volume from a 4D file:
# Load the 5th time point from a 4D fMRI file
fmri_vol = load_image("data/fmri.nii.gz", dataset_index=4)
Loading a cropped mask and repositioning to match main image:
main_img = load_image("ct_scan/")
mask = load_image("cropped_mask.dcm", reference_image=main_img)
# mask now has same shape as main_img
Loading a DICOM SEG file (auto-detected):
# DICOM SEG files are automatically detected and loaded
seg = load_image("segmentation.dcm")
print(f"Modality: {seg.modality}") # Output: Modality: SEG
# Segments are combined into a label image by default
Loading a specific phase from a multi-phase DICOM series:
from pictologics.utilities import get_dicom_phases
# Discover available phases
phases = get_dicom_phases("cardiac_ct/")
print(f"Found {len(phases)} phases")
for p in phases:
print(f" {p.index}: {p.label} ({p.num_slices} slices)")
# Load the 5th phase (40%)
img = load_image("cardiac_ct/", dataset_index=4)
Loading a PET series as SUV (body weight):
Source code in pictologics/loader.py
978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 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 | |
save_image(image, path)
Save an image, a mask or a response map as a NIfTI file (.nii or .nii.gz).
The geometry goes back to the RAS+ affine of NIfTI (the X and Y rows change sign),
so load_image reads the same array and geometry. NIfTI keeps the geometry in
float32. A bool array is saved as uint8, and a 64-bit integer array as int32 when its
values fit (few programs read 64-bit NIfTI integers); other arrays keep their type
(float64 images, float32 response maps, uint8 masks).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
image
|
Image
|
The Image to save. |
required |
path
|
str | Path
|
The file path, ending with .nii or .nii.gz. A missing folder is made. |
required |
Raises:
| Type | Description |
|---|---|
ValueError
|
If the path does not end with .nii or .nii.gz. |
Example
Source code in pictologics/loader.py
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 | |
load_and_merge_images(image_paths, reference_image=None, conflict_resolution='max', dataset_index=0, recursive=False, binarize=None, reposition_to_reference=False, transpose_axes=None, fill_value=0.0, relabel_masks=False, apply_rescale=True, subvoxel_tolerance=0.5, subvoxel_warning_threshold=0.01, min_overlap_fraction=0.5)
Load multiple images (e.g., masks or partial scans) and merge them into a single image.
This function loads images from the provided paths, validates that they all share the same geometry (dimensions, spacing, origin, direction), and merges them according to the specified conflict resolution strategy.
Use Cases:
- Merging multiple segmentation masks into a single ROI.
- Merging split image volumes (though typically less common than mask merging).
- Merging cropped/bounding-box segmentation masks (with reposition_to_reference=True).
Format & Path Support:
Since this function uses load_image internally for each path, it supports:
- NIfTI files (.nii, .nii.gz).
- NRRD and MetaImage files (.nrrd, .nhdr, .mha, .mhd).
- DICOM series (directories containing DICOM files).
- Single DICOM files (with or without .dcm extension).
- Nested directories (if paths point to folders containing DICOMs).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
image_paths
|
Sequence[str | Path]
|
List of absolute or relative paths to the images. These can be file paths or directory paths. |
required |
reference_image
|
Optional[Image]
|
An optional reference image (e.g., the scan
corresponding to the masks). If provided, the merged image is validated
against this image's geometry. Required when |
None
|
conflict_resolution
|
str
|
Strategy to resolve voxel values when multiple images have non-zero values at the same location. Options: - 'max': Use the maximum value (default). - 'min': Use the minimum value. - 'first': Keep the value from the first image encountered (earlier in list). - 'last': Overwrite with the value from the last image encountered (later in list). |
'max'
|
dataset_index
|
int
|
For multi-volume datasets, specifies which volume to extract for all images (0-indexed). This works for:
Defaults to 0 (the first volume/phase). |
0
|
recursive
|
bool
|
If True, recursively searches subdirectories
for each path in |
False
|
binarize
|
bool | int | list[int] | tuple[int, int] | None
|
Rules for binarizing the merged image.
- |
None
|
reposition_to_reference
|
bool
|
If True and reference_image is provided, each loaded image will be repositioned into the reference coordinate space before merging. This is required when loading cropped segmentation masks that have different dimensions than the reference. Geometry validation is performed AFTER repositioning. Defaults to False. |
False
|
transpose_axes
|
tuple[int, int, int] | None
|
Axis transposition to apply
when repositioning. E.g., (0, 2, 1) swaps Y and Z axes.
Only used when |
None
|
fill_value
|
float
|
Fill value for regions outside cropped masks when
repositioning (default: 0.0). Only used when |
0.0
|
relabel_masks
|
bool
|
If True, assigns unique label values (1, 2, 3, ...)
to each mask file based on its order in |
False
|
apply_rescale
|
bool
|
If True (default), apply RescaleSlope and RescaleIntercept transformation for DICOM files to convert stored pixel values to real-world values (e.g., Hounsfield Units for CT). Set to False if you need raw stored values. |
True
|
subvoxel_tolerance
|
float
|
Maximum permitted fractional-voxel offset when
repositioning (default: 0.5). Only used when |
0.5
|
subvoxel_warning_threshold
|
float
|
Fractional-voxel drift above which a
|
0.01
|
min_overlap_fraction
|
float
|
Minimum fraction of each mask volume that must
intersect with the reference image space (default: 0.5). Only used when
|
0.5
|
Note
The binarize parameter is intended for mask filtering (e.g., selecting specific
ROI labels). To filter image intensity values (e.g., HU ranges), use the preprocessing
steps in the radiomics pipeline configuration instead.
Returns:
| Name | Type | Description |
|---|---|---|
Image |
Image
|
A new |
Raises:
| Type | Description |
|---|---|
ValueError
|
If |
Example
Merging cropped segmentation masks:
Source code in pictologics/loader.py
1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 | |
create_full_mask(reference_image, dtype=np.uint8)
Create a whole-image ROI mask matching a reference image.
This utility is primarily used when a user does not provide a segmentation mask. The returned mask has the same geometry (shape, spacing, origin, direction) as the reference image and contains a value of 1 for every voxel.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
reference_image
|
Image
|
Image whose geometry should be copied. |
required |
dtype
|
DTypeLike
|
Numpy dtype to use for the mask array. Defaults to |
uint8
|
Returns:
| Type | Description |
|---|---|
Image
|
An |
Raises:
| Type | Description |
|---|---|
ValueError
|
If the reference image does not have a valid 3D array. |
Example
import numpy as np
from pictologics.loader import Image, create_full_mask
image = Image(array=np.zeros((10, 10, 5)), spacing=(1.0, 1.0, 2.0), origin=(0.0, 0.0, 0.0))
mask = create_full_mask(image)
print(mask.array.shape, mask.array.dtype)
# (10, 10, 5) uint8
print(mask.array.min(), mask.array.max())
# 1 1
Source code in pictologics/loader.py
pictologics.loaders.seg_loader
DICOM Segmentation (SEG) Loader
This module provides functionality for loading DICOM Segmentation objects as pictologics Image instances. SEG files are specialized DICOM objects that store segmentation masks with multi-segment support.
The files are read with pydicom, and the frames are decoded one at a time, only for the requested segments.
load_seg(path, segment_numbers=None, combine_segments=True, reference_image=None, transpose_axes=None, subvoxel_tolerance=0.5, subvoxel_warning_threshold=0.01, min_overlap_fraction=0.5, fractional_threshold=0.5)
Load a DICOM SEG file as a mask Image.
This function loads a DICOM Segmentation object and converts it to the standard pictologics Image format. The resulting Image has the same structure as images returned by load_image():
- array: uint8 (uint16 above 255 labels) with shape (X, Y, Z)
- spacing: tuple[float, float, float] in mm
- origin: tuple[float, float, float] in mm
- direction: Optional[npt.NDArray[np.floating[Any]]] - 3x3 direction cosines
- modality: str - set to "SEG"
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
path
|
str | Path
|
Path to the DICOM SEG file. |
required |
segment_numbers
|
list[int] | None
|
Specific segment numbers to extract. If None, all segments are extracted. Segment numbers are 1-indexed as per DICOM convention. |
None
|
combine_segments
|
bool
|
Controls how segments are returned:
|
True
|
reference_image
|
'Image | None'
|
Optional reference Image for geometry alignment. When provided, the output mask is placed on the grid of the reference (repositioned, not resampled: a mask of another spacing raises an error). |
None
|
transpose_axes
|
tuple[int, int, int] | None
|
Optional axis transposition to apply before reference alignment. |
None
|
subvoxel_tolerance
|
float
|
Maximum permitted fractional-voxel offset during reference alignment. |
0.5
|
subvoxel_warning_threshold
|
float
|
Fractional-voxel drift above which a warning is emitted during reference alignment. |
0.01
|
min_overlap_fraction
|
float
|
Minimum fraction of mask volume that must overlap the reference image during alignment. |
0.5
|
fractional_threshold
|
float
|
For a FRACTIONAL SEG (probability or occupancy), a voxel is in a segment when its value is at least this fraction of the MaximumFractionalValue (and above 0). Default 0.5. BINARY and LABELMAP SEGs do not use it. |
0.5
|
Returns:
| Type | Description |
|---|---|
'Image | dict[int, Image]'
|
If combine_segments is True: A single Image with segment labels; the labels |
'Image | dict[int, Image]'
|
are uint8, or uint16 for segment numbers above 255. |
'Image | dict[int, Image]'
|
If combine_segments is False: A dict of {segment_number: Image}. |
Raises:
| Type | Description |
|---|---|
ValueError
|
If the file is not a valid DICOM SEG object. |
FileNotFoundError
|
If the file does not exist. |
Example
Load a SEG file with all segments combined (label map):
from pictologics.loaders import load_seg
import numpy as np
mask = load_seg("segmentation.dcm")
print(mask.array.shape) # (X, Y, Z)
print(np.unique(mask.array)) # [0, 1, 2, ...]
Load specific segments as separate binary masks:
masks = load_seg("segmentation.dcm", segment_numbers=[1, 2], combine_segments=False)
for seg_num, mask in masks.items():
print(f"Segment {seg_num}: {mask.array.sum()} voxels")
Align mask to a reference CT image:
Source code in pictologics/loaders/seg_loader.py
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 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 | |
get_segment_info(path)
Get information about the segments of a DICOM SEG file, the ROIs of a DICOM RTSTRUCT file, or the segments of a 3D Slicer .seg.nrrd file.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
path
|
str | Path
|
Path to the DICOM SEG file, the RTSTRUCT file, or the .seg.nrrd file. |
required |
Returns:
| Type | Description |
|---|---|
list[dict[str, str | int]]
|
List of dicts with segment information. For DICOM SEG: |
list[dict[str, str | int]]
|
|
list[dict[str, str | int]]
|
|
list[dict[str, str | int]]
|
|
list[dict[str, str | int]]
|
|
list[dict[str, str | int]]
|
For RTSTRUCT: |
list[dict[str, str | int]]
|
|
list[dict[str, str | int]]
|
|
list[dict[str, str | int]]
|
|
list[dict[str, str | int]]
|
|
list[dict[str, str | int]]
|
For .seg.nrrd (the fields |
list[dict[str, str | int]]
|
|
list[dict[str, str | int]]
|
|
list[dict[str, str | int]]
|
|
list[dict[str, str | int]]
|
|
list[dict[str, str | int]]
|
|
Raises:
| Type | Description |
|---|---|
ValueError
|
If the file is not a valid DICOM SEG or RTSTRUCT object, or a NRRD file without segments. |
Example
Source code in pictologics/loaders/seg_loader.py
pictologics.loaders.rtstruct_loader
DICOM RTSTRUCT Loader
Reads DICOM RT Structure Sets: the closed planar contours of each ROI, filled onto the voxel grid of a reference image. A voxel is in an ROI when its center lies inside an odd number of the contours of the ROI on its slice (the even-odd rule), so a contour inside another contour cuts a hole.
load_rtstruct(path, reference_image, roi_names=None, combine_rois=True, subvoxel_tolerance=0.5, subvoxel_warning_threshold=0.01)
Load the ROIs of a DICOM RTSTRUCT file as masks on the grid of reference_image.
The closed planar contours of each ROI are filled onto the slices of the reference image: a voxel is in the ROI when its center lies inside an odd number of the contours of the ROI on its slice, so a contour inside another contour cuts a hole. A center on an edge is inside on one side of the edge only, so two ROIs that share an edge share no voxel. The plane of each contour must be a slice plane of the reference image (axial, sagittal or coronal on its grid).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
path
|
str | Path
|
Path to the RTSTRUCT file. |
required |
reference_image
|
Image
|
The image whose grid the masks fill (the image that the contours were drawn on, in the LPS+ frame as every loaded image). |
required |
roi_names
|
list[str] | None
|
The names of the ROIs to load. None loads every ROI with closed contours (the others are left out with a warning). |
None
|
combine_rois
|
bool
|
True gives one label image, with the ROI Number of each ROI as its label (a later ROI wins where ROIs overlap; uint8, or uint16 for ROI numbers above 255). False gives a dict of binary masks by ROI name, which keeps overlapping ROIs. |
True
|
subvoxel_tolerance
|
float
|
Largest distance (in voxels) of a contour from the nearest slice of the reference image; a contour farther away raises an error. |
0.5
|
subvoxel_warning_threshold
|
float
|
Distance (in voxels) above which a warning tells that the contours are filled on the nearest slices. |
0.01
|
Returns:
| Type | Description |
|---|---|
Image | dict[str, Image]
|
One label Image (combine_rois=True) or a dict {ROI name: binary mask Image}, |
Image | dict[str, Image]
|
with the geometry of the reference image and modality "RTSTRUCT". |
Raises:
| Type | Description |
|---|---|
ValueError
|
If the file is not an RTSTRUCT, a requested ROI is not in the file or has no closed contours, ROI names repeat where names must be unique, or a contour does not lie on the slices of the reference image. |
FileNotFoundError
|
If the file does not exist. |
Example
Source code in pictologics/loaders/rtstruct_loader.py
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 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 | |