Core¶
from medaugmentx import Compose, MedVolume, OneOf, PerChannel, SomeOf, Transform
The data container¶
MedVolume is the single type that flows through every pipeline. It is
immutable in practice: transforms return a new volume via
replace() or warp()
rather than mutating the one they were given.
Coordinates in keypoints and bboxes use array-index order — the same
order you would use to index image, so (z, y, x) for 3D and (y, x)
for 2D — and boxes are laid out low corner first, [min…, max…].
- class medaugmentx.MedVolume(image, mask=None, spacing=(), metadata=<factory>, keypoints=None, keypoint_labels=None, bboxes=None, bbox_labels=None, affine=None, channels=<factory>)[source]¶
Bases:
objectA medical image (2D or 3D) with optional registered channels and targets.
All transforms in MedAugmentX operate on this container so that masks, geometric targets, and metadata stay in lockstep with the image array.
- Variables:
image (numpy.ndarray) – 2D
(H, W)or 3D(D, H, W)array. Recommended dtype isfloat32; integer inputs are accepted but will be cast where arithmetic is required.mask (numpy.ndarray | None) – Optional integer label map with the same shape as
image.keypoints (numpy.ndarray | None) – Optional
(N, ndim)float array of landmark coordinates in array-index order ((z, y, x)for 3D,(y, x)for 2D — the same order used to indeximage). Spatial transforms warp these points in lockstep with the pixels; intensity and artifact transforms pass them through unchanged. Seemedaugmentx.core.geometry.keypoint_labels (numpy.ndarray | None) – Optional
(N,)array of per-keypoint labels (class ids, landmark names, …). Carried through untouched.bboxes (numpy.ndarray | None) – Optional
(M, 2*ndim)float array of axis-aligned bounding boxes laid out as[min…, max…]in array-index order. Warped in lockstep with the image; under rotation each box becomes the axis-aligned bounding box of its transformed corners.bbox_labels (numpy.ndarray | None) – Optional
(M,)array of per-box labels. Carried through untouched.spacing (tuple[float, ...]) – Voxel size in millimetres, one entry per spatial axis. For 3D volumes this is
(slice_thickness, row_mm, col_mm).metadata (dict[str, Any]) – Free-form dictionary. Conventional keys:
modality("MR" | "CT" | "DX" | "DBT"),vendor,patient_id,original_dtype.affine (numpy.ndarray | None) – Optional 4x4 matrix mapping array-axis voxel centres to RAS patient coordinates in millimetres.
Nonemeans patient geometry is unknown. Spacing is derived from its column lengths.channels (dict[str, numpy.ndarray]) – Named additional intensity arrays already on the primary image’s grid. Use
with_channels()to check separately loaded volumes before attaching them.
- image: ndarray¶
- mask: ndarray | None = None¶
- spacing: tuple[float, ...] = ()¶
- metadata: dict[str, Any]¶
- keypoints: ndarray | None = None¶
- keypoint_labels: ndarray | None = None¶
- bboxes: ndarray | None = None¶
- bbox_labels: ndarray | None = None¶
- affine: ndarray | None = None¶
- channels: dict[str, ndarray]¶
- property voxel_volume: float¶
Physical voxel volume (3D) or pixel area (2D), including shear.
- index_to_world(points)[source]¶
Convert array-index points to RAS millimetres; unknown grids raise.
- Return type:
ndarray
- world_to_index(points, *, tolerance_mm=1e-05)[source]¶
Convert finite
(N, 3)RAS-mm points to continuous array indices.Requires known patient geometry. For a 2D image, points must lie on its plane within
tolerance_mm; off-plane points raise rather than being silently projected. Indices can lie outside the image bounds and are never rounded or clipped.- Parameters:
points (object) – RAS coordinates in millimetres, including for 2D images.
tolerance_mm (float) – Finite non-negative distance allowed from a 2D plane.
- Return type:
ndarray
- property ndim: int¶
- property shape: tuple[int, ...]¶
- property is_3d: bool¶
- property has_mask: bool¶
- property has_keypoints: bool¶
- property has_bboxes: bool¶
- property num_keypoints: int¶
- property num_bboxes: int¶
- property modality: str | None¶
- with_channels(channels)[source]¶
Attach separately loaded images after checking known patient grids.
Only the supplied images are added. Keep shared labels and annotations on the primary volume. Resample mismatched registered grids explicitly before attaching them. Existing channel names cannot be overwritten.
- Return type:
- stack_channels(*names)[source]¶
Return a channel-first array with the primary image first.
List additional channel names to specify their order or select a subset. With no names, use all additional channels in their insertion order.
- Return type:
ndarray
- select_channel(name=None)[source]¶
Return a single-channel volume with the shared annotations and grid.
- Return type:
- replace(*, image=None, mask=None, keypoints=None, keypoint_labels=None, bboxes=None, bbox_labels=None, spacing=None, metadata=None, affine=None, channels=None)[source]¶
Return a new MedVolume with selected fields swapped out.
Any field left as
Nonekeeps its current value, so a transform that only rewrites the image (every intensity/artifact transform) implicitly carries the mask and geometric targets through unchanged. Metadata is shallow-copied to avoid silent aliasing across volumes. A newaffinewithoutspacingre-derives spacing from the affine.- Return type:
- warp(point_map, *, image=None, image_map=None, mask=None, spacing=None, grid_map=None)[source]¶
Return a new volume with a warped image and geometrically mapped targets.
The single entry point every spatial transform uses: it applies
point_map(an(K, ndim) -> (K, ndim)coordinate map) to the keypoints and, via their corners, the bounding boxes, then swaps in the already-warpedimage/mask. Labels ride along unchanged. When the volume carries no targets this is justreplace().- Parameters:
point_map (PointMap) – The forward coordinate map matching the pixel warp — see
medaugmentx.core.geometryfor the standard maps.image (ndarray | None) – The already-transformed image array for single-channel inputs.
image_map (Callable[[ndarray], ndarray] | None) – Apply the same precomputed spatial operation to every intensity image. Supply either
imageorimage_map. Sample random parameters before building this callable.mask (ndarray | None) – The already-transformed mask, if any.
spacing (tuple[float, ...] | None) – New voxel spacing (only
Resizeneeds this);Nonekeeps the current spacing.grid_map (ndarray | None) – Optional 4x4 output-to-input grid map. Changes the sampling grid’s affine; anatomy augmentations leave this unset.
- Return type:
- remove_out_of_bounds_targets(min_visibility=0.0)[source]¶
Drop targets that fall outside the current image, in lockstep with labels.
Spatial transforms map targets faithfully and never drop them, so after a crop a keypoint may land at a negative coordinate and a box may hang off the edge. Call this to prune such targets for a detection/landmark head:
keypoints inside
[0, size - 1](the span of voxel centres) on every axis are kept; the rest (and their labels) are removed. The interval matches box clipping and is symmetric under flips;boxes are clipped to
[0, size - 1]and dropped when their retained fraction of the original area is< min_visibility(with the default0.0only boxes with no overlap at all are dropped).
The transform contract¶
Every augmentation subclasses Transform. Subclasses implement
apply() and draw all randomness from self.rng;
the base class handles probability gating, seeding, and serialisation, so a
custom transform gets those for free.
- class medaugmentx.Transform(p=1.0, seed=None)[source]¶
Bases:
ABCBase class for all augmentations.
Subclasses must override
apply()and acceptpandseedthroughsuper().__init__. The base class handles probabilistic application, seeding, and serialisation.Probabilistic application is gated on
self.rngso that two transforms in the sameComposewith the same seed do not share a random stream — seemedaugmentx.core.utils.derive_rng().Example
- class MyShift(Transform):
- def __init__(self, max_shift=0.1, p=1.0, seed=None):
super().__init__(p=p, seed=seed) self.max_shift = max_shift
- def apply(self, volume):
delta = self.rng.uniform(-self.max_shift, self.max_shift) return volume.replace(image=volume.image + delta)
- abstractmethod apply(volume)[source]¶
Perform the transform unconditionally — already past probability gate.
- Return type:
Pipeline containers¶
Containers are themselves transforms, so they nest freely. Each one seeds its children from its own generator rather than sharing a stream, which keeps two identically-seeded transforms in the same pipeline from drawing the same numbers.
- class medaugmentx.Compose(transforms, p=1.0, seed=None)[source]¶
Bases:
TransformApply transforms sequentially.
All children share a deterministic seeding chain derived from the top-level seed. Fresh equivalent pipelines reproduce the same sequence of draws in the same software environment; successive calls advance RNG state. Serialisation stores configuration, not the current RNG state.
- Parameters:
transforms (Iterable[Transform]) – Transforms to apply in order.
p (float) – Probability of applying the whole sequence.
seed (SeedLike) – Seed for the children’s derived streams.
- class medaugmentx.OneOf(transforms, weights=None, p=1.0, seed=None)[source]¶
Bases:
TransformPick exactly one child uniformly at random and apply it.
The container’s
pcontrols whether any child runs at all. When weights are provided they are normalised; otherwise the choice is uniform.- Parameters:
transforms (Sequence[Transform]) – Candidate transforms; the chosen one runs regardless of its
p.weights (Sequence[float] | None) – Optional non-negative relative weights, one per transform.
p (float) – Probability of applying any child.
seed (SeedLike) – Seed for the choice and the children’s derived streams.
- class medaugmentx.SomeOf(transforms, n=1, p=1.0, seed=None)[source]¶
Bases:
TransformPick
nchildren at random (without replacement) and apply them in order.nmay be an int or a(low, high)inclusive range — when a range, a value is sampled per call.- Parameters:
transforms (Sequence[Transform]) – Candidate transforms; chosen ones run regardless of their
p.n (int | tuple[int, int]) – Number of transforms to apply, or an inclusive
(low, high)range.p (float) – Probability of applying the container.
seed (SeedLike) – Seed for the selection and the children’s derived streams.
PerChannel wraps an intensity policy so it also augments the named
registered channels, with independent or shared draws per image.
- class medaugmentx.PerChannel(transform, channels=None, include_primary=True, shared=False, p=1.0, seed=None)[source]¶
Bases:
TransformApply an intensity transform to each registered image channel.
Spatial transforms already share one sampled geometry across the named
MedVolume.channels, while intensity transforms act on the primary image only. Wrap an intensity or appearance policy inPerChannelto augment the primary image and selected channels inside one serialisable, replayable policy.By default every image receives its own draw from one deterministic stream, in order: the primary image, then the selected channels. With
shared=Trueevery image reuses the first image’s random draws, which suits channels with a common intensity scale.The wrapped transform must leave the image shape, mask, geometry and targets unchanged; spatial transforms raise
ValueError. Metadata comes from the primary image’s result, or is unchanged when it is excluded.- Parameters:
transform (Transform) – Intensity transform or pipeline to apply per image.
channels (Sequence[str] | None) – Named channels to augment, in order.
Noneselects every channel present in insertion order. Missing names raiseKeyError.include_primary (bool) – Also augment the primary image.
shared (bool) – Reuse the same random draws for every selected image.
p (float) – Probability of applying the wrapper at all.
seed (SeedLike) – Seed for the wrapped transform’s derived stream.
Coordinate maps¶
These are the building blocks behind the Targets column of the
catalog. You need them only when writing a spatial transform
of your own: build a point map describing how coordinates move, then hand it to
warp() along with the resampled image, and
keypoints and boxes are carried along for you.
Coordinate geometry for keypoint and bounding-box targets.
MedAugmentX carries two optional geometric targets on every
MedVolume — keypoints (landmark points) and
bounding boxes — so that detection and landmark annotations stay in lockstep
with the image and mask when spatial transforms warp the pixel grid.
Coordinate convention¶
Both targets are stored in array-index order, matching the image axes:
3D volumes
(D, H, W)→ coordinates are(z, y, x).2D images
(H, W)→ coordinates are(y, x).
This is deliberately the same order used to index image/mask and to
address scipy.ndimage() displacement fields, so a spatial transform can
reuse the exact geometry it already computes for the pixels. (Note this is the
transpose of the (x, y) order some 2D libraries use; convert on the way in
and out if you follow that convention.)
keypoints:floatarray of shape(N, ndim).bboxes:floatarray of shape(M, 2 * ndim)laid out as[min_axis0, …, min_axis(ndim-1), max_axis0, …, max_axis(ndim-1)]— the low corner followed by the high corner, both in array-index order.
Every function here is a pure NumPy helper with no MedVolume dependency, so the
transforms can compose them freely. A spatial transform only needs to express
its pixel mapping as a point map — a callable taking an (K, ndim) array of
coordinates and returning the transformed (K, ndim) array — and this module
threads that map through both keypoints and (via their corners) bounding boxes.
- medaugmentx.core.geometry.map_keypoints(keypoints, point_map)[source]¶
Apply a coordinate
point_mapto a(N, ndim)keypoint array.- Return type:
ndarray
- medaugmentx.core.geometry.map_bboxes(bboxes, ndim, point_map)[source]¶
Map every box through
point_mapvia its corners, re-bounding to AABB.Each box is expanded to its
2**ndimcorners, the corners are pushed through the same point map used for keypoints, and the transformed box is the axis-aligned bounding box of the mapped corners. This keeps boxes correct under rotation and reflection, not only translation/scaling.- Return type:
ndarray
- medaugmentx.core.geometry.flip_map(flip_axes, shape)[source]¶
Point map reflecting coordinates along
flip_axesof a gridshape.- Return type:
PointMap
- medaugmentx.core.geometry.affine_map(forward, centre, translation_px)[source]¶
Point map for a forward affine warp about
centreplus a translation.forwardis the forward linear map (rotation @ scale); the image warp uses its inverse to pull pixels, so points move the opposite way — hence the forward matrix here.- Return type:
PointMap
- medaugmentx.core.geometry.translate_map(offset)[source]¶
Point map adding a constant
offset(e.g. crop origin or pad width).- Return type:
PointMap
- medaugmentx.core.geometry.scale_map(factors)[source]¶
Point map scaling each axis independently (e.g. resample zoom factors).
- Return type:
PointMap
- medaugmentx.core.geometry.displacement_map(displacements, mode='reflect')[source]¶
Point map for an elastic displacement field.
displacements[ax]is the per-axis fielddsuch that the image warp readsout[q] = in[q + d[q]]. A landmark at input locationpmust satisfyq + d(q) = pin the output. Fixed-point iteration solves that equation using linearly interpolated fields, with a residual tolerance of1e-5voxels and at most 100 iterations. RaisesValueErrorif the inverse cannot be solved, rather than returning a misaligned target.Convergence is expected for smooth fields with displacement gradients below one. This is not a guarantee of a globally invertible or fold-free warp.
- Return type:
PointMap