Salt and Pepper in python

In image processing, "salt and pepper" refers to a type of image noise that appears as random, isolated pixels with very high or very low intensity values, resembling salt and pepper sprinkled on an image. Python provides various techniques to remove or reduce salt and pepper noise from images. Here's an example of how you can implement salt and pepper noise generation in Python:

pythonCopy codeimport numpy as np
import cv2

def add_salt_and_pepper_noise(image, salt_ratio=0.05, pepper_ratio=0.05):
    """
    Adds salt and pepper noise to an image.

    Args:
        image (numpy.ndarray): Input image.
        salt_ratio (float): Ratio of salt noise (default: 0.05).
        pepper_ratio (float): Ratio of pepper noise (default: 0.05).

    Returns:
        numpy.ndarray: Image with salt and pepper noise.
    """
    row, col, _ = image.shape
    salt = np.random.rand(row, col) < salt_ratio
    pepper = np.random.rand(row, col) < pepper_ratio
    noisy_image = np.copy(image)
    noisy_image[salt] = 1
    noisy_image[pepper] = 0
    return noisy_image

# Load image
image = cv2.imread('image.jpg', cv2.IMREAD_GRAYSCALE)

# Add salt and pepper noise
noisy_image = add_salt_and_pepper_noise(image)

# Display original and noisy image
cv2.imshow('Original Image', image)
cv2.imshow('Noisy Image', noisy_image)
cv2.waitKey(0)
cv2.destroyAllWindows()

In this example, the add_salt_and_pepper_noise() function takes an input image and adds salt and pepper noise to it based on the given salt and pepper ratios. The salt and pepper noise is generated using NumPy's random functions, and the noisy image is obtained by copying the original image and setting pixel values to 1 for salt noise and 0 for pepper noise. Finally, the original and noisy image are displayed using OpenCV's imshow() function. Note that the image.jpg is the file name of the input image that you want to add salt and pepper noise to, and you may need to change it to the appropriate file name or path based on your specific use case.