In this blog, we will discuss how we can add different types of noise in an image like Gaussian, salt-and-pepper, speckle, etc. By knowing this, you will be able to evaluate various image filtering, restoration, and many other techniques. So, let’s get started.
1. Using Scikit-image
In Scikit-image, there is a builtin function random_noise that adds random noise of various types to a floating-point image. Let’s first check the function arguments and then we will see how to implement it.
Basic syntax of the random_noise function is shown below. You can read more about the arguments in the scikit-image documentation.
1 |
random_noise(image, mode='gaussian', seed=None, clip=True, **kwargs) |
This returns a floating-point image data on the range [0, 1] or [-1, 1] depending on whether the input image was unsigned or signed, respectively.
Let’s take an example to understand how to use this function
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 |
import cv2 import numpy as np from skimage.util import random_noise # Load the image img = cv2.imread("D:/downloads/opencv_logo.PNG") # Add salt-and-pepper noise to the image. noise_img = random_noise(img, mode='s&p',amount=0.3) # The above function returns a floating-point image # on the range [0, 1], thus we changed it to 'uint8' # and from [0,255] noise_img = np.array(255*noise_img, dtype = 'uint8') # Display the noise image cv2.imshow('blur',noise_img) cv2.waitKey(0) |
The output image with salt-and-pepper noise looks like this
You can add several builtin noise patterns, such as Gaussian, salt and pepper, Poisson, speckle, etc. by changing the ‘mode’ argument.
2. Using Numpy
Image noise is a random variation in the intensity values. Thus, by randomly inserting some values in an image, we can reproduce any noise pattern. For randomly inserting values, Numpy random module comes handy. Let’s see how
Gaussian Noise
1 2 3 4 5 6 7 8 9 10 11 12 |
import cv2 import numpy as np img = cv2.imread('D:/downloads/opencv_logo.PNG') # Generate Gaussian noise gauss = np.random.normal(0,1,img.size) gauss = gauss.reshape(img.shape[0],img.shape[1],img.shape[2]).astype('uint8') # Add the Gaussian noise to the image img_gauss = cv2.add(img,gauss) # Display the image cv2.imshow('a',img_gauss) cv2.waitKey(0) |
Speckle Noise
1 2 3 4 5 6 7 8 9 10 11 |
import cv2 import numpy as np img = cv2.imread('D:/downloads/opencv_logo.PNG') gauss = np.random.normal(0,1,img.size) gauss = gauss.reshape(img.shape[0],img.shape[1],img.shape[2]).astype('uint8') noise = img + img * gauss cv2.imshow('a',noise) cv2.waitKey(0) |
Similarly, you can add other noises as well. Hope you enjoy reading.
If you have any doubt/suggestion please feel free to ask and I will do my best to help or improve myself. Good-bye until next time.