3D transforms#

Operators for volumetric (B, C, D, H, W) tensors, e.g. medical volumes or video treated as 3D data.

Geometric#

class kornia.augmentation.CenterCrop3D(size, align_corners=True, resample=Resample.BILINEAR.name, p=1.0, keepdim=False)[source]#

Apply center crop on 3D volumes (5D torch.Tensor).

Parameters:
  • p (float, optional) – probability of applying the transformation for the whole batch. Default: 1.0

  • size (Tuple[int, int, int] or int) – Desired output size (out_d, out_h, out_w) of the crop. If integer, out_d = out_h = out_w = size. If Tuple[int, int, int], out_d = size[0], out_h = size[1], out_w = size[2].

  • resample (Union[str, int, Resample], optional) – resample mode from “nearest” (0) or “bilinear” (1). Default: Resample.BILINEAR.name

  • align_corners (bool, optional) – interpolation flag. Default: True

  • keepdim (bool, optional) – whether to keep the output shape the same as input (True) or broadcast it to the batch form (False). Default: False

Shape:
  • Input: \((C, D, H, W)\) or \((B, C, D, H, W)\)

  • Output: \((B, C, out_d, out_h, out_w)\)

Note

Input torch.Tensor must be float and normalized into [0, 1] for the best differentiability support.

Convention:

