Skip to content

🐍 Geometric Computer Vision Library for Spatial AI

fix(enhance): compute non-RGB contrast mean per image (#4816)

Keshav Chhabra7091413e7942
diff --git a/changelog.d/4793.fixed.md b/changelog.d/4793.fixed.md
index 8b5a91594..23a08b588 100644
--- a/changelog.d/4793.fixed.md
+++ b/changelog.d/4793.fixed.md
@@ -1 +1 @@
-Corrected the 2D intensity augmentation docstrings and the `kornia.enhance` `AdjustHue`, `AdjustContrastWithMeanSubtraction`, `AdjustSaturationWithGraySubtraction` and `AdjustBrightnessAccumulative` summaries: `RandomBrightness`, `RandomContrast` and `RandomSaturation` no longer claim to match PIL and torchvision (their formulas differ, and `ColorJitter` is the class whose steps use torchvision's), `RandomHue`, `RandomGamma` and the `enhance` modules state the mapping they do share with torchvision, the stale MPS and raw-error notes on `RandomEqualize` and `RandomClahe` are gone, and the convention blocks are trimmed to kornia's own behaviour. Newly found defects are linked as known issues: #4781, #4782, #4783, #4784, #4785, #4806, #4807, #4810, #4811 and #4813.
+Corrected the 2D intensity augmentation docstrings and the `kornia.enhance` `AdjustHue`, `AdjustContrastWithMeanSubtraction`, `AdjustSaturationWithGraySubtraction` and `AdjustBrightnessAccumulative` summaries: `RandomBrightness`, `RandomContrast` and `RandomSaturation` no longer claim to match PIL and torchvision (their formulas differ, and `ColorJitter` is the class whose steps use torchvision's), `RandomHue`, `RandomGamma` and the `enhance` modules state the mapping they do share with torchvision, the stale MPS and raw-error notes on `RandomEqualize` and `RandomClahe` are gone, and the convention blocks are trimmed to kornia's own behaviour. Newly found defects are linked as known issues: #4781, #4782, #4783, #4784, #4785, #4807, #4810, #4811 and #4813.
diff --git a/changelog.d/4816.breaking.md b/changelog.d/4816.breaking.md
new file mode 100644
index 000000000..3ce490a59
--- /dev/null
+++ b/changelog.d/4816.breaking.md
@@ -0,0 +1,5 @@
+`adjust_contrast_with_mean_subtraction`, `AdjustContrastWithMeanSubtraction` and the contrast step of `ColorJitter`
+now blend an input that is not three-channel with each image's own mean over its channels and pixels. They used to
+blend it with the mean of the whole tensor, batch and any other leading dimensions included, so an image's result
+depended on the other images in the batch. Batched outputs for such inputs change; a single image, `(C, H, W)` or
+a batch of one, and three-channel inputs give the same results as before. Fixes #4806.
diff --git a/kornia/augmentation/_2d/intensity/color_jitter.py b/kornia/augmentation/_2d/intensity/color_jitter.py
index d5a50516d..a6a81520b 100644
--- a/kornia/augmentation/_2d/intensity/color_jitter.py
+++ b/kornia/augmentation/_2d/intensity/color_jitter.py
@@ -82,11 +82,6 @@ class ColorJitter(IntensityAugmentationBase2D):
out-of-range input. Tracked in
`#4785 <https://github.com/kornia/kornia/issues/4785>`_.
- .. warning::
- On an input that is not three-channel, which only a fixed ``order`` admits, the contrast step blends each
- sample with the mean of the whole batch rather than its own. Tracked in
- `#4806 <https://github.com/kornia/kornia/issues/4806>`_.
-
.. warning::
After this class's own ``.compile()`` the module no longer pickles or passes through ``torch.save``.
Tracked in `#4807 <https://github.com/kornia/kornia/issues/4807>`_.
diff --git a/kornia/enhance/adjust.py b/kornia/enhance/adjust.py
index 631ce9fd6..2a82954c8 100644
--- a/kornia/enhance/adjust.py
+++ b/kornia/enhance/adjust.py
@@ -511,7 +511,7 @@ def adjust_contrast_with_mean_subtraction(image: torch.Tensor, factor: Union[flo
if image.shape[-3] == 3:
img_mean = rgb_to_grayscale(image).mean((-2, -1), True)
else:
- img_mean = image.mean()
+ img_mean = image.mean((-3, -2, -1), True)
# Apply contrast factor subtracting the mean
img_adjust: torch.Tensor = image * factor + img_mean * (1 - factor)
@@ -1468,8 +1468,7 @@ class AdjustContrastWithMeanSubtraction(nn.Module):
r"""Adjust Contrast of an image.
For an RGB image it blends the image with its grayscale mean, ``factor * image + (1 - factor) * mean``, as
- torchvision and PIL do. Any other channel count takes the mean over the whole batch rather than per image
- (`#4806 <https://github.com/kornia/kornia/issues/4806>`_).
+ torchvision and PIL do.
The input image is expected to be in the range of [0, 1].
Args:
diff --git a/tests/augmentation/test_augmentation.py b/tests/augmentation/test_augmentation.py
index 9f418a498..b92bd14c1 100644
--- a/tests/augmentation/test_augmentation.py
+++ b/tests/augmentation/test_augmentation.py
@@ -2001,6 +2001,15 @@ class TestColorJitter(BaseTester):
self.assert_close(f(input), expected, low_tolerance=True)
+ def test_non_rgb_contrast_is_batch_independent(self, device, dtype):
+ image = torch.tensor([[[[0.8, 0.9], [0.7, 0.6]]], [[[0.0, 0.1], [0.2, 0.1]]]], device=device, dtype=dtype)
+ jitter = ColorJitter(contrast=(0.5, 0.5), p=1.0, order=(1,))
+
+ batched = jitter(image)
+ separate = torch.cat([jitter(sample.unsqueeze(0)) for sample in image])
+
+ self.assert_close(batched, separate)
+
def _get_expected_saturation(self, device, dtype):
return torch.tensor(
[
diff --git a/tests/enhance/test_adjust.py b/tests/enhance/test_adjust.py
index 17d05cef4..29bfd22ab 100644
--- a/tests/enhance/test_adjust.py
+++ b/tests/enhance/test_adjust.py
@@ -382,6 +382,21 @@ class TestAdjustContrast(BaseTester):
out = kornia.enhance.adjust_contrast_with_mean_subtraction(img, 0.5)
assert out.shape == shape
+ @pytest.mark.parametrize("shape", [(4, 2, 3), (2, 1, 2, 3), (2, 3, 4, 2, 3)])
+ def test_non_rgb_mean_with_leading_dimensions(self, device, dtype, shape):
+ numel = torch.Size(shape).numel()
+ image = torch.arange(numel, device=device, dtype=dtype).reshape(shape) / numel
+ factor = torch.linspace(0.25, 0.75, image[..., 0, 0, 0].numel(), device=device, dtype=dtype).reshape(
+ image.shape[:-3]
+ )
+ factor_broadcast = factor.reshape(*factor.shape, 1, 1, 1)
+ expected = image * factor_broadcast + image.mean((-3, -2, -1), keepdim=True) * (1 - factor_broadcast)
+
+ actual = kornia.enhance.adjust_contrast_with_mean_subtraction(image, factor)
+
+ assert actual.shape == shape
+ self.assert_close(actual, expected)
+
def test_factor_zero(self, device, dtype):
# prepare input data
data = torch.tensor(
@@ -672,17 +687,16 @@ class TestAdjustContrast(BaseTester):
img = torch.rand(batch_size, channels, height, width, device=device, dtype=torch.float64)
self.gradcheck(kornia.enhance.adjust_contrast_with_mean_subtraction, (img, 2.0))
- # Issue #4806: a non-RGB input blends with the mean of the whole batch, so a sample's result depends on
- # its batch-mates; an RGB input uses each image's own mean. A per-image fix flips the one-channel leg.
- @pytest.mark.parametrize(("channels", "contaminated"), [(1, True), (3, False)])
- def test_wart_mean_subtraction_non_rgb_uses_the_batch_mean_4806(self, device, dtype, channels, contaminated):
+ # Regression for #4806: every channel count must use each image's own mean.
+ @pytest.mark.parametrize("channels", [1, 3, 4])
+ def test_mean_subtraction_is_batch_independent_4806(self, device, dtype, channels):
bright = torch.full((1, channels, 2, 2), 0.8, device=device, dtype=dtype)
dark = torch.full((1, channels, 2, 2), 0.2, device=device, dtype=dtype)
factor = torch.tensor([0.5, 0.5], device=device, dtype=dtype)
alone = kornia.enhance.adjust_contrast_with_mean_subtraction(dark, factor[:1])
batched = kornia.enhance.adjust_contrast_with_mean_subtraction(torch.cat([bright, dark]), factor)[1:]
self.assert_close(alone, dark)
- assert (not torch.allclose(batched, alone)) is contaminated
+ self.assert_close(batched, alone)
def test_dynamo(self, device, dtype, torch_optimizer):
B, C, H, W = 2, 3, 4, 4