How to remove noise from images in OpenCV

This recipe helps you remove noise from images in OpenCV

Recipe Objective: How to remove noise from images in OpenCV?

Let us take this recipe to understand what noise is and how to eliminate them in an image.

Explore Fascinating Image Processing Project Ideas With Source Code

Step 1: Import the libraries and read the image.

Let us first import the necessary libraries and read the image. The image that we are using here is the one shown below.

Input image

import numpy as np
import cv2
from matplotlib import pyplot as plt
image = cv2.imread('projectpro_noise_20.jpg',1)
image_bw = cv2.imread('projectpro_noise_20.jpg',0)

The image variable stores the image in BGR format, while the image_bw stores the image in Grayscale format.

Step 2: Denoising using OpenCV

We already know why eliminating noise is essential in an image. We might also be aware of various smoothing techniques such as Gaussian Smoothing, Median Smoothing, and so on. But it is necessary to understand that in those techniques, we considered a small neighborhood kernel matrix around a pixel, found its Gaussian weighted average or median, and replaced that value in the center of the kernel matrix. But in most cases, noise is not just subjected to the neighborhood. That is when we need other methods to denoise the image.

So before we begin with understanding how to denoise an image, let us first comprehend the basic property of noise. Noise is a random variable with its mean as 0. Let us consider a noisy pixel P = p + n where p is the pixel value, and n is the noise. Suppose we consider the same pixel from different frames (i.e., if we hold the camera still and capture a certain subject for a couple of seconds in a video, we might get different frames) of the same image and compute their average. Then we can obtain P = p, which implies that n = 0. But most of the time, we might not be readily having different frames of the same image. In that case, we can consider similar areas within the same image using a 5 x 5 or 7 x 7 window and find their average. This is the principle that drive the cv.fastNlMeansDenoising() and cv.fastNlMeansDenoisingColored() functions. The former is used on grayscale images, while the latter is used on colored images.

The standard parameters are

  • src: The input image
  • dst: The output dimension
  • h: The strength of the filter. 10 is the ideal value
  • hForColorComponents: Same as h but for colored images
  • templateWindowSize: The window size of the template. 7 is the ideal value.
  • searchWindowSize: The window size of the search area. 21 is the ideal value.

It is also to be noted that both templateWindowSize and searchWindowSize should always be odd. Let us jump into the code now.

noiseless_image_bw = cv2.fastNlMeansDenoising(image_bw, None, 20, 7, 21)
noiseless_image_colored = cv2.fastNlMeansDenoisingColored(image,None,20,20,7,21)

Step 3: Displaying the Output

Let us display the results using matplotlib.

titles = ['Original Image(colored)','Image after removing the noise (colored)', 'Original Image (grayscale)','Image after removing the noise (grayscale)']
images = [image,noiseless_image_colored, image_bw, noiseless_image_bw]
plt.figure(figsize=(13,5))
for i in range(4):
    plt.subplot(2,2,i+1)
    plt.imshow(cv2.cvtColor(images[i],cv2.COLOR_BGR2RGB))
    plt.title(titles[i])
    plt.xticks([])
    plt.yticks([])
plt.tight_layout()
plt.show()

Output:

Denoising

This method can be less fast than the other neighborhood functions like Gaussian and median smoothing, but this is way more effective than those functions!

What Users are saying..

profile image

Ed Godalle

Director Data Analytics at EY / EY Tech
linkedin profile url

I am the Director of Data Analytics with over 10+ years of IT experience. I have a background in SQL, Python, and Big Data working with Accenture, IBM, and Infosys. I am looking to enhance my skills... Read More

Relevant Projects

Learn Object Tracking (SOT, MOT) using OpenCV and Python
Get Started with Object Tracking using OpenCV and Python - Learn to implement Multiple Instance Learning Tracker (MIL) algorithm, Generic Object Tracking Using Regression Networks Tracker (GOTURN) algorithm, Kernelized Correlation Filters Tracker (KCF) algorithm, Tracking, Learning, Detection Tracker (TLD) algorithm for single and multiple object tracking from various video clips.

Personalized Medicine: Redefining Cancer Treatment
In this Personalized Medicine Machine Learning Project you will learn to classify genetic mutations on the basis of medical literature into 9 classes.

Deep Learning Project for Time Series Forecasting in Python
Deep Learning for Time Series Forecasting in Python -A Hands-On Approach to Build Deep Learning Models (MLP, CNN, LSTM, and a Hybrid Model CNN-LSTM) on Time Series Data.

Time Series Project to Build a Multiple Linear Regression Model
Learn to build a Multiple linear regression model in Python on Time Series Data

Build ARCH and GARCH Models in Time Series using Python
In this Project we will build an ARCH and a GARCH model using Python

AWS MLOps Project for Gaussian Process Time Series Modeling
MLOps Project to Build and Deploy a Gaussian Process Time Series Model in Python on AWS

MLOps Project to Deploy Resume Parser Model on Paperspace
In this MLOps project, you will learn how to deploy a Resume Parser Streamlit Application on Paperspace Private Cloud.

Learn Hyperparameter Tuning for Neural Networks with PyTorch
In this Deep Learning Project, you will learn how to optimally tune the hyperparameters (learning rate, epochs, dropout, early stopping) of a neural network model in PyTorch to improve model performance.

Learn to Build an End-to-End Machine Learning Pipeline - Part 2
In this Machine Learning Project, you will learn how to build an end-to-end machine learning pipeline for predicting truck delays, incorporating Hopsworks' feature store and Weights and Biases for model experimentation.

Build a Speech-Text Transcriptor with Nvidia Quartznet Model
In this Deep Learning Project, you will leverage transfer learning from Nvidia QuartzNet pre-trained models to develop a speech-to-text transcriptor.