D4
Apply one of eight D4 square symmetries (rotations and reflections). Keeps square shape. Use group_element for deterministic TTA (e.g. run all 8 then inverse).
The D4 group transformations include:
- 'e' (identity): No transformation is applied.
- 'r90' (rotation by 90 degrees counterclockwise)
- 'r180' (rotation by 180 degrees)
- 'r270' (rotation by 270 degrees counterclockwise)
- 'v' (reflection across the vertical midline)
- 'hvt' (reflection across the anti-diagonal)
- 'h' (reflection across the horizontal midline)
- 't' (reflection across the main diagonal)
Even if the probability (p) of applying the transform is set to 1, the identity transformation
'e' may still occur, which means the input will remain unchanged in one out of eight cases.
When group_element is specified, the transform is deterministic—useful for TTA (Test Time
Augmentation) where you need to apply each of the 8 symmetries explicitly and invert predictions.
Call inverse() on a deterministic instance to get a new transform that undoes the operation.
pProbability of applying the transform. Default: 1.0.
group_elementIf set, always apply this specific D4 group element instead of sampling randomly. Use for TTA. Default: None (random choice).
>>> import numpy as np
>>> import albumentations as A
>>> image = np.random.randint(0, 256, (100, 100, 3), dtype=np.uint8)
>>> transform = A.Compose([
... A.D4(p=1.0),
... ])
>>> transformed = transform(image=image)
>>> transformed_image = transformed['image']
# The resulting image will be one of the 8 possible D4 transformations of the input
>>> # TTA: apply each D4 symmetry, run inference, then undo the transform on the prediction
>>> from albumentations.core.type_definitions import d4_group_elements
>>> predictions = []
>>> for element in d4_group_elements:
... aug = A.D4(p=1.0, group_element=element)
... aug_image = aug(image=image)["image"]
... pred_mask = np.zeros((100, 100, 1), dtype=np.uint8) # placeholder for model output
... restored = aug.inverse()(image=pred_mask)["image"]
... predictions.append(restored)- This transform is particularly useful for augmenting data that does not have a clear orientation, such as top-view satellite or drone imagery, or certain types of medical images.
- Square inputs keep their shape. On rectangular inputs,
r90,r270,t, andhvtswap height and width. - To use
additional_targetsfor images and masks at different resolutions, setCompose(is_check_shapes=False). Each image and mask receives the same symmetry at its own resolution. - When applied to bounding boxes or keypoints, their coordinates will be adjusted according to the selected transformation.
inverse()requiresgroup_elementto be set explicitly; raisesValueErrorotherwise.