Guide to Adding Noise Images with Python and OpenCV

Image Noise Feature

How we can implement Image Noise using Python and OpenCV and gain in-depth knowledge about it through this article

Let’s begin our journey by getting a little theoretical knowledge about the above topics.

Significance of Image Noise in Various Applications

Image noise is one factor that continuously compromises this goal. Image noise is the unintentional variation in pixel values that obstructs an image’s clarity and quality.

This flaw may seem like it is not required, but it has significant uses in various disciplines. Photography, medical imaging, and computer vision are included in these disciplines. Depending on the application, image noise has different effects. Artistic and retro effects in photos can be created by using it.

In computer vision and machine learning, the generalization and robustness of algorithms can be improved with controlled noise. To get an accurate diagnosis in medical imaging, it is important to have knowledge of noise. Steganography and cryptography for security use noise. To boost model performance, improve realism, and simulate reality, simulation, gaming, and data augmentation use Noise.

Highlighting its critical function in several fields and offering useful knowledge in noise management and its wide-ranging applications, this article will examine how Noise can be added using Python and OpenCV.

Impact of Different Types of Noise on Image Quality

A normal distribution-based Gaussian noise adds mild randomness and gives the image a soft, grainy texture. Images suffer greatly from salt and pepper noise, which produces bright, isolated areas and sometimes black and white pixels. Electrical interference is one type of random noise that blurs edges and reduces clarity.

Important factors such as contrast, blurred edges, and overall image clarity, which are important in a variety of applications, are affected by these noise patterns. Making and identifying these effects are things on which the maintenance of image integrity and the guarantee of correct analyses depend.

Role of Python and OpenCV

Quick and effective image processing is enabled when Python and OpenCV work together.

Thanks to Python’s user-friendly syntax and OpenCV’s extensive image-handling capabilities, users can quickly complete tasks ranging from basic operations to complex transformations. Supporting a variety of formats, conversion, loading, and saving are made simple by Python and OpenCV.

These tools improve image quality as they provide creative effect application, contrast adjustment, and noise reduction. It is simple to do complex geometric transformations like rotation and scaling. The pair supports applications for computer vision and machine learning that implement algorithms.

Real-time processing capabilities, cross-platform interoperability, and a wealth of community resources are the reasons for the powerful partnership between Python and OpenCV that pushes creativity and problem-solving.

Understanding Image Noise

Image Noise and Its Characteristics

A variety of factors, including faulty sensors and transmission faults, cause an unavoidable component of digital imaging called image noise. It’s fundamental randomness and unpredictable nature make total eradication difficult.

Adaptive noise reduction techniques are needed because the amount of noise varies across an image, having varying effects on different regions. Uncertainty is induced by noise modifications to pixel values, which impact the image analysis Clarity, contrast, and overall appeal are all reduced by noise. It is not uniformly distributed across frequencies and is most noticeable in high-frequency regions with more complex characteristics.

Gaussian, salt and pepper, and random noise types should all be understood for effective mitigation. Although it can be creatively used, regulating loudness is crucial. Skilful implementation of reduction strategies and knowledge of noise’s characteristics are required for effective noise control, utility, and integrity to be maintained.

Types of Noise

Gaussian Noise

Additive white Gaussian noise (AWGN), another name for Gaussian noise, has a Gaussian distribution. Signal transmission, sensor limits and electrical components are the factors that bring about the random changes that arise. Gaussian noise appears as a soft, undetectable disturbance that gives pixels random values.

The spread results in a grainy, soft appearance to the image. This kind of noise is frequently seen in photographic photographs and is similar to the randomness that occurs naturally in real-world situations.

Salt and Pepper Noise

Random black and white pixels are added to an image via salt and pepper noise, also known as impulse noise. This kind of noise produces abrupt, sharp fluctuations, similar to what would happen if salt and pepper were sprinkled on an image. It may result from gearbox issues or sensor issues. Image quality is considerably reduced by salt and pepper noise, which obscures features and makes it more difficult to understand images. For the purpose of successfully restoring the original image, this form of noise needs specific filtering methods.

