Transforms¶
from medaugmentx.transforms import BiasField, MRIMotion, RandomAffine
Full documentation for every shipped augmentation. For a side-by-side view of what each one simulates and whether it moves your annotations, see the transform catalog.
Two arguments are common to all of them and are not repeated below unless a transform treats them specially:
pProbability of applying the transform, in
[0, 1]. When it does not fire, the input volume is returned unchanged.seedInteger seed or
numpy.random.Generator. Containers override this for their children, giving each an independent stream derived from the parent.
Ranges follow one convention throughout: a scalar means a symmetric range around
zero or a fixed value, depending on the parameter, and a (low, high) tuple
is always explicit. Each docstring states which applies.
Spatial¶
Geometry: resampling, cropping, flipping, and deformation. Masks are resampled with nearest-neighbour interpolation so label values are never blended.
- class medaugmentx.transforms.RandomAffine(rotation=0.0, scale=(1.0, 1.0), translation=(0.0, 0.0), axes_enabled=('x', 'y', 'z'), order=1, mode='constant', cval=0.0, p=1.0, seed=None, space='physical', translation_units='fraction', scale_axes=None)[source]¶
Bases:
TransformRandom affine transform around the volume centre.
Supports both 2D and 3D inputs. For 3D, rotation is sampled per axis, and you can disable specific axes with
axes_enabled. Scaling and translation are sampled independently per axis from shared ranges.For in-plane-only rotation of a 3D volume, pass
axes_enabled=("z",): rotation about the slice axis mixes only the row/column coordinates. Rotations default to an orthonormal image frame using the physical grid metric, preserving distances when scaling is one. Array axis names are not anatomical RAS directions. Use space=”voxel” for legacy index angles.- Parameters:
rotation (Range) – Maximum rotation in degrees. Either a scalar (interpreted as
(-rotation, rotation)) or a(low, high)tuple.scale (tuple[float, float]) – Per-axis scale factor range. Default
(1.0, 1.0)(no scale).translation (tuple[float, float]) – Per-axis translation as a fraction of the volume size,
(low, high). Default(0.0, 0.0)(no translation).axes_enabled (tuple[str, ...]) – Axes to rotate about. Defaults to all axes. Use
("z",)for in-plane-only 3D rotation. For 2D, including"x"or"y"enables the single in-plane angle.order (int) – Spline order for image interpolation (0–5). Mask uses
order=0.mode (str) –
scipy.ndimageboundary mode ('constant','reflect','nearest').cval (float) – Fill value for
mode='constant'.p (float) – Probability of applying the transform.
seed (SeedLike) – RNG seed.
space (str) –
"physical"rotates rigidly in an orthonormal image frame using the grid metric;"voxel"uses legacy index-space angles.translation_units (str) –
"fraction"of axis size,"voxels", or"mm".scale_axes (tuple[str, ...] | None) – Array axis labels eligible for scaling; None means all.
- class medaugmentx.transforms.RandomFlip(axes=('x',), p_per_axis=0.5, p=1.0, seed=None, label_map=None, keypoint_label_map=None, bbox_label_map=None, label_axis='x')[source]¶
Bases:
TransformFlip the volume along selected axes, each with probability
p_per_axis.Axes can be given as integer indices (using NumPy ordering, where 3D is
(D, H, W)and 2D is(H, W)) or as the labels"x","y","z"."x"always means the column axis,"y"the row axis, and"z"the slice axis (3D only).Notes
Task and acquisition conventions determine whether any reflection is valid. Array x does not establish anatomical laterality. Presets leave flips disabled unless explicitly enabled.
- Parameters:
axes (Iterable[AxisSpec]) – Axes to consider for flipping.
p_per_axis (float) – Independent probability of flipping each enumerated axis, evaluated when the transform fires.
p (float) – Top-level probability that the transform runs at all.
seed (SeedLike) – Optional integer seed or
numpy.random.Generator.label_map (dict[int, int] | None) – Optional involutive segmentation class mapping on label_axis flips.
keypoint_label_map (dict | None) – Optional involutive landmark-name/class mapping.
bbox_label_map (dict | None) – Optional involutive box-class mapping.
label_axis (str) – Array axis whose flip triggers label remapping, default x.
- class medaugmentx.transforms.AnatomicCrop(size, foreground_prob=0.5, foreground_threshold=0.0, p=1.0, seed=None)[source]¶
Bases:
TransformRandom crop biased toward foreground (non-zero) anatomy.
Behaviour:
With probability
foreground_prob(and only when a non-empty mask or foreground exists) the crop is sampled to ensure at least one foreground voxel lies inside the patch.Otherwise a uniform random crop is taken.
If the requested
sizeis larger than the volume on any axis the volume is returned unchanged on that axis (centre-aligned, no padding).- Parameters:
size (Sequence[int]) – Target crop size per axis. Must match the volume ndim.
foreground_prob (float) – Probability of biasing the sample toward foreground.
foreground_threshold (float) – Pixel intensity above which a voxel counts as foreground when no mask is present.
p (float) – Probability of applying the transform.
seed (SeedLike) – RNG seed.
- class medaugmentx.transforms.ClassBalancedCrop(size, foreground_prob=0.5, *, labels=None, cval=0.0, p=1.0, seed=None)[source]¶
Bases:
TransformExtract a fixed-size training patch, optionally anchored on a mask class.
The foreground branch picks uniformly among the eligible classes present in this volume, then uniformly among voxels of that class. The crop origin is sampled uniformly from origins that include the selected voxel. If this branch is skipped, the mask is missing or no eligible class is present, origins are sampled uniformly across the image. This branch can also include foreground. Class balancing applies to the anchor within each image.
Short axes are padded symmetrically, with an odd extra voxel at the high end. Mask padding uses label 0. Images are converted to float32 when padding is needed. Spacing is preserved, and the affine and targets follow the patch origin. Targets outside the patch keep their translated coordinates.
- Parameters:
size (Sequence[int]) – Fixed patch shape of positive voxel counts in array-axis order.
foreground_prob (float) – Probability of taking the class-anchored branch.
labels (Sequence[int] | None) – Eligible nonzero integer label IDs, or None for all nonzero classes. Supply IDs explicitly to exclude ignore labels.
cval (float) – Image padding value in the current intensity units.
p (float) – Probability of applying. Use 1 for guaranteed patch shape.
seed (SeedLike) – RNG seed.
- class medaugmentx.transforms.ElasticDeform(alpha=30.0, sigma=4.0, order=1, mode='reflect', cval=0.0, p=1.0, seed=None, units='voxels', max_gradient=0.5, min_jacobian=None, max_displacement=None, bbox_mode='conservative')[source]¶
Bases:
TransformElastic deformation via Gaussian-smoothed random displacements.
Implementation follows the standard Simard / Castro-Pereira approach:
Sample independent uniform displacement fields per spatial axis.
Smooth every field with the same spatial Gaussian sigmas.
Scale each field by axis-specific
alpha.Warp the image (linear interp) and mask (nearest neighbour) using
scipy.ndimage.map_coordinates()with the same displacement.
Anisotropic
alphaandsigmaare essential for tomosynthesis-like volumes where the slice axis has very different sampling than the in-plane axes (e.g.alpha=(10, 120, 120),sigma=(3, 10, 10)in(z, y, x)order). Parameters default to voxels. With units=”mm”, values are converted along each grid axis using its spacing; smoothing on a sheared grid is separable in grid axes rather than isotropic in RAS.- Parameters:
alpha (ScalarOrSeq) – Per-axis displacement magnitude in pixels.
sigma (ScalarOrSeq) – Gaussian smoothing sigma per spatial axis, applied to every displacement component in array-axis order.
order (int) – Spline order for image interpolation (mask always uses 0).
mode (str) – Image/mask
map_coordinatesboundary mode. For constant padding modes, target inversion extends the displacement field with its nearest boundary value, independently of image fill.cval (float) – Fill value for
mode='constant'.p (float) – Probability of applying the transform.
seed (SeedLike) – RNG seed.
units (str) –
"voxels"or"mm"for alpha, sigma, and displacement cap.max_gradient (float | None) – Maximum sampled displacement-gradient norm; None disables automatic limiting. The default reduces extreme draws before warping.
min_jacobian (float | None) – Reject sampled pull-map folds below this determinant; None disables.
max_displacement (float | None) – Optional per-component absolute displacement cap.
bbox_mode (str) –
"conservative"bounds using global displacement extrema,"corners"for an explicit approximation, or"reject".
- class medaugmentx.transforms.CoarseDropout(num_holes=(1, 4), hole_size=(0.05, 0.2), fill_value=0.0, fill_mask=False, p=1.0, seed=None)[source]¶
Bases:
TransformZero out a random number of rectangular (2D) or box (3D) regions.
Also known as cutout. Forces the network to use the whole field of view rather than over-relying on a single salient region — a strong regulariser for both classification and segmentation. Hole sizes are expressed as a fraction of each axis so the transform is resolution-independent and works on 2-D and 3-D volumes alike.
The mask is left untouched by default (the ground-truth annotation is still valid behind an occlusion); pass
fill_mask=Trueto also blank the mask inside each hole.- Parameters:
num_holes (IntRange) – Number of holes to drop. Int (fixed) or
(low, high)inclusive range sampled per call.hole_size (tuple[float, float]) – Fractional extent of each hole along every axis, as
(min_frac, max_frac)in(0, 1]. Each hole samples an independent size per axis.fill_value (float) – Value written inside the holes (default
0.0).fill_mask (bool) – If True, also set the mask to
0inside each hole.p (float) – Probability of applying.
seed (SeedLike) – RNG seed.
- class medaugmentx.transforms.Resize(size, order=1, p=1.0, seed=None, antialias=True, clip_output=False)[source]¶
Bases:
TransformResample the volume to a fixed
size(one entry per spatial axis).The image is resampled with spline interpolation of order
order; the mask always uses nearest-neighbour (order=0) so label values are preserved.spacingis rescaled to reflect the new voxel grid.- Parameters:
size (Sequence[int]) – Target shape, matching the volume ndim (2D or 3D).
order (int) – Spline order for the image (0–3). Mask is always
order=0.p (float) – Probability of applying.
seed (SeedLike) – RNG seed (unused — Resize is deterministic, kept for API parity).
antialias (bool) – Prefilter the image before downsampling; never filters masks.
clip_output (bool) – Clamp interpolation overshoot to the input intensity range.
- class medaugmentx.transforms.ResampleToSpacing(spacing, order=1, p=1.0, seed=None, antialias=True, clip_output=False, max_voxels=None)[source]¶
Bases:
TransformResample to a requested voxel spacing in millimetres along the grid axes.
Keeps the physical image centre and grid directions (including shear). Each output size is
max(1, floor(size * old_spacing / spacing + 0.5)). Spacing is exact; rounding changes the voxel extent by at most half an output voxel per axis, except when the minimum size of one is needed. Unlike Resize, this does not preserve the exact field of view or produce a fixed batch shape. Border samples use nearest-edge extension.- Parameters:
spacing (float | Sequence[float]) – Positive finite millimetres, either an isotropic scalar or one entry per array axis (z, y, x for 3D; y, x for 2D).
order (int) – Image spline interpolation order (0–3); masks always use 0.
p (float) – Probability of applying; use 1 for deterministic preprocessing.
seed (SeedLike) – RNG seed, used only for probability gating.
antialias (bool) – Smooth the image before downsampling; never filters masks.
clip_output (bool) – Clamp spline overshoot to the input intensity range.
max_voxels (int | None) – Optional positive output voxel limit, checked before allocating resampled arrays. None disables this limit.
- class medaugmentx.transforms.ResampleToGrid(shape, affine, order=1, *, cval=0.0, max_voxels=None, p=1.0, seed=None)[source]¶
Bases:
TransformResample already registered data onto an explicit patient-space grid.
The target shape and array-index-to-RAS-mm affine determine the output field of view, orientation and spacing. For 2D, source and target planes must be coplanar. Uses float32 spline interpolation for the image and nearest-neighbour with zero padding for the mask. The image interpolates against
cvalbeyond the source grid. There is no antialiasing filter, so downsampling can alias the image and omit small labels.- Parameters:
shape (Sequence[int]) – Target shape in spatial array-axis order, with two or three entries.
affine (object) – Target 4x4 affine mapping array indices to RAS millimetres.
order (int) – Image spline order (0–3). The mask always uses nearest-neighbour.
cval (float) – Image fill in its current intensity units.
max_voxels (int | None) – Optional positive limit on the number of output voxels.
p (float) – Probability of applying. Use 1 for a fixed output grid.
seed (SeedLike) – RNG seed, used only for probability gating.
- class medaugmentx.transforms.Pad(size, mode='constant', cval=0.0, p=1.0, seed=None)[source]¶
Bases:
TransformPad the volume (centred) up to
sizealong each axis.Axes already at or above the target size are left unchanged —
Padnever crops. Pair withCenterCropto force an exact shape.- Parameters:
size (Sequence[int]) – Minimum target shape, matching the volume ndim.
mode (str) – Padding mode forwarded to
numpy.pad()(e.g."constant","edge","reflect").cval (float) – Constant fill value when
mode="constant"(image only; the mask is always padded with0).p (float) – Probability of applying.
seed (SeedLike) – RNG seed (unused — Pad is deterministic, kept for API parity).
- class medaugmentx.transforms.CenterCrop(size, p=1.0, seed=None)[source]¶
Bases:
TransformCrop the centred region of
sizealong each axis.Axes smaller than the target size are left unchanged —
CenterCropnever pads. Pair withPadto force an exact shape.- Parameters:
size (Sequence[int]) – Target shape, matching the volume ndim.
p (float) – Probability of applying.
seed (SeedLike) – RNG seed (unused — CenterCrop is deterministic, kept for API parity).
Intensity¶
Signal-domain changes that leave geometry alone — noise, contrast, blur, and bias. Masks and geometric targets always pass through untouched.
- class medaugmentx.transforms.RicianNoise(std=0.01, clip=None, p=1.0, seed=None)[source]¶
Bases:
TransformRician magnitude noise under a single-complex-signal model.
Rician noise arises naturally because the magnitude of complex Gaussian noise (which corrupts both real and imaginary k-space channels) is no longer Gaussian:
|N(s, σ) + j·N(0, σ)|follows a Rice distribution. For high SNR it approaches Gaussian behaviour; for low-signal regions (e.g. CSF or air outside the head) it produces the characteristic elevated noise floor seen on real MRI.Treats the input as a non-negative signal amplitude. Applying this to an already noisy reconstruction adds another perturbation; it does not infer or replace its existing noise. Multi-coil combination, parallel imaging, and reconstruction processing can require different noise models.
- Parameters:
std (Range) – Per-channel sigma — the standard deviation of the underlying real/imaginary Gaussians. Either a scalar or
(low, high).clip (tuple[float, float] | None) – Optional
(min, max)to clip the result.p (float) – Probability of applying.
seed (SeedLike) – RNG seed.
- class medaugmentx.transforms.GaussianNoise(std=0.01, relative=False, clip=None, p=1.0, seed=None)[source]¶
Bases:
TransformAdditive zero-mean Gaussian noise.
The standard deviation is interpreted in the intensity units of the image. For images normalised to
[0, 1]typical values are0.005–0.05. For raw HU CT images you’d pass tens to hundreds.- Parameters:
std (Range) – Either a fixed value or a
(low, high)range to sample from.relative (bool) – If True,
stdis interpreted as a fraction of the current image standard deviation (per-call).clip (tuple[float, float] | None) – Optional
(min, max)to clip the output.Noneskips clipping.p (float) – Probability of applying.
seed (SeedLike) – RNG seed.
- class medaugmentx.transforms.GammaCorrection(gamma=(0.8, 1.2), invert=False, p=1.0, seed=None)[source]¶
Bases:
TransformPower-law (gamma) intensity transformation.
Applied on the normalised image (rescaled to
[0, 1]per call), then unscaled back to the original intensity range. This makes the transform behave consistently regardless of whether the input is[0, 1], raw HU, or scanner-native MR intensities.For breast tomosynthesis a common range is
gamma=(0.85, 1.15).- Parameters:
gamma (Range) – Either a fixed gamma or a
(low, high)range. Values < 1 brighten mid-tones, values > 1 darken mid-tones.invert (bool) – If True, apply gamma to the inverted image (useful for contrast on dark backgrounds).
p (float) – Probability of applying.
seed (SeedLike) – RNG seed.
- class medaugmentx.transforms.BiasField(alpha=0.3, coarse_shape=4, order=3, p=1.0, seed=None)[source]¶
Bases:
TransformSmooth multiplicative bias field simulating MRI intensity non-uniformity.
MRI scans exhibit spatially-varying signal because RF coil sensitivity, B0 field inhomogeneity, and other hardware effects modulate the apparent tissue intensity across the field of view. This transform approximates that effect by generating a smooth random log-scale field on a coarse grid, upsampling it to the full volume size, and multiplying the image pointwise.
The multiplicative field is
exp(F)whereFis drawn fromU(-alpha, alpha)on a coarse grid of shapecoarse_shape, then spline-upsampled. Effective per-voxel multiplier range is[exp(-alpha), exp(alpha)].For typical MRI bias-field augmentation use
alpha=0.3(±30% signal variation). Larger values (e.g.0.5) model strong coil effects.- Parameters:
alpha (float) – Maximum log-scale deviation. Must be >= 0.
coarse_shape (int | tuple[int, ...]) – Shape of the coarse random grid. An integer means the same size for every axis; pass a tuple for per-axis control.
order (int) – Spline interpolation order for upsampling (3 = cubic).
p (float) – Probability of applying.
seed (SeedLike) – RNG seed.
- class medaugmentx.transforms.WindowLevel(center_shift_frac=0.1, width_scale=(0.8, 1.2), rescale_output=True, p=1.0, seed=None)[source]¶
Bases:
TransformRandom window-level augmentation — simulates CT viewer protocol variation.
Randomly shifts the window centre (by a fraction of the window width) and scales the window width, then clips the image to the resulting window. By default the output is linearly rescaled to
[0, 1].If the volume’s metadata contains
"window_center"and"window_width"keys those are used as the nominal values; otherwise the image min/max define the full-range window.This varies the displayed intensity window; it does not simulate changes in acquisition dose or the reconstruction kernel. Choose nominal windows and perturbation ranges for the intended model input.
- Parameters:
center_shift_frac (Range) – Fractional shift of the window centre relative to the window width. Scalar → symmetric
(-v, +v)range.width_scale (Range) – Multiplicative scale on the window width. Scalar → fixed; tuple → sampled from
(lo, hi). Must be > 0.rescale_output (bool) – If True (default) linearly rescale the clipped output to
[0, 1]. Set False to keep the clipped native intensity range.p (float) – Probability of applying.
seed (SeedLike) – RNG seed.
- class medaugmentx.transforms.BrightnessContrast(brightness=0.0, contrast=(0.9, 1.1), clip=None, p=1.0, seed=None)[source]¶
Bases:
TransformAdditive brightness shift + multiplicative contrast factor.
Applies:
out = clip(image * contrast + brightness, *clip)Both parameters operate in the image’s native intensity space — no normalisation is applied. Scale the ranges to your dataset:
Normalised
[0, 1]images:brightness=0.05,contrast=(0.9, 1.1)CT in Hounsfield units:
brightness=30.0,contrast=(0.95, 1.05)
The mask is never modified.
- Parameters:
brightness (Range) – Additive offset range. Scalar → symmetric
(-v, +v); tuple → explicit(lo, hi).contrast (Range) – Multiplicative factor. Scalar → fixed factor; tuple → sampled from
(lo, hi). Must be > 0;1.0is identity.clip (tuple[float, float] | None) – Optional
(min, max)to clamp the result.p (float) – Probability of applying.
seed (SeedLike) – RNG seed.
- class medaugmentx.transforms.GaussianBlur(sigma=(0.5, 1.5), order=0, mode='reflect', p=1.0, seed=None, units='voxels')[source]¶
Bases:
TransformIsotropic Gaussian blur applied to the image.
The mask is never blurred — blurring annotation boundaries degrades segmentation labels. For anisotropic sigma control call
scipy.ndimage.gaussian_filterdirectly.Typical values:
2-D mammography / DXR:
sigma=(0.5, 1.5)3-D MRI / CT:
sigma=(0.5, 2.0)
- Parameters:
sigma (Range) – Blur sigma in voxels. Scalar → fixed; tuple
(lo, hi)→ sampled per call. Same sigma applied to every axis.order (int) – Gaussian derivative order (0 = standard blur).
mode (str) – Boundary mode for
scipy.ndimage.gaussian_filter().p (float) – Probability of applying.
seed (SeedLike) – RNG seed.
units (str) – Sigma units,
"voxels"or per-axis"mm".
- class medaugmentx.transforms.MedianBlur(ksize=3, mode='reflect', p=1.0, seed=None)[source]¶
Bases:
TransformMedian filter — edge-preserving smoothing, strong against salt-and-pepper.
Unlike
GaussianBlur, the median filter removes impulse noise (hot/dead detector pixels, speckle) while keeping edges crisp. The window is a cube of sideksizevoxels applied across all axes.Note
A 3-D median filter is a cubic-window rank filter and is intrinsically expensive on large volumes. Prefer a small
ksize(3) and/or a modestpon full-resolution 3-D data — seebenchmarks/.The mask is never modified.
- Parameters:
ksize (IntRange) – Window side length in voxels. Must be a positive odd integer, or a
(low, high)inclusive range of odd integers sampled per call.mode (str) – Boundary mode for
scipy.ndimage.median_filter().p (float) – Probability of applying.
seed (SeedLike) – RNG seed.
- class medaugmentx.transforms.SimulateLowResolution(zoom_range=(0.5, 0.9), order_down=1, order_up=1, per_axis=False, p=1.0, seed=None, antialias=True, clip_output=False)[source]¶
Bases:
TransformSimulate a lower-resolution acquisition by down- then upsampling.
Downsamples the image by a random factor drawn from
zoom_range, then upsamples back to the original shape. The resulting image contains the same number of voxels as the input but with blurred detail that mimics a scanner running at lower spatial resolution.This teaches models to be robust across scanner sites with different acquisition protocols — a common problem in multi-centre studies.
The mask is left at full resolution (it represents the ground-truth annotation and remains valid regardless of image resolution).
- Parameters:
zoom_range (tuple[float, float]) –
(min, max)downsampling factor per axis; values in(0, 1). E.g.(0.5, 0.9)means the temporary downsampled image has 50–90 % of the original voxels per side.order_down (int) – Spline order for the downsampling step.
order_up (int) – Spline order for the upsampling step.
per_axis (bool) – If True, sample an independent zoom factor per axis (useful for anisotropic volumes). Default False.
p (float) – Probability of applying.
seed (SeedLike) – RNG seed.
antialias (bool) – Smooth the image before downsampling; never filters masks.
clip_output (bool) – Clamp interpolation overshoot to the input range.
- class medaugmentx.transforms.Sharpen(alpha=(0.2, 0.8), sigma=(0.7, 1.5), clip=None, p=1.0, seed=None)[source]¶
Bases:
TransformSharpen the image with an unsharp mask.
Computes a blurred copy and adds back the high-frequency residual:
out = image + alpha * (image - gaussian_blur(image, sigma))Mimics the edge-enhancement filters radiologists routinely apply at the viewing workstation, and the variation between different vendor recon kernels. The mask is never modified.
- Parameters:
alpha (Range) – Sharpening strength. Scalar → fixed; tuple
(lo, hi)→ sampled per call.0is identity; typical values0.2–1.5.sigma (Range) – Gaussian sigma (voxels) of the blur used to extract detail. Scalar → fixed; tuple → sampled per call.
clip (tuple[float, float] | None) – Optional
(min, max)to clamp the result.p (float) – Probability of applying.
seed (SeedLike) – RNG seed.
- class medaugmentx.transforms.CLAHEContrast(clip_limit=(1.0, 3.0), grid=(8, 8), n_bins=256, p=1.0, seed=None)[source]¶
Bases:
TransformContrast Limited Adaptive Histogram Equalization.
CLAHE equalises contrast locally rather than globally, revealing detail in both dark and bright regions without amplifying noise the way plain histogram equalisation does (the per-tile histogram is clipped before the mapping is built). It is one of the most widely used pre-processing / augmentation steps in radiology, especially for chest X-ray and mammography.
The image is rescaled to
[0, 1]internally and mapped back to its original intensity range on output. For 3-D volumes CLAHE is applied slice-by-slice along the first (Z) axis. The mask is never modified.- Parameters:
clip_limit (Range) – Contrast-clip threshold relative to the per-tile mean histogram height. Higher → more contrast (and more noise). Scalar → fixed; tuple
(lo, hi)→ sampled per call. Typical values1.0–4.0.grid (tuple[int, int]) – Number of tiles per axis as
(rows, cols)for the 2-D equalisation grid (applied in-plane).n_bins (int) – Number of histogram bins (256 by default).
p (float) – Probability of applying.
seed (SeedLike) – RNG seed.
- class medaugmentx.transforms.HistogramMatch(reference=None, blend=1.0, n_quantiles=256, p=1.0, seed=None, reference_quantiles=None)[source]¶
Bases:
TransformMatch the image intensity histogram to a reference distribution.
Standardising intensity profiles across scanners and acquisition protocols is a common harmonisation step for multi-centre studies; used as an augmentation it teaches a model to be robust to that variation by re-shaping each volume toward a fixed reference distribution.
Provide one reference image (any shape) whose intensity distribution is the target. The output preserves the input shape; only voxel intensities are remapped. The mask is never modified.
Note
Policies store a compact sorted quantile summary, rather than the source image. This summary still describes its intensity distribution; inspect it before sharing. A missing reference is an identity operation.
- Parameters:
reference (Any) – Array-like whose histogram is the matching target, or
Nonefor an identity no-op.blend (Range) – Blend ratio between the original and matched image, in
[0, 1].1= full match (default),0= identity. Scalar → fixed; tuple(lo, hi)→ sampled per call.n_quantiles (int) – Number of quantiles used to summarise the reference CDF.
p (float) – Probability of applying.
seed (SeedLike) – RNG seed.
reference_quantiles (Any) – Optional serialized sorted quantile summary instead of a reference image; v1 policies store this compact representation.
- class medaugmentx.transforms.NormalizeIntensity(percentiles=(0.5, 99.5), p=1.0, seed=None)[source]¶
Bases:
TransformClip to chosen percentiles and map the image into [0, 1].
Constant finite images become zero. This changes the intensity domain and must precede normalized-domain noise; it is inappropriate for preserving HU.
- Parameters:
percentiles (tuple[float, float]) – Ordered lower/upper percentiles in [0,100].
p (float) – Probability of applying; use 1 for model input preparation.
seed (SeedLike) – RNG seed, used only for probability gating.
MRI¶
Acquisition artifacts specific to magnetic resonance: k-space corruption, ghosting along the phase-encode axis, and rigid motion.
- class medaugmentx.transforms.GhostingArtifact(ghost_intensity=(0.05, 0.15), ghost_shift=(8, 32), phase_encode_axis='y', num_ghosts=1, p=1.0, seed=None)[source]¶
Bases:
TransformSimulate MRI phase-encoding ghosting.
Ghosting arises from periodic motion during the phase-encode direction acquisition — cardiac pulsation, breathing, or patient movement produce attenuated shifted replicas of the anatomy overlaid on the image.
Implementation: add one or more rolled, attenuated copies of the image along the phase-encode axis. Each replica is the image scaled by the ghost intensity, so the effect is consistent across intensity scales. Shifts are taken modulo the axis length; a replica whose shift wraps to zero would only rescale the image, so it is skipped.
Works on 2-D and 3-D inputs. For 3-D, ghosting is applied in each axial plane (i.e. along the in-plane axis selected by
phase_encode_axis).- Parameters:
ghost_intensity (Range) – Ghost-to-original amplitude ratio. Scalar → fixed; tuple → sampled from
(lo, hi). Typical MRI values: 0.05–0.20.ghost_shift (IntRange) – Shift in pixels. Scalar → fixed; tuple → sampled.
phase_encode_axis (str) –
"y"(row, default) or"x"(column).num_ghosts (int) – Number of independent ghost replicas to superimpose.
p (float) – Probability of applying.
seed (SeedLike) – RNG seed.
- class medaugmentx.transforms.KSpaceDropout(dropout_fraction=(0.01, 0.05), phase_encode_axis='y', p=1.0, seed=None)[source]¶
Bases:
TransformZero a fraction of k-space lines to simulate acquisition errors.
Real MRI scanners occasionally produce corrupted k-space lines from hardware glitches, RF interference, or momentary gradient failure. This transform simulates that by:
Taking the 2-D FFT of each slice (or the 2-D image).
Randomly zeroing
dropout_fractionof lines along the phase-encode direction.Reconstructing the magnitude image via inverse FFT.
The result can exhibit ringing and aliasing. This is an approximation on reconstructed image data; measured complex k-space and scanner-specific acquisition/reconstruction effects are not modelled.
Works on 2-D and 3-D volumes. For 3-D, each axial slice is corrupted independently (independent random line selection per slice).
- Parameters:
dropout_fraction (Range) – Fraction of k-space lines to zero. Scalar → fixed; tuple → sampled from
(lo, hi).phase_encode_axis (str) – Axis along which lines are dropped (
"y"rows or"x"columns).p (float) – Probability of applying.
seed (SeedLike) – RNG seed.
- class medaugmentx.transforms.MRIMotion(degrees=(1.0, 5.0), translation=(1.0, 4.0), num_movements=(1, 3), p=1.0, seed=None)[source]¶
Bases:
TransformSimulate MRI in-plane rigid-body motion (blur + ghosting).
During a scan the patient occupies several slightly different positions. This image-domain approximation produces blur and ghost-like replicas. It does not simulate the timing or phase inconsistency of motion during k-space acquisition, which generally differs from averaging images.
This transform averages the original image with a few mildly rotated/translated copies (in-plane only). For 3-D volumes the same in-plane motion is applied to every slice. The mask is treated as an intensity artifact source and is not moved — the true anatomy annotation stays valid.
- Parameters:
degrees (Range) – In-plane rotation per motion state, in degrees. Scalar → symmetric
(-v, +v). A non-negative tuple(lo, hi)is a magnitude range: each draw also gets a random sign, so motion is unbiased. A tuple with a negative bound is an explicit signed range.translation (Range) – In-plane translation per motion state, in pixels, with the same scalar, magnitude-range and signed-range rules as
degrees.num_movements (IntRange) – Number of additional motion states to blend in. Int (fixed) or
(low, high)inclusive range.p (float) – Probability of applying.
seed (SeedLike) – RNG seed.
CT¶
Polychromatic-beam and high-density-implant effects seen on computed tomography reconstructions.
- class medaugmentx.transforms.BeamHardening(alpha=(0.02, 0.08), power=2.0, p=1.0, seed=None)[source]¶
Bases:
TransformSimulate CT beam hardening (cupping) artifact.
When a polychromatic X-ray beam passes through tissue, lower-energy photons are preferentially absorbed (photoelectric absorption dominates). The beam reaching the centre of a homogeneous object is richer in high-energy photons with lower effective attenuation than assumed by a simple reconstruction — the centre can look darker than the periphery. This is the cupping artifact.
Implementation: subtract a smooth radially-symmetric bowl profile from each axial slice, scaled by
alpha * image_range. The bowl peaks at the centre (maximal darkening) and tapers to zero at the edges.out = image - alpha * bowl(H, W) * image_rangeThis is an image-domain cupping approximation. It does not trace rays, model the X-ray spectrum, or infer patient/material attenuation.
Works on 2-D and 3-D inputs. For 3-D, the same bowl is applied to every axial slice. The mask is never modified.
- Parameters:
alpha (Range) – Artifact strength relative to the image intensity range. Scalar → fixed; tuple → sampled from
(lo, hi). Typical values:0.02–0.10.power (float) – Exponent controlling the bowl shape (higher → sharper cupping restricted to the very centre; lower → broader dimming).
p (float) – Probability of applying.
seed (SeedLike) – RNG seed.
- class medaugmentx.transforms.MetalStreak(intensity=(0.1, 0.3), num_streaks=(6, 12), num_sources=1, falloff=0.5, p=1.0, seed=None)[source]¶
Bases:
TransformSimulate CT metal streak artifacts.
Dense implants (dental fillings, hip prostheses, surgical clips) attenuate the X-ray beam so strongly that the reconstruction produces bright and dark streaks radiating from the metal. This transform adds a star-burst pattern of streaks emanating from one or more seed points, with a radial fall-off so the effect is strongest near the metal.
Applied per axial slice; the same seed point and streak pattern are used on every slice of a 3-D volume. The mask is never modified.
- Parameters:
intensity (Range) – Streak amplitude relative to the image intensity range. Scalar → fixed; tuple
(lo, hi)→ sampled per call. Typical values0.1–0.4.num_streaks (IntRange) – Number of angular streak lobes in the star-burst. Int or
(low, high)inclusive range.num_sources (IntRange) – Number of independent metal seed points.
falloff (float) – Radial decay scale as a fraction of the image half-diagonal (smaller → streaks stay close to the metal).
p (float) – Probability of applying.
seed (SeedLike) – RNG seed.
X-ray (DXR)¶
Projection-radiography effects: Compton scatter and anti-scatter grid line artifacts.
- class medaugmentx.transforms.ScatterSimulation(fraction=(0.1, 0.4), sigma=(15.0, 40.0), p=1.0, seed=None)[source]¶
Bases:
TransformSimulate X-ray scatter (veiling glare) that lowers contrast.
Compton-scattered photons add a smooth, low-frequency haze across the detector, reducing local contrast — especially pronounced in thick body regions and when no anti-scatter grid is used. This transform adds a heavily blurred copy of the image as a scatter background.
out = image + fraction * gaussian_blur(image, sigma)The mask is never modified.
- Parameters:
fraction (Range) – Scatter-to-primary amplitude ratio. Scalar → fixed; tuple
(lo, hi)→ sampled per call. Typical values0.1–0.5.sigma (Range) – Gaussian sigma (voxels) of the scatter blur — large, since scatter is low-frequency. Scalar → fixed; tuple → sampled.
p (float) – Probability of applying.
seed (SeedLike) – RNG seed.
- class medaugmentx.transforms.GridArtifact(amplitude=(0.03, 0.1), frequency=(0.2, 0.45), axis='x', p=1.0, seed=None)[source]¶
Bases:
TransformSimulate stationary anti-scatter grid lines.
A non-reciprocating (stationary) anti-scatter grid leaves fine periodic line shadows across the radiograph. This transform multiplies the image by a sinusoidal stripe pattern oriented along one in-plane axis.
out = image * (1 + amplitude * sin(2*pi*frequency*coord + phase))The mask is never modified.
- Parameters:
amplitude (Range) – Peak relative modulation of the grid lines. Scalar → fixed; tuple
(lo, hi)→ sampled per call. Typical values0.02–0.12.frequency (Range) – Grid spatial frequency in cycles per pixel. Scalar → fixed; tuple → sampled.
0.25≈ a line every 4 pixels.axis (str) – Stripe orientation —
"x"for vertical lines (varying along columns) or"y"for horizontal lines (varying along rows).p (float) – Probability of applying.
seed (SeedLike) – RNG seed.
Tomosynthesis (DBT)¶
Limited-angle reconstruction effects. These act on the reconstructed volume with explicit slice-axis operations and per-axis voxel parameters.
- class medaugmentx.transforms.SlabShift(max_shift=2, cval=0.0, p=1.0, seed=None)[source]¶
Bases:
TransformShift the entire volume along the slice (Z) axis.
Simulates inter-scan variation in the reconstruction centre between two DBT acquisitions of the same patient. The number of slices and the voxel spacing are preserved; gaps introduced by the shift are filled with
cval(default zero, i.e. air). Images are returned as float32 socvalis never truncated or wrapped by an integer input dtype.- Parameters:
max_shift (IntRange) – Maximum absolute shift in slices. Either an int (treated as
(-max_shift, max_shift)) or a(low, high)tuple.cval (float) – Fill value for newly empty slices. Defaults to
0.0.p (float) – Probability of applying.
seed (SeedLike) – RNG seed.
- Raises:
ValueError – If applied to a 2D volume — DBT is 3D by definition.
- class medaugmentx.transforms.LimitedAngleBlur(arc_degrees=(15.0, 25.0), base_sigma=1.0, reference_arc_deg=20.0, p=1.0, seed=None)[source]¶
Bases:
TransformZ-axis Gaussian blur scaled by the acquisition arc.
Tomosynthesis reconstructions exhibit out-of-plane blur because the detector samples projections over a limited arc (15–25° for typical clinical systems). Wider arcs reduce blur (more depth resolution), narrower arcs increase it.
The transform models that effect with a 1-D Gaussian along the slice axis. The relationship between sigma (in slices) and the arc angle is intentionally approximate — the goal is realistic variability, not a physics simulator.
sigma_slices = base_sigma * (reference_arc_deg / arc_degrees)
- Parameters:
arc_degrees (Range) – Either a fixed arc angle or a
(low, high)range.base_sigma (float) – Reference sigma at
reference_arc_deg.reference_arc_deg (float) – Angle at which sigma equals
base_sigma.p (float) – Probability of applying.
seed (SeedLike) – RNG seed.
Notes
Mask blur would corrupt label boundaries, so the mask is left untouched. The image’s blur is along Z only — XY is preserved.
- class medaugmentx.transforms.SliceDropout(num_slices=1, cval=0.0, affect_mask=False, p=1.0, seed=None)[source]¶
Bases:
TransformZero one or more slices along the Z axis.
This is a robustness augmentation: models trained with occasional blanked slices learn not to assume strict per-slice continuity, which matters when DBT reconstructions occasionally drop frames or contain severe streak artifacts on isolated slices.
- Parameters:
num_slices (IntRange) – How many slices to drop. Either an int (fixed count) or a
(low, high)inclusive range to sample from.cval (float) – Fill value (defaults to
0.0). Images are returned as float32.affect_mask (bool) – If True, also zero the mask on the dropped slices. Defaults to False — most segmentation pipelines want the ground truth preserved.
p (float) – Probability of applying.
seed (SeedLike) – RNG seed.
- class medaugmentx.transforms.AnisotropicElastic(alpha=(8.0, 100.0, 100.0), sigma=(2.0, 8.0, 8.0), order=1, p=1.0, seed=None, units='voxels', max_gradient=0.5, min_jacobian=None, max_displacement=None, bbox_mode='conservative')[source]¶
Bases:
TransformElastic deformation with sensible DBT defaults.
Tomosynthesis voxels are anisotropic (typically ~0.1×0.1mm in-plane vs ~1mm slice). Standard isotropic elastic settings warp the slice axis far more than is anatomically plausible. This transform is a thin wrapper around
ElasticDeformwith defaults appropriate for DBT, and fails fast on 2D input.Defaults in
(z, y, x)order:alpha=(8, 100, 100),sigma=(2, 8, 8). These are voxel-space settings, not an automatic conversion from the volume’s spacing.- Parameters:
alpha (Sequence[float]) – Per-axis displacement magnitude in pixels.
sigma (Sequence[float]) – Per-axis Gaussian sigma.
order (int) – Image interpolation order (mask uses 0 always).
p (float) – Probability of applying.
seed (SeedLike) – RNG seed.
units (str) –
"voxels"or"mm"for field parameters.max_gradient (float | None) – Optional sampled displacement-gradient norm bound.
min_jacobian (float | None) – Optional minimum sampled pull-map Jacobian determinant.
max_displacement (float | None) – Optional per-component displacement cap in units.
bbox_mode (str) – Conservative bounds, explicit corner approximation, or rejection.
- class medaugmentx.transforms.CompressionVariation(scale=(0.85, 1.15), axis='y', order=1, p=1.0, seed=None)[source]¶
Bases:
TransformSimulate variation in breast-paddle compression for DBT.
Between acquisitions the same breast is compressed by differing amounts, stretching or squeezing the tissue along the compression direction (the in-plane axis perpendicular to the chest wall). This transform applies an anisotropic scaling along a single in-plane axis while keeping the volume shape and the slice axis untouched.
The image and mask share the same sampled scale; the mask is resampled with nearest-neighbour interpolation so label values are preserved. Squeezing exposes background at both ends of the axis: the image is filled with
0and the mask with label0, for everyorder.- Parameters:
scale (Range) – Multiplicative scale along the compression axis. Scalar → fixed; tuple
(lo, hi)→ sampled per call. Values < 1 squeeze, > 1 stretch. Must be > 0. Typical values0.85–1.15.axis (str) – In-plane compression axis —
"y"(row, default) or"x".order (int) – Image interpolation order (mask always uses
0).p (float) – Probability of applying.
seed (SeedLike) – RNG seed.
- Raises:
ValueError – If applied to a 2D volume — DBT is 3D by definition.
- class medaugmentx.transforms.ReconStreak(amplitude=(0.05, 0.2), num_planes=(1, 3), displacement=1.5, decay=0.6, axis='x', p=1.0, seed=None)[source]¶
Bases:
TransformSimulate DBT out-of-plane reconstruction streaks.
Because tomosynthesis reconstructs from a limited scan arc, high-contrast structures are not fully localised to their true slice: they reappear as faded, in-plane-shifted replicas in neighbouring slices (the parallax of limited-angle reconstruction). This transform superimposes such shifted, attenuated copies from adjacent planes onto each slice.
The mask is treated as an intensity-artifact source and is never modified — the true anatomy annotation stays valid.
- Parameters:
amplitude (Range) – Strength of the spilled replicas relative to the source. Scalar → fixed; tuple
(lo, hi)→ sampled per call. Typical values0.05–0.25.num_planes (IntRange) – Number of neighbouring planes (on each side) to spill from. Int or
(low, high)inclusive range.displacement (float) – In-plane shift (pixels) per plane of separation — the parallax slope.
decay (float) – Per-plane geometric fall-off of the replica amplitude.
axis (str) – In-plane direction of the parallax shift —
"x"(default) or"y".p (float) – Probability of applying.
seed (SeedLike) – RNG seed.
- Raises:
ValueError – If applied to a 2D volume — DBT is 3D by definition.