Skip to content

🐍 Geometric Computer Vision Library for Spatial AI

fix(color): guard zero denominators in rgb_to_hls (#4583)

Dex Hunter5821ff5ead02
diff --git a/changelog.d/4583.fixed.md b/changelog.d/4583.fixed.md
new file mode 100644
index 000000000..6db937d8a
--- /dev/null
+++ b/changelog.d/4583.fixed.md
@@ -0,0 +1,4 @@
+Use safe denominators in `rgb_to_hls` for achromatic inputs and out-of-range colors with lightness zero or one.
+For achromatic inputs in every supported float dtype, hue-gradient magnitudes now scale as `pi / 3`
+instead of `pi / (3 * eps)`, reducing them from about `1e8` to about `1` with the default `eps`;
+in `float16` they were `nan`/`inf` and are now finite.
diff --git a/kornia/augmentation/_2d/intensity/random_snow.py b/kornia/augmentation/_2d/intensity/random_snow.py
index f20f0fcc0..b300744e9 100644
--- a/kornia/augmentation/_2d/intensity/random_snow.py
+++ b/kornia/augmentation/_2d/intensity/random_snow.py
@@ -58,7 +58,7 @@ class RandomSnow(IntensityAugmentationBase2D):
``rgb_to_hls``'s saturation denominator vanishes, which collapse whether the snow covers them or not:
lightness exactly ``1``, where ``2 - max - min`` is zero and ``(1.5, 0.5, 0.5)`` comes back white,
and its mirror at lightness exactly ``0``, where ``max + min`` is zero and ``(2.0, -2.0, -2.0)``
- comes back black. Both are NaN in ``float16`` (see below). The collapse is at the point, not around
+ comes back black. The collapse is at the point, not around
it: ``(1.4, 0.5, 0.5)`` and a lightness more than about ``1e-7`` off ``1`` come back close to their
input. Within ``rgb_to_hls``'s ``eps`` of ``1e-8`` of the point, which only ``float64`` can
represent, they do not: a lightness of ``1 + 1e-8`` comes back as ``(2, 0, 0)`` and ``1 + 5e-9`` as
@@ -70,12 +70,6 @@ class RandomSnow(IntensityAugmentationBase2D):
``(2.0, -2.0, -2.0)``, which is neither all-negative nor has a negative lightness. Tracked in
`#4430 <https://github.com/kornia/kornia/issues/4430>`_.
- .. warning::
- In ``float16`` every achromatic pixel -- black, gray or white -- comes back as NaN, and so does an
- out-of-range pixel whose lightness is exactly ``0`` or exactly ``1``, because ``rgb_to_hls``'s ``eps``
- underflows there. Tracked in
- `#4571 <https://github.com/kornia/kornia/issues/4571>`_.
-
Examples:
>>> inputs = torch.rand(2, 3, 4, 4)
>>> snow = kornia.augmentation.RandomSnow(p=1.0, snow_coefficient=(0.1, 0.6), brightness=(1.0, 5.0))
diff --git a/kornia/color/hls.py b/kornia/color/hls.py
index f7febc642..2892e46d2 100644
--- a/kornia/color/hls.py
+++ b/kornia/color/hls.py
@@ -35,7 +35,9 @@ def rgb_to_hls(image: torch.Tensor, eps: float = 1e-8) -> torch.Tensor:
Args:
image: RGB image to be converted to HLS with shape :math:`(*, 3, H, W)`.
- eps: epsilon value to avoid div by zero.
+ eps: bias added to the chroma and lightness denominators before dividing. The zero
+ denominators themselves are handled by a safe-substitution guard, so ``eps`` is not
+ what keeps the result finite and ``eps=0`` is well defined.
Returns:
HLS version of the image with shape :math:`(*, 3, H, W)`.
@@ -78,11 +80,16 @@ def rgb_to_hls(image: torch.Tensor, eps: float = 1e-8) -> torch.Tensor:
torch.add(maxc, minc, out=l_) # l = max + min
torch.sub(maxc, minc, out=s) # s = max - min
- # precompute image / (max - min)
- im = image / (s + eps).unsqueeze(-3)
+ # 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)
- # epsilon cannot be inside the where to avoid precision issues
- s /= torch.where(l_ < 1.0, l_, 2.0 - l_) + eps # saturation
+ lightness_denominator = torch.where(l_ < 1.0, l_, 2.0 - l_)
+ saturation_denominator = torch.where(
+ lightness_denominator == 0, torch.ones_like(lightness_denominator), lightness_denominator + eps
+ )
+ s /= saturation_denominator # saturation
l_ /= 2 # luminance
# note that r,g and b were previously div by (max - min)
diff --git a/testing/half_precision_xfails/cpu_float16.txt b/testing/half_precision_xfails/cpu_float16.txt
index eb113c71e..26953f1bd 100644
--- a/testing/half_precision_xfails/cpu_float16.txt
+++ b/testing/half_precision_xfails/cpu_float16.txt
@@ -206,8 +206,6 @@ call builtins.AssertionError tests/augmentation/test_random_generator_3d.py::Tes
call builtins.AssertionError tests/augmentation/test_random_generator_3d.py::TestRandomAffineGen3D::test_same_on_batch[cpu-float16]
call builtins.AssertionError tests/augmentation/test_random_generator_3d.py::TestRandomPerspectiveGen3D::test_random_gen[cpu-float16]
call builtins.AssertionError tests/augmentation/test_random_generator_3d.py::TestRandomPerspectiveGen3D::test_same_on_batch[cpu-float16]
-call builtins.AssertionError tests/color/test_hls.py::TestRgbToHls::test_jit[cpu-float16]
-call builtins.AssertionError tests/color/test_hls.py::TestRgbToHls::test_module[cpu-float16]
call builtins.AssertionError tests/color/test_rgb.py::TestRgb255Normals::test_back_and_forth[cpu-float16]
call builtins.AssertionError tests/filters/test_canny.py::TestCanny::test_magnitude[cpu-float16]
call builtins.AssertionError tests/filters/test_canny.py::TestCanny::test_magnitude_hyst[cpu-float16]
diff --git a/tests/augmentation/test_augmentation.py b/tests/augmentation/test_augmentation.py
index 316d6a15e..70027018e 100644
--- a/tests/augmentation/test_augmentation.py
+++ b/tests/augmentation/test_augmentation.py
@@ -5648,6 +5648,25 @@ class TestRandomSnow(BaseTester):
output_data = aug(input_data)
assert output_data.shape == input_data.shape
+ def test_gray_patch_is_finite_and_replayed(self, device, dtype):
+ input_data = torch.full((1, 3, 4, 4), 0.25, device=device, dtype=dtype)
+ input_data[:, 0, 2:, 2:] = 0.9
+ input_data[:, 1, 2:, 2:] = 0.2
+ input_data[:, 2, 2:, 2:] = 0.4
+ aug = RandomSnow(snow_coefficient=(0.5, 0.5), brightness=(2.0, 2.0), p=1.0)
+ params = aug.forward_parameters(input_data.shape)
+ params["snow_coefficient"].fill_(0.5)
+ params["brightness"].fill_(2.0)
+ output_data = aug(input_data, params=params)
+ assert torch.isfinite(output_data).all(), "random-snow-gray-oracle: nonfinite output"
+ expected_gray = torch.full_like(output_data[..., :2, :2], 0.5)
+ self.assert_close(output_data[..., :2, :2], expected_gray)
+ replayed = aug(input_data, params=params)
+ self.assert_close(replayed, output_data)
+ assert output_data.shape == input_data.shape
+ assert output_data.device == input_data.device
+ assert output_data.dtype == input_data.dtype
+
@pytest.mark.slow
def test_gradcheck(self, device):
input_data = torch.rand(1, 3, 6, 8, device=device, dtype=torch.float64)
diff --git a/tests/augmentation/test_conventions_intensity_ops.py b/tests/augmentation/test_conventions_intensity_ops.py
index b7ec1c3ed..87c5040e9 100644
--- a/tests/augmentation/test_conventions_intensity_ops.py
+++ b/tests/augmentation/test_conventions_intensity_ops.py
@@ -1234,7 +1234,7 @@ class TestNoiseAndWeatherConventions(BaseTester):
# trip, which is not the identity at either singular lightness: (1.5, 0.5, 0.5) has lightness exactly 1,
# where `2 - max - min` vanishes, and comes back white; (2, -2, -2) has lightness exactly 0, where
# `max + min` vanishes, and comes back black although it is neither all-negative nor negative in
- # lightness. Both are NaN in float16, where `eps` underflows and the saturation is 0 / 0 (#4571).
+ # lightness. The guarded denominators make both endpoints finite in every supported dtype.
# The coefficient is 0.9, not 1.0, and (1.8, 0, 0) is the last row: coverage is `lightness < coefficient`
# at random_snow.py:118, so the only pixel that can tell `<` from `<=` is one whose lightness equals the
# coefficient exactly. At coefficient 1.0 that pixel was (1.5, 0.5, 0.5) -- but it is also the lightness-1
@@ -1248,9 +1248,9 @@ class TestNoiseAndWeatherConventions(BaseTester):
# x = torch.tensor([[1.5, 0.0, 0.0], [2.0, 1.5, 1.5], [1.2, -2.0, -2.0], [1.5, 0.5, 0.5],
# [2.0, -2.0, -2.0], [1.7999999523162842, 0.0, 0.0]]).T.reshape(1, 3, 1, 6)
# torch.manual_seed(0); print(K.RandomSnow(snow_coefficient=(0.9, 0.9), brightness=(2.0, 2.0), p=1.0)(x))
- # executed 2026-09-16 (torch 2.14.0, cpu float32/float64/float16/bfloat16 and mps float32) -> the pixels
+ # executed 2026-09-16 (torch 2.9.1, cpu float32/float64/float16/bfloat16) -> the pixels
# `(1, 1, 1)`, `(2, 1.5, 1.5)`, `(0, 0, 0)`, `(1, 1, 1)`, `(0, 0, 0)` and the boundary pixel unchanged;
- # rows 3 and 4 are `(nan, nan, nan)` in float16.
+ # rows 3 and 4 are finite white and black in every supported dtype.
def test_convention_random_snow_clamps_only_covered_lightness(self, device, dtype):
pixels = torch.tensor(
[
@@ -1270,12 +1270,8 @@ class TestNoiseAndWeatherConventions(BaseTester):
self.assert_close(out[:3], pixels.new_tensor([[1.0, 1.0, 1.0], [2.0, 1.5, 1.5], [0.0, 0.0, 0.0]]))
# Lightness exactly at the coefficient is missed, so the pixel survives the round trip unchanged.
self.assert_close(out[5], pixels[5])
- if dtype == torch.float16:
- assert bool(out[3].isnan().all())
- assert bool(out[4].isnan().all())
- else:
- self.assert_close(out[3], pixels.new_ones(3))
- self.assert_close(out[4], pixels.new_zeros(3))
+ self.assert_close(out[3], pixels.new_ones(3))
+ self.assert_close(out[4], pixels.new_zeros(3))
# The singular region at lightness 1 has the width of rgb_to_hls's eps = 1e-8: a lightness 2e-7 off
# comes back close to its input in float32 and float64 (half precision rounds it onto the point), while
@@ -1288,7 +1284,7 @@ class TestNoiseAndWeatherConventions(BaseTester):
# `[-82271062.5, 82271064.5, 82271064.5]`.
def test_convention_random_snow_singularity_has_eps_width(self, device, dtype):
if dtype in (torch.float16, torch.bfloat16):
- pytest.skip("half precision: 1.5 + 4e-7 rounds onto the singular point (float16 is NaN there, #4571)")
+ pytest.skip("half precision: 1.5 + 4e-7 rounds onto the singular point")
def run(lightness: float) -> torch.Tensor:
pixel = torch.tensor([2 * lightness - 0.5, 0.5, 0.5], dtype=torch.float64).reshape(1, 3, 1, 1)
@@ -1302,19 +1298,20 @@ class TestNoiseAndWeatherConventions(BaseTester):
self.assert_close(run(1 + 1e-8), near.new_tensor([2.0, 0.0, 0.0]))
assert float(run(1 + 5e-9).abs().min()) > 1e6
- # float16, so every achromatic pixel -- black, gray or white -- gets a NaN hue that the HLS round trip
- # spreads to all three channels. bfloat16 keeps the exponent range of float32 and is finite.
+ # Every achromatic pixel -- black, gray or white -- stays finite through the HLS round trip.
# Snippet used to generate expected:
# for dt in (torch.float16, torch.bfloat16, torch.float32):
- # torch.manual_seed(0); print(dt, K.RandomSnow(p=1.0)(torch.full((1, 3, 2, 2), 0.5, dtype=dt)).isnan().any())
- # executed 2026-09-15 (torch 2.14.0, cpu; mps float16 as well) -> `True`, `False`, `False`, and the
- # same for the constants 0.0 and 1.0.
+ # torch.manual_seed(0); y = K.RandomSnow(p=1.0)(torch.full((1, 3, 2, 2), 0.5, dtype=dt))
+ # print(dt, torch.isfinite(y).all())
+ # current CPU run -> True for float16, bfloat16 and float32, and the same for constants 0.0 and 1.0.
@pytest.mark.parametrize("value", [0.0, 0.5, 1.0])
- def test_wart_random_snow_achromatic_pixel_is_nan_in_float16_4571(self, device, dtype, value):
+ def test_convention_random_snow_achromatic_pixel_is_finite_4571(self, device, dtype, value):
gray = torch.full((1, 3, 2, 2), value, device=device, dtype=dtype)
torch.manual_seed(_FORWARD_SEED)
out = K.RandomSnow(p=1.0)(gray)
- assert bool(out.isnan().any()) == (dtype == torch.float16)
+ assert bool(torch.isfinite(out).all())
+ expected = gray.new_full(gray.shape, value)
+ self.assert_close(out, expected)
# The channel-count precondition is a class-by-class contract, so it is pinned as one table rather
# than per class: five of these were documented before this batch and five were not, and the split
diff --git a/tests/augmentation/test_conventions_intensity_values.py b/tests/augmentation/test_conventions_intensity_values.py
index 1678903f0..65a191cab 100644
--- a/tests/augmentation/test_conventions_intensity_values.py
+++ b/tests/augmentation/test_conventions_intensity_values.py
@@ -443,15 +443,15 @@ class TestIntensityValueRangeConventions(BaseTester):
image = torch.full((2, 3, 6, 8), -1.0, device=device, dtype=dtype)
every, some = [], []
for name in sorted(_INTENSITY_FACTORIES):
- if name == "RandomEqualize" or (dtype == torch.float16 and name in ("ColorJitter", "RandomSnow")):
- continue # raises out of range; float16 ColorJitter (#4560) and RandomSnow (#4571) are NaN there
+ if name == "RandomEqualize" or (dtype == torch.float16 and name == "ColorJitter"):
+ continue # raises out of range; float16 ColorJitter (#4560) is NaN there
if name in ("RandomBoxBlur", "RandomGaussianBlur") and not supports_reflect_padding(device, dtype):
continue # torch 2.5.1 has no half reflection_pad2d on the CPU
zeros = sum(float(_run(name, image, seed=seed).abs().max()) == 0.0 for seed in range(5))
(every if zeros == 5 else some if zeros else []).append(name)
expected = set(self._COLLAPSES_ON_CONSTANT_MINUS_ONE)
if dtype == torch.float16:
- expected -= {"ColorJitter", "RandomSnow"}
+ expected -= {"ColorJitter"}
assert set(every) == expected
assert set(some) <= {"ColorJiggle", "RandomPlasmaContrast"}
# The two constant-image artefacts do not collapse the non-constant audit fixture on any of 20 seeds.
diff --git a/tests/color/test_hls.py b/tests/color/test_hls.py
index c94bf757a..d7cf31872 100644
--- a/tests/color/test_hls.py
+++ b/tests/color/test_hls.py
@@ -110,8 +110,6 @@ class TestRgbToHls(BaseTester):
self.assert_close(kornia.color.rgb_to_hls(data), expected, low_tolerance=True)
def test_nan_rgb_to_hls(self, device, dtype):
- if dtype == torch.float16:
- pytest.skip("not work for half-precision")
data = torch.ones(2, 3, 5, 5, device=device, dtype=dtype)
# OpenCV
@@ -125,11 +123,71 @@ class TestRgbToHls(BaseTester):
)
self.assert_close(kornia.color.rgb_to_hls(data), expected)
+ @pytest.mark.parametrize("gray_level", [0.0, 0.25, 0.5, 1.0])
+ @pytest.mark.parametrize("shape", [(3, 4, 4), (2, 3, 4, 4)])
+ @pytest.mark.parametrize("requires_grad", [False, True])
+ def test_achromatic_values_are_finite_and_canonical(self, device, dtype, gray_level, shape, requires_grad):
+ input_data = torch.full(shape, gray_level, device=device, dtype=dtype)
+ input_data.requires_grad_(requires_grad)
+ output = kornia.color.rgb_to_hls(input_data)
+ expected = torch.empty_like(output)
+ expected[..., 0, :, :].fill_(0.0)
+ expected[..., 1, :, :].fill_(gray_level)
+ expected[..., 2, :, :].fill_(0.0)
+ assert torch.isfinite(output).all(), "hls-achromatic-oracle: nonfinite output"
+ self.assert_close(output, expected)
+ if requires_grad:
+ output.sum().backward()
+ assert input_data.grad is not None
+ assert torch.isfinite(input_data.grad).all(), "hls-achromatic-oracle: nonfinite backward gradient"
+ assert output.shape == input_data.shape
+ assert output.device == input_data.device
+ assert output.dtype == input_data.dtype
+
+ @pytest.mark.parametrize(
+ ("rgb", "expected"),
+ [
+ ([1.5, 0.5, 0.5], [0.0, 1.0, 1.0]),
+ ([2.0, -2.0, -2.0], [0.0, 0.0, 4.0]),
+ ],
+ )
+ def test_out_of_range_zero_lightness_denominator_values(self, device, dtype, rgb, expected):
+ image = torch.tensor(rgb, device=device, dtype=dtype).reshape(1, 3, 1, 1)
+ actual = kornia.color.rgb_to_hls(image)
+ self.assert_close(actual, image.new_tensor(expected).reshape(1, 3, 1, 1))
+
+ @pytest.mark.parametrize("gray_level", [0.0, 0.25, 0.5, 1.0])
+ @pytest.mark.parametrize("shape", [(3, 4, 4), (2, 3, 4, 4)])
+ def test_achromatic_round_trip_is_finite(self, device, dtype, gray_level, shape):
+ input_data = torch.full(shape, gray_level, device=device, dtype=dtype)
+ hls = kornia.color.rgb_to_hls(input_data)
+ output = kornia.color.hls_to_rgb(hls)
+ assert torch.isfinite(hls).all(), "hls-roundtrip-oracle: nonfinite HLS"
+ assert torch.isfinite(output).all(), "hls-roundtrip-oracle: nonfinite RGB"
+ self.assert_close(output, input_data)
+ assert output.shape == input_data.shape
+ assert output.device == input_data.device
+ assert output.dtype == input_data.dtype
+
def test_nan_random_extreme_values(self, device, dtype):
# generate extreme colors randomly
ext_rand_slice = (torch.rand((1, 3, 32, 32), dtype=dtype, device=device) >= 0.5).float()
assert not kornia.color.rgb_to_hls(ext_rand_slice).isnan().any()
+ # Independent oracle for RGB=(0.2, 0.5, 0.4): chroma=0.3, lightness=0.35,
+ # and green-max hue=((0.4-0.2)/(0.3+eps)+2)*pi/3, saturation=0.3/(0.7+eps).
+ @pytest.mark.parametrize(
+ ("eps", "expected"),
+ [
+ (0.0, [2.792526803190927, 0.35, 0.4285714285714286]),
+ (0.1, [2.617993877991494, 0.35, 0.375]),
+ ],
+ )
+ def test_eps_is_added_to_both_nonzero_denominators(self, device, dtype, eps, expected):
+ image = torch.tensor([[[[0.2]], [[0.5]], [[0.4]]]], device=device, dtype=dtype)
+ actual = kornia.color.rgb_to_hls(image, eps=eps)
+ self.assert_close(actual, image.new_tensor(expected).reshape(1, 3, 1, 1))
+
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)