π Geometric Computer Vision Library for Spatial AI
Python artificial-intelligencecomputer-visiondeep-learninghacktoberfestimage-processingmachine-learningneural-networkpythonpytorchroboticsspatial-ai
fix(enhance): reject over-ranked gamma/gain in adjust_gamma (#4755)
yi1114d645c01c25e
diff --git a/changelog.d/4755.breaking.md b/changelog.d/4755.breaking.mdnew file mode 100644index 000000000..7b849eda1--- /dev/null+++ b/changelog.d/4755.breaking.md@@ -0,0 +1 @@+`adjust_gamma` and `AdjustGamma` now raise `ValueError` when `gamma` or `gain` has more dimensions than the image, the same error `adjust_brightness`, `adjust_contrast`, `adjust_saturation` and `adjust_hue` raise for such a `factor` (#4720). Previously the over-ranked factor silently broadcast the image up to a larger output shape: a `(3, 4, 4)` image with a `(2, 1, 1, 1)` `gamma` returned a `(2, 3, 4, 4)` tensor.diff --git a/kornia/enhance/adjust.py b/kornia/enhance/adjust.pyindex 9c6ea2a1c..2f6514b26 100644--- a/kornia/enhance/adjust.py+++ b/kornia/enhance/adjust.py@@ -379,11 +379,8 @@ def adjust_gamma("Gain must be non-negative. Clamp it first: max(gain, 0.0) for floats, gain.clamp_min(0.0) for tensors.",)- for _ in range(len(input.shape) - len(gamma.shape)):- gamma = torch.unsqueeze(gamma, dim=-1)-- for _ in range(len(input.shape) - len(gain.shape)):- gain = torch.unsqueeze(gain, dim=-1)+ gamma = _make_factor_broadcastable(gamma, input)+ gain = _make_factor_broadcastable(gain, input)# Apply the gamma correctionx_adjust: torch.Tensor = gain * torch.pow(input, gamma)diff --git a/tests/enhance/test_adjust.py b/tests/enhance/test_adjust.pyindex dde5db32b..64f98d7ae 100644--- a/tests/enhance/test_adjust.py+++ b/tests/enhance/test_adjust.py@@ -1428,11 +1428,15 @@ _FACTOR_OPS = [kornia.enhance.adjust_contrast_with_mean_subtraction,kornia.enhance.adjust_brightness,kornia.enhance.adjust_brightness_accumulative,+ kornia.enhance.adjust_gamma,]class TestFactorBroadcast(BaseTester):- """A factor carrying more dimensions than the image used to spin forever while broadcasting."""+ """A factor carrying more dimensions than the image must raise.++ The other factor ops used to spin forever while broadcasting it; ``adjust_gamma`` returned a larger tensor.+ """@pytest.mark.parametrize("op", _FACTOR_OPS)@pytest.mark.parametrize("img_shape", [(3, 4, 4), (2, 3, 4, 4)])@@ -1465,3 +1469,9 @@ class TestFactorBroadcast(BaseTester):factor = torch.tensor([0.25, 0.75], device=device, dtype=dtype)out = kornia.enhance.adjust_brightness(img, factor)assert out.shape == img.shape++ def test_overranked_gain_raises(self, device, dtype):+ img = torch.rand(2, 3, 4, 4, device=device, dtype=dtype)+ gain = torch.ones(2, 1, 1, 1, 1, device=device, dtype=dtype)+ with pytest.raises(ValueError):+ kornia.enhance.adjust_gamma(img, 1.0, gain)