albumentations.augmentations.transforms3d.functional


Module containing functional implementations of 3D transformations. This module provides a collection of utility functions for manipulating and transforming 3D volumetric data (such as medical imaging data). The functions here implement the core algorithms for operations like padding, cropping, rotation, and other spatial manipulations specifically designed for 3D data.

create_affine_transformation_matrix_3dfunction

create_affine_transformation_matrix_3d(
    translate: AxisValues3D,
    scale: AxisValues3D,
    rotate: AxisValues3D,
    volume_shape: tuple[int, int, int]
)

Build a forward 4x4 affine matrix around a volume centre from sampled 3D parameters in Albucore's explicit `(x, y, z)` voxel-coordinate convention. The matrix follows Albucore's `(x, y, z)` coordinate order while `volume_shape` is `(depth, height, width)`. Positive rotations use the same screen-coordinate convention as `Affine`: the transform applies scale, then x-, y-, and z-axis rotations, then translation.

Parameters

NameTypeDefaultDescription
translateAxisValues3D--
scaleAxisValues3D--
rotateAxisValues3D--
volume_shapetuple[int, int, int]--

affine_3dfunction

affine_3d(
    volume: VolumeType | torch.Tensor,
    matrix: np.ndarray,
    output_shape: tuple[int, int, int],
    interpolation: int,
    border_mode: int,
    fill: float | tuple[float, ...] | None,
    is_mask: bool = False
)

Resample one volume with Albucore's true 3D affine router while preserving public channel and mask layouts, dtypes, borders, and interpolation policies. Albucore owns CPU Torch sampling and its matrix, interpolation, and border semantics. This adapter adds or removes the implicit channel required by channel-less masks and temporarily promotes non-native integer masks when needed.

Parameters

NameTypeDefaultDescription
volume
One of:
  • VolumeType
  • torch.Tensor
--
matrixnp.ndarray--
output_shapetuple[int, int, int]--
interpolationint--
border_modeint--
fill
One of:
  • float
  • tuple[float, ...]
  • None
--
is_maskboolFalse-

keypoints_affine_3dfunction

keypoints_affine_3d(
    keypoints: np.ndarray,
    matrix: np.ndarray
)

Map XYZ keypoints with the forward voxel-space affine matrix used for volume and mask, preserving additional attribute and the input coordinate-array dtype. The first three columns use Albucore's `(x, y, z)` order; homogeneous coordinates apply the same sampled matrix as the volume and mask routes, leaving angle, scale, labels, and any extra columns untouched.

Parameters

NameTypeDefaultDescription
keypointsnp.ndarray--
matrixnp.ndarray--

get_anisotropy_downsample_shapefunction

get_anisotropy_downsample_shape(
    spatial_shape: tuple[int, int, int],
    axes: tuple[int, ...],
    downscale_factor: float
)

Derive an anisotropic intermediate shape by scaling selected axes while retaining non-selected axes, ensuring every requested spatial dimension remains valid.

Parameters

NameTypeDefaultDescription
spatial_shapetuple[int, int, int]--
axestuple[int, ...]--
downscale_factorfloat--

anisotropy_3dfunction

anisotropy_3d(
    volume: VolumeType | torch.Tensor,
    downsample_shape: tuple[int, int, int],
    antialias: bool
)

Simulate thicker or lower-resolution volume acquisition by shrinking selected spatial axes and restoring the original shape for 3D robustness training. Both routes delegate to Albucore `resize3d`, which resizes only spatial axes and preserves the input representation. NumPy applies antialiasing while shrinking; PyTorch does not yet provide 5D trilinear antialiasing, so Tensor input uses the non-antialiased native route until upstream support is available.

Parameters

NameTypeDefaultDescription
volume
One of:
  • VolumeType
  • torch.Tensor
--
downsample_shapetuple[int, int, int]--
antialiasbool--

keypoints_scale_3dfunction

keypoints_scale_3d(
    keypoints: np.ndarray,
    source_shape: tuple[int, int, int],
    target_shape: tuple[int, int, int]
)

Scale XYZ keypoints across voxel grids while leaving every user-provided attribute after their three spatial coordinates unchanged. Coordinates use Albumentations' pixel-index convention: `x`, `y`, and `z` scale from the origin by the output-to-input ratio. All remaining columns preserve their input values.

