Skip to content

🐍 Geometric Computer Vision Library for Spatial AI

Update algorithm using indexing (#2762)

Vicent Gilabert5d4ec5206343
diff --git a/kornia/augmentation/_2d/intensity/salt_pepper_noise.py b/kornia/augmentation/_2d/intensity/salt_pepper_noise.py
index 3734e97c7..7a3e791ac 100644
--- a/kornia/augmentation/_2d/intensity/salt_pepper_noise.py
+++ b/kornia/augmentation/_2d/intensity/salt_pepper_noise.py
@@ -121,8 +121,10 @@ class RandomSaltAndPepperNoise(IntensityAugmentationBase2D):
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)
+ noisy_image = input.clone()
- return noisy_image.clamp(0, 1)
+ # Apply noise masks using indexing.
+ noisy_image[params["mask_salt"].to(input.device)] = 1.0
+ noisy_image[params["mask_pepper"].to(input.device)] = 0.0
+
+ return noisy_image
diff --git a/kornia/augmentation/random_generator/_2d/salt_pepper_noise.py b/kornia/augmentation/random_generator/_2d/salt_pepper_noise.py
index 10e484807..9aeca2f38 100644
--- a/kornia/augmentation/random_generator/_2d/salt_pepper_noise.py
+++ b/kornia/augmentation/random_generator/_2d/salt_pepper_noise.py
@@ -20,8 +20,8 @@ class SaltAndPepperGenerator(RandomGeneratorBase):
- 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).
+ - mask_salt: Binary masks (bool) indicating the presence of Salt noise with a shape of (B, C, H, W).
+ - mask_pepper: Binary masks (bool) 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,
@@ -82,8 +82,8 @@ class SaltAndPepperGenerator(RandomGeneratorBase):
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)
+ mask_pepper = (~mask_salt & mask_noise).to(device=_device)
+ mask_salt = (mask_salt & mask_noise).to(device=_device)
return {
"amount_factor": amount_factor,