π Geometric Computer Vision Library for Spatial AI
Python artificial-intelligencecomputer-visiondeep-learninghacktoberfestimage-processingmachine-learningneural-networkpythonpytorchroboticsspatial-ai
Add Random rain augmentation (#2268)
Bogdan9c06e7ab0eac
diff --git a/docs/source/augmentation.module.rst b/docs/source/augmentation.module.rstindex 09d91d151..143a513de 100644--- a/docs/source/augmentation.module.rst+++ b/docs/source/augmentation.module.rst@@ -35,6 +35,7 @@ Intensity.. autoclass:: RandomSolarize.. autoclass:: RandomMedianBlur.. autoclass:: RandomSnow+.. autoclass:: RandomRainGeometric~~~~~~~~~diff --git a/kornia/augmentation/_2d/intensity/__init__.py b/kornia/augmentation/_2d/intensity/__init__.pyindex 53f78be9e..b16faef7f 100644--- a/kornia/augmentation/_2d/intensity/__init__.py+++ b/kornia/augmentation/_2d/intensity/__init__.py@@ -20,6 +20,7 @@ from kornia.augmentation._2d.intensity.normalize import Normalizefrom kornia.augmentation._2d.intensity.planckian_jitter import RandomPlanckianJitterfrom kornia.augmentation._2d.intensity.plasma import RandomPlasmaBrightness, RandomPlasmaContrast, RandomPlasmaShadowfrom kornia.augmentation._2d.intensity.posterize import RandomPosterize+from kornia.augmentation._2d.intensity.random_rain import RandomRainfrom kornia.augmentation._2d.intensity.random_rgb_shift import RandomRGBShiftfrom kornia.augmentation._2d.intensity.random_snow import RandomSnowfrom kornia.augmentation._2d.intensity.saturation import RandomSaturationdiff --git a/kornia/augmentation/_2d/intensity/random_rain.py b/kornia/augmentation/_2d/intensity/random_rain.pynew file mode 100644index 000000000..d3573868f--- /dev/null+++ b/kornia/augmentation/_2d/intensity/random_rain.py@@ -0,0 +1,91 @@+from __future__ import annotations++from typing import Any++import torch++from kornia.augmentation._2d.intensity.base import IntensityAugmentationBase2D+from kornia.augmentation.random_generator._2d import RainGenerator+from kornia.core import Tensor+from kornia.core.check import KORNIA_CHECK+++class RandomRain(IntensityAugmentationBase2D):+ r"""Add Random Rain to the image.++ Args:+ p: probability of applying the transformation.+ number_of_drops: number of drops per image+ drop_height: height of the drop in image(same for each drops in one image)+ drop_width: width of the drop in image(same for each drops in one image)+ Shape:+ - Input: :math:`(C, H, W)` or :math:`(B, C, H, W)`+ - Output: :math:`(B, C, H, W)`++ Examples:+ >>> rng = torch.manual_seed(0)+ >>> input = torch.rand(1, 1, 5, 5)+ >>> rain = RandomRain(p=1,drop_height=(1,2),drop_width=(1,2),number_of_drops=(1,1))+ >>> rain(input)+ tensor([[[[0.4963, 0.7843, 0.0885, 0.1320, 0.3074],+ [0.6341, 0.4901, 0.8964, 0.4556, 0.6323],+ [0.3489, 0.4017, 0.0223, 0.1689, 0.2939],+ [0.5185, 0.6977, 0.8000, 0.1610, 0.2823],+ [0.6816, 0.9152, 0.3971, 0.8742, 0.4194]]]])+ """++ def __init__(+ self,+ same_on_batch: bool = False,+ p: float = 0.5,+ keepdim: bool = False,+ number_of_drops: tuple[int, int] = (1000, 2000),+ drop_height: tuple[int, int] = (5, 20),+ drop_width: tuple[int, int] = (-5, 5),+ ):+ super().__init__(p=p, same_on_batch=same_on_batch, p_batch=1.0, keepdim=keepdim)+ self._param_generator = RainGenerator(number_of_drops, drop_height, drop_width)++ def apply_transform(+ self, image: Tensor, params: dict[str, Tensor], flags: dict[str, Any], transform: Tensor | None = None+ ) -> Tensor:+ # Check array and drops size+ KORNIA_CHECK(image.shape[1] == 3 or image.shape[1] == 1, "Number of color channels should be 1 or 3.")+ KORNIA_CHECK(+ bool(+ torch.all(params['drop_height_factor'] <= image.shape[2])+ and torch.all(params['drop_height_factor'] > 0)+ ),+ "Height of drop should be greater than zero and less than image height.",+ )++ KORNIA_CHECK(+ bool(torch.all(torch.abs(params['drop_width_factor']) <= image.shape[3])),+ "Width of drop should be less than image width.",+ )++ for i in range(image.shape[0]):+ number_of_drops: int = int(params['number_of_drops_factor'][i])+ # We generate tensor with maximum number of drops, and then remove unnecessary drops.++ coordinates_of_drops: Tensor = params['coordinates_factor'][i][:number_of_drops]+ height_of_drop: int = int(params['drop_height_factor'][i])+ width_of_drop: int = int(params['drop_width_factor'][i])++ # Generate start coordinates for each drop+ random_y_coords = coordinates_of_drops[:, 0] * (image.shape[2] - height_of_drop - 1)+ if width_of_drop > 0:+ random_x_coords = coordinates_of_drops[:, 1] * (image.shape[3] - width_of_drop - 1)+ else:+ random_x_coords = coordinates_of_drops[:, 1] * (image.shape[3] + width_of_drop - 1) - width_of_drop++ coords = torch.cat([random_y_coords[None], random_x_coords[None]], dim=0).to(image.device, dtype=torch.long)++ # Generate how our drop will look like into the image+ size_of_line: int = max(height_of_drop, abs(width_of_drop))+ x = torch.linspace(start=0, end=height_of_drop, steps=size_of_line, dtype=torch.long).to(image.device)+ y = torch.linspace(start=0, end=width_of_drop, steps=size_of_line, dtype=torch.long).to(image.device)+ # Draw lines+ for k in range(x.shape[0]):+ image[i, :, coords[0] + x[k], coords[1] + y[k]] = 200 / 255+ return imagediff --git a/kornia/augmentation/__init__.py b/kornia/augmentation/__init__.pyindex deea44669..212d70add 100644--- a/kornia/augmentation/__init__.py+++ b/kornia/augmentation/__init__.py@@ -39,6 +39,7 @@ from kornia.augmentation._2d import (RandomPlasmaContrast,RandomPlasmaShadow,RandomPosterize,+ RandomRain,RandomResizedCrop,RandomRGBShift,RandomRotation,@@ -128,6 +129,7 @@ __all__ = ["RandomSolarize","RandomSharpness","RandomSnow",+ "RandomRain","RandomPosterize","RandomEqualize","RandomMotionBlur",diff --git a/kornia/augmentation/random_generator/_2d/__init__.py b/kornia/augmentation/random_generator/_2d/__init__.pyindex 3cb9a073e..c05ec5342 100644--- a/kornia/augmentation/random_generator/_2d/__init__.py+++ b/kornia/augmentation/random_generator/_2d/__init__.py@@ -13,6 +13,7 @@ from kornia.augmentation.random_generator._2d.plain_uniform import *from kornia.augmentation.random_generator._2d.planckian_jitter import *from kornia.augmentation.random_generator._2d.posterize import *from kornia.augmentation.random_generator._2d.probability import *+from kornia.augmentation.random_generator._2d.random_rain import *from kornia.augmentation.random_generator._2d.rectangle_earase import *from kornia.augmentation.random_generator._2d.resize import *from kornia.augmentation.random_generator._2d.shear import *diff --git a/kornia/augmentation/random_generator/_2d/random_rain.py b/kornia/augmentation/random_generator/_2d/random_rain.pynew file mode 100644index 000000000..dedf08711--- /dev/null+++ b/kornia/augmentation/random_generator/_2d/random_rain.py@@ -0,0 +1,77 @@+from __future__ import annotations++import torch+from torch.distributions import Uniform++from kornia.augmentation.random_generator.base import RandomGeneratorBase+from kornia.augmentation.utils import _adapted_rsampling, _common_param_check, _range_bound+from kornia.core import Tensor+from kornia.utils import _extract_device_dtype+++class RainGenerator(RandomGeneratorBase):+ def __init__(+ self, number_of_drops: tuple[int, int], drop_height: tuple[int, int], drop_width: tuple[int, int]+ ) -> None:+ super().__init__()+ self.number_of_drops = number_of_drops+ self.drop_height = drop_height+ self.drop_width = drop_width++ def __repr__(self) -> str:+ repr = f"number_of_drops={self.number_of_drops}, drop_height={self.drop_height}, drop_width={self.drop_width}"+ return repr++ def make_samplers(self, device: torch.device, dtype: torch.dtype) -> None:+ number_of_drops = _range_bound(+ self.number_of_drops,+ 'number_of_drops',+ center=self.number_of_drops[0] / 2 + self.number_of_drops[1] / 2,+ bounds=(self.number_of_drops[0], self.number_of_drops[1] + 1),+ ).to(device)+ drop_height = _range_bound(+ self.drop_height,+ 'drop_height',+ center=self.drop_height[0] / 2 + self.drop_height[1] / 2,+ bounds=(self.drop_height[0], self.drop_height[1] + 1),+ ).to(device)+ drop_width = _range_bound(+ self.drop_width,+ 'drop_width',+ center=self.drop_width[0] / 2 + self.drop_width[1] / 2,+ bounds=(self.drop_width[0], self.drop_width[1] + 1),+ ).to(device)++ drop_coordinates = _range_bound((0, 1), 'drops_coordinate', center=0.5, bounds=(0, 1)).to(+ device=device, dtype=dtype+ )+ self.number_of_drops_sampler = Uniform(number_of_drops[0], number_of_drops[1], validate_args=False)+ self.drop_height_sampler = Uniform(drop_height[0], drop_height[1], validate_args=False)+ self.drop_width_sampler = Uniform(drop_width[0], drop_width[1], validate_args=False)+ self.coordinates_sampler = Uniform(drop_coordinates[0], drop_coordinates[1], validate_args=False)++ def forward(self, batch_shape: tuple[int, ...], same_on_batch: bool = False) -> dict[str, Tensor]:+ batch_size = batch_shape[0]+ _common_param_check(batch_size, same_on_batch)+ _device, _dtype = _extract_device_dtype([self.drop_width, self.drop_height, self.number_of_drops])+ # self.ksize_factor.expand((batch_size, -1))+ number_of_drops_factor = _adapted_rsampling((batch_size,), self.number_of_drops_sampler).to(+ device=_device, dtype=torch.long+ )+ drop_height_factor = _adapted_rsampling((batch_size,), self.drop_height_sampler, same_on_batch).to(+ device=_device, dtype=torch.long+ )+ drop_width_factor = _adapted_rsampling((batch_size,), self.drop_width_sampler, same_on_batch).to(+ device=_device, dtype=torch.long+ )+ coordinates_factor = _adapted_rsampling(+ (batch_size, int(number_of_drops_factor.max().item()), 2),+ self.coordinates_sampler,+ same_on_batch=same_on_batch,+ ).to(device=_device)+ return dict(+ number_of_drops_factor=number_of_drops_factor,+ coordinates_factor=coordinates_factor,+ drop_height_factor=drop_height_factor,+ drop_width_factor=drop_width_factor,+ )diff --git a/test/augmentation/test_augmentation.py b/test/augmentation/test_augmentation.pyindex 966d26e45..b1fbd35b6 100644--- a/test/augmentation/test_augmentation.py+++ b/test/augmentation/test_augmentation.py@@ -37,6 +37,7 @@ from kornia.augmentation import (RandomPlasmaContrast,RandomPlasmaShadow,RandomPosterize,+ RandomRain,RandomResizedCrop,RandomRGBShift,RandomRotation,@@ -66,6 +67,7 @@ class CommonTests(BaseTester):############################################################################################################_augmentation_cls: Optional[Type[AugmentationBase2D]] = None_default_param_set: Dict["str", Any] = {}+############################################################################################################# Fixtures############################################################################################################@@ -4187,3 +4189,52 @@ class TestRandomMedianBlur:)utils.assert_close(out, expected)+++class TestRandomRain(BaseTester):+ torch.manual_seed(0) # for random reproductibility++ def _get_exception_test_data(self, device, dtype):+ err_msg_height_bigger = "Height of drop should be greater than zero and less than image height."+ err_msg_width_bigger = 'Width of drop should be less than image width'+ err_msg_wrong_ch = 'Number of color channels should be 1 or 3.'++ return [+ (err_msg_height_bigger, (-2, 0), (2, 3), torch.rand(1, 5, 5, device=device, dtype=dtype)),+ (err_msg_height_bigger, (6, 6), (2, 3), torch.rand(1, 5, 5, device=device, dtype=dtype)),+ (err_msg_width_bigger, (2, 2), (6, 6), torch.rand(1, 5, 5, device=device, dtype=dtype)),+ (err_msg_wrong_ch, (1, 2), (1, 2), torch.rand(2, 4, 5, device=device, dtype=dtype)),+ ]++ @pytest.mark.parametrize("batch_shape", [(1, 3, 5, 7), (1, 3, 6, 9)])+ def test_cardinality(self, batch_shape, device, dtype):+ input_data = torch.rand(batch_shape, device=device, dtype=dtype)+ output_data = RandomRain(p=1.0, drop_height=(3, 4), drop_width=(2, 3), number_of_drops=(1, 3))(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 = RandomRain(p=1.0, drop_height=(2, 3), drop_width=(2, 3), number_of_drops=(1, 3))+ output_data = aug(input_data)+ assert output_data.shape == input_data.shape+ input_data = torch.rand(1, 3, 8, 9, device=device, dtype=dtype)+ aug = RandomRain(p=1.0, drop_height=(2, 3), drop_width=(-3, -2), number_of_drops=(1, 3))+ output_data = aug(input_data)+ assert output_data.shape == input_data.shape++ @pytest.mark.skip(reason="not implemented yet")+ def test_gradcheck(self, device):+ pass++ def test_exception(self, device, dtype):+ exception_test_data = self._get_exception_test_data(device, dtype)+ for err_msg, drop_height, drop_width, input_data in exception_test_data:+ with pytest.raises(Exception) as errinfo:+ aug = RandomRain(p=1.0, drop_height=drop_height, drop_width=drop_width)+ aug(input_data)++ assert err_msg in str(errinfo)++ @pytest.mark.skip(reason="not implemented yet")+ def test_module(self, device, dtype):+ pass