π Geometric Computer Vision Library for Spatial AI
Python artificial-intelligencecomputer-visiondeep-learninghacktoberfestimage-processingmachine-learningneural-networkpythonpytorchroboticsspatial-ai
fix(augmentation): accept integer Denormalize statistics (#4581)
Dex Hunter1d015c35fe22
diff --git a/changelog.d/4581.fixed.md b/changelog.d/4581.fixed.mdnew file mode 100644index 000000000..1b6e1e341--- /dev/null+++ b/changelog.d/4581.fixed.md@@ -0,0 +1 @@+Fixes `augmentation.Denormalize` so integer `mean` and `std` values are accepted alongside floating-point, list, tuple, and tensor statistics.diff --git a/kornia/augmentation/_2d/intensity/denormalize.py b/kornia/augmentation/_2d/intensity/denormalize.pyindex 3bbc66e3c..a013f3138 100644--- a/kornia/augmentation/_2d/intensity/denormalize.py+++ b/kornia/augmentation/_2d/intensity/denormalize.py@@ -53,10 +53,8 @@ class Denormalize(IntensityAugmentationBase2D):`#4496 <https://github.com/kornia/kornia/issues/4496>`_ and is removed here.- the statistics live in ``flags`` rather than in a buffer, so ``state_dict()`` is empty and``Module.to(...)`` leaves their device and dtype alone.- - this class inverts :class:`Normalize` built with the same float, sequence or tensor ``mean`` and- ``std``, up to float rounding, when both apply -- each draws its own ``p`` gate. An ``int``- statistic, which :class:`Normalize` accepts, raises here on the forward pass- (`#4573 <https://github.com/kornia/kornia/issues/4573>`_).+ - this class inverts :class:`Normalize` built with the same float, integer, sequence or tensor ``mean`` and+ ``std``, up to float rounding, when both apply -- each draws its own ``p`` gate.- the result is not clamped: it is ``input * std + mean`` whatever range the input is in... note::@@ -79,10 +77,10 @@ class Denormalize(IntensityAugmentationBase2D):keepdim: bool = False,) -> None:super().__init__(p=p, same_on_batch=True, keepdim=keepdim)- if isinstance(mean, float):+ if isinstance(mean, (int, float)):mean = torch.tensor([mean])- if isinstance(std, float):+ if isinstance(std, (int, float)):std = torch.tensor([std])if isinstance(mean, (tuple, list)):diff --git a/kornia/augmentation/_2d/intensity/normalize.py b/kornia/augmentation/_2d/intensity/normalize.pyindex 114cb1f96..8565686ec 100644--- a/kornia/augmentation/_2d/intensity/normalize.py+++ b/kornia/augmentation/_2d/intensity/normalize.py@@ -54,10 +54,8 @@ class Normalize(IntensityAugmentationBase2D):``same_on_batch`` argument of its own.- the statistics live in ``flags`` rather than in a buffer, so ``state_dict()`` is empty and``Module.to(...)`` leaves their device and dtype alone.- - :class:`Denormalize` built with the same float, sequence or tensor ``mean`` and ``std`` inverts this- class, up to float rounding, when both apply -- each draws its own ``p`` gate. An ``int`` statistic,- which this class accepts, makes :class:`Denormalize` raise on the forward pass- (`#4573 <https://github.com/kornia/kornia/issues/4573>`_).+ - :class:`Denormalize` built with the same float, integer, sequence or tensor ``mean`` and ``std``+ inverts this class, up to float rounding, when both apply -- each draws its own ``p`` gate.- the result is not clamped: moving an image out of ``[0, 1]`` is what this class is for... warning::diff --git a/tests/augmentation/test_augmentation.py b/tests/augmentation/test_augmentation.pyindex f0ebf5de7..5e0afec52 100644--- a/tests/augmentation/test_augmentation.py+++ b/tests/augmentation/test_augmentation.py@@ -4754,6 +4754,43 @@ class TestDenormalize(BaseTester):self.assert_close(f1(inputs), inputs)self.assert_close(f1.transform_matrix, identity)+ @pytest.mark.parametrize(+ "mean, std",+ [+ (0, 255),+ (2, 0.5),+ (0.25, 4),+ ],+ )+ @pytest.mark.parametrize("batched", [False, True])+ def test_integer_statistics_affine_and_normalize_inverse(self, device, dtype, mean, std, batched):+ values = torch.tensor(+ [+ [+ [0.125, 0.5],+ [0.75, 1.25],+ ],+ [+ [1.5, 2.25],+ [3.0, 4.5],+ ],+ ],+ device=device,+ dtype=dtype,+ )+ inputs = values.unsqueeze(0).repeat(2, 1, 1, 1) if batched else values+ expected = inputs * std + mean++ output = Denormalize(mean=mean, std=std, p=1.0, keepdim=True)(inputs)+ assert output.shape == inputs.shape+ assert output.device == inputs.device+ assert output.dtype == inputs.dtype+ self.assert_close(output, expected)++ normalized = Normalize(mean=mean, std=std, p=1.0, keepdim=True)(inputs)+ recovered = Denormalize(mean=mean, std=std, p=1.0, keepdim=True)(normalized)+ self.assert_close(recovered, inputs)+def test_batch_random_denormalize(self, device, dtype):f = Denormalize(mean=torch.tensor([1.0]), std=torch.tensor([0.5]), p=1.0)f1 = Denormalize(mean=torch.tensor([1.0]), std=torch.tensor([0.5]), p=0.0)diff --git a/tests/augmentation/test_conventions_intensity_ops.py b/tests/augmentation/test_conventions_intensity_ops.pyindex 35ad41bf0..cbfd7545e 100644--- a/tests/augmentation/test_conventions_intensity_ops.py+++ b/tests/augmentation/test_conventions_intensity_ops.py@@ -1840,20 +1840,20 @@ class TestIlluminationAndNormalizeConventions(BaseTester):with pytest.raises(ValueError, match="do not match"):_sync(cls(mean=mean, std=std, p=1.0)(image).device)- # Issue #4573: Normalize wraps an `int` mean or std into a tensor, Denormalize wraps only a `float`, so- # the pair built with `mean=0, std=255` cannot round-trip: Denormalize reaches kornia.enhance.denormalize- # with a bare int and fails there on the forward pass.+ # Issue #4573: Normalize and Denormalize both accept integer scalar statistics, so the pair+ # built with ``mean=0, std=255`` round-trips.# Snippet used to generate expected:- # x = torch.rand(2, 3, 4, 4); y = K.Normalize(mean=0, std=255, p=1.0)(x); K.Denormalize(mean=0, std=255, p=1.0)(y)- # executed 2026-09-15 (torch 2.14.0, cpu) -> `AttributeError: 'int' object has no attribute 'shape'`.+ # x = torch.rand(2, 3, 4, 4); y = K.Normalize(mean=0, std=255, p=1.0)(x)+ # z = K.Denormalize(mean=0, std=255, p=1.0)(y)+ # torch.testing.assert_close(z, x)+ # executed 2026-09-16 (torch 2.5.1, cpu).@pytest.mark.device_agnostic- def test_wart_denormalize_rejects_the_int_statistics_normalize_accepts_4573(self):+ def test_convention_denormalize_accepts_the_int_statistics_normalize_accepts_4573(self):torch.manual_seed(_FIXTURE_SEED)image = torch.rand(2, 3, 4, 4)normalized = K.Normalize(mean=0, std=255, p=1.0)(image)self.assert_close(normalized, image / 255)- with pytest.raises(AttributeError, match="shape"):- K.Denormalize(mean=0, std=255, p=1.0)(normalized)+ self.assert_close(K.Denormalize(mean=0, std=255, p=1.0)(normalized), image)self.assert_close(K.Denormalize(mean=0.0, std=255.0, p=1.0)(normalized), image)# Rows 6c-17 and 6c-18: Normalize and Denormalize hard-code ``same_on_batch=True`` (normalize.py