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:
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)inverse() requires group_element to be set explicitly; raises ValueError otherwise.