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

Natural language processing Chatbot application using NLTK for text classification
In this NLP AI application, we build the core conversational engine for a chatbot. We use the popular NLTK text classification library to achieve this.

Build a Face Recognition System in Python using FaceNet
In this deep learning project, you will build your own face recognition system in Python using OpenCV and FaceNet by extracting features from an image of a person's face.

Build a Credit Default Risk Prediction Model with LightGBM
In this Machine Learning Project, you will build a classification model for default prediction with LightGBM.

Model Deployment on GCP using Streamlit for Resume Parsing
Perform model deployment on GCP for resume parsing model using Streamlit App.

NLP Project to Build a Resume Parser in Python using Spacy
Use the popular Spacy NLP python library for OCR and text classification to build a Resume Parser in Python.

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.

MLOps Project for a Mask R-CNN on GCP using uWSGI Flask
MLOps on GCP - Solved end-to-end MLOps Project to deploy a Mask RCNN Model for Image Segmentation as a Web Application using uWSGI Flask, Docker, and TensorFlow.

Build an End-to-End AWS SageMaker Classification Model
MLOps on AWS SageMaker -Learn to Build an End-to-End Classification Model on SageMaker to predict a patient’s cause of death.

BigMart Sales Prediction ML Project in Python
The goal of the BigMart Sales Prediction ML project is to build and evaluate different predictive models and determine the sales of each product at a store.

Classification Projects on Machine Learning for Beginners - 1
Classification ML Project for Beginners - A Hands-On Approach to Implementing Different Types of Classification Algorithms in Machine Learning for Predictive Modelling