Parameters

NameTypeDefaultDescription
keypointsnp.ndarray--
source_shapetuple[int, int, int]--
target_shapetuple[int, int, int]--

keypoints_flip_3dfunction

keypoints_flip_3d(
    keypoints: np.ndarray,
    flip_axes: tuple[Literal[0, 1, 2], ...],
    volume_shape: tuple[int, int, int]
)

Reflect XYZ keypoints across selected depth, height, and width voxel-index axes while preserving all extra columns and dtype.

Parameters

NameTypeDefaultDescription
keypointsnp.ndarray--
flip_axestuple[Literal[0, 1, 2], ...]--
volume_shapetuple[int, int, int]--

adjust_padding_by_position3dfunction

adjust_padding_by_position3d(
    paddings: list[tuple[int, int]],
    position: Literal['center', 'random'],
    py_random: random.Random
)

Adjust 3D padding by position. paddings [(d),(h),(w)]; position center or random. Returns (d_front, d_back, h_top, h_bottom, w_left, w_right). Args: paddings (list[tuple[int, int]]): List of tuples containing padding pairs for each dimension [(d_pad), (h_pad), (w_pad)] position (Literal['center', 'random']): Position of the image after padding. py_random (random.Random): Random number generator Returns: tuple[int, int, int, int, int, int]: Final padding values (d_front, d_back, h_top, h_bottom, w_left, w_right)

Parameters

NameTypeDefaultDescription
paddingslist[tuple[int, int]]--
position
One of:
  • 'center'
  • 'random'
--
py_randomrandom.Random--

pad_3d_with_paramsfunction

pad_3d_with_params(
    volume: VolumeType,
    padding: tuple[int, int, int, int, int, int],
    value: tuple[float, ...] | float
)

Pad 3D volume. padding (d_front, d_back, h_top, h_bottom, w_left, w_right); value: fill. (D,H,W) or (D,H,W,C). Used by Pad3D and PadIfNeeded3D. Args: volume (VolumeType): Input volume with shape (depth, height, width) or (depth, height, width, channels) padding (tuple[int, int, int, int, int, int]): Padding values in format: (depth_front, depth_back, height_top, height_bottom, width_left, width_right) where: - depth_front/back: padding at start/end of depth axis (z) - height_top/bottom: padding at start/end of height axis (y) - width_left/right: padding at start/end of width axis (x) value (tuple[float, ...] | float): Value to fill the padding Returns: VolumeType: Padded volume with same number of dimensions as input Note: The padding order matches the volume dimensions (depth, height, width). For each dimension, the first value is padding at the start (smaller indices), and the second value is padding at the end (larger indices).

Parameters

NameTypeDefaultDescription
volumeVolumeType--
paddingtuple[int, int, int, int, int, int]--
value
One of:
  • tuple[float, ...]
  • float
--

crop3dfunction

crop3d(
    volume: ImageType,
    crop_coords: tuple[int, int, int, int, int, int]
)

Crop 3D volume using coordinates. crop_coords: (z_min, z_max, y_min, y_max, x_min, x_max). Volume (D,H,W) or (D,H,W,C). Used by CenterCrop3D and RandomCrop3D. Args: volume (ImageType): Input volume with shape (z, y, x) or (z, y, x, channels) crop_coords (tuple[int, int, int, int, int, int]): (z_min, z_max, y_min, y_max, x_min, x_max) coordinates for cropping Returns: ImageType: Cropped volume with same number of dimensions as input

Parameters

NameTypeDefaultDescription
volumeImageType--
crop_coordstuple[int, int, int, int, int, int]--

cutout3dfunction

cutout3d(
    volume: ImageType,
    holes: np.ndarray,
    fill: tuple[float, ...] | float
)

Cut out holes in 3D volume and fill. holes (n, 6) [z1,y1,x1,z2,y2,x2]; fill scalar or per-channel. Used by CoarseDropout3D. Returns volume. Args: volume (ImageType): Input volume with shape (depth, height, width) or (depth, height, width, channels) holes (np.ndarray): Array of holes with shape (num_holes, 6). Each hole is represented as [z1, y1, x1, z2, y2, x2] fill (tuple[float, ...] | float): Value to fill the holes Returns: ImageType: Volume with holes filled with the given value

