🐍 Geometric Computer Vision Library for Spatial AI
Python artificial-intelligencecomputer-visiondeep-learninghacktoberfestimage-processingmachine-learningneural-networkpythonpytorchroboticsspatial-ai
implement adjust_gamma
edgarriba9b1452eeaabf
diff --git a/kornia/__init__.py b/kornia/__init__.pyindex c08881d0c..f93fa94d2 100644--- a/kornia/__init__.py+++ b/kornia/__init__.py@@ -25,6 +25,7 @@ from kornia.color import (normalize,adjust_brightness,adjust_contrast,+ adjust_gamma,)from kornia.contrib import (extract_tensor_patches,diff --git a/kornia/color/__init__.py b/kornia/color/__init__.pyindex a811925e6..5afcc42b7 100644--- a/kornia/color/__init__.py+++ b/kornia/color/__init__.py@@ -4,7 +4,7 @@ from .rgb import RgbToBgr, rgb_to_bgrfrom .hsv import RgbToHsv, rgb_to_hsvfrom .hsv import HsvToRgb, hsv_to_rgbfrom .normalize import Normalize, normalize-from .adjust import AdjustBrightness, AdjustContrast, adjust_brightness, adjust_contrast+from .adjust import AdjustBrightness, AdjustContrast, AdjustGamma, adjust_brightness, adjust_contrast, adjust_gamma__all__ = ["rgb_to_grayscale",@@ -15,6 +15,7 @@ __all__ = ["normalize","adjust_brightness","adjust_contrast",+ "adjust_gamma","RgbToGrayscale","BgrToRgb","RgbToBgr",@@ -23,5 +24,5 @@ __all__ = ["Normalize","AdjustBrightness","AdjustContrast",-+ "AdjustGamma",]diff --git a/kornia/color/adjust.py b/kornia/color/adjust.pyindex 915eeab0f..3c6539e89 100644--- a/kornia/color/adjust.py+++ b/kornia/color/adjust.py@@ -4,6 +4,30 @@ import torchimport torch.nn as nn+def adjust_gamma(input: torch.Tensor, gamma: float, gain: float = 1.) -> torch.Tensor:+ r"""Perform gamma correction on an image.++ See :class:`~kornia.color.AdjustGamma` for details.+ """++ if not torch.is_tensor(input):+ raise TypeError(f"Input type is not a torch.Tensor. Got {type(input)}")++ if not isinstance(gamma, float) and gamma > 0.:+ raise TypeError(f"The gamma should be a positive a float. Got {type(gamma)}")++ if not isinstance(gain, float) and gain >= 1.:+ raise TypeError(f"The gamma should be a positive a float. Got {type(gain)}")++ # Apply the gamma correction+ x_adjust: torch.Tensor = gain * torch.pow(input, gamma)++ # Truncate between pixel values+ out: torch.Tensor = torch.clamp(x_adjust, 0.0, 1.0)++ return out++def adjust_contrast(input: torch.Tensor,contrast_factor: Union[float, torch.Tensor]) -> torch.Tensor:r"""Adjust Contrast of an image.@@ -23,7 +47,7 @@ def adjust_contrast(input: torch.Tensor,contrast_factor = contrast_factor.to(input.device).to(input.dtype)- if (contrast_factor < torch.zeros(1)).any():+ if (contrast_factor < 0).any():raise ValueError(f"Contrast factor must be non-negative. Got {contrast_factor}")for _ in input.shape[1:]:@@ -57,7 +81,7 @@ def adjust_brightness(input: torch.Tensor,brightness_factor = brightness_factor.to(input.device).to(input.dtype)- if (brightness_factor < torch.zeros(1)).any():+ if (brightness_factor < 0).any():raise ValueError(f"Brightness factor must be non-negative. Got {brightness_factor}")for _ in input.shape[1:]:@@ -72,6 +96,31 @@ def adjust_brightness(input: torch.Tensor,return out+class AdjustGamma(nn.Module):+ r"""Perform gamma correction on an image.++ The input image is expected to be in the range of [0, 1].++ Args:+ image (torch.Tensor): Image to be adjusted in the shape of (*, N).+ gamma (float): Non negative real number, same as γ\gammaγ in the equation.+ gamma larger than 1 make the shadows darker, while gamma smaller than 1 make+ dark regions lighter.+ gain (float optional): The constant multiplier. Default 1.++ Returns:+ torch.Tensor: Adjusted image.+ """++ def __init__(self, gamma: float, gain: float = 1.) -> None:+ super(AdjustGamma, self).__init__()+ self.gamma: float = gamma+ self.gain: float = gain++ def forward(self, input: torch.Tensor) -> torch.Tensor: # type: ignore+ return adjust_gamma(input, self.gamma, self.gain)++class AdjustContrast(nn.Module):r"""Adjust Contrast of an image.@@ -118,5 +167,3 @@ class AdjustBrightness(nn.Module):def forward(self, input: torch.Tensor) -> torch.Tensor: # type: ignorereturn adjust_brightness(input, self.brightness_factor)--diff --git a/test/color/test_adjust.py b/test/color/test_adjust.pyindex 505c70b91..f1a5314c2 100644--- a/test/color/test_adjust.py+++ b/test/color/test_adjust.py@@ -9,6 +9,87 @@ from torch.autograd import gradcheckfrom torch.testing import assert_allclose+class TestAdjustGamma:+ def test_gamma_zero(self):+ data = torch.tensor([[[1., 1.],+ [1., 1.]],++ [[.5, .5],+ [.5, .5]],++ [[.25, .25],+ [.25, .25]]]) # 3x2x2++ expected = torch.ones_like(data)+ f = kornia.color.AdjustGamma(0.)+ assert_allclose(f(data), expected)++ def test_gamma_one(self):+ data = torch.tensor([[[1., 1.],+ [1., 1.]],++ [[.5, .5],+ [.5, .5]],++ [[.25, .25],+ [.25, .25]]]) # 3x2x2++ expected = data+ f = kornia.color.AdjustGamma(1.)+ assert_allclose(f(data), expected)++ def test_gamma_one_gain_two(self):+ data = torch.tensor([[[1., 1.],+ [1., 1.]],++ [[.5, .5],+ [.5, .5]],++ [[.25, .25],+ [.25, .25]]]) # 3x2x2++ expected = torch.tensor([[[1., 1.],+ [1., 1.]],++ [[1., 1.],+ [1., 1.]],++ [[.5, .5],+ [.5, .5]]]) # 3x2x2++ f = kornia.color.AdjustGamma(1., 2.)+ assert_allclose(f(data), expected)++ def test_gamma_two(self):+ data = torch.tensor([[[1., 1.],+ [1., 1.]],++ [[.5, .5],+ [.5, .5]],++ [[.25, .25],+ [.25, .25]]]) # 3x2x2++ expected = torch.tensor([[[1., 1.],+ [1., 1.]],++ [[.25, .25],+ [.25, .25]],++ [[.0625, .0625],+ [.0625, .0625]]]) # 3x2x2++ f = kornia.color.AdjustGamma(2.)+ assert_allclose(f(data), expected)++ def test_gradcheck(self):+ batch_size, channels, height, width = 2, 3, 4, 5+ img = torch.ones(batch_size, channels, height, width)+ img = utils.tensor_to_gradcheck_var(img) # to var+ assert gradcheck(kornia.adjust_gamma, (img, 1., 2.),+ raise_exception=True)++class TestAdjustContrast:def test_factor_zero(self):# prepare input data@@ -24,7 +105,6 @@ class TestAdjustContrast:expected = dataf = kornia.color.AdjustContrast(0.)-assert_allclose(f(data), expected)def test_factor_one(self):@@ -41,7 +121,6 @@ class TestAdjustContrast:expected = torch.ones_like(data)f = kornia.color.AdjustContrast(1.)-assert_allclose(f(data), expected)def test_factor_tensor(self):@@ -106,6 +185,13 @@ class TestAdjustContrast:f = kornia.color.AdjustContrast(factor)assert_allclose(f(data), expected)+ def test_gradcheck(self):+ batch_size, channels, height, width = 2, 3, 4, 5+ img = torch.ones(batch_size, channels, height, width)+ img = utils.tensor_to_gradcheck_var(img) # to var+ assert gradcheck(kornia.adjust_contrast, (img, 2.),+ raise_exception=True)+class TestAdjustBrightness:def test_factor_zero(self):@@ -285,3 +371,10 @@ class TestAdjustBrightness:factor = torch.tensor([1.5, 2.])f = kornia.color.AdjustBrightness(factor)assert_allclose(f(data), expected)++ def test_gradcheck(self):+ batch_size, channels, height, width = 2, 3, 4, 5+ img = torch.ones(batch_size, channels, height, width)+ img = utils.tensor_to_gradcheck_var(img) # to var+ assert gradcheck(kornia.adjust_brightness, (img, 2.),+ raise_exception=True)