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

Anand Kumpatla

Sr Data Scientist @ Doubleslash Software Solutions Pvt Ltd
linkedin profile url

ProjectPro is a unique platform and helps many people in the industry to solve real-life problems with a step-by-step walkthrough of projects. A platform with some fantastic resources to gain... Read More

Relevant Projects

Build OCR from Scratch Python using YOLO and Tesseract
In this deep learning project, you will learn how to build your custom OCR (optical character recognition) from scratch by using Google Tesseract and YOLO to read the text from any images.

Topic modelling using Kmeans clustering to group customer reviews
In this Kmeans clustering machine learning project, you will perform topic modelling in order to group customer reviews based on recurring patterns.

Recommender System Machine Learning Project for Beginners-3
Content Based Recommender System Project - Building a Content-Based Product Recommender App with Streamlit

Learn to Build Generative Models Using PyTorch Autoencoders
In this deep learning project, you will learn how to build a Generative Model using Autoencoders in PyTorch

NLP Project for Multi Class Text Classification using BERT Model
In this NLP Project, you will learn how to build a multi-class text classification model using using the pre-trained BERT model.

Build a Music Recommendation Algorithm using KKBox's Dataset
Music Recommendation Project using Machine Learning - Use the KKBox dataset to predict the chances of a user listening to a song again after their very first noticeable listening event.

Build an AI Quiz Generator from Video with OpenAI API
In this LLM project, you will build a model to automate the transcription of video content and generate interactive quizzes using OpenAI’s Whisper and GPT-4o.

Build a Multi Touch Attribution Machine Learning Model in Python
Identifying the ROI on marketing campaigns is an essential KPI for any business. In this ML project, you will learn to build a Multi Touch Attribution Model in Python to identify the ROI of various marketing efforts and their impact on conversions or sales..

Build Real Estate Price Prediction Model with NLP and FastAPI
In this Real Estate Price Prediction Project, you will learn to build a real estate price prediction machine learning model and deploy it on Heroku using FastAPI Framework.

Time Series Classification Project for Elevator Failure Prediction
In this Time Series Project, you will predict the failure of elevators using IoT sensor data as a time series classification machine learning problem.

OSZAR »