Parameters

NameTypeDefaultDescription
volumeImageType--
holesnp.ndarray--
fill
One of:
  • tuple[float, ...]
  • float
--

rotate90_3dfunction

rotate90_3d(
    volume: VolumeType,
    rot90_count: Literal[0, 1, 2, 3],
    axis_pair: tuple[int, int]
)

Rotate a 3D or channel-last 4D volume by 90-degree increments along a selected spatial axis pair, preserving dtype and channel order.

Parameters

NameTypeDefaultDescription
volumeVolumeType--
rot90_count
One of:
  • 0
  • 1
  • 2
  • 3
--
axis_pairtuple[int, int]--

keypoints_rotate90_3dfunction

keypoints_rotate90_3d(
    keypoints: np.ndarray,
    rot90_count: Literal[0, 1, 2, 3],
    axis_pair: tuple[int, int],
    volume_shape: tuple[int, int, int]
)

Rotate XYZ keypoints to match `rotate90_3d` on a volume, keeping their additional attributes and mapping the chosen axis pair exactly.

Parameters

NameTypeDefaultDescription
keypointsnp.ndarray--
rot90_count
One of:
  • 0
  • 1
  • 2
  • 3
--
axis_pairtuple[int, int]--
volume_shapetuple[int, int, int]--

transform_cubefunction

transform_cube(
    cube: np.ndarray,
    index: int
)

Reorient a cube with one of 48 exact cubic symmetries, using only axis permutations and reflections to move voxels without interpolation. Args: cube (np.ndarray): Input array with shape (D, H, W) or (D, H, W, C) index (int): Integer from 0 to 47 specifying which transformation to apply Returns: np.ndarray: Transformed cube with same shape as input

Parameters

NameTypeDefaultDescription
cubenp.ndarray--
indexint--

filter_keypoints_in_holes3dfunction

filter_keypoints_in_holes3d(
    keypoints: np.ndarray,
    holes: np.ndarray
)

Filter keypoints inside any 3D hole. keypoints (N,3+); holes (K,6). Returns keypoints not in holes. For CoarseDropout3D. Args: keypoints (np.ndarray): Array of keypoints with shape (num_keypoints, 3+). The first three columns are x, y, z coordinates. holes (np.ndarray): Array of holes with shape (num_holes, 6). Each hole is represented as [z1, y1, x1, z2, y2, x2]. Returns: np.ndarray: Array of keypoints that are not inside any hole.

Parameters

NameTypeDefaultDescription
keypointsnp.ndarray--
holesnp.ndarray--

keypoints_rot90function

keypoints_rot90(
    keypoints: np.ndarray,
    k: int,
    axes: tuple[int, int],
    volume_shape: tuple[int, int, int]
)

Rotate keypoints 90° k times around axes. k in [0,3]; volume_shape for bounds. Used by transform_cube_keypoints. Counterclockwise. Args: keypoints (np.ndarray): Array of keypoints with shape (num_keypoints, 3+). The first three columns are x, y, z coordinates. k (int): Number of times to rotate by 90 degrees. axes (tuple[int, int]): Axes to rotate around. volume_shape (tuple[int, int, int]): Shape of the volume (depth, height, width). Returns: np.ndarray: Rotated keypoints with same shape as input.

Parameters

NameTypeDefaultDescription
keypointsnp.ndarray--
kint--
axestuple[int, int]--
volume_shapetuple[int, int, int]--

transform_cube_keypointsfunction

transform_cube_keypoints(
    keypoints: np.ndarray,
    index: int,
    volume_shape: tuple[int, int, int]
)

Transform keypoints by cube index (0-47). volume_shape for bounds. Matches transform_cube geometry. For CubicSymmetry keypoints. Args: keypoints (np.ndarray): Array of keypoints with shape (num_keypoints, 3+). The first three columns are x, y, z coordinates. index (int): Integer from 0 to 47 specifying which transformation to apply. volume_shape (tuple[int, int, int]): Shape of the volume (depth, height, width). Returns: np.ndarray: Transformed keypoints with same shape as input.