Random Noise

The broad category of “random noise” includes several sources of unpredictable disturbance in photographs. Electrical noise, quantization mistakes and others are irregular fluctuations created during the image capture process and stored in it

Random noise can appear as variations in pixel values throughout the entire image and has no discernible pattern. It is difficult to successfully mitigate because of the complexity of its effects, which vary according to their source and severity.

Impact of Noise on Image

Analysis of the photos and quality are both significantly impacted by the natural noise of digital photographs. Its pixel value variations at random result in decreased clarity, lost details, and poor contrast. Making accurate interpretations and analyses difficult, this interference reduces the visual attraction of the image. Medical imaging and computer vision produce unreliable results because noise distorts the algorithms in these applications.

The usability of images is impaired due to the loss of important information, which may be caused by high noise. Compression efficiency suffers, requiring additional bandwidth and storage. Workflows must often be changed as a result of the additional processing needed to address noise. When processing and enhancing images, the need to take the wide range of effects of noise into account is highlighted.

Since we’ve gained an overview of what Image Noise is and the various concepts related to that, it is time that we get into the skin of Image noise by understanding the various types in depth and with the help of simple examples, so let’s jump to the next section wherein we will gain some practical knowledge about adding noise to images using OpenCV and Python.

Gaussian Noise

Gaussian Noise and its Characteristics

By adding values sampled from a Gaussian distribution to each pixel in an image, Gaussian noise provides randomness. With fewer instances of extreme values and a bell-shaped curve for this sort of noise, most noise levels tend to cluster around the mean. Gaussian noise frequently has a subtle appearance and matches the unpredictable nature found in actual situations.

Its regulated participation can simulate flaws in picture-capture hardware and provide realism.

The Role of Normal Distribution

Gaussian noise is mostly produced by the normal distribution, commonly referred to as the Gaussian distribution. The probability that various events will occur in the vicinity of a mean value is described by this probability distribution.

With regard to Gaussian noise, the mean denotes the pixel intensity at rest, while the standard deviation regulates the distribution of noise values around the mean. In order to simulate real-world unpredictability, the normal distribution makes sure that most noise values are close to the mean and less frequently vary greatly from it.

Adding Gaussian Noise using OpenCV

Let’s see, through an example, how we can implement Gaussian Noise using OpenCV and Python. To begin, we need to have two import tools that we will be using in this example, which are numpy and OpenCV, so let’s begin by downloading them first so we can start with our example.

To install the tools, use the below-given command in your terminal:

pip install numpy
pip install opencv-python

Running the above two lines will successfully install the required tools for this example, and now we are ready to begin with our example. You can follow the below code to implement Gaussian Noise yourself; if you find any difficulty in understanding the code, you can refer to the code explanation below the code snippet, followed by the actual output produced by the given code.

import cv2
import numpy as np

def add_gaussian_noise(image, mean=0, std=25):
    noise = np.random.normal(mean, std, image.shape).astype(np.uint8)
    noisy_image = cv2.add(image, noise)
    return noisy_image

original_image = cv2.imread('testimg.jpeg')

if original_image is None:
    raise Exception("Image not loaded properly. Check the file path.")

noisy_image = add_gaussian_noise(original_image, mean=0, std=25)

cv2.imshow("Original Image", original_image)
cv2.imshow("Noisy Image", noisy_image)
cv2.waitKey(0)
cv2.destroyAllWindows()

The first two lines import the required libraries: numpy for numerical operations and array manipulation and cv2 for OpenCV functionalities. The function add_gaussian_noise, which accepts the three parameters image, mean, and std (standard deviation), is present starting on line 4. Using np.random.normal(), it creates Gaussian noise with a defined mean and standard deviation.

The supplied image’s dimensions are used to generate an array of noise using the image.shape attribute. A noisy image is produced by using cv2.add() to combine the created noise with the original image. The function returns a noisy image.

Line 11’s conditional statement determines whether the original_image variable was correctly loaded. If it is None, an exception is raised along with an error message, indicating that the picture was not successfully loaded.

