Skip to content

🐍 Geometric Computer Vision Library for Spatial AI

denormalize module (#331)

Diego80793b4ca60a
diff --git a/docs/source/color.rst b/docs/source/color.rst
index d2f9ab445..6241ed322 100644
--- a/docs/source/color.rst
+++ b/docs/source/color.rst
@@ -14,6 +14,7 @@ The functions in this section perform various color space conversions.
.. autofunction:: rgb_to_bgr
.. autofunction:: bgr_to_rgb
.. autofunction:: normalize
+.. autofunction:: denormalize
.. autofunction:: adjust_brightness
.. autofunction:: adjust_contrast
.. autofunction:: adjust_saturation
@@ -31,6 +32,7 @@ The functions in this section perform various color space conversions.
.. autoclass:: RgbToBgr
.. autoclass:: BgrToRgb
.. autoclass:: Normalize
+.. autoclass:: Denormalize
.. autoclass:: AdjustBrightness
.. autoclass:: AdjustContrast
.. autoclass:: AdjustSaturation
diff --git a/kornia/__init__.py b/kornia/__init__.py
index 3ecfb1ae5..1f6ddf0e6 100644
--- a/kornia/__init__.py
+++ b/kornia/__init__.py
@@ -27,6 +27,7 @@ from kornia.color import (
rgb_to_hls,
hls_to_rgb,
normalize,
+ denormalize,
adjust_brightness,
adjust_contrast,
adjust_gamma,
diff --git a/kornia/color/__init__.py b/kornia/color/__init__.py
index 0dab3d3c5..d26278f8b 100644
--- a/kornia/color/__init__.py
+++ b/kornia/color/__init__.py
@@ -6,7 +6,7 @@ from .hsv import RgbToHsv, rgb_to_hsv
from .hsv import HsvToRgb, hsv_to_rgb
from .hls import RgbToHls, rgb_to_hls
from .hls import HlsToRgb, hls_to_rgb
-from .normalize import Normalize, normalize
+from .normalize import Normalize, normalize, Denormalize, denormalize
from .core import add_weighted, AddWeighted
from .adjust import (
AdjustBrightness, AdjustContrast, AdjustGamma, AdjustHue, AdjustSaturation,
@@ -25,6 +25,7 @@ __all__ = [
"rgb_to_hls",
"hls_to_rgb",
"normalize",
+ "denormalize",
"adjust_brightness",
"adjust_contrast",
"adjust_gamma",
@@ -41,6 +42,7 @@ __all__ = [
"RgbToHls",
"HlsToRgb",
"Normalize",
+ "Denormalize",
"AdjustBrightness",
"AdjustContrast",
"AdjustGamma",
diff --git a/kornia/color/normalize.py b/kornia/color/normalize.py
index 1049d0f09..872c2b9ea 100644
--- a/kornia/color/normalize.py
+++ b/kornia/color/normalize.py
@@ -81,3 +81,82 @@ def normalize(
out: torch.Tensor = (data - mean) / std
return out
+
+
+class Denormalize(nn.Module):
+ r"""Denormalize a tensor image or a batch of tensor images
+ . Input must be a tensor of shape (C, H, W) or a batch of tensors :math:`(*, C, H, W)`.
+
+ Given mean: ``(M1,...,Mn)`` and std: ``(S1,..,Sn)`` for ``n`` channels,
+ this transform will denormalize each channel of the input ``torch.Tensor``
+ i.e. ``input[channel] = (input[channel] * std[channel]) + mean[channel]``
+
+ Args:
+ mean (torch.Tensor or float): Mean for each channel.
+ std (torch.Tensor or float): Standard deviations for each channel.
+ """
+
+ def __init__(self, mean: Union[torch.Tensor, float], std: Union[torch.Tensor, float]) -> None:
+
+ super(Denormalize, self).__init__()
+
+ self.mean = mean
+ self.std = std
+
+ def forward(self, input: torch.Tensor) -> torch.Tensor: # type: ignore
+ return denormalize(input, self.mean, self.std)
+
+ def __repr__(self):
+ repr = "(mean={0}, std={1})".format(self.mean, self.std)
+ return self.__class__.__name__ + repr
+
+
+def denormalize(
+ data: torch.Tensor, mean: Union[torch.Tensor, float], std: Union[torch.Tensor, float]
+) -> torch.Tensor:
+ r"""Denormalize the image given 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 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)))
+
+ if not torch.is_tensor(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 or float. Got {}".format(type(std)))
+
+ # 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]:
+ raise ValueError("mean length and number of channels do not match")
+
+ # 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]:
+ raise ValueError("std length and number of channels do not match")
+
+ if mean.shape:
+ mean = mean[..., :, None, None].to(data.device)
+ if std.shape:
+ std = std[..., :, None, None].to(data.device)
+
+ out: torch.Tensor = (data * std) + mean
+
+ return out
diff --git a/test/color/test_normalize.py b/test/color/test_normalize.py
index ae074e5d9..704e23f07 100644
--- a/test/color/test_normalize.py
+++ b/test/color/test_normalize.py
@@ -110,3 +110,108 @@ class TestNormalize:
expected = (data - mean) / std
assert_allclose(kornia.normalize(data, mean, std), expected)
+
+
+class TestDenormalize:
+ def test_smoke(self):
+ mean = [0.5]
+ std = [0.1]
+ repr = "Denormalize(mean=[0.5], std=[0.1])"
+ assert str(kornia.color.Denormalize(mean, std)) == repr
+
+ def test_denormalize(self):
+
+ # prepare input data
+ data = torch.ones(1, 2, 2)
+ mean = torch.tensor([0.5])
+ std = torch.tensor([2.0])
+
+ # expected output
+ expected = torch.tensor([2.5]).repeat(1, 2, 2).view_as(data)
+
+ f = kornia.color.Denormalize(mean, std)
+ assert_allclose(f(data), expected)
+
+ def test_broadcast_denormalize(self):
+
+ # prepare input data
+ data = torch.ones(2, 3, 1, 1)
+ data += 2
+
+ mean = torch.tensor([2.0])
+ std = torch.tensor([0.5])
+
+ # expected output
+ expected = torch.ones_like(data) + 2.5
+
+ f = kornia.color.Denormalize(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) + 2.5
+
+ f = kornia.color.Denormalize(mean, std)
+ assert_allclose(f(data), expected)
+
+ def test_batch_denormalize(self):
+
+ # prepare input data
+ data = torch.ones(2, 3, 1, 1)
+ data += 2
+
+ 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 output
+ expected = torch.tensor([6.5, 7, 8]).repeat(2, 1, 1).view_as(data)
+
+ f = kornia.color.Denormalize(mean, std)
+ assert_allclose(f(data), expected)
+
+ @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:
+ return kornia.denormalize(data, mean, std)
+
+ data = torch.ones(2, 3, 1, 1)
+ data += 2
+
+ mean = torch.tensor([0.5, 1.0, 2.0]).repeat(2, 1)
+ std = torch.tensor([2.0, 2.0, 2.0]).repeat(2, 1)
+
+ actual = op_script(data, mean, std)
+ expected = kornia.denormalize(data, mean, std)
+ assert_allclose(actual, expected)
+
+ def test_gradcheck(self):
+
+ # prepare input data
+ data = torch.ones(2, 3, 1, 1)
+ data += 2
+ mean = torch.tensor([0.5, 1.0, 2.0]).double()
+ std = torch.tensor([2.0, 2.0, 2.0]).double()
+
+ data = utils.tensor_to_gradcheck_var(data) # to var
+
+ assert gradcheck(kornia.color.Denormalize(mean, std), (data,), raise_exception=True)
+
+ def test_single_value(self):
+
+ # prepare input data
+ mean = torch.tensor(2)
+ std = torch.tensor(3)
+ data = torch.ones(2, 3, 256, 313).float()
+
+ # expected output
+ expected = (data * std) + mean
+
+ assert_allclose(kornia.denormalize(data, mean, std), expected)