stouputils.data_science.data_processing.image.salt_pepper module#
- salt_pepper_image(image: ndarray[Any, dtype[Any]], density: float, ignore_dtype: bool = False) ndarray[Any, dtype[Any]] [source]#
Add salt and pepper noise to an image.
- Parameters:
image (NDArray[Any]) – Image to add noise to
density (float) – Density of the noise (between 0 and 1)
ignore_dtype (bool) – Ignore the dtype check
- Returns:
Image with salt and pepper noise
- Return type:
NDArray[Any]
>>> ## Basic tests >>> image = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]]) >>> noisy = salt_pepper_image(image.astype(np.uint8), 0.1) >>> noisy.shape == image.shape True
>>> np.random.seed(42) >>> img = np.full((4,4), 128, dtype=np.uint8) >>> noisy = salt_pepper_image(img, 1.0) >>> sorted(np.unique(noisy).tolist()) # Should only contain 0 and 255 [0, 255]
>>> rgb = np.full((3,3,3), 128, dtype=np.uint8) >>> noisy_rgb = salt_pepper_image(rgb, 0.1) >>> noisy_rgb.shape == (3,3,3) True
>>> ## Test invalid inputs >>> salt_pepper_image("not an image", 0.1) Traceback (most recent call last): ... AssertionError: Image must be a numpy array
>>> salt_pepper_image(image.astype(np.uint8), "0.1") Traceback (most recent call last): ... AssertionError: density must be a number, got <class 'str'>
>>> salt_pepper_image(image.astype(np.uint8), 1.5) Traceback (most recent call last): ... AssertionError: density must be between 0 and 1, got 1.5