There are several methods to add noise to images in Python using OpenCV. Common noise types include Gaussian noise and Salt and Pepper noise. The following sections detail how to add each of these noise types.
1. Gaussian Noise
Gaussian noise is a statistical noise type where the probability density function follows a normal distribution (Gaussian distribution). One common method involves generating a Gaussian random array of the same dimensions as the original image and adding it to the image.
pythonimport numpy as np import cv2 # Read the original image image = cv2.imread('path_to_image.jpg') # Obtain the image dimensions rows, cols, channels = image.shape # Generate Gaussian noise mean = 0 # Mean var = 10 # Variance sigma = var ** 0.5 gaussian = np.random.normal(mean, sigma, (rows, cols, channels)) # Create random array gaussian = gaussian.reshape(rows, cols, channels) # Add Gaussian noise to the original image noisy_image = cv2.add(image, gaussian) # Display images cv2.imshow('Original', image) cv2.imshow('Gaussian Noise', noisy_image) cv2.waitKey(0) cv2.destroyAllWindows()
2. Salt and Pepper Noise
Salt and Pepper noise is characterized by black and white speckles appearing on the image, simulating random pixel changes to black or white. This noise can be added by randomly selecting pixels and setting them to the maximum (255) or minimum (0) values.
pythonimport numpy as np import cv2 import random # Read the original image image = cv2.imread('path_to_image.jpg') # Obtain the image dimensions rows, cols, channels = image.shape # Salt and Pepper noise ratio salt_pepper_ratio = 0.02 output = np.copy(image) # Add salt noise num_salt = np.ceil(salt_pepper_ratio * image.size * 0.5) coords = [np.random.randint(0, i - 1, int(num_salt)) for i in image.shape] output[coords[0], coords[1], :] = 255 # Add pepper noise num_pepper = np.ceil(salt_pepper_ratio * image.size * 0.5) coords = [np.random.randint(0, i - 1, int(num_pepper)) for i in image.shape] output[coords[0], coords[1], :] = 0 # Display images cv2.imshow('Original', image) cv2.imshow('Salt and Pepper Noise', output) cv2.waitKey(0) cv2.destroyAllWindows()
In both methods, you can adjust parameters such as variance and noise ratio to achieve different levels of noise effects. These techniques are commonly used in image processing to test algorithm robustness or for enhancing training data.