Skip to content

🐍 Geometric Computer Vision Library for Spatial AI

add option for mean and std to be tuples (#987)

Joan Fontanals92793cdcc17b
diff --git a/kornia/augmentation/augmentation.py b/kornia/augmentation/augmentation.py
index 8d2bb52ac..24a5e32ca 100644
--- a/kornia/augmentation/augmentation.py
+++ b/kornia/augmentation/augmentation.py
@@ -1341,7 +1341,7 @@ class Normalize(IntensityAugmentationBase2D):
Examples:
- >>> norm = Normalize(mean=torch.zeros(1, 4), std=torch.ones(1, 4))
+ >>> norm = Normalize(mean=torch.zeros(4), std=torch.ones(4))
>>> x = torch.rand(1, 4, 3, 3)
>>> out = norm(x)
>>> out.shape
@@ -1350,13 +1350,25 @@ class Normalize(IntensityAugmentationBase2D):
def __init__(
self,
- mean: torch.Tensor,
- std: torch.Tensor,
+ mean: Union[torch.Tensor, Tuple[float], List[float], float],
+ std: Union[torch.Tensor, Tuple[float], List[float], float],
return_transform: bool = False,
p: float = 1.0,
keepdim: bool = False,
) -> None:
super(Normalize, self).__init__(p=p, return_transform=return_transform, same_on_batch=True, keepdim=keepdim)
+ if isinstance(mean, float):
+ mean = torch.tensor([mean])
+
+ if isinstance(std, float):
+ std = torch.tensor([std])
+
+ if isinstance(mean, (tuple, list)):
+ mean = torch.tensor(mean)
+
+ if isinstance(std, (tuple, list)):
+ std = torch.tensor(std)
+
self.mean = mean
self.std = std
diff --git a/kornia/enhance/normalize.py b/kornia/enhance/normalize.py
index a21466e42..47d3a1403 100644
--- a/kornia/enhance/normalize.py
+++ b/kornia/enhance/normalize.py
@@ -1,6 +1,6 @@
"""Module containing functionals for intensity normalisation."""
-from typing import Union
+from typing import List, Tuple, Union
import torch
import torch.nn as nn
@@ -31,17 +31,32 @@ class Normalize(nn.Module):
torch.Size([1, 4, 3, 3])
>>> x = torch.rand(1, 4, 3, 3)
- >>> mean = torch.zeros(1, 4)
- >>> std = 255. * torch.ones(1, 4)
+ >>> mean = torch.zeros(4)
+ >>> std = 255. * torch.ones(4)
>>> out = Normalize(mean, std)(x)
>>> out.shape
torch.Size([1, 4, 3, 3])
"""
- def __init__(self, mean: Union[torch.Tensor, float], std: Union[torch.Tensor, float]) -> None:
-
+ def __init__(
+ self,
+ mean: Union[torch.Tensor, Tuple[float], List[float], float],
+ std: Union[torch.Tensor, Tuple[float], List[float], float],
+ ) -> None:
super(Normalize, self).__init__()
+ if isinstance(mean, float):
+ mean = torch.tensor([mean])
+
+ if isinstance(std, float):
+ std = torch.tensor([std])
+
+ if isinstance(mean, (tuple, list)):
+ mean = torch.tensor(mean)
+
+ if isinstance(std, (tuple, list)):
+ std = torch.tensor(std)
+
self.mean = mean
self.std = std
@@ -53,7 +68,7 @@ class Normalize(nn.Module):
return self.__class__.__name__ + repr
-def normalize(data: torch.Tensor, mean: Union[torch.Tensor, float], std: Union[torch.Tensor, float]) -> torch.Tensor:
+def normalize(data: torch.Tensor, mean: torch.Tensor, std: torch.Tensor) -> torch.Tensor:
r"""Normalize a tensor image with mean and standard deviation.
.. math::
@@ -71,42 +86,31 @@ def normalize(data: torch.Tensor, mean: Union[torch.Tensor, float], std: Union[t
Examples:
>>> x = torch.rand(1, 4, 3, 3)
- >>> out = normalize(x, 0.0, 255.)
+ >>> out = normalize(x, torch.tensor([0.0]), torch.tensor([255.]))
>>> out.shape
torch.Size([1, 4, 3, 3])
>>> x = torch.rand(1, 4, 3, 3)
- >>> mean = torch.zeros(1, 4)
- >>> std = 255. * torch.ones(1, 4)
+ >>> mean = torch.zeros(4)
+ >>> std = 255. * torch.ones(4)
>>> out = normalize(x, mean, std)
>>> out.shape
torch.Size([1, 4, 3, 3])
"""
shape = data.shape
-
- if isinstance(mean, float):
- mean = torch.tensor([mean] * shape[1], device=data.device, dtype=data.dtype)
-
- if isinstance(std, float):
- std = torch.tensor([std] * shape[1], device=data.device, dtype=data.dtype)
-
- if not isinstance(data, torch.Tensor):
- raise TypeError("data should be a tensor. Got {}".format(type(data)))
-
- if not isinstance(mean, torch.Tensor):
- raise TypeError("mean should be a tensor or a float. Got {}".format(type(mean)))
-
- if not isinstance(std, torch.Tensor):
- raise TypeError("std should be a tensor or float. Got {}".format(type(std)))
+ if len(mean.shape) == 0 or mean.shape[0] == 1:
+ mean = mean.expand(shape[1])
+ if len(std.shape) == 0 or std.shape[0] == 1:
+ std = std.expand(shape[1])
# Allow broadcast on channel dimension
if 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 dimension
if 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/test/augmentation/test_augmentation.py b/test/augmentation/test_augmentation.py
index fac0b4530..0e413b05a 100644
--- a/test/augmentation/test_augmentation.py
+++ b/test/augmentation/test_augmentation.py
@@ -2603,6 +2603,27 @@ class TestNormalize:
)
assert str(f) == repr
+ @staticmethod
+ @pytest.mark.parametrize(
+ "mean, std", [((1.0, 1.0, 1.0), (0.5, 0.5, 0.5)), (1.0, 0.5), (torch.tensor([1.0]), torch.tensor([0.5]))]
+ )
+ def test_random_normalize_different_parameter_types(mean, std):
+ f = Normalize(mean=mean, std=std, p=1)
+ data = torch.ones(2, 3, 256, 313)
+ if isinstance(mean, float):
+ expected = (data - torch.tensor(mean)) / torch.tensor(std)
+ else:
+ expected = (data - torch.tensor(mean[0])) / torch.tensor(std[0])
+ assert_close(f(data), expected)
+
+ @staticmethod
+ @pytest.mark.parametrize("mean, std", [((1.0, 1.0, 1.0, 1.0), (0.5, 0.5, 0.5, 0.5)), ((1.0, 1.0), (0.5, 0.5))])
+ def test_random_normalize_invalid_parameter_shape(mean, std):
+ f = Normalize(mean=mean, std=std, p=1.0, return_transform=True)
+ inputs = torch.arange(0.0, 16.0, step=1).reshape(1, 4, 4).unsqueeze(0)
+ with pytest.raises(ValueError):
+ f(inputs)
+
def test_random_normalize(self, device, dtype):
f = Normalize(mean=torch.tensor([1.0]), std=torch.tensor([0.5]), p=1.0, return_transform=True)
f1 = Normalize(mean=torch.tensor([1.0]), std=torch.tensor([0.5]), p=0.0, return_transform=True)
diff --git a/test/enhance/test_normalize.py b/test/enhance/test_normalize.py
index 95a433080..c6a2edc38 100644
--- a/test/enhance/test_normalize.py
+++ b/test/enhance/test_normalize.py
@@ -11,7 +11,7 @@ class TestNormalize:
def test_smoke(self, device, dtype):
mean = [0.5]
std = [0.1]
- repr = "Normalize(mean=[0.5], std=[0.1])"
+ repr = "Normalize(mean=tensor([0.5000]), std=tensor([0.1000]))"
assert str(kornia.enhance.Normalize(mean, std)) == repr
def test_normalize(self, device, dtype):
@@ -117,6 +117,27 @@ class TestNormalize:
assert_close(op(*inputs), op_module(data))
+ @staticmethod
+ @pytest.mark.parametrize(
+ "mean, std", [((1.0, 1.0, 1.0), (0.5, 0.5, 0.5)), (1.0, 0.5), (torch.tensor([1.0]), torch.tensor([0.5]))]
+ )
+ def test_random_normalize_different_parameter_types(mean, std):
+ f = kornia.enhance.Normalize(mean=mean, std=std)
+ data = torch.ones(2, 3, 256, 313)
+ if isinstance(mean, float):
+ expected = (data - torch.tensor(mean)) / torch.tensor(std)
+ else:
+ expected = (data - torch.tensor(mean[0])) / torch.tensor(std[0])
+ assert_close(f(data), expected)
+
+ @staticmethod
+ @pytest.mark.parametrize("mean, std", [((1.0, 1.0, 1.0, 1.0), (0.5, 0.5, 0.5, 0.5)), ((1.0, 1.0), (0.5, 0.5))])
+ def test_random_normalize_invalid_parameter_shape(mean, std):
+ f = kornia.enhance.Normalize(mean=mean, std=std)
+ inputs = torch.arange(0.0, 16.0, step=1).reshape(1, 4, 4).unsqueeze(0)
+ with pytest.raises(ValueError):
+ f(inputs)
+
class TestDenormalize:
def test_smoke(self, device, dtype):