Skip to content

🐍 Geometric Computer Vision Library for Spatial AI

fix(augmentation): use PIL-style enhancement factors in auto policies (#6254)

Hsn4a50c2c96340
diff --git a/changelog.d/6254.fixed.md b/changelog.d/6254.fixed.md
new file mode 100644
index 000000000..f82fb0fb4
--- /dev/null
+++ b/changelog.d/6254.fixed.md
@@ -0,0 +1 @@
+`Brightness`, `Contrast` and `Saturate` in `kornia.augmentation.auto.operations`, and with them the `brightness`, `contrast` and `color` entries of `AutoAugment`, `RandAugment` and `TrivialAugment`, now apply the PIL `ImageEnhance` formulas their 0.1 to 1.9 factor ranges come from: brightness multiplies the image by the factor, contrast blends each image with its mean grayscale level, and color blends it with its grayscale version. They used to add `factor - 1` for brightness, multiply the image by the factor for contrast and scale the HSV saturation for color, so a brightness factor of 0.3 clipped most of an image to black. `Saturate` now also returns a single-channel image unchanged instead of raising. `RandomBrightness`, `RandomContrast` and `RandomSaturation` are unchanged.
diff --git a/kornia/augmentation/auto/operations/ops.py b/kornia/augmentation/auto/operations/ops.py
index effdfa993..b9d25620d 100644
--- a/kornia/augmentation/auto/operations/ops.py
+++ b/kornia/augmentation/auto/operations/ops.py
@@ -15,12 +15,22 @@
# limitations under the License.
#
-from typing import Dict, Optional, Tuple
+from typing import Any, Dict, Optional, Tuple
import torch
import kornia.augmentation as K
+from kornia.augmentation._2d.intensity.base import _clamp_unit_range
+from kornia.augmentation._2d.intensity.brightness import RandomBrightness
+from kornia.augmentation._2d.intensity.contrast import RandomContrast
+from kornia.augmentation._2d.intensity.saturation import RandomSaturation
from kornia.augmentation.auto.operations.base import OperationBase
+from kornia.core.utils import _to_device_nonblocking
+from kornia.enhance import (
+ adjust_brightness_accumulative,
+ adjust_contrast_with_mean_subtraction,
+ adjust_saturation_with_gray_subtraction,
+)
def _fraction_to_pixels(mag: Optional[torch.Tensor], size: int) -> Optional[torch.Tensor]:
@@ -52,6 +62,45 @@ __all__ = [
]
+class _PILBrightness(RandomBrightness):
+ def apply_transform(
+ self,
+ input: torch.Tensor,
+ params: Dict[str, torch.Tensor],
+ flags: Dict[str, Any],
+ transform: Optional[torch.Tensor] = None,
+ ) -> torch.Tensor:
+ """Apply the sampled PIL-style enhancement factor to the input."""
+ factor = _to_device_nonblocking(params["brightness_factor"], input.device, input.dtype)
+ return adjust_brightness_accumulative(_clamp_unit_range(input), factor)
+
+
+class _PILContrast(RandomContrast):
+ def apply_transform(
+ self,
+ input: torch.Tensor,
+ params: Dict[str, torch.Tensor],
+ flags: Dict[str, Any],
+ transform: Optional[torch.Tensor] = None,
+ ) -> torch.Tensor:
+ """Apply the sampled PIL-style enhancement factor to the input."""
+ factor = _to_device_nonblocking(params["contrast_factor"], input.device, input.dtype)
+ return adjust_contrast_with_mean_subtraction(_clamp_unit_range(input), factor)
+
+
+class _PILSaturation(RandomSaturation):
+ def apply_transform(
+ self,
+ input: torch.Tensor,
+ params: Dict[str, torch.Tensor],
+ flags: Dict[str, Any],
+ transform: Optional[torch.Tensor] = None,
+ ) -> torch.Tensor:
+ """Apply the sampled PIL-style enhancement factor to the input."""
+ factor = _to_device_nonblocking(params["saturation_factor"], input.device, input.dtype)
+ return adjust_saturation_with_gray_subtraction(_clamp_unit_range(input), factor)
+
+
class AutoContrast(OperationBase):
"""Apply auto_contrast operation.
@@ -75,7 +124,10 @@ class AutoContrast(OperationBase):
class Brightness(OperationBase):
- """Apply brightness operation.
+ """Apply PIL-style multiplicative brightness for automatic augmentation.
+
+ Unlike :class:`~kornia.augmentation.RandomBrightness`, the factor multiplies
+ the input. The policy factors match the PIL ImageEnhance convention.
Args:
initial_probability: the initial probability. If None, the augmentation will be randomly
@@ -96,7 +148,7 @@ class Brightness(OperationBase):
symmetric_megnitude: bool = False,
) -> None:
super().__init__(
- K.RandomBrightness(magnitude_range, same_on_batch=False, p=initial_probability),
+ _PILBrightness(magnitude_range, same_on_batch=False, p=initial_probability),
initial_magnitude=[("brightness_factor", initial_magnitude)],
temperature=temperature,
symmetric_megnitude=symmetric_megnitude,
@@ -104,7 +156,10 @@ class Brightness(OperationBase):
class Contrast(OperationBase):
- """Apply contrast operation.
+ """Apply PIL-style contrast by blending each image towards its mean grayscale value.
+
+ Unlike :class:`~kornia.augmentation.RandomContrast`, the factor scales the
+ difference from the mean rather than multiplying the input directly.
Args:
initial_probability: the initial probability. If None, the augmentation will be randomly
@@ -125,7 +180,7 @@ class Contrast(OperationBase):
symmetric_megnitude: bool = False,
) -> None:
super().__init__(
- K.RandomContrast(magnitude_range, same_on_batch=False, p=initial_probability),
+ _PILContrast(magnitude_range, same_on_batch=False, p=initial_probability),
initial_magnitude=[("contrast_factor", initial_magnitude)],
temperature=temperature,
symmetric_megnitude=symmetric_megnitude,
@@ -162,7 +217,10 @@ class Hue(OperationBase):
class Saturate(OperationBase):
- """Apply saturation operation.
+ """Apply PIL-style color enhancement by blending with grayscale.
+
+ Unlike :class:`~kornia.augmentation.RandomSaturation`, this blends RGB
+ values with grayscale rather than scaling HSV saturation.
Args:
initial_probability: the initial probability. If None, the augmentation will be randomly
@@ -183,7 +241,7 @@ class Saturate(OperationBase):
symmetric_megnitude: bool = False,
) -> None:
super().__init__(
- K.RandomSaturation(magnitude_range, same_on_batch=False, p=initial_probability),
+ _PILSaturation(magnitude_range, same_on_batch=False, p=initial_probability),
initial_magnitude=[("saturation_factor", initial_magnitude)],
temperature=temperature,
symmetric_megnitude=symmetric_megnitude,
diff --git a/tests/augmentation/test_auto_operation.py b/tests/augmentation/test_auto_operation.py
index b4bd52d67..4e65fc8e0 100644
--- a/tests/augmentation/test_auto_operation.py
+++ b/tests/augmentation/test_auto_operation.py
@@ -493,3 +493,89 @@ def test_operation_base_deepcopy_after_use() -> None:
aug.eval()
copy.deepcopy(aug)
+
+
+# Generated with Pillow 12.3.0:
+# from PIL import Image, ImageEnhance
+# image = Image.new("RGB", (2, 2))
+# image.putdata([(32, 96, 160), (224, 64, 128), (80, 192, 48), (144, 112, 208)])
+# for enhancer in (ImageEnhance.Brightness, ImageEnhance.Contrast, ImageEnhance.Color):
+# for factor in (0.3, 1.9):
+# print(list(enhancer(image).enhance(factor).getdata()))
+# Source: PIL.ImageEnhance, the reference enhancer formulas used by the policies.
+ "operation,factor,pixels",
+ [
+ (ops.Brightness, 0.3, [(9, 28, 48), (67, 19, 38), (24, 57, 14), (43, 33, 62)]),
+ (ops.Brightness, 1.9, [(60, 182, 255), (255, 121, 243), (152, 255, 91), (255, 212, 255)]),
+ (ops.Contrast, 0.3, [(93, 112, 132), (151, 103, 122), (108, 141, 98), (127, 117, 146)]),
+ (ops.Contrast, 1.9, [(0, 74, 196), (255, 13, 135), (44, 255, 0), (165, 104, 255)]),
+ (ops.Saturate, 0.3, [(68, 87, 106), (150, 102, 121), (123, 157, 113), (136, 126, 155)]),
+ (ops.Saturate, 1.9, [(0, 106, 228), (255, 14, 136), (24, 237, 0), (153, 93, 255)]),
+ ],
+)
+def test_auto_enhancer_matches_pil_6253(operation, factor, pixels, device, dtype):
+ """Match reference pixels and deterministic replay on the selected device."""
+ image = (
+ torch.tensor(
+ [(32, 96, 160), (224, 64, 128), (80, 192, 48), (144, 112, 208)],
+ device=device,
+ dtype=dtype,
+ )
+ .reshape(2, 2, 3)
+ .permute(2, 0, 1)
+ .unsqueeze(0)
+ / 255
+ )
+ expected = torch.tensor(pixels, device=device, dtype=dtype).reshape(2, 2, 3).permute(2, 0, 1).unsqueeze(0) / 255
+ # Keep learnable magnitudes with the default CPU parameter generator, as
+ # policy containers do; the enhancement transfers factors to the input device.
+ aug = operation(initial_magnitude=factor, initial_probability=1.0, magnitude_range=(0.1, 1.9)).to(dtype=dtype)
+ params = aug.forward_parameters(image.shape)
+ output = aug(image, params=params)
+ # PIL quantizes intermediate grayscale and the final blend to uint8;
+ # Kornia keeps float intermediates. Compare at the same 8-bit precision.
+ assert_close((output * 255).round(), (expected * 255).round(), rtol=0, atol=1 + 255 * torch.finfo(dtype).eps)
+ assert_close(aug(image, params=params), output, rtol=0, atol=0)
+
+
+def test_auto_contrast_blends_towards_each_images_own_mean_6253(device, dtype):
+ """Blend each image towards its own grayscale mean, as PIL does, not towards the batch mean."""
+ # A constant image is its own grayscale mean, so PIL's contrast leaves it unchanged at any factor.
+ image = torch.stack([torch.full((3, 4, 5), 0.2), torch.full((3, 4, 5), 0.8)]).to(device=device, dtype=dtype)
+ aug = ops.Contrast(initial_magnitude=0.5, initial_probability=1.0).to(dtype=dtype)
+ assert_close(aug(image), image)
+
+
[email protected]("operation", [ops.Brightness, ops.Contrast, ops.Saturate])
+def test_auto_enhancer_keeps_magnitude_gradient_6253(operation, device, dtype):
+ """Keep finite nonzero magnitude gradients for each enhancement operation."""
+ image = torch.tensor(
+ [[[[0.2, 0.4]], [[0.5, 0.7]], [[0.3, 0.6]]]],
+ device=device,
+ dtype=dtype,
+ )
+ aug = operation(initial_magnitude=0.7, initial_probability=1.0).to(dtype=dtype)
+ assert aug._magnitude is not None
+ (gradient,) = torch.autograd.grad(aug(image).square().sum(), aug._magnitude)
+ assert torch.isfinite(gradient).all()
+ assert gradient.abs().sum() > 0
+ assert aug.op.p == 1.0
+ assert aug.op.p_batch == 1.0
+
+
[email protected]("policy", ["auto", "rand", "trivial"])
+def test_policy_brightness_uses_multiplicative_factor_6253(policy, device, dtype):
+ """Use multiplicative brightness through all three policy containers."""
+ image = torch.full((2, 3, 4, 5), 0.4, device=device, dtype=dtype)
+ if policy == "auto":
+ aug = AutoAugment(policy=[[("brightness", 1.0, 5)]])
+ elif policy == "rand":
+ aug = RandAugment(n=1, m=12, policy=[[("brightness", 0.1, 1.9)]])
+ else:
+ aug = TrivialAugment(policy=[[("brightness", 0.1, 1.9)]])
+ aug = aug.to(device=device, dtype=dtype)
+ params = aug.forward_parameters(image.shape)
+ factor = params[0].data[0].data["brightness_factor"].to(image)
+ expected = (image * factor[:, None, None, None]).clamp(0, 1)
+ assert_close(aug(image, params=params), expected)