π Geometric Computer Vision Library for Spatial AI
Python artificial-intelligencecomputer-visiondeep-learninghacktoberfestimage-processingmachine-learningneural-networkpythonpytorchroboticsspatial-ai
fix(enhance): validate denormalize statistics against the channel axis (#5384)
AhmetHakanBezir5f4d84bdde77
diff --git a/changelog.d/5384.breaking.md b/changelog.d/5384.breaking.mdnew file mode 100644index 000000000..a73ad4faf--- /dev/null+++ b/changelog.d/5384.breaking.md@@ -0,0 +1 @@+`denormalize` and `Denormalize` used to accept a `(C,)` mean or std whose length matched dimension -3 of a rank-3 or rank-5 input instead of its channel count, and broadcast a 1-channel input to C channels (a `(2, 1, 4, 2, 2)` input with 4-element statistics returned a `(2, 4, 4, 2, 2)` tensor). They now raise `ValueError` for that input, as `normalize` does.diff --git a/changelog.d/5384.fixed.md b/changelog.d/5384.fixed.mdnew file mode 100644index 000000000..23c9ce50e--- /dev/null+++ b/changelog.d/5384.fixed.md@@ -0,0 +1 @@+`denormalize` and `Denormalize` check a `(C,)` mean or std against dimension 1, as `normalize` does, so every documented `(B, C, *)` rank works: rank-2 input no longer raises `IndexError`, and rank-3 or rank-5 input whose dimension -3 differs from C, including float statistics, is no longer rejected.diff --git a/docs/source/get-started/conventions.rst b/docs/source/get-started/conventions.rstindex 15a34283c..c54ff13b1 100644--- a/docs/source/get-started/conventions.rst+++ b/docs/source/get-started/conventions.rst@@ -364,9 +364,7 @@ Enhancementoperate on HSV data.- :func:`kornia.enhance.normalize` and :func:`kornia.enhance.denormalize` use channel axis 1in ``(B, C, ...)``. :func:`kornia.enhance.normalize_min_max` takes ``(*, C, H, W)`` and rescales- each ``H x W`` plane independently. Outside rank 4, ``denormalize`` checks ``(C,)`` statistics- against the wrong axis; pass ``(1, C)``- (`#5318 <https://github.com/kornia/kornia/issues/5318>`_).+ each ``H x W`` plane independently.- :func:`kornia.enhance.integral_image` sums inclusively over the last two axes. The returnedimage has the input shape, without an extra zero border.- :class:`kornia.enhance.ZCAWhitening` uses ``dim`` as the sample axis and flattens all otherdiff --git a/kornia/enhance/normalize.py b/kornia/enhance/normalize.pyindex d06025ffd..324319cfc 100644--- a/kornia/enhance/normalize.py+++ b/kornia/enhance/normalize.py@@ -314,11 +314,6 @@ def denormalize(data: torch.Tensor, mean: Union[torch.Tensor, float], std: UnionThis is the elementwise inverse of :func:`normalize` for matching mean and stdon ``(B, C, *)`` input.- .. warning::- Outside rank four, a ``(C,)`` mean or std is checked against the wrong axis, so valid- statistics can be rejected and mismatched ones accepted; pass ``(1, C)`` instead- (`#5318 <https://github.com/kornia/kornia/issues/5318>`_).-.. math::\text{input[channel] = (input[channel] * std[channel]) + mean[channel]}@@ -377,12 +372,12 @@ def denormalize(data: torch.Tensor, mean: Union[torch.Tensor, float], std: Union# Allow broadcast on channel dimensionif mean.shape and mean.shape[0] != 1:- if mean.shape[0] != data.shape[-3] and mean.shape[:2] != data.shape[:2]:+ if mean.shape[0] != data.shape[1] and mean.shape[:2] != data.shape[:2]:raise ValueError(f"mean length and number of channels do not match. Got {mean.shape} and {data.shape}.")# Allow broadcast on channel dimensionif std.shape and std.shape[0] != 1:- if std.shape[0] != data.shape[-3] and std.shape[:2] != data.shape[:2]:+ if std.shape[0] != data.shape[1] and std.shape[:2] != data.shape[:2]:raise ValueError(f"std length and number of channels do not match. Got {std.shape} and {data.shape}.")mean = torch.as_tensor(mean, device=data.device, dtype=data.dtype)diff --git a/tests/enhance/test_conventions_enhance.py b/tests/enhance/test_conventions_enhance.pyindex bbb138c86..b50f896ee 100644--- a/tests/enhance/test_conventions_enhance.py+++ b/tests/enhance/test_conventions_enhance.py@@ -49,16 +49,28 @@ class TestEnhanceConventions(BaseTester):@pytest.mark.parametrize("shape",[- pytest.param((2, 4), marks=pytest.mark.xfail(strict=True, reason="#5318: C vector indexes missing axis")),- pytest.param((2, 4, 3, 2, 2), marks=pytest.mark.xfail(strict=True, reason="#5318: C vector checks depth")),+ (2, 4),+ (2, 4, 3, 2, 2),],)- def test_wart_denormalize_is_inverse_for_channel_vector_5318(self, shape, device, dtype):+ def test_convention_denormalize_is_inverse_for_channel_vector_5318(self, shape, device, dtype):data = torch.arange(torch.tensor(shape).prod(), device=device, dtype=dtype).reshape(shape) / 32.0mean = torch.tensor([0.1, 0.2, 0.3, 0.4], device=device, dtype=dtype)std = torch.tensor([0.5, 0.6, 0.7, 0.8], device=device, dtype=dtype)normalized = kornia.enhance.normalize(data, mean, std)self.assert_close(kornia.enhance.denormalize(normalized, mean, std), data)+ self.assert_close(kornia.enhance.Denormalize(mean, std)(normalized), data)++ @pytest.mark.parametrize("wrong", ["mean", "std"])+ def test_convention_denormalize_rejects_channel_vector_of_other_length_5318(self, wrong, device, dtype):+ # Depth 4 matches the vector, the single channel does not: dimension -3 accepted this and+ # broadcast the channel axis to four.+ data = torch.zeros(2, 1, 4, 2, 2, device=device, dtype=dtype)+ one = torch.ones(1, device=device, dtype=dtype)+ four = torch.ones(4, device=device, dtype=dtype)+ mean, std = (four, one) if wrong == "mean" else (one, four)+ with pytest.raises(ValueError):+ kornia.enhance.denormalize(data, mean, std)def test_convention_denormalize_rank5_batch_channel_statistics_workaround(self, device, dtype):data = torch.arange(2 * 4 * 3 * 2 * 2, device=device, dtype=dtype).reshape(2, 4, 3, 2, 2) / 32.0