π Geometric Computer Vision Library for Spatial AI
Python artificial-intelligencecomputer-visiondeep-learninghacktoberfestimage-processingmachine-learningneural-networkpythonpytorchroboticsspatial-ai
normalize accepts floats and allows broadcast over channel dimension
dvd423a24667bf9a2
diff --git a/kornia/color/normalize.py b/kornia/color/normalize.pyindex e37ca695d..d52092beb 100644--- a/kornia/color/normalize.py+++ b/kornia/color/normalize.py@@ -1,5 +1,6 @@import torchimport torch.nn as nn+from typing import Unionclass Normalize(nn.Module):@@ -27,39 +28,50 @@ class Normalize(nn.Module):return normalize(input, self.mean, self.std)def __repr__(self):- repr = '(mean={0}, std={1})'.format(self.mean, self.std)+ repr = "(mean={0}, std={1})".format(self.mean, self.std)return self.__class__.__name__ + repr-def normalize(data: torch.Tensor, mean: torch.Tensor,- std: torch.Tensor) -> torch.Tensor:+def normalize(+ data: torch.Tensor, mean: Union[torch.Tensor, float], std: Union[torch.Tensor, float]+) -> torch.Tensor:r"""Normalise the image with channel-wise mean and standard deviation.See :class:`~kornia.color.Normalize` for details.Args:data (torch.Tensor): The image tensor to be normalised.- mean (torch.Tensor): Mean for each channel.- std (torch.Tensor): Standard deviations for each channel.+ mean (torch.Tensor or float): Mean for each channel.+ std (torch.Tensor or float): Standard deviations for each channel.Returns:torch.Tensor: The normalised image tensor."""+ if isinstance(mean, float):+ mean = torch.tensor([mean]) # prevent 0 sized tensors++ if isinstance(std, float):+ std = torch.tensor([std]) # prevent 0 sized tensors+if not torch.is_tensor(data):- raise TypeError('data should be a tensor. Got {}'.format(type(data)))+ raise TypeError("data should be a tensor. Got {}".format(type(data)))if not torch.is_tensor(mean):- raise TypeError('mean should be a tensor. Got {}'.format(type(mean)))+ raise TypeError("mean should be a tensor or a float. Got {}".format(type(mean)))if not torch.is_tensor(std):- raise TypeError('std should be a tensor. Got {}'.format(type(std)))+ raise TypeError("std should be a tensor or float. Got {}".format(type(std)))- if mean.shape[0] != data.shape[-3] and mean.shape[:2] != data.shape[:2]:- raise ValueError('mean lenght and number of channels do not match')+ # Allow broadcast on channel dimension+ if mean.shape[0] != 1:+ if mean.shape[0] != data.shape[-3] and mean.shape[:2] != data.shape[:2]:+ raise ValueError("mean length and number of channels do not match")- if std.shape[0] != data.shape[-3] and std.shape[:2] != data.shape[:2]:- raise ValueError('std lenght and number of channels do not match')+ # Allow broadcast on channel dimension+ if std.shape[0] != 1:+ if std.shape[0] != data.shape[-3] and std.shape[:2] != data.shape[:2]:+ raise ValueError("std length and number of channels do not match")mean = mean[..., :, None, None].to(data.device)std = std[..., :, None, None].to(data.device)diff --git a/test/color/test_normalize.py b/test/color/test_normalize.pyindex 2a64c3b4c..1c179ef55 100644--- a/test/color/test_normalize.py+++ b/test/color/test_normalize.py@@ -13,7 +13,7 @@ class TestNormalize:def test_smoke(self):mean = [0.5]std = [0.1]- repr = 'Normalize(mean=[0.5], std=[0.1])'+ repr = "Normalize(mean=[0.5], std=[0.1])"assert str(kornia.color.Normalize(mean, std)) == reprdef test_normalize(self):@@ -35,11 +35,25 @@ class TestNormalize:data = torch.ones(2, 3, 1, 1)data += 2- mean = torch.tensor([0.5, 1.0, 2.0])- std = torch.tensor([2.0, 2.0, 2.0])+ mean = torch.tensor([2.0])+ std = torch.tensor([0.5])# expected output- expected = torch.tensor([1.25, 1, 0.5]).repeat(2, 1, 1).view_as(data)+ expected = torch.ones_like(data) + 1++ f = kornia.color.Normalize(mean, std)+ assert_allclose(f(data), expected)++ def test_float_input(self):++ data = torch.ones(2, 3, 1, 1)+ data += 2++ mean = 2.0+ std = 0.5++ # expected output+ expected = torch.ones_like(data) + 1f = kornia.color.Normalize(mean, std)assert_allclose(f(data), expected)@@ -52,7 +66,6 @@ class TestNormalize:mean = torch.tensor([0.5, 1.0, 2.0]).repeat(2, 1)std = torch.tensor([2.0, 2.0, 2.0]).repeat(2, 1)-# expected outputexpected = torch.tensor([1.25, 1, 0.5]).repeat(2, 1, 1).view_as(data)@@ -62,8 +75,7 @@ class TestNormalize:@pytest.mark.skip(reason="turn off all jit for a while")def test_jit(self):@torch.jit.script- def op_script(data: torch.Tensor, mean: torch.Tensor,- std: torch.Tensor) -> torch.Tensor:+ def op_script(data: torch.Tensor, mean: torch.Tensor, std: torch.Tensor) -> torch.Tensor:return kornia.normalize(data, mean, std)data = torch.ones(2, 3, 1, 1)@@ -82,9 +94,8 @@ class TestNormalize:data = torch.ones(2, 3, 1, 1)data += 2mean = torch.tensor([0.5, 1.0, 2.0]).double()- std = torch.tensor([2., 2., 2.]).double()+ std = torch.tensor([2.0, 2.0, 2.0]).double()data = utils.tensor_to_gradcheck_var(data) # to var- assert gradcheck(kornia.color.Normalize(mean, std), (data,),- raise_exception=True)+ assert gradcheck(kornia.color.Normalize(mean, std), (data,), raise_exception=True)