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.
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.
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). |
Source code in pictologics/loader.py
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 | |
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 doesn't match image shape. |
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)
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 :func:pictologics.loaders.load_seg
internally. For more control over segment extraction (e.g., selecting specific
segments or extracting them separately), use load_seg() directly.
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. |
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
|
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
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 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 | |
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)
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
|
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
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 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 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 | |
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. |
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)
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
|
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 | |
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. |