What is adaptive thresholding in OpenCV

This recipe explains what is adaptive thresholding in OpenCV

Recipe Objective: What is adaptive thresholding in OpenCV?

This recipe lets us understand what adaptive thresholding is and why it is better than simple thresholding.

Step 1: Import the necessary libraries and read the image

Let us first import the required libraries and read the pictures. The image that we are using here is the one shown below. It is crucial to read the image in grayscale format to perform thresholding.

book image
import cv2
from matplotlib import pyplot as plt
image = cv2.imread('book image.png',0)

Step 2: Adaptive Thresholding

In the Simple Thresholding technique, a global threshold is set, and all the image pixel values are compared with that threshold. But in most cases, the lighting and the image's brightness will not be the same in all areas of the image for various reasons. A simple thresholding technique might fail in such cases.

In the Adaptive thresholding technique, the threshold values are dynamically calculated for smaller regions of the image. Hence, there will be different threshold values for different photo areas depending on their surrounding areas.

There are two ways of calculating the adaptive threshold. They are

  • cv2.ADAPTIVE_THRESH_MEAN_C
  • cv2.ADAPTIVE_THRESH_GAUSSIAN_C

The cv2.ADAPTIVE_THRESH_MEAN_C method calculates the threshold by taking the mean of the pixel values in the neighborhood area.

The cv2.ADAPTIVE_THRESH_GAUSSIAN_C method calculates the threshold by taking the weighted sum of the pixel values in the neighborhood area where the weights are assigned using the gaussian window technique.

The function cv2.adaptiveThreshold() is used to perform adaptive threshold, and it takes the following parameters

  • src: The image on which thresholding is to be performed
  • maxValue: Maximum value
  • adaptiveMethod: The adaptive thresholding method which is to be used
  • thresholdType: The thresholding technique which should be used
  • blockSize: The size of the neighborhood to be considered
  • C: A constant which is subtracted from the mean or weighted mean (obtained from adaptiveMethod)

Let us now implement this using python

_,th0 = cv2.threshold(image,150,255,cv2.THRESH_BINARY)
th1 = cv2.adaptiveThreshold(image,255,cv2.ADAPTIVE_THRESH_MEAN_C,cv2.THRESH_BINARY,11,2)
th2 = cv2.adaptiveThreshold(image,255,cv2.ADAPTIVE_THRESH_GAUSSIAN_C,cv2.THRESH_BINARY,15,5)

Step 3: Display the Output

Let us now display the output of the above images on a plot for easy comparison.

titles = ['Original Image','Simple Binary Thresholding','Adaptive Mean Thresholding','Adaptive Gaussian Thresholding']
images = [image,th0, th1, th2]
plt.figure(figsize=(13,8))
for i in range(4):
    plt.subplot(1,4,i+1)
    plt.imshow(images[i],'gray')
    plt.title(titles[i])
    plt.xticks([])
    plt.yticks([])
plt.tight_layout()
plt.show()

Output:

output

This clearly shows the difference between simple thresholding and adaptive thresholding.

Download Materials

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

Build an Image Segmentation Model using Amazon SageMaker
In this Machine Learning Project, you will learn to implement the UNet Architecture and build an Image Segmentation Model using Amazon SageMaker

Build a Text Classification Model with Attention Mechanism NLP
In this NLP Project, you will learn to build a multi class text classification model with attention mechanism.

Tensorflow Transfer Learning Model for Image Classification
Image Classification Project - Build an Image Classification Model on a Dataset of T-Shirt Images for Binary Classification

GCP MLOps Project to Deploy ARIMA Model using uWSGI Flask
Build an end-to-end MLOps Pipeline to deploy a Time Series ARIMA Model on GCP using uWSGI and Flask

A/B Testing Approach for Comparing Performance of ML Models
The objective of this project is to compare the performance of BERT and DistilBERT models for building an efficient Question and Answering system. Using A/B testing approach, we explore the effectiveness and efficiency of both models and determine which one is better suited for Q&A tasks.

PyCaret Project to Build and Deploy an ML App using Streamlit
In this PyCaret Project, you will build a customer segmentation model with PyCaret and deploy the machine learning application using Streamlit.

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.

End-to-End Speech Emotion Recognition Project using ANN
Speech Emotion Recognition using RAVDESS Audio Dataset - Build an Artificial Neural Network Model to Classify Audio Data into various Emotions like Sad, Happy, Angry, and Neutral

Build a Multi Class Image Classification Model Python using CNN
This project explains How to build a Sequential Model that can perform Multi Class Image Classification in Python using CNN

Build Portfolio Optimization Machine Learning Models in R
Machine Learning Project for Financial Risk Modelling and Portfolio Optimization with R- Build a machine learning model in R to develop a strategy for building a portfolio for maximized returns.