See GeometricAugmentationBase3D for the shared 3D geometry contract.

  • size is (D, H, W). The crop is shared across the batch; its p is the call-wide gate, so a valid p=0 request returns the un-cropped input and p=1 returns the requested crop. Size validation still runs when the call is skipped, so an oversized crop raises ValueError even at p=0, naming size and the input spatial size. A tuple with other than three elements, or with a Python or NumPy float element, raises TypeError naming the supplied value; NumPy integers and 0-d integer tensors are accepted. An integer size is supported here but not by RandomCrop3D (#4417).

  • defaults are bilinear resampling and align_corners=True.

Examples

>>> import torch
>>> rng = torch.manual_seed(0)
>>> inputs = torch.randn(1, 1, 2, 4, 6)
>>> inputs
tensor([[[[[-1.1258, -1.1524, -0.2506, -0.4339,  0.8487,  0.6920],
           [-0.3160, -2.1152,  0.3223, -1.2633,  0.3500,  0.3081],
           [ 0.1198,  1.2377,  1.1168, -0.2473, -1.3527, -1.6959],
           [ 0.5667,  0.7935,  0.5988, -1.5551, -0.3414,  1.8530]],

          [[ 0.7502, -0.5855, -0.1734,  0.1835,  1.3894,  1.5863],
           [ 0.9463, -0.8437, -0.6136,  0.0316, -0.4927,  0.2484],
           [ 0.4397,  0.1124,  0.6408,  0.4412, -0.1023,  0.7924],
           [-0.2897,  0.0525,  0.5229,  2.3022, -1.4689, -1.5867]]]]])
>>> aug = CenterCrop3D(2, p=1.)
>>> aug(inputs)
tensor([[[[[ 0.3223, -1.2633],
           [ 1.1168, -0.2473]],

          [[-0.6136,  0.0316],
           [ 0.6408,  0.4412]]]]])
To apply the exact augmenation again, you may take the advantage of the previous parameter state:
>>> input = torch.rand(1, 3, 32, 32, 32)
>>> aug = CenterCrop3D(24, p=1.)
>>> (aug(input) == aug(input, params=aug._params)).all()
tensor(True)
class kornia.augmentation.RandomAffine3D(degrees, translate=None, scale=None, shears=None, resample=Resample.BILINEAR.name, same_on_batch=False, align_corners=False, p=0.5, keepdim=False)[source]#

Apply affine transformation 3D volumes (5D torch.Tensor).

The transformation is computed so that the center is kept invariant.

Parameters:
  • degrees (Union[Tensor, float, Tuple[float, float], Tuple[float, float, float], Tuple[Tuple[float, float], Tuple[float, float], Tuple[float, float]]]) – Range of yaw (x-axis), pitch (y-axis), roll (z-axis) to select from. The three are sampled independently and concatenated into one axis-angle vector, not composed as per-axis Euler rotations; see RandomRotation3D for the convention. If degrees is a number, then yaw, pitch, roll will be generated from the range of (-degrees, +degrees). If degrees is a tuple of (min, max), then yaw, pitch, roll will be generated from the range of (min, max). If degrees is a list of floats [a, b, c], then yaw, pitch, roll will be generated from (-a, a), (-b, b) and (-c, c). If degrees is a list of tuple ((a, b), (m, n), (x, y)), then yaw, pitch, roll will be generated from (a, b), (m, n) and (x, y). Set to 0 to deactivate rotations.

  • translate (Union[Tensor, Tuple[float, float, float], None], optional) – tuple of maximum absolute fraction for horizontal, vertical and depthical translations (dx,dy,dz). For example translate=(a, b, c), then horizontal shift will be randomly sampled in the range -img_width * a < dx < img_width * a vertical shift will be randomly sampled in the range -img_height * b < dy < img_height * b. depthical shift will be randomly sampled in the range -img_depth * c < dz < img_depth * c. Will not translate by default. Default: None

  • scale (Union[Tensor, Tuple[float, float], Tuple[Tuple[float, float], Tuple[float, float], Tuple[float, float]], None], optional) – scaling factor interval. If (a, b) represents isotropic scaling, the scale is randomly sampled from the range a <= scale <= b. If ((a, b), (c, d), (e, f)), the scale is randomly sampled from the range a <= scale_x <= b, c <= scale_y <= d, e <= scale_z <= f. Will keep original scale by default. Default: None

  • shears (Union[Tensor, float, Tuple[float, float], Tuple[float, float, float, float, float, float], Tuple[Tuple[float, float], Tuple[float, float], Tuple[float, float], Tuple[float, float], Tuple[float, float], Tuple[float, float]], None], optional) – Range of degrees to select from. If shear is a number, a shear to the 6 facets in the range (-shear, +shear) will be applied. If shear is a tuple of 2 values, a shear to the 6 facets in the range (shear[0], shear[1]) will be applied. If shear is a tuple of 6 values, a shear to the i-th facet in the range (-shear[i], shear[i]) will be applied. If shear is a tuple of 6 tuples, a shear to the i-th facet in the range (shear[i, 0], shear[i, 1]) will be applied. Default: None

  • resample (Union[str, int, Resample], optional) – resample mode from “nearest” (0) or “bilinear” (1). Default: Resample.BILINEAR.name

  • same_on_batch (bool, optional) – apply the same transformation across the batch. Default: False

  • align_corners (bool, optional) – interpolation flag. Default: False

  • keepdim (bool, optional) – whether to keep the output shape the same as input (True) or broadcast it to the batch form (False). Default: False.

Shape:
  • Input: \((C, D, H, W)\) or \((B, C, D, H, W)\)

  • Output: \((B, C, D, H, W)\)

Note

Input torch.Tensor must be float and normalized into [0, 1] for the best differentiability support.

Convention:

See GeometricAugmentationBase3D for the shared 3D geometry contract.

  • each sampled degrees triple (yaw, pitch, roll) = (rx, ry, rz) is one axis-angle vector in degrees and is converted into a single Rodrigues rotation, not composed as per-axis Euler rotations; see RandomRotation3D for the convention.

  • A positive roll turns a displayed H x W slice counter-clockwise, and the rotation block is the transpose of RandomRotation3D’s (#4408).

  • the default is bilinear resampling with align_corners=False.

  • a two-value scale=(a, b) is isotropic: one factor per sample is drawn from [a, b] and applied to all three axes, as the 2D RandomAffine does. The three-pair form ((a, b), (c, d), (e, f)) draws each axis independently.

Examples

>>> import torch
>>> rng = torch.manual_seed(0)
>>> input = torch.rand(1, 1, 3, 3, 3)
>>> aug = RandomAffine3D((15., 20., 20.), p=1.)
>>> aug(input), aug.transform_matrix
(tensor([[[[[0.4503, 0.4763, 0.1680],
           [0.2029, 0.4267, 0.3515],
           [0.3195, 0.5436, 0.3706]],

          [[0.5255, 0.3508, 0.4858],
           [0.0795, 0.1689, 0.4220],
           [0.5306, 0.7234, 0.6879]],

          [[0.2971, 0.2746, 0.3471],
           [0.4924, 0.4960, 0.6460],
           [0.3187, 0.4556, 0.7596]]]]]), tensor([[[ 0.9722, -0.0603,  0.2262, -0.1381],
         [ 0.1131,  0.9669, -0.2286,  0.1486],
         [-0.2049,  0.2478,  0.9469,  0.0102],
         [ 0.0000,  0.0000,  0.0000,  1.0000]]]))
To apply the exact augmenation again, you may take the advantage of the previous parameter state:
>>> input = torch.rand(1, 3, 32, 32, 32)
>>> aug = RandomAffine3D((15., 20., 20.), p=1.)
>>> (aug(input) == aug(input, params=aug._params)).all()
tensor(True)
class kornia.augmentation.RandomCrop3D(size, padding=None, pad_if_needed=False, fill=0, padding_mode='constant', resample=Resample.BILINEAR.name, same_on_batch=False, align_corners=True, p=1.0, keepdim=False)[source]#

Apply random crop on 3D volumes (5D torch.Tensor).

Crops random sub-volumes on a given size.

Parameters:
  • p (float, optional) – probability of applying the transformation for the whole batch. When skipped, the input is returned without padding or cropping. Default: 1.0

  • size (Union[Tuple[int, int, int], List[int]]) – Desired output size (out_d, out_h, out_w) of the crop. Must be a three-element tuple or list of integers, then out_d = size[0], out_h = size[1], out_w = size[2].

  • padding (Union[int, Tuple[int, int, int], Tuple[int, int, int, int, int, int], None], optional) – Optional padding on each border of the image. Default is None, i.e no padding. If a sequence of length 6 is provided, it is passed to F.pad as left, right, top, bottom, front, back borders respectively. If a sequence of length 3 is provided, it is used to F.pad left/right, top/bottom, front/back borders, respectively. Default: None

  • pad_if_needed (Optional[bool], optional) – It will F.pad the image if smaller than the desired size to avoid raising an exception. Since cropping is done after padding, the padding seems to be done at a random offset. Default: False

  • fill (Union[float, Sequence[float]], optional) – Voxel fill value for constant fill. Default is 0. A sequence gives one value per channel, so it must be as long as the input’s channel dimension. This value is only used when the padding_mode is constant, and a sequence requires it. Default: 0

  • padding_mode (str, optional) – Type of padding, passed to F.pad. Should be: constant, reflect, replicate or circular. Default is constant. Default: "constant"

  • resample (Union[str, int, Resample], optional) – resample mode from “nearest” (0) or “bilinear” (1). Default: Resample.BILINEAR.name

  • same_on_batch (bool, optional) – apply the same transformation across the batch. Default: False

  • align_corners (bool, optional) – interpolation flag. Default: True

  • keepdim (bool, optional) – whether to keep the output shape the same as input (True) or broadcast it to the batch form (False). Default: False

Shape:
  • Input: \((C, D, H, W)\) or \((B, C, D, H, W)\)

  • Output: \((B, C, out_d, out_h, out_w)\)

Note

Input torch.Tensor must be float and normalized into [0, 1] for the best differentiability support.

Convention:

See GeometricAugmentationBase3D for the shared 3D geometry contract.

  • size and the output shape are ordered (D, H, W). A scalar padding expands to every side; three values expand as (left/right, top/bottom, front/back), and six are passed to torch.nn.functional.pad() as (left, right, top, bottom, front, back) before the crop is drawn.

  • transform_matrix maps original input (x, y, z) coordinates to the crop, including the left, top, and front translation from explicit padding and pad_if_needed.

  • its p is a call-wide gate. Size validation uses the padded input even when the call is skipped: a crop larger than the padded volume along any axis, even by one voxel, raises; a crop equal to it is valid. An oversized crop raises ValueError naming size and the padded input spatial size. Unsupported size types, sequences with other than three elements, or Python or NumPy float elements raise TypeError naming size and the required integer (D, H, W) values (NumPy integers and 0-d integer tensors are accepted); unlike CenterCrop3D, an integer size remains unsupported (#4417). A valid gated-off call returns the input unchanged – unpadded, at the input shape rather than size – with an identity transform_matrix. Defaults are bilinear resampling and align_corners=True.

Examples

>>> import torch
>>> rng = torch.manual_seed(0)
>>> inputs = torch.randn(1, 1, 3, 3, 3)
>>> aug = RandomCrop3D((2, 2, 2), p=1.)
>>> aug(inputs)
tensor([[[[[-1.1258, -1.1524],
           [-0.4339,  0.8487]],

          [[-1.2633,  0.3500],
           [ 0.1665,  0.8744]]]]])
To apply the exact augmenation again, you may take the advantage of the previous parameter state:
>>> input = torch.rand(1, 3, 32, 32, 32)
>>> aug = RandomCrop3D((24, 24, 24), p=1.)
>>> (aug(input) == aug(input, params=aug._params)).all()
tensor(True)
class kornia.augmentation.RandomDepthicalFlip3D(same_on_batch=False, p=0.5, keepdim=False)[source]#

Apply random flip along the depth axis of 3D volumes (5D tensor).

Input should be a tensor of shape \((C, D, H, W)\) or a batch of tensors \((*, C, D, H, W)\).

Parameters:
  • p (float, optional) – probability of the image being flipped. Default: 0.5

  • same_on_batch (bool, optional) – apply the same transformation across the batch. Default: False

  • keepdim (bool, optional) – whether to keep the output shape the same as input True or broadcast it to the batch form False. Default: False

Shape:
  • Input: \((C, D, H, W)\) or \((B, C, D, H, W)\)

  • Output: \((B, C, D, H, W)\)

Note

Input tensor must be float and normalized into [0, 1] for the best differentiability support.

Convention:

See GeometricAugmentationBase3D for the shared 3D geometry contract.

  • flips the depth D axis (tensor axis -3, coordinate z). Its matrix maps z to D - 1 - z in inclusive voxel coordinates, rounded where the dtype cannot represent it (see the base).

Examples

>>> import torch
>>> x = torch.eye(3).repeat(3, 1, 1)
>>> seq = RandomDepthicalFlip3D(p=1.0)
>>> seq(x), seq.transform_matrix
(tensor([[[[[1., 0., 0.],
           [0., 1., 0.],
           [0., 0., 1.]],

          [[1., 0., 0.],
           [0., 1., 0.],
           [0., 0., 1.]],

          [[1., 0., 0.],
           [0., 1., 0.],
           [0., 0., 1.]]]]]), tensor([[[ 1.,  0.,  0.,  0.],
         [ 0.,  1.,  0.,  0.],
         [ 0.,  0., -1.,  2.],
         [ 0.,  0.,  0.,  1.]]]))
To apply the exact augmenation again, you may take the advantage of the previous parameter state:
>>> input = torch.rand(1, 3, 32, 32, 32)
>>> aug = RandomDepthicalFlip3D(p=1.)
>>> (aug(input) == aug(input, params=aug._params)).all()
tensor(True)
class kornia.augmentation.RandomHorizontalFlip3D(same_on_batch=False, p=0.5, keepdim=False)[source]#

Apply random horizontal flip to 3D volumes (5D tensor).

Parameters:
  • p (float, optional) – probability of the image being flipped. Default: 0.5

  • same_on_batch (bool, optional) – apply the same transformation across the batch. Default: False

  • keepdim (bool, optional) – whether to keep the output shape the same as input True or broadcast it to the batch form False. Default: False

Shape:
  • Input: \((C, D, H, W)\) or \((B, C, D, H, W)\)

  • Output: \((B, C, D, H, W)\)

Note

Input tensor must be float and normalized into [0, 1] for the best differentiability support.

Convention:

See GeometricAugmentationBase3D for the shared 3D geometry contract.

  • flips the width W axis (tensor axis -1, coordinate x). Its matrix maps x to W - 1 - x in inclusive voxel coordinates, rounded where the dtype cannot represent it (see the base).

Examples

>>> import torch
>>> x = torch.eye(3).repeat(3, 1, 1)
>>> seq = RandomHorizontalFlip3D(p=1.0)
>>> seq(x), seq.transform_matrix
(tensor([[[[[0., 0., 1.],
           [0., 1., 0.],
           [1., 0., 0.]],

          [[0., 0., 1.],
           [0., 1., 0.],
           [1., 0., 0.]],

          [[0., 0., 1.],
           [0., 1., 0.],
           [1., 0., 0.]]]]]), tensor([[[-1.,  0.,  0.,  2.],
         [ 0.,  1.,  0.,  0.],
         [ 0.,  0.,  1.,  0.],
         [ 0.,  0.,  0.,  1.]]]))
To apply the exact augmenation again, you may take the advantage of the previous parameter state:
>>> input = torch.rand(1, 3, 32, 32, 32)
>>> aug = RandomHorizontalFlip3D(p=1.)
>>> (aug(input) == aug(input, params=aug._params)).all()
tensor(True)
class kornia.augmentation.RandomPerspective3D(distortion_scale=0.5, resample=Resample.BILINEAR.name, same_on_batch=False, align_corners=False, p=0.5, keepdim=False)[source]#

Apply random perspective transformation to 3D volumes (5D torch.Tensor).

Parameters:
  • p (float, optional) – probability of the image being perspectively transformed. Default: 0.5

  • distortion_scale (Union[Tensor, float], optional) – it controls the degree of distortion and ranges from 0 to 1. Default: 0.5

  • resample (Union[str, int, Resample], optional) – resample mode from “nearest” (0) or “bilinear” (1). Default: Resample.BILINEAR.name

  • same_on_batch (bool, optional) – apply the same transformation across the batch. Default: False

  • align_corners (bool, optional) – interpolation flag. Default: False

  • keepdim (bool, optional) – whether to keep the output shape the same as input (True) or broadcast it to the batch form (False). Default: False

Shape:
  • Input: \((C, D, H, W)\) or \((B, C, D, H, W)\)

  • Output: \((B, C, D, H, W)\)

Note

Input torch.Tensor must be float and normalized into [0, 1] for the best differentiability support.

Convention:

See GeometricAugmentationBase3D for the shared 3D geometry contract.

  • distortion_scale=0 generates identical source and destination corners. The default bilinear, align_corners=False perspective warp nevertheless does not reproduce its input, even a constant one; use align_corners=True for an identity warp up to floating-point roundoff in float32 and float64. The false-setting normalization defect is tracked in #4503.

  • the default interpolation is bilinear and the default align_corners is False.

  • a spatial dimension of 1 gets a unit source extent and no corner offset, so its single slice, row or column maps onto itself. At distortion_scale=0 the transform matrix is the identity; output identity still requires align_corners=True as described above.

Examples

>>> import torch
>>> rng = torch.manual_seed(0)
>>> inputs= torch.tensor([[[
...    [[1., 0., 0.],
...     [0., 1., 0.],
...     [0., 0., 1.]],
...    [[1., 0., 0.],
...     [0., 1., 0.],
...     [0., 0., 1.]],
...    [[1., 0., 0.],
...     [0., 1., 0.],
...     [0., 0., 1.]]
... ]]])
>>> aug = RandomPerspective3D(0.5, p=1., align_corners=True)
>>> aug(inputs)
tensor([[[[[0.3976, 0.2651, 0.0000],
           [0.5507, 0.4657, 0.1153],
           [0.0000, 0.0000, 0.0000]],

          [[0.0901, 0.1390, 0.0000],
           [0.3668, 0.5174, 0.0000],
           [0.0000, 0.0000, 0.0000]],

          [[0.0000, 0.0000, 0.0000],
           [0.0000, 0.0000, 0.0000],
           [0.0000, 0.0000, 0.0000]]]]])
To apply the exact augmenation again, you may take the advantage of the previous parameter state:
>>> input = torch.rand(1, 3, 32, 32, 32)
>>> aug = RandomPerspective3D(0.5, p=1.)
>>> (aug(input) == aug(input, params=aug._params)).all()
tensor(True)
class kornia.augmentation.RandomRotation3D(degrees, resample=Resample.BILINEAR.name, same_on_batch=False, align_corners=False, p=0.5, keepdim=False)[source]#

Apply random rotations to 3D volumes (5D torch.Tensor).

Input should be a torch.Tensor of shape (C, D, H, W) or a batch of tensors \((B, C, D, H, W)\).

Parameters:
  • degrees (Union[Tensor, float, Tuple[float, float, float], Tuple[Tuple[float, float], Tuple[float, float], Tuple[float, float]]]) – Range of degrees to select from. If degrees is a number, then yaw, pitch, roll will be generated from the range of (-degrees, +degrees). If degrees is a tuple of (min, max), then yaw, pitch, roll will be generated from the range of (min, max). If degrees is a list of floats [a, b, c], then yaw, pitch, roll will be generated from (-a, a), (-b, b) and (-c, c). If degrees is a list of tuple ((a, b), (m, n), (x, y)), then yaw, pitch, roll will be generated from (a, b), (m, n) and (x, y). Set to 0 to deactivate rotations.

  • resample (Union[str, int, Resample], optional) – resample mode from “nearest” (0) or “bilinear” (1). Default: Resample.BILINEAR.name

  • same_on_batch (bool, optional) – apply the same transformation across the batch. Default: False

  • align_corners (bool, optional) – interpolation flag. Default: False

  • keepdim (bool, optional) – whether to keep the output shape the same as input (True) or broadcast it to the batch form (False). Default: False

Shape:
  • Input: \((C, D, H, W)\) or \((B, C, D, H, W)\)

  • Output: \((B, C, D, H, W)\)

Note

Input torch.Tensor must be float and normalized into [0, 1] for the best differentiability support.

Convention:

See GeometricAugmentationBase3D for the shared 3D geometry contract.

  • each sampled degrees triple (yaw, pitch, roll) = (rx, ry, rz) is one axis-angle vector in degrees and is converted into a single Rodrigues rotation, not composed as per-axis Euler rotations, exactly as kornia.geometry.transform.rotate3d() does. The rotation axis is (rx, ry, rz) / ||(rx, ry, rz)|| and the angle is ||(rx, ry, rz)|| degrees, so a sampled (90, 90, 0) turns through 90 * sqrt(2) degrees about (1, 1, 0) / sqrt(2) while a sampled (30, 0, 0) is a 30-degree turn about x. One non-zero component is therefore the per-axis rotation it names; two or more are not, and neither Euler order reproduces the axis-angle result. To rotate about the axes in turn, compose the rotation matrix yourself and convert it with rotation_matrix_to_axis_angle(), which returns radians.

  • A positive roll turns a displayed H x W slice clockwise, as kornia.geometry.transform.rotate3d() does; RandomAffine3D, the 2D RandomRotation and kornia.geometry.transform.rotate() turn it counter-clockwise (#4408).

  • the default interpolation is bilinear with align_corners=False.

Examples

>>> import torch
>>> rng = torch.manual_seed(0)
>>> input = torch.rand(1, 1, 3, 3, 3)
>>> aug = RandomRotation3D((15., 20., 20.), p=1.0)
>>> aug(input), aug.transform_matrix
(tensor([[[[[0.3819, 0.4886, 0.2111],
           [0.1196, 0.3833, 0.4722],
           [0.3432, 0.5951, 0.4223]],

          [[0.5553, 0.4374, 0.2780],
           [0.2423, 0.1689, 0.4009],
           [0.4516, 0.6376, 0.7327]],

          [[0.1605, 0.3112, 0.3673],
           [0.4931, 0.4620, 0.5700],
           [0.3505, 0.4685, 0.8092]]]]]), tensor([[[ 0.9722,  0.1131, -0.2049,  0.1196],
         [-0.0603,  0.9669,  0.2478, -0.1545],
         [ 0.2262, -0.2286,  0.9469,  0.0556],
         [ 0.0000,  0.0000,  0.0000,  1.0000]]]))
To apply the exact augmenation again, you may take the advantage of the previous parameter state:
>>> input = torch.rand(1, 3, 32, 32, 32)
>>> aug = RandomRotation3D((15., 20., 20.), p=1.)
>>> (aug(input) == aug(input, params=aug._params)).all()
tensor(True)
class kornia.augmentation.RandomVerticalFlip3D(same_on_batch=False, p=0.5, keepdim=False)[source]#

Apply random vertical flip to 3D volumes (5D tensor).

Input should be a tensor of shape \((C, D, H, W)\) or a batch of tensors \((*, C, D, H, W)\).

Parameters:
  • p (float, optional) – probability of the image being flipped. Default: 0.5

  • same_on_batch (bool, optional) – apply the same transformation across the batch. Default: False

  • keepdim (bool, optional) – whether to keep the output shape the same as input True or broadcast it to the batch form False. Default: False

Shape:
  • Input: \((C, D, H, W)\) or \((B, C, D, H, W)\)

  • Output: \((B, C, D, H, W)\)

Note

Input tensor must be float and normalized into [0, 1] for the best differentiability support.

Convention:

See GeometricAugmentationBase3D for the shared 3D geometry contract.

  • flips the height H axis (tensor axis -2, coordinate y). Its matrix maps y to H - 1 - y in inclusive voxel coordinates, rounded where the dtype cannot represent it (see the base).

Examples

>>> import torch
>>> x = torch.eye(3).repeat(3, 1, 1)
>>> seq = RandomVerticalFlip3D(p=1.0)
>>> seq(x), seq.transform_matrix
(tensor([[[[[0., 0., 1.],
           [0., 1., 0.],
           [1., 0., 0.]],

          [[0., 0., 1.],
           [0., 1., 0.],
           [1., 0., 0.]],

          [[0., 0., 1.],
           [0., 1., 0.],
           [1., 0., 0.]]]]]), tensor([[[ 1.,  0.,  0.,  0.],
         [ 0., -1.,  0.,  2.],
         [ 0.,  0.,  1.,  0.],
         [ 0.,  0.,  0.,  1.]]]))
To apply the exact augmenation again, you may take the advantage of the previous parameter state:
>>> input = torch.rand(1, 3, 32, 32, 32)
>>> aug = RandomVerticalFlip3D(p=1.)
>>> (aug(input) == aug(input, params=aug._params)).all()
tensor(True)

Intensity#

class kornia.augmentation.RandomEqualize3D(p=0.5, same_on_batch=False, keepdim=False)[source]#

Apply random equalization to 3D volumes (5D tensor).

Parameters:
  • p (float, optional) – probability of the image being equalized. Default: 0.5

  • same_on_batch (bool, optional) – apply the same transformation across the batch. Default: False

  • keepdim (bool, optional) – whether to keep the output shape the same as input (True) or broadcast it to the batch form (False). Default: False

Shape:
  • Input: \((C, D, H, W)\) or \((B, C, D, H, W)\)

  • Output: \((B, C, D, H, W)\)

Note

Input tensor must be float and normalized into [0, 1].

Convention:

See IntensityAugmentationBase3D for the shared 3D intensity contract.

  • values the 256-bin lookup cannot index (outside roughly [0, 1]) raise a RuntimeError naming the range. Each channel’s whole volume supplies one 256-bin histogram (kornia.enhance.equalize3d()), so a volume with at most 255 voxels per channel is returned unchanged up to roundoff.

Examples

>>> import torch
>>> rng = torch.manual_seed(0)
>>> input = torch.rand(1, 1, 3, 3, 3)
>>> aug = RandomEqualize3D(p=1.0)
>>> aug(input)
tensor([[[[[0.4963, 0.7682, 0.0885],
           [0.1320, 0.3074, 0.6341],
           [0.4901, 0.8964, 0.4556]],

          [[0.6323, 0.3489, 0.4017],
           [0.0223, 0.1689, 0.2939],
           [0.5185, 0.6977, 0.8000]],

          [[0.1610, 0.2823, 0.6816],
           [0.9152, 0.3971, 0.8742],
           [0.4194, 0.5529, 0.9527]]]]])
To apply the exact augmenation again, you may take the advantage of the previous parameter state:
>>> input = torch.rand(1, 3, 32, 32, 32)
>>> aug = RandomEqualize3D(p=1.)
>>> (aug(input) == aug(input, params=aug._params)).all()
tensor(True)
class kornia.augmentation.RandomMotionBlur3D(kernel_size, angle, direction, border_type=BorderType.CONSTANT.name, resample=Resample.NEAREST.name, same_on_batch=False, p=0.5, keepdim=False)[source]#

Apply random motion blur on 3D volumes (5D torch.Tensor).

Parameters:
  • p (float, optional) – probability of applying the transformation. Default: 0.5

  • kernel_size (Union[int, Tuple[int, int]]) – motion kernel size (odd and at least 3). If int, the kernel will have a fixed size. If Tuple[int, int], it will randomly generate the value from the range batch-wisely.

  • angle (Union[Tensor, float, Tuple[float, float, float], Tuple[Tuple[float, float], Tuple[float, float], Tuple[float, float]]]) – Range of degrees to select from. If angle is a number, then yaw, pitch, roll will be generated from the range of (-angle, +angle). If angle is a tuple of (min, max), then yaw, pitch, roll will be generated from the range of (min, max). If angle is a list of floats [a, b, c], then yaw, pitch, roll will be generated from (-a, a), (-b, b) and (-c, c). If angle is a list of tuple ((a, b), (m, n), (x, y)), then yaw, pitch, roll will be generated from (a, b), (m, n) and (x, y). Set to 0 to deactivate rotations.

  • direction (Union[Tensor, float, Tuple[float, float]]) – forward/backward direction of the motion blur. Lower values towards -1.0 will point the motion blur towards the back (with angle provided via angle), while higher values towards 1.0 will point the motion blur forward. A value of 0.0 leads to a uniformly (but still angled) motion blur. If float, it will generate the value from (-direction, direction). If Tuple[int, int], it will randomly generate the value from the range.

  • border_type (Union[int, str, BorderType], optional) – the padding mode to be applied before convolving. CONSTANT = 0, REFLECT = 1, REPLICATE = 2, CIRCULAR = 3. Default: BorderType.CONSTANT.

  • resample (Union[str, int, Resample], optional) – resample mode from “nearest” (0) or “bilinear” (1). Default: Resample.NEAREST.name

  • keepdim (bool, optional) – whether to keep the output shape the same as input (True) or broadcast it to the batch form (False). Default: False

Shape:
  • Input: \((C, D, H, W)\) or \((B, C, D, H, W)\)

  • Output: \((B, C, D, H, W)\)

Note

Input torch.Tensor must be float and normalized into [0, 1] for the best differentiability support.

Convention:

See IntensityAugmentationBase3D for the shared 3D intensity contract.

  • each sampled angle triple (yaw, pitch, roll) = (rx, ry, rz) is one axis-angle vector in degrees and is converted into a single Rodrigues rotation, not composed as per-axis Euler rotations; see RandomRotation3D for the convention.

  • A positive roll turns the blur kernel clockwise as displayed, as RandomRotation3D does and opposite to the 2D RandomMotionBlur (#4408). Its default resampling is nearest-neighbour, unlike the geometric 3D defaults.

  • an integer kernel_size is one odd scalar applied to all three spatial axes. A tuple kernel_size is drawn once per call and shared across the batch, and each odd size inside the range is equally likely, bounds included, so (3, 5) draws 3 and 5 and (3, 20) draws 3, 5, ..., 19. A range holding no odd size is rounded up out of the requested range instead, so (4, 4) draws 5; a reversed pair such as (20, 3) raises a ValueError at construction.

  • a volume smaller than the kernel is accepted, down to 1 x 1 x 1, at the default border_type="constant" and at "replicate". "reflect" needs each of depth, height and width longer than the kernel radius, and "circular" at least that long; below that both raise a ValueError naming the class, the drawn kernel, the axis and the input shape, as RandomMotionBlur does for an image.

  • this class fixes p_batch=1; its p remains the per-sample gate.

Examples

>>> import torch
>>> rng = torch.manual_seed(0)
>>> input = torch.rand(1, 1, 3, 5, 5)
>>> motion_blur = RandomMotionBlur3D(3, 35., 0.5, p=1.)
>>> motion_blur(input)
tensor([[[[[0.1654, 0.4772, 0.2004, 0.3566, 0.2613],
           [0.4557, 0.3131, 0.4809, 0.2574, 0.2696],
           [0.2721, 0.5998, 0.3956, 0.5363, 0.1541],
           [0.3006, 0.4773, 0.6395, 0.2856, 0.3989],
           [0.4491, 0.5595, 0.1836, 0.3811, 0.1398]],

          [[0.1843, 0.4240, 0.3370, 0.1231, 0.2186],
           [0.4047, 0.3332, 0.1901, 0.5329, 0.3023],
           [0.3070, 0.3088, 0.4807, 0.4928, 0.2590],
           [0.2416, 0.4614, 0.7091, 0.5237, 0.1433],
           [0.1582, 0.4577, 0.2749, 0.1369, 0.1607]],

          [[0.2733, 0.4040, 0.4396, 0.2284, 0.3319],
           [0.3856, 0.6730, 0.4624, 0.3878, 0.3076],
           [0.4307, 0.4217, 0.2977, 0.5086, 0.5406],
           [0.3686, 0.2778, 0.5228, 0.7592, 0.6455],
           [0.2033, 0.3014, 0.4898, 0.6164, 0.3117]]]]])
To apply the exact augmenation again, you may take the advantage of the previous parameter state:
>>> input = torch.rand(1, 3, 32, 32, 32)
>>> aug = RandomMotionBlur3D(3, 35., 0.5, p=1.)
>>> (aug(input) == aug(input, params=aug._params)).all()
tensor(True)

Mix#

class kornia.augmentation.RandomTransplantation3D(excluded_labels=None, p=0.5, p_batch=1.0, data_keys=None)[source]#

RandomTransplantation3D augmentation.

3D version of the kornia.augmentation.RandomTransplantation augmentation intended to be used with kornia.augmentation.container.AugmentationSequential. The interface is identical to the 2D version.

See the Convention block on RandomTransplantation.

Convention:
  • called directly it behaves exactly like the 2D class; it exists so that AugmentationSequential dispatches it as a 3D augmentation. Inside a container use it for (B, C, D, H, W) volumes and RandomTransplantation for (B, C, H, W) images; the container rejects 4D input for this class and 5D input for the 2D one.