Line 14 uses the add_gaussian_noise function using the original_image and the mean (0) and standard deviation (25) values that are provided. It produces a noisy copy of the initial image. The cv2.imshow() function is then used in lines 16 through 19 to display the original and noisy images. The window titles for the original image and the noisy image are provided by the arguments “Original Image” and “Noisy Image,” respectively.

When the code execution is finished, cv2.destroyAllWindows() kills every window, whereas cv2.waitKey(0) waits for a key press to dismiss the windows.

You can see the difference between the actual image and the noisy image in the image shown below:

Gaussian Noise Example
Gaussian Noise Example

Salt and Pepper Noise

Introduction to Salt and Pepper Noise

A method for simulating random and irregular disturbances in digital photographs is to add salt and pepper noise. By adding white (salt) and black (pepper) pixels to an image, this kind of noise creates a special kind of interference. Simulating actual image flaws requires learning salt and pepper noise’s characteristics as well as how to apply them using OpenCV.

The presence of lone white and black pixels in an image is a feature of salt and pepper noise, often referred to as impulse noise. This kind of noise simulates the appearance of salt and peppercorns that have been randomly dispersed on a picture canvas. The severe and abrupt pixel changes give the image a speckled appearance. Different things, such as sensor problems or gearbox issues, can cause salt and pepper noise.

Concept of Random Pixel Replacement

The random replacement of pixels with either white (salt) or black (pepper) values is the fundamental component of salt and pepper noise. These replacements, which are random and unrelated to the surrounding pixel values, create sharp contrasts. This form of noise is difficult to manage and minimise since it is random and unpredictable.

Adding Salt and Pepper Noise Using OpenCV

Let’s jump to an example to actually see how we can add salt and pepper using OpenCV. I will be using the same image that I used in the previous example. 

Follow along with the code given below, followed by the code explanation, and lastly, the output image.

import cv2
import numpy as np


def add_salt_and_pepper_noise(image, noise_ratio=0.02):
    noisy_image = image.copy()
    h, w, c = noisy_image.shape
    noisy_pixels = int(h * w * noise_ratio)

    for _ in range(noisy_pixels):
        row, col = np.random.randint(0, h), np.random.randint(0, w)
        if np.random.rand() < 0.5:
            noisy_image[row, col] = [0, 0, 0] 
        else:
            noisy_image[row, col] = [255, 255, 255]

    return noisy_image

original_image = cv2.imread('testimg.jpeg')

if original_image is None:
    raise Exception("Image not loaded properly. Check the file path.")

noisy_image = add_salt_and_pepper_noise(original_image, noise_ratio=0.02)

cv2.imshow("Original Image", original_image)
cv2.imshow("Noisy Image (Salt and Pepper)", noisy_image)
cv2.waitKey(0)
cv2.destroyAllWindows()

The add-salt-and-pepper-noise function on line 5 requires two inputs: image (the input image) and noise_ratio (the required percentage of noisy pixels). To prevent altering the original, a copy of the input image (noisy_image) is made. The image’s dimensions are then determined (H, W, and C for height, width, and channels).

Based on the supplied noise_ratio, the noisy_pixels variable determines how many pixels should be subject to salt and pepper noise. The function continues by iterating over a set of noisy_pixels. It chooses a pixel location (row, col) inside the image at random for each cycle. The random value produced by the np.random.rand() function ranges from 0 to 1. In order to simulate pepper noise, if the generated value is less than 0.5, the pixel is converted to black ([0, 0, 0]).

If not, a white ([255, 255, 255]) pixel is substituted, simulating salt noise. Line 24 invokes the add_salt_and_pepper_noise function with the original image loaded and a noise_ratio of 0.02 (which denotes that 2% of the pixels will be influenced by noise). It creates a fresh image with more noise, like salt and pepper. Using cv2.imshow(), lines 26 to 29 display both the original and the noisy images.

A title for the image window is provided by the first argument. When the code execution is finished, cv2.destroyAllWindows() kills every window. cv2.waitKey(0) waits for a key press before closing the windows.

