π Geometric Computer Vision Library for Spatial AI
Python artificial-intelligencecomputer-visiondeep-learninghacktoberfestimage-processingmachine-learningneural-networkpythonpytorchroboticsspatial-ai
fix(color): wrap rounded HLS hue endpoint (#5378)
Karnajeet Gosavief10d59bbbf0
diff --git a/changelog.d/5378.fixed.md b/changelog.d/5378.fixed.mdnew file mode 100644index 000000000..d26033a2f--- /dev/null+++ b/changelog.d/5378.fixed.md@@ -0,0 +1,3 @@+`rgb_to_hls` returns hue 0 instead of the period itself for a red hue just below 0: `[1, 0, 6e-8]` used to return+`6.2831855` in float32, above 2Ο, and `[1, 0, 0.001]` returned `6.28125`, float16's 2Ο. Hues now stay in `[0, 2Ο)` in+every dtype, as documented and as `rgb_to_hsv` returns them. All other values are unchanged.diff --git a/kornia/color/hls.py b/kornia/color/hls.pyindex 0ec70e61f..7ad29f1f1 100644--- a/kornia/color/hls.py+++ b/kornia/color/hls.py@@ -111,6 +111,10 @@ def rgb_to_hls(image: torch.Tensor, eps: float = 1e-8) -> torch.Tensor:h += (r - g + 4) * cond[..., 2, :, :]# h = 2.0 * math.pi * (60.0 * h) / 360.0h *= math.pi / 3.0 # hue [0, 2*pi]+ if image.requires_grad:+ h = h.masked_fill(h >= 2.0 * math.pi, 0.0)+ else:+ h.masked_fill_(h >= 2.0 * math.pi, 0.0)if image.requires_grad:return torch.stack([h, l_, s], -3)diff --git a/tests/color/test_hls.py b/tests/color/test_hls.pyindex 7f591738e..4c040daf6 100644--- a/tests/color/test_hls.py+++ b/tests/color/test_hls.py@@ -27,6 +27,23 @@ from testing.base import BaseTesterclass TestRgbToHls(BaseTester):+ @pytest.mark.parametrize("requires_grad", [False, True])+ def test_red_hue_rounded_to_period_is_wrapped(self, device, dtype, requires_grad):+ # A tiny negative red-max hue rounds up to the dtype's 2Ο (#5369); 4 * eps gives the largest hue below it.+ blue = {torch.float16: 1e-3, torch.bfloat16: 1e-2, torch.float32: 6e-8, torch.float64: 1e-17}[dtype]+ near_seam = 4 * torch.finfo(dtype).eps+ image = torch.tensor([[1.0, 1.0], [0.0, 0.0], [blue, near_seam]], device=device, dtype=dtype)+ image = image.reshape(1, 3, 1, 2).requires_grad_(requires_grad)+ hls = kornia.color.rgb_to_hls(image)+ hue = hls[0, 0, 0]++ assert hue[0] == 0+ assert 6.2 < hue[1] < 2 * math.pi+ if requires_grad:+ hls.sum().backward()+ assert image.grad is not None+ assert torch.isfinite(image.grad).all()+def test_smoke(self, device, dtype):C, H, W = 3, 4, 5img = torch.rand(C, H, W, device=device, dtype=dtype)