π Geometric Computer Vision Library for Spatial AI
Python artificial-intelligencecomputer-visiondeep-learninghacktoberfestimage-processingmachine-learningneural-networkpythonpytorchroboticsspatial-ai
Fix Bug #2876: normalize_min_max now supports 3D tensors (C, H, W) (#3352)
funnym0nk3yeae117b7af12
diff --git a/kornia/enhance/normalize.py b/kornia/enhance/normalize.pyindex 0b7f49f16..bae4c8971 100644--- a/kornia/enhance/normalize.py+++ b/kornia/enhance/normalize.py@@ -23,6 +23,7 @@ import torchfrom kornia.core import ImageModule as Modulefrom kornia.core import Tensor+from kornia.utils.image import perform_keep_shape_image__all__ = ["Denormalize", "Normalize", "denormalize", "normalize", "normalize_min_max"]@@ -274,6 +275,7 @@ def denormalize(data: Tensor, mean: Union[Tensor, float], std: Union[Tensor, floreturn torch.addcmul(mean, data, std)+@perform_keep_shape_imagedef normalize_min_max(x: Tensor, min_val: float = 0.0, max_val: float = 1.0, eps: float = 1e-6) -> Tensor:r"""Normalise an image/video tensor by MinMax and re-scales the value between a range.@@ -285,13 +287,13 @@ def normalize_min_max(x: Tensor, min_val: float = 0.0, max_val: float = 1.0, epswhere :math:`a` is :math:`\text{min_val}` and :math:`b` is :math:`\text{max_val}`.Args:- x: The image tensor to be normalised with shape :math:`(B, C, *)`.+ x: The image tensor to be normalised with shape :math:`(*, C, H, W)`.min_val: The minimum value for the new range.max_val: The maximum value for the new range.eps: Float number to avoid zero division.Returns:- The normalised image tensor with same shape as input :math:`(B, C, *)`.+ The normalised image tensor with same shape as input :math:`(*, C, H, W)`.Example:>>> x = torch.rand(1, 5, 3, 3)@@ -309,10 +311,7 @@ def normalize_min_max(x: Tensor, min_val: float = 0.0, max_val: float = 1.0, epsraise TypeError(f"'min_val' should be a float. Got: {type(min_val)}.")if not isinstance(max_val, float):- raise TypeError(f"'b' should be a float. Got: {type(max_val)}.")-- if len(x.shape) < 3:- raise ValueError(f"Input shape must be at least a 3d tensor. Got: {x.shape}.")+ raise TypeError(f"'max_val' should be a float. Got: {type(max_val)}.")shape = x.shapeB, C = shape[0], shape[1]diff --git a/tests/enhance/test_normalize.py b/tests/enhance/test_normalize.pyindex 24465eae0..f9aa8213f 100644--- a/tests/enhance/test_normalize.py+++ b/tests/enhance/test_normalize.py@@ -317,7 +317,7 @@ class TestNormalizeMinMax(BaseTester):actual = kornia.enhance.normalize_min_max(x, min_val=-1.0, max_val=1.0)self.assert_close(actual, expected, low_tolerance=True)- @pytest.mark.jit()+ @pytest.mark.skip(reason="args and kwargs in decorator")def test_jit(self, device, dtype):x = torch.ones(1, 1, 1, 1, device=device, dtype=dtype)op = kornia.enhance.normalize_min_max@@ -328,3 +328,51 @@ class TestNormalizeMinMax(BaseTester):def test_gradcheck(self, device):x = torch.ones(1, 1, 1, 1, device=device, dtype=torch.float64, requires_grad=True)self.gradcheck(kornia.enhance.normalize_min_max, (x,))++ def test_3d_tensor(self, device, dtype):+ # Test with 3D tensor (C, H, W) - the main bug fix+ x = torch.tensor([[[0.0, 1.0, 3.0], [-1.0, 4.0, 3.0], [9.0, 5.0, 2.0]]], device=device, dtype=dtype)++ # Expected: normalized to [-1, 1] range+ expected = torch.tensor([[[-0.8, -0.6, -0.2], [-1.0, 0.0, -0.2], [1.0, 0.2, -0.4]]], device=device, dtype=dtype)++ actual = kornia.enhance.normalize_min_max(x, min_val=-1.0, max_val=1.0)++ # Verify shape is preserved+ assert actual.shape == x.shape+ self.assert_close(actual, expected, low_tolerance=True)++ def test_3d_tensor_multiple_channels(self, device, dtype):+ # Test with 3D tensor with multiple channels (C, H, W)+ x = torch.rand(3, 4, 5, device=device, dtype=dtype)+ out = kornia.enhance.normalize_min_max(x, min_val=0.0, max_val=1.0)++ # Verify shape is preserved+ assert out.shape == x.shape++ # Verify per-channel normalization+ for c in range(x.shape[0]):+ channel_out = out[c]+ self.assert_close(channel_out.min(), torch.tensor(0.0, device=device, dtype=dtype), low_tolerance=True)+ self.assert_close(channel_out.max(), torch.tensor(1.0, device=device, dtype=dtype), low_tolerance=True)++ def test_2d_tensor(self, device, dtype):+ # Test with 2D tensor (H, W)+ x = torch.tensor([[0.0, 5.0], [10.0, 15.0]], device=device, dtype=dtype)+ out = kornia.enhance.normalize_min_max(x, min_val=0.0, max_val=1.0)++ # Verify shape is preserved+ assert out.shape == x.shape++ # Verify normalization+ expected = torch.tensor([[0.0, 1.0 / 3.0], [2.0 / 3.0, 1.0]], device=device, dtype=dtype)+ self.assert_close(out, expected, low_tolerance=True)++ @pytest.mark.parametrize("input_shape", [(3, 4, 5), (1, 32, 32), (4, 8, 8)])+ def test_3d_shapes(self, device, dtype, input_shape):+ # Test various 3D tensor shapes+ x = torch.rand(input_shape, device=device, dtype=dtype)+ out = kornia.enhance.normalize_min_max(x, min_val=-1.0, max_val=1.0)++ # Verify shape is preserved+ assert out.shape == input_shape