Skip to content

🐍 Geometric Computer Vision Library for Spatial AI

fix(enhance): reject a factor with more dims than the image instead of hanging (#4720)

Mohansree Vijayakumar5e76781d2272
diff --git a/changelog.d/4720.fixed.md b/changelog.d/4720.fixed.md
new file mode 100644
index 000000000..13762b5b4
--- /dev/null
+++ b/changelog.d/4720.fixed.md
@@ -0,0 +1 @@
+`adjust_brightness`, `adjust_contrast`, `adjust_saturation`, `adjust_hue` and their variants now raise `ValueError` for a `factor` with more dimensions than the image, instead of hanging forever (#4718).
diff --git a/kornia/enhance/adjust.py b/kornia/enhance/adjust.py
index c9cedcfc3..9c6ea2a1c 100644
--- a/kornia/enhance/adjust.py
+++ b/kornia/enhance/adjust.py
@@ -71,6 +71,25 @@ def _lookup_value_check(cond: torch.Tensor, msg: str) -> None:
torch._assert_async(cond, msg)
+def _make_factor_broadcastable(factor: torch.Tensor, image: torch.Tensor) -> torch.Tensor:
+ """Right-pad ``factor`` with singleton dimensions so it broadcasts against ``image``.
+
+ A ``factor`` with more dimensions than ``image`` can never reach the image rank by appending
+ dimensions, so padding it would loop forever. Reject it here instead of hanging. The padding
+ only lines the ranks up: shapes that still do not broadcast are reported by the op itself.
+ """
+ if factor.dim() > image.dim():
+ raise ValueError(
+ f"Factor has more dimensions than the image and cannot be broadcast: got factor shape "
+ f"{tuple(factor.shape)} for image shape {tuple(image.shape)}."
+ )
+
+ while factor.dim() != image.dim():
+ factor = factor[..., None]
+
+ return factor
+
+
def adjust_saturation_raw(image: torch.Tensor, factor: Union[float, torch.Tensor]) -> torch.Tensor:
r"""Adjust color saturation of an image.
@@ -85,9 +104,7 @@ def adjust_saturation_raw(image: torch.Tensor, factor: Union[float, torch.Tensor
elif isinstance(factor, torch.Tensor):
factor = factor.to(image.device, image.dtype)
- # make factor broadcastable
- while len(factor.shape) != len(image.shape):
- factor = factor[..., None]
+ factor = _make_factor_broadcastable(factor, image)
# unpack the hsv values
h, s, v = torch.chunk(image, chunks=3, dim=-3)
@@ -143,9 +160,7 @@ def adjust_saturation_with_gray_subtraction(image: torch.Tensor, factor: Union[f
elif isinstance(factor, torch.Tensor):
factor = factor.to(image.device, image.dtype)
- # make factor broadcastable
- while len(factor.shape) != len(image.shape):
- factor = factor[..., None]
+ factor = _make_factor_broadcastable(factor, image)
x_other: torch.Tensor = rgb_to_grayscale(image)
@@ -203,8 +218,7 @@ def adjust_saturation(image: torch.Tensor, factor: Union[float, torch.Tensor]) -
else:
factor = factor.to(image.device, image.dtype)
- while len(factor.shape) != len(image.shape):
- factor = factor[..., None]
+ factor = _make_factor_broadcastable(factor, image)
if factor.shape[-3] != 1:
raise ValueError(f"Factor must hold one value per image, not per channel. Got shape {factor.shape}")
@@ -241,9 +255,7 @@ def adjust_hue_raw(image: torch.Tensor, factor: Union[float, torch.Tensor]) -> t
factor = factor.to(image.device, image.dtype)
- # make factor broadcastable
- while len(factor.shape) != len(image.shape):
- factor = factor[..., None]
+ factor = _make_factor_broadcastable(factor, image)
# unpack the hsv values
h, s, v = torch.chunk(image, chunks=3, dim=-3)
@@ -438,9 +450,7 @@ def adjust_contrast(image: torch.Tensor, factor: Union[float, torch.Tensor], cli
elif isinstance(factor, torch.Tensor):
factor = factor.to(image.device, image.dtype)
- # make factor broadcastable
- while len(factor.shape) != len(image.shape):
- factor = factor[..., None]
+ factor = _make_factor_broadcastable(factor, image)
_assert_async_value_check(
(factor >= 0).all(),
@@ -497,9 +507,7 @@ def adjust_contrast_with_mean_subtraction(image: torch.Tensor, factor: Union[flo
elif isinstance(factor, torch.Tensor):
factor = factor.to(image.device, image.dtype)
- # make factor broadcastable
- while len(factor.shape) != len(image.shape):
- factor = factor[..., None]
+ factor = _make_factor_broadcastable(factor, image)
# KORNIA_CHECK(any(factor >= 0), "Contrast factor must be positive.")
@@ -570,9 +578,7 @@ def adjust_brightness(
elif isinstance(factor, torch.Tensor):
factor = factor.to(image.device, image.dtype)
- # make factor broadcastable
- while len(factor.shape) != len(image.shape):
- factor = factor[..., None]
+ factor = _make_factor_broadcastable(factor, image)
# shift pixel values
img_adjust: torch.Tensor = image + factor
@@ -625,9 +631,7 @@ def adjust_brightness_accumulative(
elif isinstance(factor, torch.Tensor):
factor = factor.to(image.device, image.dtype)
- # make factor broadcastable
- while len(factor.shape) != len(image.shape):
- factor = factor[..., None]
+ factor = _make_factor_broadcastable(factor, image)
# shift pixel values
img_adjust: torch.Tensor = image * factor
diff --git a/tests/enhance/test_adjust.py b/tests/enhance/test_adjust.py
index 640158578..dde5db32b 100644
--- a/tests/enhance/test_adjust.py
+++ b/tests/enhance/test_adjust.py
@@ -1416,3 +1416,52 @@ class TestPosterize(BaseTester):
op = kornia.enhance.posterize
op_optimized = torch_optimizer(op)
self.assert_close(op(img, 3), op_optimized(img, 3))
+
+
+_FACTOR_OPS = [
+ kornia.enhance.adjust_saturation,
+ kornia.enhance.adjust_saturation_raw,
+ kornia.enhance.adjust_saturation_with_gray_subtraction,
+ kornia.enhance.adjust_hue,
+ kornia.enhance.adjust_hue_raw,
+ kornia.enhance.adjust_contrast,
+ kornia.enhance.adjust_contrast_with_mean_subtraction,
+ kornia.enhance.adjust_brightness,
+ kornia.enhance.adjust_brightness_accumulative,
+]
+
+
+class TestFactorBroadcast(BaseTester):
+ """A factor carrying more dimensions than the image used to spin forever while broadcasting."""
+
+ @pytest.mark.parametrize("op", _FACTOR_OPS)
+ @pytest.mark.parametrize("img_shape", [(3, 4, 4), (2, 3, 4, 4)])
+ def test_factor_with_more_dims_raises(self, device, dtype, op, img_shape):
+ img = torch.rand(img_shape, device=device, dtype=dtype)
+ factor = torch.ones(2, *([1] * len(img_shape)), device=device, dtype=dtype)
+ with pytest.raises(ValueError):
+ op(img, factor)
+
+ @pytest.mark.parametrize("op", _FACTOR_OPS)
+ def test_per_image_factor_with_equal_rank(self, device, dtype, op):
+ img = torch.rand(2, 3, 4, 4, device=device, dtype=dtype)
+ values = [0.3, 0.7]
+ factor = torch.tensor(values, device=device, dtype=dtype).view(2, 1, 1, 1)
+ out = op(img, factor)
+ for i, v in enumerate(values):
+ self.assert_close(out[i : i + 1], op(img[i : i + 1], v))
+
+ @pytest.mark.parametrize("op", [kornia.enhance.adjust_brightness, kornia.enhance.adjust_contrast])
+ def test_per_channel_factor_with_equal_rank(self, device, dtype, op):
+ img = torch.rand(2, 3, 4, 4, device=device, dtype=dtype)
+ values = [0.2, 0.5, 0.8]
+ factor = torch.tensor(values, device=device, dtype=dtype).view(1, 3, 1, 1)
+ out = op(img, factor)
+ for c, v in enumerate(values):
+ self.assert_close(out[:, c : c + 1], op(img[:, c : c + 1], v))
+
+ def test_factor_with_fewer_dims_still_broadcasts(self, device, dtype):
+ img = torch.rand(2, 3, 4, 4, device=device, dtype=dtype)
+ factor = torch.tensor([0.25, 0.75], device=device, dtype=dtype)
+ out = kornia.enhance.adjust_brightness(img, factor)
+ assert out.shape == img.shape