You can see the difference between the actual image and the salt and pepper noise in the image below:

Salt Pepper Noise
Salt and Pepper Noise

Random Noise

Random Noise and Its Applications

Electrical interference, sensor errors, gearbox hiccups, and other erratic causes can all result in random noise, a type of interference. Random noise lacks identifiable trends and can take many different forms, as opposed to specialized noise types like Gaussian or salt and pepper noise.

The analysis and interpretation of images are made more difficult by this noise, which is frequently present during image acquisition, transmission, or storage.

Including Random Noise Using OpenCV

In this example, I will also be using the same image that I’ve been using in the previous few examples.

Please follow along with the code provided below to add random noise. If you find something not so clear in the code example, you can read through the code explanation after the code example, followed by the output of the code after execution.

import cv2
import numpy as np

def add_random_noise(image, intensity=25):
    noisy_image = image.copy()
    noise = np.random.randint(-intensity, intensity + 1, noisy_image.shape)
    noisy_image = np.clip(noisy_image + noise, 0, 255).astype(np.uint8)
    return noisy_image

original_image = cv2.imread('testimg.jpeg')

if original_image is None:
    raise Exception("Image not loaded properly. Check the file path.")

noisy_image = add_random_noise(original_image, intensity=25)

cv2.imshow("Original Image", original_image)
cv2.imshow("Noisy Image (Random)", noisy_image)
cv2.waitKey(0)
cv2.destroyAllWindows()

The add_random_noise function on line 4 requires two inputs: image (the input image) and intensity (the intensity range for noise generation). To prevent altering the original, a copy of the input image (noisy_image) is made. Random noise is guaranted by the functions due to construction of an array of random numbers within the desired intensity range. Between -intensity and intensity + 1, the np.random.randint() function generates random integers.

The shape of this noise array matches that of the noisy input image (noisy_image.shape). The created noise is combined with original image by the element-wise addition used by the function By using the np.clip() function, pixels values are kept within the acceptable range of 0 to 255. The output is then a noisy image. The add_random_noise function is called on line 15 with the loaded original_image and an intensity of 25.

A fresh image is created with additional random noise.

Using cv2.imshow(), lines 17 to 20 display both the original and the noisy images. A title for the image window is provided by the first argument. When the code execution is finished, cv2.destroyAllWindows() kills every window. cv2.waitKey(0) waits for a key press before closing the windows.

The difference between the normal image and the image after random noise is added can be seen in the below image:

Random Noise Example
Random Noise Example

For better understanding, I’ve shown all three above-discussed methods in one single image below:

All In One Noise Example
All In One Noise Example

Real-World Applications

Industries like medical imaging, where diagnosis depends on noise reduction, have a variety of real-world applications for image noise. Noise reduction in remote sensing provides a proper interpretation of environmental data from satellites. Distant celestial objects are captured by astronomers, helped by noise reduction. Surveillance in security systems increases vision, for which noise reduction is essential.

To achieve the desired results in art and photography, noise reduction can be used intentionally. For precise analysis, computer vision and machine learning require robust algorithms for noise issues. Forensic scientists depend on noise reduction for a proper interpretation of the findings, even if microscopy gives more accurate sample insights. Automotive vision, industrial quality control, and precise flaw detection essentially need noise reduction.

Conclusion

In conclusion, while being obstructive, picture noise has huge value in various real-world applications. Astronomical study, medical diagnosis, and artistic expression are affected due to the wide effect of noise.

Understanding the many types of noise and their impacts is required by professionals to create noise reduction procedures specific to each field’s needs. These examples highlight how crucial noise control is for accurate analysis, reasoned judgment, and trustworthy automation.

As technology develops, it is becoming more and more important to have the ability to manage noise successfully. Improving our capacity to extract useful information from images while navigating the difficulties presented by real-world circumstances.

Reference

Stackoverflow Query

To learn more about Python Programming, check out the other articles on askpython.

To learn more about Pycharm, which is the IDE that I used in this tutorial, check out the linked article.