π Geometric Computer Vision Library for Spatial AI
Python artificial-intelligencecomputer-visiondeep-learninghacktoberfestimage-processingmachine-learningneural-networkpythonpytorchroboticsspatial-ai
Feat/random snow (#2229)
Angelo70cc420c82a2
diff --git a/kornia/augmentation/_2d/intensity/__init__.py b/kornia/augmentation/_2d/intensity/__init__.pyindex 17705efc2..53f78be9e 100644--- a/kornia/augmentation/_2d/intensity/__init__.py+++ b/kornia/augmentation/_2d/intensity/__init__.py@@ -21,6 +21,7 @@ from kornia.augmentation._2d.intensity.planckian_jitter import RandomPlanckianJifrom kornia.augmentation._2d.intensity.plasma import RandomPlasmaBrightness, RandomPlasmaContrast, RandomPlasmaShadowfrom kornia.augmentation._2d.intensity.posterize import RandomPosterizefrom kornia.augmentation._2d.intensity.random_rgb_shift import RandomRGBShift+from kornia.augmentation._2d.intensity.random_snow import RandomSnowfrom kornia.augmentation._2d.intensity.saturation import RandomSaturationfrom kornia.augmentation._2d.intensity.sharpness import RandomSharpnessfrom kornia.augmentation._2d.intensity.solarize import RandomSolarizediff --git a/kornia/augmentation/_2d/intensity/random_snow.py b/kornia/augmentation/_2d/intensity/random_snow.pynew file mode 100644index 000000000..52f6d76be--- /dev/null+++ b/kornia/augmentation/_2d/intensity/random_snow.py@@ -0,0 +1,76 @@+from typing import Any, Dict, Optional, Tuple++import torch++from kornia.augmentation import random_generator as rg+from kornia.augmentation._2d.intensity.base import IntensityAugmentationBase2D+from kornia.color import hls_to_rgb, rgb_to_hls+from kornia.core import Tensor+from kornia.core.check import KORNIA_CHECK+++class RandomSnow(IntensityAugmentationBase2D):+ r"""Generates snow effect on given tensor image or a batch tensor images.++ Args:+ snow_coefficient: A tuple of floats (lower and upper bound) between 0 and 1 that control+ the amount of snow to add to the image, the larger value corresponds to the more snow.+ brightness: A tuple of floats (lower and upper bound) greater than 1 that controls the+ brightness of the snow.+ same_on_batch: If True, apply the same transformation to each image in a batch. Default: False.+ p: Probability of applying the transformation. Default: 0.5.+ keepdim: Keep the output tensor with the same shape as input. Default: False.++ Shape:+ - Input: :math:`(C, H, W)` or :math:`(B, C, H, W)`+ - Output: :math:`(B, C, H, W)`++ Examples:+ >>> inputs = torch.rand(2, 3, 4, 4)+ >>> snow = kornia.augmentation.RandomSnow(p=1.0, snow_coefficient=(0.1, 0.6), brightness=(1.0, 5.0))+ >>> output = snow(inputs)+ >>> output.shape+ torch.Size([2, 3, 4, 4])+ """++ def __init__(+ self,+ snow_coefficient: Tuple[float, float] = (0.5, 0.5),+ brightness: Tuple[float, float] = (2, 2),+ same_on_batch: bool = False,+ p: float = 1.0,+ keepdim: bool = False,+ ) -> None:+ super().__init__(p=p, same_on_batch=same_on_batch, keepdim=keepdim)+ KORNIA_CHECK(all([0 <= el <= 1 for el in snow_coefficient]), "Snow coefficient values must be between 0 and 1.")+ KORNIA_CHECK(all([1 <= el for el in brightness]), "Brightness values must be greater than 1.")++ self._param_generator = rg.PlainUniformGenerator(+ (snow_coefficient, "snow_coefficient", 0.5, (0.0, 1.0)), (brightness, "brightness", None, None)+ )++ def apply_transform(+ self, input: Tensor, params: Dict[str, Tensor], flags: Dict[str, Any], transform: Optional[Tensor] = None+ ) -> Tensor:+ KORNIA_CHECK(input.shape[1] == 3, "Number of color channels should be 3.")+ KORNIA_CHECK(len(input.shape) in (3, 4), "Wrong input dimension.")++ if len(input.shape) == 3:+ input = input[None, :, :, :]+ input_HLS = rgb_to_hls(input)++ mask = torch.zeros_like(input_HLS)+ # Retrieve generated parameters+ snow_coefficient = params["snow_coefficient"].to(input)+ brightness = params["brightness"].to(input)+ snow_coefficient = snow_coefficient[:, None, None, None]+ brightness = brightness[:, None, None, None]++ mask[:, 1, :, :] = torch.where(input_HLS[:, 1, :, :] < snow_coefficient[:, 0, :, :], 1, 0)++ # Increase Light channel of the image by given brightness for areas based on snow coefficient.+ new_light = (input_HLS * mask * brightness).clamp(min=0.0, max=1.0)+ input_HLS = input_HLS * (1 - mask) + new_light++ output = hls_to_rgb(input_HLS)+ return outputdiff --git a/kornia/augmentation/__init__.py b/kornia/augmentation/__init__.pyindex edd0e3e2b..deea44669 100644--- a/kornia/augmentation/__init__.py+++ b/kornia/augmentation/__init__.py@@ -45,6 +45,7 @@ from kornia.augmentation._2d import (RandomSaturation,RandomSharpness,RandomShear,+ RandomSnow,RandomSolarize,RandomThinPlateSpline,RandomTranslate,@@ -126,6 +127,7 @@ __all__ = ["RandomSaturation","RandomSolarize","RandomSharpness",+ "RandomSnow","RandomPosterize","RandomEqualize","RandomMotionBlur",diff --git a/test/augmentation/test_augmentation.py b/test/augmentation/test_augmentation.pyindex abcc3f9d4..966d26e45 100644--- a/test/augmentation/test_augmentation.py+++ b/test/augmentation/test_augmentation.py@@ -41,6 +41,7 @@ from kornia.augmentation import (RandomRGBShift,RandomRotation,RandomSaturation,+ RandomSnow,RandomThinPlateSpline,RandomVerticalFlip,Resize,@@ -4115,6 +4116,58 @@ class TestRandomAutoContrast:assert gradcheck(kornia.augmentation.RandomAutoContrast(p=1.0), (input,), raise_exception=True, fast_mode=True)+class TestRandomSnow(BaseTester):+ torch.manual_seed(0) # for random reproductibility++ def _get_exception_test_data(self, device, dtype):+ err_msg_sw_coef = 'Snow coefficient values must be between 0 and 1.'+ err_msg_brght_coef = 'Brightness values must be greater than 1.'+ err_msg_wrong_ch = 'Number of color channels should be 3.'+ err_msg_wrong_sh = 'Input size must have a shape of either (H, W), (C, H, W) or (*, C, H, W).'++ return [+ (err_msg_sw_coef, (-0.3, 0.6), (1.2, 3.4), torch.rand(1, 3, 3, device=device, dtype=dtype)),+ (err_msg_sw_coef, (0.3, -0.9), (1.3, 2.5), torch.rand(1, 3, 4, device=device, dtype=dtype)),+ (err_msg_sw_coef, (-0.6, -0.9), (1.1, 3.1), torch.rand(2, 3, 4, device=device, dtype=dtype)),+ (err_msg_brght_coef, (0.1, 0.7), (0.3, 1.5), torch.rand(1, 3, 5, device=device, dtype=dtype)),+ (err_msg_brght_coef, (0.4, 0.6), (1.3, 0.8), torch.rand(1, 3, 6, device=device, dtype=dtype)),+ (err_msg_brght_coef, (0.3, 0.9), (0.5, 0.7), torch.rand(1, 3, 7, device=device, dtype=dtype)),+ (err_msg_wrong_ch, (0.2, 0.8), (1.6, 3.7), torch.rand(1, 4, 7, device=device, dtype=dtype)),+ (err_msg_wrong_sh, (0.1, 0.5), (1.1, 2.5), torch.rand(1, 2, 3, 4, 5, device=device, dtype=dtype)),+ ]++ @pytest.mark.parametrize("batch_shape", [(1, 3, 4, 7), (1, 3, 6, 9)])+ def test_cardinality(self, batch_shape, device, dtype):+ input_data = torch.rand(batch_shape, device=device, dtype=dtype)+ aug = RandomSnow(p=1.0, snow_coefficient=(0.0, 0.5), brightness=(1.0, 3.0))+ output_data = aug(input_data)+ assert output_data.shape == batch_shape++ def test_smoke(self, device, dtype):+ input_data = torch.rand(1, 3, 8, 9, device=device, dtype=dtype)+ aug = RandomSnow(p=1.0, snow_coefficient=(0.0, 0.5), brightness=(1.0, 2.0))+ output_data = aug(input_data)+ assert output_data.shape == input_data.shape++ def test_gradcheck(self, device):+ input_data = torch.rand(1, 3, 6, 8, device=device)+ grad_input = utils.tensor_to_gradcheck_var(input_data)+ self.gradcheck(RandomSnow(p=1.0), (grad_input,))++ def test_exception(self, device, dtype):+ exception_test_data = self._get_exception_test_data(device, dtype)+ for err_msg, snow_coef, brght_coef, input_data in exception_test_data:+ with pytest.raises(Exception) as errinfo:+ aug = RandomSnow(p=1.0, snow_coefficient=snow_coef, brightness=brght_coef)+ aug(input_data)++ assert err_msg in str(errinfo)++ @pytest.mark.skip(reason="not implemented yet")+ def test_module(self, device, dtype):+ pass++class TestRandomMedianBlur:def test_smoke(self, device, dtype):image = torch.rand(1, 1, 2, 2, device=device, dtype=dtype)