Skip to content

🐍 Geometric Computer Vision Library for Spatial AI

fix(enhance): preserve Python scalar precision in image dtype (#5358)

AhmetHakanBeziradcf449b88d9
diff --git a/changelog.d/5358.fixed.md b/changelog.d/5358.fixed.md
new file mode 100644
index 000000000..d9cbd4718
--- /dev/null
+++ b/changelog.d/5358.fixed.md
@@ -0,0 +1,5 @@
+`adjust_hue_raw`, `adjust_gamma` and `solarize` build a Python-float parameter in the image dtype instead of rounding
+it to `float32` first. A `float64` image used to get a `float32`-rounded `factor`, `gamma`, `gain`, `thresholds` or
+`additions` (relative error up to 6e-8, so `solarize(x, 0.1)` left a pixel equal to `0.1` uninverted); it now gets the
+value as given. `float32` results are unchanged, and `float16`/`bfloat16` ones change only where rounding the float
+once instead of twice gives a different value.
diff --git a/kornia/enhance/adjust.py b/kornia/enhance/adjust.py
index 79c476f4f..f0307220b 100644
--- a/kornia/enhance/adjust.py
+++ b/kornia/enhance/adjust.py
@@ -269,7 +269,7 @@ def adjust_hue_raw(image: torch.Tensor, factor: Union[float, torch.Tensor]) -> t
)
if isinstance(factor, float):
- factor = torch.as_tensor(factor)
+ factor = torch.as_tensor(factor, device=image.device, dtype=image.dtype)
factor = factor.to(image.device, image.dtype)
@@ -389,10 +389,10 @@ def adjust_gamma(
raise TypeError(f"The gain should be a positive float or torch.Tensor. Got {type(gain)}")
if isinstance(gamma, float):
- gamma = torch.Tensor([gamma])
+ gamma = torch.tensor([gamma], device=input.device, dtype=input.dtype)
if isinstance(gain, float):
- gain = torch.Tensor([gain])
+ gain = torch.tensor([gain], device=input.device, dtype=input.dtype)
gamma = gamma.to(input.device).to(input.dtype)
gain = gain.to(input.device).to(input.dtype)
@@ -846,17 +846,22 @@ def solarize(
raise TypeError(f"The factor should be either a float or torch.Tensor. Got {type(thresholds)}")
if isinstance(thresholds, float):
- thresholds = torch.as_tensor(thresholds)
+ thresholds = torch.as_tensor(thresholds, device=input.device, dtype=input.dtype)
if additions is not None:
if not isinstance(additions, (float, torch.Tensor)):
raise TypeError(f"The factor should be either a float or torch.Tensor. Got {type(additions)}")
if isinstance(additions, float):
- additions = torch.as_tensor(additions)
+ # Check the Python value on the host: rounded to float16/bfloat16, a value just past the bound
+ # passes, and the check is skipped for a tensor on MPS.
+ in_range = torch.tensor(-0.5 <= additions <= 0.5)
+ additions = torch.as_tensor(additions, device=input.device, dtype=input.dtype)
+ else:
+ in_range = ((additions <= 0.5) & (additions >= -0.5)).all()
_assert_async_value_check(
- ((additions <= 0.5) & (additions >= -0.5)).all(),
+ in_range,
"The addition must be in the closed range [-0.5, 0.5]. Clamp it first: min(max(additions, -0.5), 0.5) "
"for floats, additions.clamp(-0.5, 0.5) for tensors.",
)
diff --git a/tests/enhance/test_adjust.py b/tests/enhance/test_adjust.py
index a6d623ca1..a32ca8758 100644
--- a/tests/enhance/test_adjust.py
+++ b/tests/enhance/test_adjust.py
@@ -33,6 +33,23 @@ def _sync(device) -> None:
torch.mps.synchronize()
+class TestFloatScalarPrecision(BaseTester):
+ @pytest.mark.parametrize(
+ "operation,kwargs",
+ [
+ (kornia.enhance.adjust_hue_raw, {"factor": 0.1}),
+ (kornia.enhance.adjust_gamma, {"gamma": 0.1}),
+ (kornia.enhance.adjust_gamma, {"gamma": 1.0, "gain": 0.1}),
+ (kornia.enhance.solarize, {"thresholds": 0.1}),
+ (kornia.enhance.solarize, {"thresholds": 0.5, "additions": 0.1}),
+ ],
+ )
+ def test_float_matches_image_dtype_tensor(self, device, dtype, operation, kwargs):
+ image = torch.tensor([0.05, 0.1], device=device, dtype=dtype).repeat(1, 3, 1, 1)
+ tensors = {key: image.new_tensor(value) for key, value in kwargs.items()}
+ self.assert_close(operation(image, **kwargs), operation(image, **tensors), rtol=0, atol=0)
+
+
class TestInvert(BaseTester):
def test_smoke(self, device, dtype):
img = torch.rand(1, 3, 4, 4, device=device, dtype=dtype)
@@ -1323,6 +1340,14 @@ class TestSolarize(BaseTester):
with pytest.raises(RuntimeError, match=r"closed range \[-0\.5, 0\.5\]"):
TestSolarize.f(img, 0.5, addition)
+ @pytest.mark.parametrize("addition", [0.5001, -0.5001])
+ def test_float_additions_checked_before_rounding(self, device, dtype, addition):
+ # A float is checked as given, on the host, for every device: float16/bfloat16 round 0.5001 to 0.5,
+ # and a check on an MPS tensor is skipped.
+ img = torch.ones(2, 3, 4, 5, device=device, dtype=dtype)
+ with pytest.raises(RuntimeError, match=r"closed range \[-0\.5, 0\.5\]"):
+ TestSolarize.f(img, 0.5, addition)
+
# TODO: add better cases
def test_value(self, device, dtype):
torch.manual_seed(0)