What is image thresholding in OpenCV Why is it useful

This recipe explains what is image thresholding in OpenCV and why is it useful

Recipe Objective: What is image thresholding in OpenCV? Why is it useful?

This is a simple recipe that explains what image thresholding is, why it is useful and the different types of thresholding.

Step 1: Import libraries and read the image

Before we get into image thresholding, let us first import the necessary libraries and read the image. The image that we are using here is the one shown below. Thresholding techniques work only on grayscale images, and hence it is essential to read the image in black and white format.

black to white gradient

import cv2
from matplotlib import pyplot as plt
image = cv2.imread('b-to-wh.jpg',0)

Step 2: Image thresholding

The thresholding of an image is nothing but comparing each pixel value with a pre-defined threshold value. This process divides all the pixels of the input image into two groups which are

  • Pixels with values lesser than the threshold
  • Pixels with values greater than the threshold

This process is very much helpful in separating the background from an image. There are various methods already available in the OpenCV library to perform thresholding. They are

  • cv2.THRESH_BINARY
  • cv2.THRESH_BINARY_INV
  • cv2.THRESH_TRUNC
  • cv2.THRESH_TOZERO
  • cv2.THRESH_TOZERO_INV

The cv2.THRESH_BINARY method converts the input image into a binary image by replacing the pixel values which lesser than the threshold with 0 and the remaining values with the maximum value

The cv2.THRESH_BINARY_INV method does the same job as of cv2.THRESH_BINARY but in an inverse manner

The cv2.THRESH_TRUNC method replaces the pixel values which are greater than the threshold with the threshold value and leave the remaining pixel values as it is

The cv2.THRESH_TOZERO methods replaces the pixel values which are lesser than the threshold to zero and leave the remaining pixel values as it is

The cv2.THRESH_TOZERO_INV method does the same job as cv2.THRESH_TOZERO but in inverse order

Now let us understand how to bring this into action

_,th1 = cv2.threshold(image,127,255,cv2.THRESH_BINARY)
_,th2 = cv2.threshold(image,127,255,cv2.THRESH_BINARY_INV)
_,th3 = cv2.threshold(image,127,255,cv2.THRESH_TRUNC)
_,th4 = cv2.threshold(image,127,255,cv2.THRESH_TOZERO)
_,th5 = cv2.threshold(image,127,255,cv2.THRESH_TOZERO_INV)

The cv2.threshold() function takes four mandatory parameters, which are

  • src: The image on which thresholding is to be performed
  • thresh: The minimum threshold value
  • maxval: Maximum value
  • type: The thresholding technique which should be used

The function returns two values. One is the retVal which is not necessary, and the other is the thresholded image.

Step 3: Display the output

Let us display the output using subplots in matplotlib

    titles = ['Original Image','Binary Thresholding','Inverse Binary Thresholding','TRUNC Thresholding','TOZERO Thresholding','Inverse TOZERO Thresholding']
    images = [image, th1, th2, th3, th4, th5]
    plt.figure(figsize=(13,5))
    for i in range(6):
        plt.subplot(2,3,i+1)
        plt.imshow(images[i],'gray')
        plt.title(titles[i])
        plt.xticks([])
        plt.yticks([])
    plt.tight_layout()
    plt.show()
 

Output:

thresholding output

Download Materials

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

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.

Locality Sensitive Hashing Python Code for Look-Alike Modelling
In this deep learning project, you will find similar images (lookalikes) using deep learning and locality sensitive hashing to find customers who are most likely to click on an ad.

Hands-On Approach to Regression Discontinuity Design Python
In this machine learning project, you will learn to implement Regression Discontinuity Design Example in Python to determine the effect of age on Mortality Rate in Python.

Learn How to Build a Linear Regression Model in PyTorch
In this Machine Learning Project, you will learn how to build a simple linear regression model in PyTorch to predict the number of days subscribed.

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.

Credit Card Default Prediction using Machine learning techniques
In this data science project, you will predict borrowers chance of defaulting on credit loans by building a credit score prediction model.

Recommender System Machine Learning Project for Beginners-1
Recommender System Machine Learning Project for Beginners - Learn how to design, implement and train a rule-based recommender system in Python

Image Classification Model using Transfer Learning in PyTorch
In this PyTorch Project, you will build an image classification model in PyTorch using the ResNet pre-trained model.

Predictive Analytics Project for Working Capital Optimization
In this Predictive Analytics Project, you will build a model to accurately forecast the timing of customer and supplier payments for optimizing working capital.

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