π Geometric Computer Vision Library for Spatial AI
Python artificial-intelligencecomputer-visiondeep-learninghacktoberfestimage-processingmachine-learningneural-networkpythonpytorchroboticsspatial-ai
[Feat] Adds normalize_min_max functionality (#684)
Edgar Ribaf53ced556e62
diff --git a/docs/source/enhance.rst b/docs/source/enhance.rstindex f99c92b72..69c13a295 100644--- a/docs/source/enhance.rst+++ b/docs/source/enhance.rst@@ -13,6 +13,7 @@ The functions in this section perform normalisations and intensity transformatio.. autofunction:: add_weighted.. autofunction:: normalize+.. autofunction:: normalize_min_max.. autofunction:: denormalize.. autofunction:: zca_mean.. autofunction:: zca_whitendiff --git a/kornia/__init__.py b/kornia/__init__.pyindex a7db2ff6a..a078c0d7e 100644--- a/kornia/__init__.py+++ b/kornia/__init__.py@@ -47,6 +47,7 @@ from kornia.color import ()from kornia.enhance import (normalize,+ normalize_min_max,denormalize,zca_mean,zca_whiten,diff --git a/kornia/enhance/__init__.py b/kornia/enhance/__init__.pyindex 0479c282f..a7b956c1f 100644--- a/kornia/enhance/__init__.py+++ b/kornia/enhance/__init__.py@@ -1,61 +1,5 @@-'''from .gray import rgb_to_grayscale, RgbToGrayscale-from .gray import bgr_to_grayscale, BgrToGrayscale-from .rgb import BgrToRgb, bgr_to_rgb-from .rgb import RgbToBgr, rgb_to_bgr-from .rgb import RgbToRgba, rgb_to_rgba-from .rgb import BgrToRgba, bgr_to_rgba-from .rgb import RgbaToRgb, rgba_to_rgb-from .rgb import RgbaToBgr, rgba_to_bgr-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 .ycbcr import RgbToYcbcr, rgb_to_ycbcr-from .ycbcr import YcbcrToRgb, ycbcr_to_rgb-from .yuv import RgbToYuv, YuvToRgb, rgb_to_yuv, yuv_to_rgb-from .xyz import RgbToXyz, XyzToRgb, rgb_to_xyz, xyz_to_rgb-from .luv import RgbToLuv, LuvToRgb, rgb_to_luv, luv_to_rgb'''-from .normalize import Normalize, normalize, Denormalize, denormalize-from .zca import zca_mean, ZCAWhitening, zca_whiten, linear_transform-from .core import add_weighted, AddWeighted-from .histogram import histogram, histogram2d-from .adjust import (- AdjustBrightness, AdjustContrast, AdjustGamma, AdjustHue, AdjustSaturation,-)-from .adjust import (- adjust_brightness, adjust_contrast, adjust_gamma, adjust_hue, adjust_saturation,- adjust_hue_raw, adjust_saturation_raw, solarize, equalize, equalize3d, posterize, sharpness-)---__all__ = [- "normalize",- "denormalize",- "zca_mean",- "zca_whiten",- "linear_transform",- "histogram",- "histogram2d",- "adjust_brightness",- "adjust_contrast",- "adjust_gamma",- "adjust_hue",- "adjust_saturation",- "adjust_hue_raw",- "adjust_saturation_raw",- "solarize",- "equalize",- "equalize3d",- "posterize",- "sharpness",- "add_weighted",- "AddWeighted",- "ZCAWhitening",- "Normalize",- "Denormalize",- "AdjustBrightness",- "AdjustContrast",- "AdjustGamma",- "AdjustHue",- "AdjustSaturation",-]+from kornia.enhance.normalize import *+from kornia.enhance.zca import *+from kornia.enhance.core import *+from kornia.enhance.histogram import *+from kornia.enhance.adjust import *diff --git a/kornia/enhance/adjust.py b/kornia/enhance/adjust.pyindex de9680492..8d5d0fe54 100644--- a/kornia/enhance/adjust.py+++ b/kornia/enhance/adjust.py@@ -10,6 +10,27 @@ from kornia.utils.image import _to_bchwfrom kornia.constants import pi+__all__ = [+ "adjust_brightness",+ "adjust_contrast",+ "adjust_gamma",+ "adjust_hue",+ "adjust_saturation",+ "adjust_hue_raw",+ "adjust_saturation_raw",+ "solarize",+ "equalize",+ "equalize3d",+ "posterize",+ "sharpness",+ "AdjustBrightness",+ "AdjustContrast",+ "AdjustGamma",+ "AdjustHue",+ "AdjustSaturation",+]++def adjust_saturation_raw(input: torch.Tensor, saturation_factor: Union[float, torch.Tensor]) -> torch.Tensor:r"""Adjust color saturation of an image. Expecting input to be in hsv format already.diff --git a/kornia/enhance/core.py b/kornia/enhance/core.pyindex 9033e7d2e..57630a551 100644--- a/kornia/enhance/core.py+++ b/kornia/enhance/core.py@@ -2,6 +2,12 @@ import torchimport torch.nn as nn+__all__ = [+ "add_weighted",+ "AddWeighted",+]++def add_weighted(src1: torch.Tensor, alpha: float,src2: torch.Tensor, beta: float,gamma: float) -> torch.Tensor:diff --git a/kornia/enhance/histogram.py b/kornia/enhance/histogram.pyindex 646830459..281c36a08 100644--- a/kornia/enhance/histogram.py+++ b/kornia/enhance/histogram.py@@ -1,8 +1,15 @@from typing import Tuple, List+import torchimport torch.nn as nn+__all__ = [+ "histogram",+ "histogram2d",+]++def marginal_pdf(values: torch.Tensor, bins: torch.Tensor, sigma: torch.Tensor,epsilon: float = 1e-10) -> Tuple[torch.Tensor, torch.Tensor]:"""diff --git a/kornia/enhance/normalize.py b/kornia/enhance/normalize.pyindex fb8467c0f..45a5a37b1 100644--- a/kornia/enhance/normalize.py+++ b/kornia/enhance/normalize.py@@ -6,6 +6,15 @@ import torchimport torch.nn as nn+__all__ = [+ "normalize",+ "normalize_min_max",+ "denormalize",+ "Normalize",+ "Denormalize",+]++class Normalize(nn.Module):r"""Normalize a tensor image or a batch of tensor images with mean and standard deviation.@@ -184,3 +193,46 @@ def denormalize(out: torch.Tensor = (data * std) + meanreturn out+++def normalize_min_max(x: torch.Tensor, min_val: float = 0., max_val: float = 1., eps: float = 1e-6) -> torch.Tensor:+ r"""Normalise an image tensor by MinMax and re-scales the value between a range.++ The data is normalised using the following formulation:++ .. math::+ y_i = (b - a) * \frac{x_i - \text{min}(x)}{\text{max}(x) - \text{min}(x)} + a++ where :math:`a` is :math:`\text{min_val}` and :math:`b` is :math:`\text{max_val}`.++ Args:+ x (torch.Tensor): The image tensor to be normalised with shape :math:`(B, C, H, W)`.+ min_val (float): The minimum value for the new range. Default: 0.+ max_val (float): The maximum value for the new range. Default: 1.+ eps (float): Float number to avoid zero division. Default: 1e-6.++ Returns:+ torch.Tensor: The normalised image tensor with same shape as input :math:`(B, C, H, W)`.++ """+ if not isinstance(x, torch.Tensor):+ raise TypeError(f"data should be a tensor. Got: {type(x)}.")++ if not isinstance(min_val, float):+ raise 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) != 4:+ raise ValueError(f"Input shape must be a 4d tensor. Got: {x.shape}.")++ B, C, H, W = x.shape++ x_min: torch.Tensor = x.view(B, C, -1).min(-1)[0].view(B, C, 1, 1)+ x_max: torch.Tensor = x.view(B, C, -1).max(-1)[0].view(B, C, 1, 1)++ x_out: torch.Tensor = (+ (max_val - min_val) * (x - x_min) / (x_max - x_min + eps) + min_val+ )+ return x_out.expand_as(x)diff --git a/kornia/enhance/zca.py b/kornia/enhance/zca.pyindex dae4f5a9d..d287c172d 100644--- a/kornia/enhance/zca.py+++ b/kornia/enhance/zca.py@@ -5,6 +5,14 @@ import torchimport torch.nn as nn+__all__ = [+ "zca_mean",+ "zca_whiten",+ "linear_transform",+ "ZCAWhitening",+]++class ZCAWhitening(nn.Module):r"""diff --git a/kornia/testing/__init__.py b/kornia/testing/__init__.pyindex 31b830193..b2850129b 100644--- a/kornia/testing/__init__.py+++ b/kornia/testing/__init__.py@@ -1,11 +1,12 @@"""The testing package contains testing-specific utilities."""-+from abc import ABC, abstractmethodimport torchimport numpy as np+__all__ = ['tensor_to_gradcheck_var', 'create_eye_batch',]@@ -71,3 +72,25 @@ def create_random_fundamental_matrix(batch_size, std_val=1e-3):H_left = create_random_homography(batch_size, 3, std_val)H_right = create_random_homography(batch_size, 3, std_val)return H_left.permute(0, 2, 1) @ F_rect @ H_right+++class BaseTester(ABC):+ @abstractmethod+ def test_smoke(self):+ raise NotImplementedError("Implement a stupid routine.")++ @abstractmethod+ def test_exception(self):+ raise NotImplementedError("Implement a stupid routine.")++ @abstractmethod+ def test_batch(self):+ raise NotImplementedError("Implement a stupid routine.")++ @abstractmethod+ def test_jit(self):+ raise NotImplementedError("Implement a stupid routine.")++ @abstractmethod+ def test_gradcheck(self):+ raise NotImplementedError("Implement a stupid routine.")diff --git a/test/enhance/test_normalize.py b/test/enhance/test_normalize.pyindex b06ba5a03..9a0a53edc 100644--- a/test/enhance/test_normalize.py+++ b/test/enhance/test_normalize.py@@ -2,6 +2,7 @@ import pytestimport korniaimport kornia.testing as utils # test utils+from kornia.testing import BaseTesterimport torchfrom torch.autograd import gradcheck@@ -217,3 +218,64 @@ class TestDenormalize:expected = (data * std) + meanassert_allclose(kornia.denormalize(data, mean, std), expected)+++class TestNormalizeMinMax(BaseTester):+ def test_smoke(self, device, dtype):+ x = torch.ones(1, 1, 1, 1, device=device, dtype=dtype)+ assert kornia.normalize_min_max(x) is not None+ assert kornia.enhance.normalize_min_max(x) is not None++ def test_exception(self, device, dtype):+ x = torch.ones(1, 1, 3, 4, device=device, dtype=dtype)+ with pytest.raises(TypeError):+ assert kornia.normalize_min_max(0.)++ with pytest.raises(ValueError):+ assert kornia.normalize_min_max(x[0])++ with pytest.raises(TypeError):+ assert kornia.normalize_min_max(x, '', '')++ with pytest.raises(TypeError):+ assert kornia.normalize_min_max(x, 2., '')++ @pytest.mark.parametrize("input_shape", [+ (1, 2, 3, 4), (2, 1, 4, 3), (1, 3, 2, 1)])+ def test_batch(self, device, dtype, input_shape):+ x = torch.rand(input_shape, device=device, dtype=dtype)+ assert kornia.normalize_min_max(x).shape == input_shape++ @pytest.mark.parametrize("min_val, max_val", [+ (1., 2.), (2., 3.), (5., 20.), (40., 1000.)])+ def test_range(self, device, dtype, min_val, max_val):+ x = torch.rand(1, 2, 4, 5, device=device, dtype=dtype)+ out = kornia.normalize_min_max(x, min_val=min_val, max_val=max_val)+ assert_allclose(out.min(), min_val)+ assert_allclose(out.max(), max_val)++ def test_values(self, device, dtype):+ x = torch.tensor([[[+ [0., 1., 3.],+ [-1., 4., 3.],+ [9., 5., 2.],+ ]]], device=device, dtype=dtype)++ expected = torch.tensor([[[+ [-0.8, -0.6, -0.2],+ [-1., 0., -0.2],+ [1., 0.2, -0.4],+ ]]], device=device, dtype=dtype)++ actual = kornia.normalize_min_max(x, min_val=-1., max_val=1.)+ assert_allclose(actual, expected, atol=1e-6, rtol=1e-6)++ def test_jit(self, device, dtype):+ x = torch.ones(1, 1, 1, 1, device=device, dtype=dtype)+ op = kornia.normalize_min_max+ op_jit = torch.jit.script(op)+ assert_allclose(op(x), op_jit(x))++ def test_gradcheck(self, device, dtype):+ x = torch.ones(1, 1, 1, 1, device=device, dtype=torch.float64, requires_grad=True)+ assert gradcheck(kornia.normalize_min_max, (x,), raise_exception=True)