Skip to content

🐍 Geometric Computer Vision Library for Spatial AI

fix(color): avoid NaN gradients in rgb_to_linear_rgb (#5329)

msparsh13f766513847e0
diff --git a/changelog.d/5329.fixed.md b/changelog.d/5329.fixed.md
new file mode 100644
index 000000000..a9de3bfdc
--- /dev/null
+++ b/changelog.d/5329.fixed.md
@@ -0,0 +1,2 @@
+`rgb_to_linear_rgb` no longer returns NaN gradients for inputs below -0.055, and neither do `rgb_to_lab` and
+`rgb_to_luv`, which call it. The forward result is unchanged.
diff --git a/kornia/color/rgb.py b/kornia/color/rgb.py
index ba71ea915..0aa3b1723 100644
--- a/kornia/color/rgb.py
+++ b/kornia/color/rgb.py
@@ -246,7 +246,12 @@ def rgb_to_linear_rgb(image: torch.Tensor) -> torch.Tensor:
if len(image.shape) < 3 or image.shape[-3] != 3:
raise ValueError(f"Input size must have a shape of (*, 3, H, W).Got {image.shape}")
- lin_rgb: torch.Tensor = torch.where(image > 0.04045, torch.pow(((image + 0.055) / 1.055), 2.4), image / 12.92)
+ threshold = 0.04045
+ lin_rgb: torch.Tensor = torch.where(
+ image > threshold,
+ torch.pow(((image + 0.055).clamp(min=0.0) / 1.055), 2.4),
+ image / 12.92,
+ )
return lin_rgb
diff --git a/tests/color/test_rgb.py b/tests/color/test_rgb.py
index 3109bf142..f7e02a521 100644
--- a/tests/color/test_rgb.py
+++ b/tests/color/test_rgb.py
@@ -424,6 +424,38 @@ class TestLinearRgb(BaseTester):
fcn = kornia.color.linear_rgb_to_rgb
self.assert_close(ops(img), fcn(img))
+ @pytest.mark.parametrize("value", [-1.0, -0.1, -0.055, -0.03, 0.0])
+ def test_negative_gradient(self, device, dtype, value):
+ image = torch.full((1, 3, 1, 1), value, device=device, dtype=dtype, requires_grad=True)
+
+ output = kornia.color.rgb_to_linear_rgb(image)
+ output.sum().backward()
+
+ expected = torch.full_like(image, 1.0 / 12.92)
+
+ assert torch.isfinite(output).all()
+ assert torch.isfinite(image.grad).all()
+ self.assert_close(image.grad, expected)
+
+ @pytest.mark.parametrize("values", [(-0.1, -0.03, 0.5), (-1.0, 0.0, 1.0)])
+ def test_gradient(self, device, dtype, values):
+ image = torch.tensor(values, device=device, dtype=dtype).view(1, 3, 1, 1)
+ image.requires_grad_(True)
+
+ output = kornia.color.rgb_to_linear_rgb(image)
+ output.sum().backward()
+
+ assert torch.isfinite(image.grad).all()
+
+ def test_gradient_at_threshold(self, device, dtype):
+ # sRGB decodes C <= 0.04045 on the linear segment, so the threshold takes the slope 1 / 12.92;
+ # the power segment's slope there is about 1.7% steeper.
+ image = torch.full((1, 3, 1, 1), 0.04045, device=device, dtype=dtype, requires_grad=True)
+
+ kornia.color.rgb_to_linear_rgb(image).sum().backward()
+
+ self.assert_close(image.grad, torch.full_like(image, 1.0 / 12.92))
+
class TestRgb255Normals(BaseTester):
# Smoke tests: check if the functions execute and return a tensor