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

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.

Isolation Forest Model and LOF for Anomaly Detection in Python
Credit Card Fraud Detection Project - Build an Isolation Forest Model and Local Outlier Factor (LOF) in Python to identify fraudulent credit card transactions.

Credit Card Fraud Detection as a Classification Problem
In this data science project, we will predict the credit card fraud in the transactional dataset using some of the predictive models.

NLP and Deep Learning For Fake News Classification in Python
In this project you will use Python to implement various machine learning methods( RNN, LSTM, GRU) for fake news classification.

Deep Learning Project for Time Series Forecasting in Python
Deep Learning for Time Series Forecasting in Python -A Hands-On Approach to Build Deep Learning Models (MLP, CNN, LSTM, and a Hybrid Model CNN-LSTM) on Time Series Data.

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.

Build CNN Image Classification Models for Real Time Prediction
Image Classification Project to build a CNN model in Python that can classify images into social security cards, driving licenses, and other key identity information.

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.

Build Multi Class Text Classification Models with RNN and LSTM
In this Deep Learning Project, you will use the customer complaints data about consumer financial products to build multi-class text classification models using RNN and LSTM.

Digit Recognition using CNN for MNIST Dataset in Python
In this deep learning project, you will build a convolutional neural network using MNIST dataset for handwritten digit recognition.