π Geometric Computer Vision Library for Spatial AI
Python artificial-intelligencecomputer-visiondeep-learninghacktoberfestimage-processingmachine-learningneural-networkpythonpytorchroboticsspatial-ai
Add salt and pepper noise with docs and tests (#2746)
Vicent Gilabert058756c65947
diff --git a/docs/generate_examples.py b/docs/generate_examples.pyindex f57db28fd..99dbc09be 100644--- a/docs/generate_examples.py+++ b/docs/generate_examples.py@@ -158,6 +158,7 @@ def main():"RandomPosterize": (((1, 4),), 2, 2016),"RandomResizedCrop": ((img1.shape[-2:], (1.0, 2.0), (1.0, 2.0)), 2, 2020),"RandomRotation": ((45.0,), 2, 2019),+ "RandomSaltAndPepperNoise": (((0.05, 0.5), (0.1, 0.7)), 2, 2024),"RandomSaturation": (((0.5, 5.0),), 2, 2022),"RandomSharpness": ((16.0,), 1, 2019),"RandomSolarize": ((0.2, 0.2), 2, 2019),diff --git a/kornia/augmentation/_2d/intensity/__init__.py b/kornia/augmentation/_2d/intensity/__init__.pyindex b3fc0ca59..54d631489 100644--- a/kornia/augmentation/_2d/intensity/__init__.py+++ b/kornia/augmentation/_2d/intensity/__init__.py@@ -24,6 +24,7 @@ from kornia.augmentation._2d.intensity.posterize import RandomPosterizefrom kornia.augmentation._2d.intensity.random_rain import RandomRainfrom kornia.augmentation._2d.intensity.random_rgb_shift import RandomRGBShiftfrom kornia.augmentation._2d.intensity.random_snow import RandomSnow+from kornia.augmentation._2d.intensity.salt_pepper_noise import RandomSaltAndPepperNoisefrom 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/salt_pepper_noise.py b/kornia/augmentation/_2d/intensity/salt_pepper_noise.pynew file mode 100644index 000000000..3734e97c7--- /dev/null+++ b/kornia/augmentation/_2d/intensity/salt_pepper_noise.py@@ -0,0 +1,128 @@+from typing import Any, Dict, Optional, Tuple, Union++from kornia.augmentation._2d.intensity.base import IntensityAugmentationBase2D+from kornia.augmentation.random_generator._2d import SaltAndPepperGenerator+from kornia.core import Tensor+from kornia.core.check import KORNIA_CHECK+++class RandomSaltAndPepperNoise(IntensityAugmentationBase2D):+ r"""Apply random Salt and Pepper noise to input images.++ .. image:: _static/img/RandomSaltAndPepperNoise.png++ Args:+ amount: A float or a tuple representing the range for the amount of noise to apply.+ salt_vs_pepper: A float or a tuple representing the range for the ratio of Salt to Pepper noise.+ p: The probability of applying the transformation. Default is 0.5.+ same_on_batch: If True, apply the same transformation across the entire batch. Default is False.+ keepdim: whether to keep the output shape the same as input (True) or broadcast it+ to the batch form (False).++ Shape:+ - Input: :math:`(C, H, W)` or :math:`(B, C, H, W)`+ - Output: :math:`(B, C, H, W)`++ .. note::+ The `amount` parameter controls the intensity of the noise, while `salt_vs_pepper` controls the ratio+ of Salt to Pepper noise.++ The values for `amount` and `salt_vs_pepper` should be between 0 and 1. The recommended value for+ `salt_vs_pepper` is 0.5, and for `amount`, values less than 0.2 are recommended.++ If `amount` and `salt_vs_pepper` are floats (unique values), the transformation is applied with these+ exact values, rather than randomly sampling from the specified range. However, the masks are still+ generated randomly using these exact parameters.++ Examples:+ >>> rng = torch.manual_seed(5)+ >>> inputs = torch.rand(1, 3, 3, 3)+ >>> aug = RandomSaltAndPepperNoise(amount=0.5, salt_vs_pepper=0.5, p=1.)+ >>> aug(inputs)+ tensor([[[[1.0000, 0.0000, 0.0000],+ [1.0000, 1.0000, 0.1166],+ [0.1644, 0.7379, 0.0000]],+ <BLANKLINE>+ [[1.0000, 0.0000, 0.0000],+ [1.0000, 1.0000, 0.7150],+ [0.5793, 0.9809, 0.0000]],+ <BLANKLINE>+ [[1.0000, 0.0000, 0.0000],+ [1.0000, 1.0000, 0.7850],+ [0.9752, 0.0903, 0.0000]]]])++ To apply the exact augmenation again, you may take the advantage of the previous parameter state:+ >>> input = torch.rand(1, 3, 32, 32)+ >>> aug = RandomSaltAndPepperNoise(amount=0.05, salt_vs_pepper=0.5, p=1.)+ >>> (aug(input) == aug(input, params=aug._params)).all()+ tensor(True)+ """++ def __init__(+ self,+ amount: Optional[Union[float, Tuple[float, float]]] = (0.01, 0.06),+ salt_vs_pepper: Optional[Union[float, Tuple[float, float]]] = (0.4, 0.6),+ p: float = 0.5,+ same_on_batch: bool = False,+ keepdim: bool = False,+ ) -> None:+ super().__init__(p=p, same_on_batch=same_on_batch, p_batch=1.0, keepdim=keepdim)++ # Validation and initialization of amount and salt_vs_pepper parameters.+ if isinstance(salt_vs_pepper, (tuple, float)):+ if isinstance(salt_vs_pepper, float):+ salt_vs_pepper = (salt_vs_pepper, salt_vs_pepper)+ elif len(salt_vs_pepper) == 1:+ salt_vs_pepper = (salt_vs_pepper[0], salt_vs_pepper[0])+ elif len(salt_vs_pepper) > 2 or len(salt_vs_pepper) <= 0:+ raise ValueError(+ "The length of salt_vs_pepper must be greater than 0 \+ and less than or equal to 2, and it should be a tuple."+ )+ else:+ raise ValueError("salt_vs_pepper must be a tuple or a float")+ KORNIA_CHECK(+ all(0 <= el <= 1 for el in salt_vs_pepper),+ "Salt_vs_pepper values must be between 0 and 1. \+ Recommended value 0.5.",+ )++ if isinstance(amount, (tuple, float)):+ if isinstance(amount, float):+ amount = (amount, amount)+ elif len(amount) == 1:+ amount = (amount[0], amount[0])+ elif len(amount) > 2 or len(amount) <= 0:+ raise ValueError(+ "The length of amount must be greater than 0 \+ and less than or equal to 2, and it should be a tuple."+ )+ else:+ raise ValueError("amount must be a tuple or a float")+ KORNIA_CHECK(+ all(0 <= el <= 1 for el in amount),+ "amount of noise values must be between 0 and 1. \+ Recommended values less than 0.2.",+ )++ # Generator of random parameters and masks.+ self._param_generator = SaltAndPepperGenerator(amount, salt_vs_pepper)++ def apply_transform(+ self,+ input: Tensor,+ params: Dict[str, Tensor],+ flags: Dict[str, Any],+ transform: Optional[Tensor] = None,+ ) -> Tensor:+ r"""Apply random Salt and Pepper noise transformation to the input image."""+ KORNIA_CHECK(len(input.shape) in (3, 4), "Wrong input dimension.")+ if len(input.shape) == 3:+ input = input[None, :, :, :]+ KORNIA_CHECK(input.shape[1] in {3, 1}, "Number of color channels should be 1 or 3.")++ # Apply add and multiply mask.+ noisy_image = input + params["mask_salt"].to(input)+ noisy_image = noisy_image * params["mask_pepper"].to(input)++ return noisy_image.clamp(0, 1)diff --git a/kornia/augmentation/__init__.py b/kornia/augmentation/__init__.pyindex 3144be43e..6c4d02d15 100644--- a/kornia/augmentation/__init__.py+++ b/kornia/augmentation/__init__.py@@ -43,6 +43,7 @@ from kornia.augmentation._2d import (RandomResizedCrop,RandomRGBShift,RandomRotation,+ RandomSaltAndPepperNoise,RandomSaturation,RandomSharpness,RandomShear,@@ -127,6 +128,7 @@ __all__ = ["RandomResizedCrop","RandomRotation","RandomRGBShift",+ "RandomSaltAndPepperNoise","RandomSaturation","RandomSolarize","RandomSharpness",diff --git a/kornia/augmentation/random_generator/_2d/__init__.py b/kornia/augmentation/random_generator/_2d/__init__.pyindex c05ec5342..5ff0cc2a8 100644--- a/kornia/augmentation/random_generator/_2d/__init__.py+++ b/kornia/augmentation/random_generator/_2d/__init__.py@@ -16,5 +16,6 @@ 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.salt_pepper_noise import *from kornia.augmentation.random_generator._2d.shear import *from kornia.augmentation.random_generator._2d.translate import *diff --git a/kornia/augmentation/random_generator/_2d/salt_pepper_noise.py b/kornia/augmentation/random_generator/_2d/salt_pepper_noise.pynew file mode 100644index 000000000..10e484807--- /dev/null+++ b/kornia/augmentation/random_generator/_2d/salt_pepper_noise.py@@ -0,0 +1,93 @@+from __future__ import annotations++import torch++from kornia.augmentation.random_generator.base import RandomGeneratorBase, UniformDistribution+from kornia.augmentation.utils import _adapted_rsampling, _adapted_uniform, _common_param_check, _range_bound+from kornia.core import Tensor+from kornia.utils import _extract_device_dtype+++class SaltAndPepperGenerator(RandomGeneratorBase):+ r"""Generate random Salt and Pepper noise parameters for a batch of images.++ Args:+ amount: A tuple representing the range for the amount of noise to apply.+ salt_and_pepper: A tuple representing the range for the ratio of Salt and Pepper noise.++ Returns:+ A dictionary of parameters to be passed for transformation.+ - amount_factor: Element-wise factors determining the amount of noise with a shape of (B,).+ - salt_and_pepper_factor: Element-wise factors determining the ratio of Salt and Pepper noise+ with a shape of (B,).+ - mask_salt: Binary masks (float) indicating the presence of Salt noise with a shape of (B, C, H, W).+ - mask_pepper: Binary masks (float) indicating the presence of Pepper noise with a shape of (B, C, H, W).++ Note:+ The generated random numbers are not reproducible across different devices and dtypes. By default,+ the parameters will be generated on CPU. This can be changed by calling+ ``self.set_rng_device_and_dtype(device="cuda", dtype=torch.float64)``.+ """++ def __init__(+ self,+ amount: tuple[float, float],+ salt_and_pepper: tuple[float, float],+ ) -> None:+ super().__init__()+ self.amount = amount+ self.salt_and_pepper = salt_and_pepper++ def __repr__(self) -> str:+ r"""Return a string representation of the object."""+ repr = f"amount={self.amount}, salt_and_pepper={self.salt_and_pepper}"+ return repr++ def make_samplers(self, device: torch.device, dtype: torch.dtype) -> None:+ r"""Create samplers for generating random noise parameters."""+ amount = _range_bound(+ self.amount,+ "amount",+ ).to(device, dtype)+ salt_and_pepper = _range_bound(+ self.salt_and_pepper,+ "salt_and_pepper",+ ).to(device, dtype)++ self.amount_sampler = UniformDistribution(amount[0], amount[1], validate_args=False)+ self.salt_and_pepper_sampler = UniformDistribution(salt_and_pepper[0], salt_and_pepper[1], validate_args=False)++ def forward(self, batch_shape: tuple[int, ...], same_on_batch: bool = False) -> dict[str, Tensor]:+ r"""Generate Salt and Pepper noise masks for a batch of images."""+ batch_size, C, H, W = batch_shape+ _common_param_check(batch_size, same_on_batch)+ _device, _dtype = _extract_device_dtype([self.amount, self.salt_and_pepper])++ amount_factor = _adapted_rsampling((batch_size,), self.amount_sampler, same_on_batch).to(+ device=_device, dtype=_dtype+ )+ salt_and_pepper_factor = _adapted_rsampling((batch_size,), self.salt_and_pepper_sampler, same_on_batch).to(+ device=_device, dtype=_dtype+ )++ ## Generate noise masks.+ mask_noise = _adapted_uniform(+ (batch_size, 1, H, W), low=0.0, high=1.0, same_on_batch=same_on_batch+ ) < amount_factor.view(batch_size, 1, 1, 1)+ mask_salt = _adapted_uniform(+ (batch_size, 1, H, W), low=0.0, high=1.0, same_on_batch=same_on_batch+ ) < salt_and_pepper_factor.view(batch_size, 1, 1, 1)++ # If the number of channels is greater than one (3), replicate the generated mask for each channel.+ if C > 1:+ mask_noise = mask_noise.repeat(1, C, 1, 1)+ mask_salt = mask_salt.repeat(1, C, 1, 1)+ mask_pepper = (~(~mask_salt & mask_noise)).to(device=_device, dtype=_dtype)+ mask_salt = (mask_salt & mask_noise).to(device=_device, dtype=_dtype)++ return {+ "amount_factor": amount_factor,+ "salt_and_pepper_factor": salt_and_pepper_factor,+ "mask_salt": mask_salt,+ "mask_pepper": mask_pepper,+ }diff --git a/tests/augmentation/test_augmentation.py b/tests/augmentation/test_augmentation.pyindex fab512968..e2d4769dd 100644--- a/tests/augmentation/test_augmentation.py+++ b/tests/augmentation/test_augmentation.py@@ -42,6 +42,7 @@ from kornia.augmentation import (RandomResizedCrop,RandomRGBShift,RandomRotation,+ RandomSaltAndPepperNoise,RandomSaturation,RandomSnow,RandomThinPlateSpline,@@ -3209,6 +3210,86 @@ class TestRandomGaussianNoise(BaseTester):assert img.shape == aug(img).shape+class TestRandomSaltAndPepperNoise(BaseTester):+ @pytest.mark.parametrize(+ "expected",+ [+ torch.tensor(+ [+ [+ [+ [1.0000, 1.0000, 0.5000, 0.5000, 0.5000],+ [0.5000, 0.5000, 0.5000, 0.5000, 0.5000],+ [0.0000, 0.0000, 0.5000, 0.5000, 0.5000],+ [0.5000, 1.0000, 0.5000, 0.5000, 0.5000],+ [0.5000, 0.5000, 0.5000, 0.5000, 0.5000],+ ]+ ]+ ]+ )+ ],+ )+ def test_smoke(self, expected, device, dtype):+ torch.manual_seed(0)+ input_tensor = torch.ones(1, 1, 5, 5, device=device, dtype=dtype) * 0.5+ expected = expected.to(device, dtype=dtype)+ aug = RandomSaltAndPepperNoise(amount=0.2, salt_vs_pepper=0.5, p=1.0)+ res = aug(input_tensor)+ assert input_tensor.shape == res.shape+ self.assert_close(res, expected)++ def test_exception(self, device, dtype):+ with pytest.raises(ValueError, match="salt_vs_pepper must be a tuple or a float"):+ RandomSaltAndPepperNoise(salt_vs_pepper=[0.4, 0.6])+ with pytest.raises(+ ValueError,+ match="The length of salt_vs_pepper must be greater than 0 \+ and less than or equal to 2, and it should be a tuple.",+ ):+ RandomSaltAndPepperNoise(salt_vs_pepper=(0.1, 0.2, 0.3))+ with pytest.raises(+ Exception,+ match="False not true.\nSalt_vs_pepper values must be between 0 and 1. \+ Recommended value 0.5.",+ ):+ RandomSaltAndPepperNoise(salt_vs_pepper=(0.4, 3))+ with pytest.raises(ValueError, match="amount must be a tuple or a float"):+ RandomSaltAndPepperNoise(amount=[0.01, 0.06])+ with pytest.raises(+ ValueError,+ match="The length of amount must be greater than 0 \+ and less than or equal to 2, and it should be a tuple.",+ ):+ RandomSaltAndPepperNoise(amount=())+ with pytest.raises(+ Exception,+ match="False not true.\namount of noise values must be between 0 and 1. \+ Recommended values less than 0.2.",+ ):+ RandomSaltAndPepperNoise(amount=(0.05, 3))++ with pytest.raises(ValueError, match="amount must be a tuple or a float"):+ RandomSaltAndPepperNoise(amount=[0.01, 0.06])++ with pytest.raises(ValueError, match="amount must be a tuple or a float"):+ RandomSaltAndPepperNoise(amount=[0.01, 0.06])++ @pytest.mark.parametrize("batch_shape", [1, 3, 3, 5])+ @pytest.mark.parametrize("channel_shape", [1, 1, 3, 3])+ def test_cardinality(self, batch_shape, channel_shape, device, dtype):+ input_tensor = torch.ones(batch_shape, channel_shape, 16, 16, device=device, dtype=dtype) * 0.5+ transform = RandomSaltAndPepperNoise(p=1.0)+ output_tensor = transform(input_tensor)+ assert input_tensor.shape[0] == output_tensor.shape[0]+ assert input_tensor.shape[1] == output_tensor.shape[1]++ def test_same_on_batch(self, device, dtype):+ input_tensor = torch.ones(2, 1, 5, 5, device=device, dtype=dtype) * 0.5+ transform = RandomSaltAndPepperNoise(p=1.0, same_on_batch=True)+ output_tensor = transform(input_tensor)+ self.assert_close(output_tensor[0], output_tensor[1])++class TestNormalize(BaseTester):# TODO: improve and implement more meaningful smoke tests e.g check for a consistent# return values such a Tensor variable.