RandomBrightnessContrast
Adjust brightness and contrast with a torchvision-compatible default or an OpenCV-style model. Useful for training models robust to lighting variation.
brightness_rangeRange from which the brightness adjustment is
sampled. In the default torchvision-compatible mode, the multiplicative brightness
factor is 1 + adjustment; both endpoints must be at least -1. In the OpenCV-style
mode, the adjustment is an additive fraction of the dtype maximum. Default: (-0.2, 0.2).
contrast_rangeRange from which the contrast adjustment is sampled.
The contrast factor is 1 + adjustment. In the default torchvision-compatible mode,
both endpoints must be at least -1. Default: (-0.2, 0.2).
brightness_by_maxSelects the photometric model. If False, use torchvision-compatible multiplicative brightness and mean-centered contrast. If True, use the legacy OpenCV-style affine formula with additive brightness scaled by the dtype maximum. Default: False.
ensure_safe_outputIf True, reduce the combined affine gain and offset as needed so the complete input dtype range maps inside the output range without clipping. Default: False.
pProbability of applying the transform. Default: 0.5.
>>> import numpy as np
>>> import albumentations as A
>>> image = np.random.randint(0, 256, [100, 100, 3], dtype=np.uint8)
# Torchvision-compatible brightness and mean-centered contrast
>>> transform = A.RandomBrightnessContrast(p=1.0)
>>> augmented_image = transform(image=image)["image"]
# Stronger torchvision-compatible factors: brightness 0.7-1.3, contrast 0.6-1.4
>>> transform = A.RandomBrightnessContrast(
... brightness_range=(-0.3, 0.3),
... contrast_range=(-0.4, 0.4),
... p=1.0,
... )
>>> augmented_image = transform(image=image)["image"]
# Legacy OpenCV-style affine model with additive brightness
>>> transform = A.RandomBrightnessContrast(
... brightness_range=(-0.2, 0.2),
... contrast_range=(-0.2, 0.2),
... brightness_by_max=True,
... p=1.0,
... )
>>> augmented_image = transform(image=image)["image"]- The default mode applies contrast first and brightness second, matching the corresponding
torchvision operations in that fixed order.
ColorJitterrandomizes operation order. - RGB contrast uses the mean BT.601 grayscale luminance. Other multichannel inputs use the mean of their per-pixel channel averages.
- A batch uses one sampled pair of factors but computes the contrast mean independently for
each image. The
volumetarget computes it independently for each slice. - Outputs are clipped to [0, 255] for uint8 and [0, 1] for float32 unless
ensure_safe_output=Truefirst reduces the affine coefficients to avoid clipping.
- Torchvision brightness and contrast implementationhttps://docs.pytorch.org/vision/main/_modules/torchvision/transforms/v2/functional/_color.html
- OpenCV basic linear transformationshttps://docs.opencv.org/4.x/d3/dc1/tutorial_basic_linear_transform.html