Parameters

NameTypeDefaultDescription
keypointsnp.ndarray--
indexint--
volume_shapetuple[int, int, int]--

split_uniform_grid_3dfunction

split_uniform_grid_3d(
    volume_shape: tuple[int, int, int],
    grid: tuple[int, int, int],
    random_generator: np.random.Generator
)

Split 3D volume shape into uniform grid. grid (depth, rows, cols); random_generator. Returns tiles (n, 6). For tile swap. Args: volume_shape (tuple[int, int, int]): The shape of the volume as (depth, height, width). grid (tuple[int, int, int]): The grid size as (depth_slices, rows, columns). random_generator (np.random.Generator): The random generator to use for shuffling the splits. Returns: np.ndarray: An array containing the tiles' coordinates in the format (z_start, y_start, x_start, z_end, y_end, x_end).

Parameters

NameTypeDefaultDescription
volume_shapetuple[int, int, int]--
gridtuple[int, int, int]--
random_generatornp.random.Generator--

create_shape_groups_3dfunction

create_shape_groups_3d(
    tiles: np.ndarray
)

Group 3D tiles by shape (depth, height, width); return dict shape -> list of indices. For shuffle_tiles_within_shape_groups_3d and swap_tiles_on_volume.

Parameters

NameTypeDefaultDescription
tilesnp.ndarray--

shuffle_tiles_within_shape_groups_3dfunction

shuffle_tiles_within_shape_groups_3d(
    shape_groups: dict[tuple[int, int, int], list[int]],
    random_generator: np.random.Generator
)

Shuffles indices within each group of similar shapes and creates a list where each index points to the index of the tile it should be mapped to. Args: shape_groups (dict[tuple[int, int, int], list[int]]): Dictionary mapping shapes to list of tile indices with that shape. random_generator (np.random.Generator): Random number generator for shuffling Returns: list[int]: List where index i contains the new position for tile i.

Parameters

NameTypeDefaultDescription
shape_groupsdict[tuple[int, int, int], list[int]]--
random_generatornp.random.Generator--

swap_tiles_on_volumefunction

swap_tiles_on_volume(
    volume: ImageType,
    tiles: np.ndarray,
    mapping: list[int]
)

Swap tiles on 3D volume by mapping. tiles (n, 6); mapping[i] = source for position i. Variable tile sizes; loop-based. For CubicSymmetry-style shuffle. Args: volume (ImageType): Input volume with shape (D, H, W) or (D, H, W, C). tiles (np.ndarray): Array of tiles with each tile as [z_start, y_start, x_start, z_end, y_end, x_end]. mapping (list[int]): List of new tile indices. Must have the same length as tiles. Returns: ImageType: Output volume with tiles swapped according to the random shuffle. Note: This implementation uses a loop rather than vectorized operations because tiles may have variable sizes in the general case (e.g., when the volume dimensions aren't evenly divisible by the grid size). Advanced indexing with variable-sized slices isn't possible in NumPy, making this loop-based approach the most efficient solution.

Parameters

NameTypeDefaultDescription
volumeImageType--
tilesnp.ndarray--
mappinglist[int]--

swap_tiles_on_keypoints_3dfunction

swap_tiles_on_keypoints_3d(
    keypoints: np.ndarray,
    tiles: np.ndarray,
    mapping: list[int]
)

Swap 3D keypoint positions by tile mapping. keypoints (N,3+); tiles (M,6); mapping (M,). Each keypoint moves with its tile. For CubicSymmetry. Args: keypoints (np.ndarray): A 2D numpy array of shape (N, 3+) where N is the number of keypoints. Each row represents a keypoint's (x, y, z) coordinates plus other data. tiles (np.ndarray): A 2D numpy array of shape (M, 6) where M is the number of tiles. Each row represents a tile's (z_start, y_start, x_start, z_end, y_end, x_end). mapping (list[int]): A list where each element i contains the index of the tile that tile i should be swapped with. Returns: np.ndarray: A 2D numpy array of the same shape as the input keypoints, containing the new positions of the keypoints after the tile swap.

Parameters

NameTypeDefaultDescription
keypointsnp.ndarray--
tilesnp.ndarray--
mappinglist[int]--