I/O, interop & phantoms

Getting data in, plugging into a training loop, and generating something to try it all on.

Readers and writers

from medaugmentx.io import load_dicom_series, load_nifti, save_nifti

These need optional dependencies — pip install "medaugmentx[io]" for both, or [dicom] / [nifti] individually. The modules import their backend lazily, so a core-only install can still import medaugmentx.io without failing.

Unified I/O for medical image formats.

Each loader returns a MedVolume with spacing populated in millimetres and metadata carrying the modality and any vendor-specific information that callers may need.

Optional dependencies:

  • DICOM I/O requires pydicom (pip install medaugmentx[dicom]).

  • NIfTI I/O requires nibabel (pip install medaugmentx[nifti]).

If a backend is missing the loader raises a clear ImportError when called, not at import time.

medaugmentx.io.load_dicom_series(path, *, strict=True, include_patient_id=False)[source]

Load supported classic monochrome DICOM images on a regular grid.

Full inter-slice vectors preserve regular gantry tilt/shear. The affine maps array indices to RAS mm. MONOCHROME1 values are retained in modality units; photometric interpretation is recorded for the display layer. Enhanced and multiframe data and modality LUT sequences are explicitly unsupported.

Parameters:
  • path (str) – Directory or single DICOM filename.

  • strict (bool) – Fail on unreadable/nonimage candidates and missing stack geometry. False permits skipped files and unknown geometry with warnings and diagnostics in metadata. Structural inconsistencies always raise.

  • include_patient_id (bool) – Opt in to retaining PatientID; never anonymizes pixels.

Return type:

MedVolume

medaugmentx.io.load_nifti(path, dtype=<class 'numpy.float32'>, *, mask_path=None, resample_mask=False)[source]

Load 2D/3D NIfTI data and optionally a registered integer label map.

File axes are reversed into array order. Spatial units are converted to mm; unknown units are explicitly assumed mm with a warning. Source orientation is preserved, not canonicalized. Files with neither a coded qform nor a coded sform carry no patient coordinates, so they load with affine=None and spacing from the voxel sizes. Four-dimensional time/channel data is unsupported except for a trailing singleton dimension. Returned image/mask arrays own their data and retain no source-file mappings.

Parameters:
  • path (str) – NIfTI image filename.

  • dtype (Any | None) – Output intensity dtype, or None to retain the proxy’s scaled dtype.

  • mask_path (str | None) – Optional registered label-map NIfTI. The default requires matching shape and world coordinates across the grid (within 1e-4 mm), or matching shape and spacing when either file has no coded geometry.

  • resample_mask (bool) – For a grid mismatch, use the label map’s header to sample its labels onto the image grid. Enable this only for files already sharing a patient coordinate system. Uses nearest-neighbour with background 0 outside the source mask. Requires a coded qform or sform in both files and raises if all nonzero labels disappear.

Return type:

MedVolume

medaugmentx.io.save_nifti(volume, path, *, mask_path=None, allow_assumed_geometry=True)[source]

Export current geometry, setting mm units and coherent qform/sform.

Shear is preserved in sform; qform is disabled when it cannot represent the grid without approximation. Both forms carry the code of the space the affine came from (the loaded sform’s, else the qform’s, else scanner). Unknown patient geometry uses an explicitly assumed axis-aligned grid with a warning and codes 0 (no patient coordinates), or raises in strict mode. Boolean and float16 images are written as uint8 and float32.

Parameters:
  • volume (MedVolume) – Volume to write.

  • path (str) – Image output filename.

  • mask_path (str | None) – Optional separate integer-label output filename. Floating label maps must fit int64 or uint64 without changing any IDs.

  • allow_assumed_geometry (bool) – Permit axis-aligned export when affine is unknown.

Framework adapters

from medaugmentx.interop import MonaiMapTransform, TorchTransform, TorchIOTransform

The adapters wrap any MedAugmentX transform or pipeline so it can sit in a dataset or transform chain from another framework. They accept the sample shapes those frameworks use — arrays, tensors, (image, mask) pairs, dictionaries, or a TorchIO Subject — and return the same kind they were given.

The adapters accept single-channel 2D and 3D image fields. A singleton channel dimension is stripped before augmentation and restored afterwards; channel_dim controls where the adapter expects to find it. Use with_channels() to augment registered channels together, then stack them for your model.

Importing an adapter never imports its framework. Torch, MONAI, and TorchIO are touched only when a sample of that kind is actually passed through, so a single interop import costs nothing in a core-only environment.

Framework adapters for using MedAugmentX in training pipelines.

The adapters in this module are intentionally dependency-light: importing medaugmentx.interop does not import PyTorch, MONAI, or TorchIO. Tensor and subject support is duck-typed and only touches optional frameworks when their objects are passed at runtime.

