Skip to content

🐍 Geometric Computer Vision Library for Spatial AI

fix(color): keep near-gray HLS hue gradients finite (#6089)

alp0f4586a84d51
diff --git a/changelog.d/6089.fixed.md b/changelog.d/6089.fixed.md
new file mode 100644
index 000000000..2816d6160
--- /dev/null
+++ b/changelog.d/6089.fixed.md
@@ -0,0 +1 @@
+`rgb_to_hls` and `RgbToHls` now subtract color channels before dividing by chroma, avoiding NaN float16 hue gradients for near-gray pixels such as normalized RGB `(250, 251, 250)`. Hue values also move by rounding-level amounts in every dtype, closer to a float64 evaluation.
diff --git a/kornia/color/hls.py b/kornia/color/hls.py
index 5909c9bc8..a3abc2af9 100644
--- a/kornia/color/hls.py
+++ b/kornia/color/hls.py
@@ -80,7 +80,6 @@ def rgb_to_hls(image: torch.Tensor, eps: float = 1e-8) -> torch.Tensor:
# Use unit divisors when chroma or the lightness denominator is zero.
# Preserve the epsilon-adjusted calculation for nonzero denominators.
chroma_denominator = torch.where(s == 0, torch.ones_like(s), s + eps)
- im = image / chroma_denominator.unsqueeze(-3)
lightness_denominator = torch.where(l_ < 1.0, l_, 2.0 - l_)
saturation_denominator = torch.where(
@@ -89,15 +88,13 @@ def rgb_to_hls(image: torch.Tensor, eps: float = 1e-8) -> torch.Tensor:
s /= saturation_denominator # saturation
l_ /= 2 # luminance
- # note that r,g and b were previously div by (max - min)
- r, g, b = im[..., 0, :, :], im[..., 1, :, :], im[..., 2, :, :]
- # h[imax == 0] = (((g - b) / (max - min)) % 6)[imax == 0]
- # h[imax == 1] = (((b - r) / (max - min)) + 2)[imax == 1]
- # h[imax == 2] = (((r - g) / (max - min)) + 4)[imax == 2]
+ # Subtract before dividing: RGB / chroma has overflowing float16 gradients near gray,
+ # even when the hue and its gradient are representable.
+ r, g, b = image[..., 0, :, :], image[..., 1, :, :], image[..., 2, :, :]
cond = imax[..., None, :, :] == _RGB2HSL_IDX
- h = ((g - b) % 6) * cond[..., 0, :, :]
- h += (b - r + 2) * cond[..., 1, :, :]
- h += (r - g + 4) * cond[..., 2, :, :]
+ h = (((g - b) / chroma_denominator) % 6) * cond[..., 0, :, :]
+ h += ((b - r) / chroma_denominator + 2) * cond[..., 1, :, :]
+ h += ((r - g) / chroma_denominator + 4) * cond[..., 2, :, :]
# h = 2.0 * math.pi * (60.0 * h) / 360.0
h *= math.pi / 3.0 # hue [0, 2*pi]
h = h.masked_fill(h >= 2.0 * math.pi, 0.0)
diff --git a/tests/color/test_hls.py b/tests/color/test_hls.py
index 548196160..f01b6d9af 100644
--- a/tests/color/test_hls.py
+++ b/tests/color/test_hls.py
@@ -207,6 +207,24 @@ class TestRgbToHls(BaseTester):
actual = kornia.color.rgb_to_hls(image, eps=eps)
self.assert_close(actual, image.new_tensor(expected).reshape(1, 3, 1, 1))
+ @pytest.mark.parametrize("max_channel", [0, 1, 2])
+ @pytest.mark.parametrize("eps", [0.0, 1e-8, 0.1])
+ def test_near_gray_gradients(self, device, dtype, max_channel, eps):
+ # Adjacent 8-bit values near white overflow the backward of RGB / chroma in float16.
+ image = torch.full((2, 3, 2, 3), 250 / 255, device=device, dtype=dtype)
+ image[:, max_channel] = 251 / 255
+ image.requires_grad_()
+ reference_dtype = torch.float64 if dtype == torch.float64 else torch.float32
+ reference = image.detach().to(reference_dtype).requires_grad_()
+
+ actual = kornia.color.rgb_to_hls(image, eps)[..., 0, :, :]
+ expected = kornia.color.rgb_to_hls(reference, eps)[..., 0, :, :]
+ actual.sum().backward()
+ expected.sum().backward()
+
+ self.assert_close(actual, expected.to(dtype))
+ self.assert_close(image.grad, reference.grad.to(dtype))
+
def test_gradcheck(self, device, dtype):
B, C, H, W = 2, 3, 4, 4
img = torch.rand(B, C, H, W, device=device, dtype=torch.float64, requires_grad=True)