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. - 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. When using
visualization utilities like visualize_mask_overlay(), slices are internally
transposed for correct display.
World Coordinate Frames:
Origin and direction metadata are reported in the native world frame of the source format and are not converted between frames:
- DICOM (series, single files, SEG): LPS+ (Left, Posterior, Superior), as
defined by
ImagePositionPatient/ImageOrientationPatient. - NIfTI: RAS+ (Right, Anterior, Superior), as defined by the NIfTI affine read via nibabel. (Note: SimpleITK converts NIfTI to LPS+ on load; this library does not.)
The X and Y axes of the two frames point in opposite directions, so origins and
direction matrices from different formats are not directly comparable. Do
not mix formats within a single geometric operation (e.g., a DICOM-derived
reference_image with a NIfTI mask): geometry validation will fail or, worse,
repositioning may silently misalign. Keep an image and its masks in the same
format, or convert one externally beforehand. A UserWarning is emitted when
such mixing is detected.
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 expressed in the native world frame of
the source format (LPS+ for DICOM, RAS+ for NIfTI) — see the module
docstring ("World Coordinate Frames"). 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). |
Example
Source code in pictologics/loader.py
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 | |
has_source_mask
property
Whether this image has a source validity mask (indicating sentinel values were excluded).
with_source_mask(mask)
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 |
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)
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.
Warning
NIfTI and DICOM geometry live in different world coordinate frames
(RAS+ vs LPS+) and are not converted — do not mix formats between an
image and its reference_image/masks. See the module docstring
("World Coordinate Frames").
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
path
|
str
|
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. |
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. |
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). NIfTI files always apply their scaling factors via 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
|
Returns:
| Name | Type | Description |
|---|---|---|
Image |
Image
|
An |
Raises:
| Type | Description |
|---|---|
ValueError
|
If the path does not exist, the file format is not supported, or the file is corrupt/unreadable. |
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)
Source code in pictologics/loader.py
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 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 849 850 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 | |
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).
- 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
|
list[str]
|
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
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 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 | |
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.
Uses highdicom for robust SEG parsing and extraction.
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)
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: npt.NDArray[np.floating[Any]] 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 will be resampled/repositioned to match the reference geometry. |
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
|
Returns:
| Type | Description |
|---|---|
'Image | dict[int, Image]'
|
If combine_segments is True: A single Image with segment labels. |
'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
25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 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 | |
get_segment_info(path)
Get information about segments in a DICOM SEG file.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
path
|
str | Path
|
Path to the DICOM SEG file. |
required |
Returns:
| Type | Description |
|---|---|
list[dict[str, str | int]]
|
List of dicts with segment information: |
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 object. |