class medaugmentx.interop.SampleTransform(transform, *, image_key='image', mask_key='mask', spacing_key='spacing', metadata_key='metadata', channel_dim='auto', preserve_image_dtype=False, preserve_mask_dtype=True, spatial_order='array', affine_key='affine', require_mask=False)[source]

Bases: object

Adapt one image plus labels, targets, spacing, and affine in dataset samples.

Spatial order is explicit: array means DHW/HW, native means XYZ/XY. Affines use the sample’s spatial order and RAS millimetres. Arrays without affine have unknown patient geometry. Tensor processing runs on CPU and restores the input device; this is not a GPU backend.

class medaugmentx.interop.TorchTransform(transform, *, image_key='image', mask_key='mask', spacing_key='spacing', metadata_key='metadata', channel_dim='auto', preserve_image_dtype=False, preserve_mask_dtype=True, spatial_order='array', affine_key='affine', require_mask=False)[source]

Bases: SampleTransform

PyTorch dataset adapter using DHW/HW array order by default.

class medaugmentx.interop.MonaiMapTransform(transform, *, image_key='image', label_key='label', spacing_key='spacing', metadata_key='metadata', channel_dim='auto', preserve_image_dtype=False, preserve_label_dtype=True, spatial_order='native', affine_key='affine')[source]

Bases: SampleTransform

MONAI adapter using native spatial order and retaining current MetaTensor affine.

Inversion history is explicitly cleared; MedAugmentX is not MONAI-invertible. Pass label_key=None for image-only samples, or spatial_order=’array’ for a custom MONAI pipeline that has already converted its spatial axes to DHW.

class medaugmentx.interop.TorchIOTransform(transform, *, image_key=None, label_key='auto', channel_dim=0, preserve_image_dtype=False, preserve_label_dtype=True, copy=True)[source]

Bases: SampleTransform

TorchIO adapter for one intensity image plus one optional registered label.

Actual TorchIO data is (C, X, Y, Z); spatial axes and affine are converted together. Explicit keys must exist. Additional untransformed images are rejected to prevent partially augmented multimodal subjects.

Synthetic phantoms

from medaugmentx.phantoms import ct_phantom, dbt_phantom, mri_phantom, xray_phantom

Analytic phantoms used by the tutorials, examples, and tests. They are built from geometric shapes and a fixed seed: no patient data, no downloads, no network access, and byte-identical across machines — which makes them a reasonable base for a regression test.

Warning

Phantoms are illustrations, not validated models of anatomy or scanner physics. Do not draw clinical conclusions from how a transform looks on one.

Synthetic anatomical phantoms for demos, tutorials, and tests.

Every phantom here is generated from analytic shapes and a seeded RNG. Nothing in this module reads patient data, downloads a dataset, or contacts a network service, so the results are safe to publish in documentation and reproducible across machines.

These are illustrations, not simulations. Intensity values are chosen to sit in a plausible range for their modality (Hounsfield units for CT, arbitrary units elsewhere) so that window/level and intensity transforms behave sensibly, but no phantom is a validated physical model of anatomy or scanner physics. Do not use them to draw conclusions about clinical performance.

>>> from medaugmentx.phantoms import ct_phantom
>>> from medaugmentx.transforms import BeamHardening
>>> volume = ct_phantom()
>>> augmented = BeamHardening(alpha=0.10, seed=7)(volume)
medaugmentx.phantoms.mri_phantom(size=256)[source]

A 2D axial brain-like slice with grey/white contrast and ventricles.

Intensities are arbitrary units in roughly [0, 1], which is the range BiasField and RicianNoise are tuned for.

Return type:

MedVolume

medaugmentx.phantoms.ct_phantom(size=256)[source]

A 2D axial abdomen-like slice in approximate Hounsfield units.

Air sits near -1000 HU, soft tissue near 45 HU, and a dense implant near 800 HU, so window/level and beam-hardening transforms see realistic spans.

Return type:

MedVolume

medaugmentx.phantoms.xray_phantom(size=256)[source]

A 2D chest-radiograph-like projection with ribs, lungs, and mediastinum.

Intensities are arbitrary units in roughly [0, 1], matching what ScatterSimulation and GridArtifact expect.

Return type:

MedVolume

medaugmentx.phantoms.dbt_phantom(seed=2026)[source]

A true 3D tomosynthesis-like volume with scattered lesion blobs.

Shape is (64, 128, 256) with anisotropic spacing (1.0, 0.5, 0.25) — the thick-slice geometry that the DBT transforms are written for. seed controls lesion placement only; the background tissue is deterministic.

Return type:

MedVolume

medaugmentx.phantoms.DEFAULT_SIZE = 256

Side length in voxels of the 2D phantoms.

medaugmentx.phantoms.DEFAULT_SEED = 2026

Seed used for the randomly placed DBT lesions.