Utilities API
pictologics.utilities.dicom_database
DICOM Database Module
This module provides dataclass-based hierarchical organization of DICOM files with completeness validation and multi-level DataFrame exports.
The implementation supports parallel processing for improved performance on large datasets, with stateless file processing and immutable intermediate results.
DicomInstance
dataclass
Represents a single DICOM file/instance.
Attributes:
| Name | Type | Description |
|---|---|---|
sop_instance_uid |
str
|
Unique identifier for this instance. |
file_path |
Path
|
Absolute path to the DICOM file. |
instance_number |
Optional[int]
|
Instance number within the series. |
image_position_patient |
Optional[tuple[float, float, float]]
|
(x, y, z) position in patient coordinates. |
image_orientation_patient |
Optional[tuple[float, ...]]
|
Direction cosines for row and column. |
slice_location |
Optional[float]
|
Slice location value from DICOM header. |
acquisition_datetime |
Optional[str]
|
Combined acquisition date and time. |
projection_score |
Optional[float]
|
Calculated projection onto slice normal for sorting. |
metadata |
dict[str, Any]
|
Additional extracted metadata tags. |
Source code in pictologics/utilities/dicom_database.py
DicomSeries
dataclass
Represents a DICOM series containing multiple instances.
Attributes:
| Name | Type | Description |
|---|---|---|
series_instance_uid |
str
|
Unique identifier for this series. |
series_number |
Optional[int]
|
Series number within the study. |
series_description |
Optional[str]
|
Description of the series. |
modality |
Optional[str]
|
Imaging modality (CT, MR, etc.). |
frame_of_reference_uid |
Optional[str]
|
Frame of reference UID. |
instances |
list[DicomInstance]
|
List of DicomInstance objects in this series. |
common_metadata |
dict[str, Any]
|
Metadata tags identical across all instances. |
Source code in pictologics/utilities/dicom_database.py
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 | |
check_completeness(spacing_tolerance=0.1)
Check if the series has all expected slices.
Uses geometric validation based on ImagePositionPatient projection to detect missing slices and gaps.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
spacing_tolerance
|
float
|
Tolerance for gap detection (default 10%). |
0.1
|
Returns:
| Type | Description |
|---|---|
dict[str, Any]
|
Dictionary with completeness information. |
Source code in pictologics/utilities/dicom_database.py
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 | |
get_file_paths()
get_instance_uids()
get_sorted_instances()
Return instances sorted by spatial position (projection score).
Uses the same methodology as pictologics.loader for spatial sorting. Falls back to instance number if projection scores are not available.
Source code in pictologics/utilities/dicom_database.py
DicomStudy
dataclass
Represents a DICOM study containing multiple series.
Attributes:
| Name | Type | Description |
|---|---|---|
study_instance_uid |
str
|
Unique identifier for this study. |
study_date |
Optional[str]
|
Date of the study. |
study_time |
Optional[str]
|
Time of the study. |
study_description |
Optional[str]
|
Description of the study. |
series |
list[DicomSeries]
|
List of DicomSeries objects in this study. |
common_metadata |
dict[str, Any]
|
Metadata tags identical across all series. |
Source code in pictologics/utilities/dicom_database.py
get_file_paths()
Get list of all instance file paths in this study.
get_instance_uids()
Get list of all instance SOPInstanceUIDs in this study.
DicomPatient
dataclass
Represents a DICOM patient containing multiple studies.
Attributes:
| Name | Type | Description |
|---|---|---|
patient_id |
str
|
Patient identifier. |
patients_name |
Optional[str]
|
Patient's name. |
patients_birth_date |
Optional[str]
|
Patient's birth date. |
patients_sex |
Optional[str]
|
Patient's sex. |
studies |
list[DicomStudy]
|
List of DicomStudy objects for this patient. |
common_metadata |
dict[str, Any]
|
Metadata tags identical across all studies. |
Source code in pictologics/utilities/dicom_database.py
get_file_paths()
Get list of all instance file paths for this patient.
get_instance_uids()
Get list of all instance SOPInstanceUIDs for this patient.
DicomDatabase
dataclass
Top-level database containing all patients.
This class provides the main interface for building a DICOM database from folders and exporting to various formats.
Attributes:
| Name | Type | Description |
|---|---|---|
patients |
list[DicomPatient]
|
List of DicomPatient objects. |
spacing_tolerance |
float
|
Tolerance for gap detection in completeness checks. |
Source code in pictologics/utilities/dicom_database.py
280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 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 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 | |
export_csv(base_path, levels=None, include_instance_lists=False)
Export DataFrames to separate CSV files.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
base_path
|
str
|
Base path for output files (without extension). |
required |
levels
|
Optional[list[str]]
|
List of levels to export ('patients', 'studies', 'series', 'instances'). Defaults to all levels. |
None
|
include_instance_lists
|
bool
|
Whether to include InstanceSOPUIDs and InstanceFilePaths columns. Defaults to False to reduce file size. |
False
|
Returns:
| Type | Description |
|---|---|
dict[str, str]
|
Dictionary mapping level names to created file paths. |
Example
Export database to CSV files:
Source code in pictologics/utilities/dicom_database.py
export_json(json_path, include_instance_lists=True)
Export full hierarchy to JSON.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
json_path
|
str
|
Path for the output JSON file. |
required |
include_instance_lists
|
bool
|
Whether to include per-instance file paths in the JSON output. Defaults to True for full export. |
True
|
Returns:
| Type | Description |
|---|---|
str
|
Path to the created file. |
Source code in pictologics/utilities/dicom_database.py
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 | |
from_folders(paths, recursive=True, spacing_tolerance=0.1, show_progress=True, extract_private_tags=True, num_workers=None, split_multiseries=True)
classmethod
Build a database from folder paths.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
paths
|
list[str | Path]
|
List of folder paths to scan. |
required |
recursive
|
bool
|
Whether to scan subdirectories. |
True
|
spacing_tolerance
|
float
|
Tolerance for gap detection (default 10%). |
0.1
|
show_progress
|
bool
|
Whether to display progress bars. |
True
|
extract_private_tags
|
bool
|
Whether to extract vendor-specific private tags. |
True
|
num_workers
|
Optional[int]
|
Number of parallel workers. None=auto (cpu_count-1), 1=sequential (no multiprocessing). |
None
|
split_multiseries
|
bool
|
Whether to split multi-phase series (e.g. cardiac) into separate series based on tags or spatial duplicates. |
True
|
Returns:
| Type | Description |
|---|---|
'DicomDatabase'
|
DicomDatabase instance populated with all discovered DICOM files. |
Example
Build database from multiple folders:
Source code in pictologics/utilities/dicom_database.py
get_instances_df(patient_id=None, study_uid=None, series_uid=None)
Export instance-level detail DataFrame.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
patient_id
|
Optional[str]
|
Optional filter by patient ID. |
None
|
study_uid
|
Optional[str]
|
Optional filter by study UID. |
None
|
series_uid
|
Optional[str]
|
Optional filter by series UID. |
None
|
Returns:
| Type | Description |
|---|---|
DataFrame
|
DataFrame with complete instance information. |
Source code in pictologics/utilities/dicom_database.py
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 | |
get_patients_df(include_instance_lists=False)
Export patient-level summary DataFrame.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
include_instance_lists
|
bool
|
Whether to include InstanceSOPUIDs and InstanceFilePaths columns. Defaults to False to reduce memory. |
False
|
Returns:
| Type | Description |
|---|---|
DataFrame
|
DataFrame with patient information and aggregated statistics. |
Source code in pictologics/utilities/dicom_database.py
get_series_df(patient_id=None, study_uid=None, include_instance_lists=False)
Export series-level summary DataFrame with completeness info.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
patient_id
|
Optional[str]
|
Optional filter by patient ID. |
None
|
study_uid
|
Optional[str]
|
Optional filter by study UID. |
None
|
include_instance_lists
|
bool
|
Whether to include InstanceSOPUIDs and InstanceFilePaths columns. Defaults to False to reduce memory. |
False
|
Returns:
| Type | Description |
|---|---|
DataFrame
|
DataFrame with series information including completeness validation. |
Source code in pictologics/utilities/dicom_database.py
get_studies_df(patient_id=None, include_instance_lists=False)
Export study-level summary DataFrame.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
patient_id
|
Optional[str]
|
Optional filter by patient ID. |
None
|
include_instance_lists
|
bool
|
Whether to include InstanceSOPUIDs and InstanceFilePaths columns. Defaults to False to reduce memory. |
False
|
Returns:
| Type | Description |
|---|---|
DataFrame
|
DataFrame with study information. |
Source code in pictologics/utilities/dicom_database.py
pictologics.utilities.dicom_utils
DICOM Utility Functions.
This module provides shared utility functions for working with DICOM files, including multi-phase series detection and splitting logic used by both the DicomDatabase and the image loader.
DicomPhaseInfo
dataclass
Information about a detected phase in a DICOM series.
Attributes:
| Name | Type | Description |
|---|---|---|
index |
int
|
Zero-based index of this phase. |
num_slices |
int
|
Number of slices/instances in this phase. |
file_paths |
list[Path]
|
List of file paths belonging to this phase. |
label |
Optional[str]
|
Human-readable label (e.g., "Phase 0%", "Echo 1"). |
split_tag |
Optional[str]
|
The DICOM tag used to detect this phase, or "spatial" if detected via duplicate positions. |
split_value |
Optional[Any]
|
The value of the split tag for this phase. |
Source code in pictologics/utilities/dicom_utils.py
get_dicom_phases(path, recursive=False)
Discover phases in a DICOM series directory.
Scans a directory for DICOM files and detects if the series contains
multiple phases (e.g., cardiac phases, temporal positions, echo numbers).
This is useful before calling load_image() with a specific dataset_index.
Multi-phase detection uses the same logic as :class:DicomDatabase to ensure
consistent behavior across the library.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
path
|
str
|
Path to directory containing DICOM files. |
required |
recursive
|
bool
|
If True, recursively searches subdirectories. Default False. |
False
|
Returns:
| Type | Description |
|---|---|
list[DicomPhaseInfo]
|
List of :class: |
list[DicomPhaseInfo]
|
For single-phase series, returns a list with one element. |
Raises:
| Type | Description |
|---|---|
FileNotFoundError
|
If the path does not exist. |
ValueError
|
If no DICOM files are found. |
Example
Discover phases before loading:
from pictologics.utilities import get_dicom_phases
from pictologics import load_image
# Discover phases in a cardiac CT directory
phases = get_dicom_phases("cardiac_ct/")
print(f"Found {len(phases)} phases:")
for phase in phases:
print(f" Phase {phase.index}: {phase.num_slices} slices - {phase.label}")
# Load the 5th phase (40%)
img = load_image("cardiac_ct/", dataset_index=4)
# Check if series is multi-phase
if len(phases) > 1:
print("Multi-phase series detected!")
else:
print("Single-phase series")
See Also
- :func:
load_image: Main image loading function withdataset_indexsupport. - :class:
DicomDatabase: Full DICOM database parsing with automatic phase splitting.
Source code in pictologics/utilities/dicom_utils.py
153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 | |
split_dicom_phases(file_metadata)
Split DICOM file metadata into multiple phases/groups.
This function detects multi-phase DICOM series (e.g., cardiac phases, multi-echo, dynamic contrast) and splits them into separate groups.
The detection strategy is: 1. Check for distinctive DICOM tags (CardiacPhase, TemporalPosition, etc.) If a tag has >1 unique value, use it to group files. 2. Fallback: Check for duplicate spatial positions (ImagePositionPatient). If duplicates exist, group by order of appearance.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
file_metadata
|
list[dict[str, Any]]
|
List of dictionaries containing at minimum: - 'file_path': Path to the DICOM file - 'ImagePositionPatient': Optional tuple of (x, y, z) - Any of the MULTI_PHASE_TAGS (optional) |
required |
Returns:
| Type | Description |
|---|---|
list[list[dict[str, Any]]]
|
List of lists, where each inner list contains metadata dicts |
list[list[dict[str, Any]]]
|
for one phase. Single-phase series return [[all_metadata]]. |
Example
Split DICOM metadata into separate phases:
from pictologics.utilities.dicom_utils import split_dicom_phases
from pathlib import Path
# Assume metadata list already collected
metadata = [
{'file_path': Path('slice1.dcm'), 'CardiacPhase': 0},
{'file_path': Path('slice2.dcm'), 'CardiacPhase': 10},
# ... more files
]
phases = split_dicom_phases(metadata)
print(f"Found {len(phases)} phases")
Source code in pictologics/utilities/dicom_utils.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 144 145 146 147 148 149 150 | |
pictologics.utilities.sr_parser
DICOM Structured Report (SR) Parser
This module provides functionality for parsing DICOM Structured Reports (SR) and extracting measurement data into structured formats (DataFrames, CSV, JSON).
Supports TID1500 (Measurement Report) and other common SR templates. Uses highdicom for robust SR parsing and content extraction.
SRMeasurement
dataclass
Represents a single measurement from an SR document.
This dataclass captures individual measurement values extracted from DICOM Structured Reports, including the measurement name, value, units, and associated context.
Attributes:
| Name | Type | Description |
|---|---|---|
name |
str
|
Measurement concept name (e.g., "Agatston Score", "Volume"). |
value |
float
|
Numerical measurement value. |
unit |
str
|
Unit of measurement (e.g., "mm", "HU", "1" for unitless). |
finding_type |
Optional[str]
|
Type of finding this measurement relates to (optional). |
finding_site |
Optional[str]
|
Anatomical site of finding (optional). |
derivation |
Optional[str]
|
How the measurement was derived (optional). |
tracking_id |
Optional[str]
|
Optional tracking identifier for longitudinal studies. |
metadata |
dict[str, Any]
|
Additional extracted attributes not captured above. |
Source code in pictologics/utilities/sr_parser.py
SRMeasurementGroup
dataclass
Represents a group of related measurements.
SR documents often organize measurements into groups based on anatomical site, finding type, or other criteria. This dataclass captures such groupings.
Attributes:
| Name | Type | Description |
|---|---|---|
group_id |
Optional[str]
|
Identifier for this measurement group (optional). |
finding_type |
Optional[str]
|
Type of finding for this group (optional). |
finding_site |
Optional[str]
|
Anatomical site for this group (optional). |
measurements |
list[SRMeasurement]
|
List of SRMeasurement objects in this group. |
metadata |
dict[str, Any]
|
Additional group-level attributes. |
Source code in pictologics/utilities/sr_parser.py
SRDocument
dataclass
Represents a parsed DICOM Structured Report.
This class provides the main interface for accessing SR content,
following the same pattern as DicomDatabase. It can be constructed
from a file using the from_file() class method.
Attributes:
| Name | Type | Description |
|---|---|---|
file_path |
Path
|
Path to the source SR file. |
sop_instance_uid |
str
|
Unique identifier for this SR instance. |
template_id |
Optional[str]
|
SR template identifier (e.g., "1500" for TID1500). |
document_title |
Optional[str]
|
Title of the SR document. |
measurement_groups |
list[SRMeasurementGroup]
|
List of SRMeasurementGroup objects. |
patient_id |
Optional[str]
|
Patient identifier. |
study_instance_uid |
Optional[str]
|
Study UID. |
series_instance_uid |
Optional[str]
|
Series UID. |
content_datetime |
Optional[str]
|
When the SR was created. |
metadata |
dict[str, Any]
|
Additional document-level attributes. |
Example
Load and parse an SR document:
from pictologics.utilities.sr_parser import SRDocument
sr = SRDocument.from_file("measurements.dcm")
print(f"Template: {sr.template_id}")
print(f"Groups: {len(sr.measurement_groups)}")
# Export measurements to DataFrame
df = sr.get_measurements_df()
print(df[["measurement_name", "value", "unit"]])
# Export to CSV
sr.export_csv("measurements.csv")
Source code in pictologics/utilities/sr_parser.py
77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 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 | |
export_csv(path)
Export measurements to CSV file.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
path
|
str | Path
|
Output path for the CSV file. |
required |
Returns:
| Type | Description |
|---|---|
Path
|
Path to the created CSV file. |
Source code in pictologics/utilities/sr_parser.py
export_json(path)
Export full SR content to JSON.
Exports the complete document structure including all groups, measurements, and metadata.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
path
|
str | Path
|
Output path for the JSON file. |
required |
Returns:
| Type | Description |
|---|---|
Path
|
Path to the created JSON file. |
Source code in pictologics/utilities/sr_parser.py
from_file(path, extract_private_tags=False)
classmethod
Load and parse an SR document from file.
This method reads a DICOM Structured Report file and extracts all measurement content into the hierarchical dataclass structure. Follows the same pattern as DicomDatabase.from_folders().
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
path
|
str | Path
|
Path to DICOM SR file. |
required |
extract_private_tags
|
bool
|
Whether to extract vendor-specific tags into the metadata dictionaries. Defaults to False. |
False
|
Returns:
| Type | Description |
|---|---|
'SRDocument'
|
SRDocument instance with parsed content. |
Raises:
| Type | Description |
|---|---|
FileNotFoundError
|
If the file does not exist. |
ValueError
|
If the file is not a valid DICOM SR object. |
Source code in pictologics/utilities/sr_parser.py
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 | |
from_folders(paths, recursive=True, show_progress=True, num_workers=None, output_dir=None, export_csv=True, export_json=True, extract_private_tags=False)
classmethod
Batch process SR files from folders.
Scans directories for DICOM SR files, parses each one, and optionally exports individual CSV/JSON files plus a combined output and log.
This method follows the same pattern as DicomDatabase.from_folders().
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
paths
|
list[str | Path]
|
List of folder paths to scan for SR files. |
required |
recursive
|
bool
|
Whether to scan subdirectories (default: True). |
True
|
show_progress
|
bool
|
Whether to display progress bars (default: True). |
True
|
num_workers
|
Optional[int]
|
Number of parallel workers. None=auto (cpu_count-1), 1=sequential (no multiprocessing). |
None
|
output_dir
|
Optional[str | Path]
|
If specified, exports each SR to this directory. |
None
|
export_csv
|
bool
|
Export individual CSV files (default: True). |
True
|
export_json
|
bool
|
Export individual JSON files (default: True). |
True
|
extract_private_tags
|
bool
|
Whether to extract private tags (default: False). |
False
|
Returns:
| Type | Description |
|---|---|
'SRBatch'
|
SRBatch containing all parsed documents and processing log. |
Example
Process all SR files in a folder:
from pictologics.utilities.sr_parser import SRDocument
# Process folder
batch = SRDocument.from_folders(["sr_data/"])
print(f"Found {len(batch.documents)} SR files")
df = batch.get_combined_measurements_df()
# Process with exports
batch = SRDocument.from_folders(
["sr_data/"],
output_dir="sr_exports/",
export_csv=True,
export_json=True
)
batch.export_log("sr_exports/processing_log.csv")
Source code in pictologics/utilities/sr_parser.py
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 | |
get_measurements_df()
Export all measurements as a DataFrame.
Returns a flat DataFrame with all measurements from all groups, including group context for each measurement.
Returns:
| Type | Description |
|---|---|
DataFrame
|
DataFrame with columns: |
DataFrame
|
|
DataFrame
|
|
DataFrame
|
|
DataFrame
|
|
DataFrame
|
|
DataFrame
|
|
DataFrame
|
|
DataFrame
|
|
Source code in pictologics/utilities/sr_parser.py
get_summary()
Get document summary without full parsing.
Returns:
| Type | Description |
|---|---|
dict[str, Any]
|
Dictionary with summary information including: |
dict[str, Any]
|
|
dict[str, Any]
|
|
dict[str, Any]
|
|
dict[str, Any]
|
|
dict[str, Any]
|
|
dict[str, Any]
|
|
dict[str, Any]
|
|
Source code in pictologics/utilities/sr_parser.py
SRBatch
dataclass
Collection of parsed SR documents from batch processing.
This class holds the results of batch SR processing via SRDocument.from_folders(). It provides access to all parsed documents and methods for combined exports.
Attributes:
| Name | Type | Description |
|---|---|---|
documents |
list[SRDocument]
|
List of successfully parsed SRDocument objects. |
processing_log |
list[dict[str, Any]]
|
Log entries for each processed file (success/error). |
output_dir |
Optional[Path]
|
Directory where individual exports were written. |
Example
Source code in pictologics/utilities/sr_parser.py
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 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 | |
export_combined_csv(path)
Export combined measurements to a single CSV file.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
path
|
str | Path
|
Output path for the combined CSV. |
required |
Returns:
| Type | Description |
|---|---|
Path
|
Path to the created CSV file. |
Source code in pictologics/utilities/sr_parser.py
export_log(path)
Export processing log to CSV.
The log contains one row per processed file with status, output paths, and any error messages.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
path
|
str | Path
|
Output path for the log CSV. |
required |
Returns:
| Type | Description |
|---|---|
Path
|
Path to the created CSV file. |
Source code in pictologics/utilities/sr_parser.py
get_combined_measurements_df()
Combine measurements from all documents into a single DataFrame.
Each measurement row includes the source document's SOP Instance UID, patient ID, and study UID for traceability.
Returns:
| Type | Description |
|---|---|
DataFrame
|
DataFrame with all measurements from all documents. |
Source code in pictologics/utilities/sr_parser.py
is_dicom_sr(path)
Check if a DICOM file is a Structured Report.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
path
|
str | Path
|
Path to the potential DICOM file. |
required |
Returns:
| Type | Description |
|---|---|
bool
|
True if the file is a DICOM SR object, False otherwise. |
Source code in pictologics/utilities/sr_parser.py
pictologics.utilities.visualization
Visualization Module
This module provides utilities for visualizing medical images and segmentation masks. It supports interactive slice scrolling and batch export of images.
Key Features
- Interactive slice viewer with matplotlib
- Flexible display modes: image-only, mask-only, or overlay
- Multi-label mask support (up to 20+ labels with distinct colors)
- Window/Level normalization for CT/MR viewing
- Configurable output formats (PNG, JPEG, TIFF)
- Flexible slice selection for batch export
Display Modes
The visualization functions support three display modes based on which inputs are provided:
-
Image + Mask (Overlay Mode): Both
imageandmaskare provided. The mask is overlaid on the grayscale image with the specified transparency (alpha) and colormap. -
Image Only: Only
imageis provided (mask=None). The image is displayed as grayscale, optionally with window/level normalization applied. -
Mask Only: Only
maskis provided (image=None). The mask can be displayed either: - As a colormap visualization (
mask_as_colormap=True, default): Each unique label value gets a distinct color from the specified colormap. - As grayscale (
mask_as_colormap=False): Values are normalized to 0-255.
Window/Level Normalization
For medical imaging (CT, MR), window/level controls are essential for proper visualization.
When window_center and window_width are specified:
- window_center (Level): The center value of the display window (default: 200 HU for soft tissue)
- window_width (Width): The range of values displayed (default: 600 HU)
Values outside [center - width/2, center + width/2] are clipped to black/white.
Common presets: - Soft tissue: Center=40, Width=400 - Bone: Center=400, Width=1800 - Lung: Center=-600, Width=1500 - Brain: Center=40, Width=80
visualize_slices(image=None, mask=None, alpha=0.25, colormap='tab20', axis=2, initial_slice=None, window_title='Slice Viewer', window_center=None, window_width=None, mask_as_colormap=True)
Display interactive slice viewer with scrolling.
This function supports three display modes:
-
Image + Mask (Overlay Mode): Both
imageandmaskare provided. The mask is overlaid on the grayscale image with transparency. -
Image Only: Only
imageis provided. Displays grayscale slices, optionally with window/level normalization. -
Mask Only: Only
maskis provided. Displays mask visualization using either a colormap or grayscale display.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
image
|
Optional[Image]
|
Optional Pictologics Image object containing the image data. |
None
|
mask
|
Optional[Image]
|
Optional Pictologics Image object containing the mask data. |
None
|
alpha
|
float
|
Transparency of mask overlay (0-1). Only used in overlay mode. |
0.25
|
colormap
|
str
|
Colormap for mask labels. Options: - "tab10": 10 distinct colors - "tab20": 20 distinct colors (default) - "Set1": 9 bold colors - "Set2": 8 pastel colors - "Paired": 12 paired colors |
'tab20'
|
axis
|
int
|
Axis along which to slice (0=sagittal, 1=coronal, 2=axial). |
2
|
initial_slice
|
Optional[int]
|
Initial slice to display (default: middle). |
None
|
window_title
|
str
|
Title for the viewer window. |
'Slice Viewer'
|
window_center
|
Optional[float]
|
Window center (level) for normalization. Default: None (min-max). |
None
|
window_width
|
Optional[float]
|
Window width for normalization. Default: None (min-max). |
None
|
mask_as_colormap
|
bool
|
If True and mask-only mode, display with colormap. If False, display as grayscale. |
True
|
Raises:
| Type | Description |
|---|---|
ValueError
|
If neither image nor mask is provided, or if shapes don't match when both are provided. |
Example
Visualise slices interactively:
from pictologics import load_image
from pictologics.utilities import visualize_slices
# View image with mask overlay
img = load_image("scan.nii.gz")
mask = load_image("segmentation.nii.gz")
visualize_slices(image=img, mask=mask)
# View image only
visualize_slices(image=img, window_center=40, window_width=400)
# View mask only with colormap
visualize_slices(mask=mask)
Source code in pictologics/utilities/visualization.py
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 | |
save_slices(output_dir, image=None, mask=None, slice_selection='10%', format='png', dpi=300, alpha=0.25, colormap='tab20', axis=2, filename_prefix='slice', window_center=None, window_width=None, mask_as_colormap=True)
Save image slices to files.
This function supports three display modes:
-
Image + Mask (Overlay Mode): Both
imageandmaskare provided. The mask is overlaid on the grayscale image with transparency. -
Image Only: Only
imageis provided. Saves grayscale slices, optionally with window/level normalization. -
Mask Only: Only
maskis provided. Saves mask visualization using either a colormap or grayscale display.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
output_dir
|
str
|
Directory to save output images. |
required |
image
|
Optional[Image]
|
Optional Pictologics Image object containing the image data. |
None
|
mask
|
Optional[Image]
|
Optional Pictologics Image object containing the mask data. |
None
|
slice_selection
|
Union[str, int, list[int]]
|
Slice selection specification: - "every_N" or "N": Every Nth slice - "N%": Slices at each N% interval (e.g., "10%" = ~10 images) - int: Single slice index - list[int]: Specific slice indices |
'10%'
|
format
|
str
|
Output format ("png", "jpeg", "tiff"). |
'png'
|
dpi
|
int
|
Output resolution in dots per inch. |
300
|
alpha
|
float
|
Transparency of mask overlay (0-1). Only used in overlay mode. |
0.25
|
colormap
|
str
|
Colormap for mask labels. Options: - "tab10": 10 distinct colors - "tab20": 20 distinct colors (default) - "Set1": 9 bold colors - "Set2": 8 pastel colors - "Paired": 12 paired colors |
'tab20'
|
axis
|
int
|
Axis along which to slice (0=sagittal, 1=coronal, 2=axial). |
2
|
filename_prefix
|
str
|
Prefix for output filenames. |
'slice'
|
window_center
|
Optional[float]
|
Window center (level) for normalization. Default: None (min-max). |
None
|
window_width
|
Optional[float]
|
Window width for normalization. Default: None (min-max). |
None
|
mask_as_colormap
|
bool
|
If True and mask-only mode, display with colormap. If False, display as grayscale. |
True
|
Returns:
| Type | Description |
|---|---|
list[str]
|
List of paths to saved files. |
Raises:
| Type | Description |
|---|---|
ValueError
|
If neither image nor mask is provided, or if shapes don't match when both are provided. |
Example
Save image slices with and without mask overlay:
from pictologics import load_image
from pictologics.utilities import save_slices
# Save image with mask overlay
img = load_image("scan.nii.gz")
mask = load_image("segmentation.nii.gz")
files = save_slices("output/", image=img, mask=mask, slice_selection="10%")
# Save image only (no mask)
files = save_slices("output/", image=img, slice_selection="10%")
# Save mask only with colormap
files = save_slices("output/", mask=mask, slice_selection="10%")
Source code in pictologics/utilities/visualization.py
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 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 | |