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

Learn to Build a Neural network from Scratch using NumPy
In this deep learning project, you will learn to build a neural network from scratch using NumPy

Linear Regression Model Project in Python for Beginners Part 1
Machine Learning Linear Regression Project in Python to build a simple linear regression model and master the fundamentals of regression for beginners.

Learn to Build an End-to-End Machine Learning Pipeline - Part 1
In this Machine Learning Project, you will learn how to build an end-to-end machine learning pipeline for predicting truck delays, addressing a major challenge in the logistics industry.

Deep Learning Project- Real-Time Fruit Detection using YOLOv4
In this deep learning project, you will learn to build an accurate, fast, and reliable real-time fruit detection system using the YOLOv4 object detection model for robotic harvesting platforms.

Mastering A/B Testing: A Practical Guide for Production
In this A/B Testing for Machine Learning Project, you will gain hands-on experience in conducting A/B tests, analyzing statistical significance, and understanding the challenges of building a solution for A/B testing in a production environment.

FEAST Feature Store Example for Scaling Machine Learning
FEAST Feature Store Example- Learn to use FEAST Feature Store to manage, store, and discover features for customer churn prediction machine learning project.

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.

NLP Project for Beginners on Text Processing and Classification
This Project Explains the Basic Text Preprocessing and How to Build a Classification Model in Python

Azure Deep Learning-Deploy RNN CNN models for TimeSeries
In this Azure MLOps Project, you will learn to perform docker-based deployment of RNN and CNN Models for Time Series Forecasting on Azure Cloud.

Stock Price Prediction Project using LSTM and RNN
Learn how to predict stock prices using RNN and LSTM models. Understand deep learning concepts and apply them to real-world financial data for accurate forecasting.