Image Thresholding in OpenCV – Python Full Tutorial

In Image processing, thresholding is a fundamental technique that is used to separate objects or regions in an image based on pixel intensity. Image thresholding is commonly used for image segmentation and feature extraction.

In Python, OpenCV is a popular library for computer vision and provides powerful tools for thresholding images.

In this tutorial, I’ll explain how different types of image thresholding techniques using OpenCV in Python work. I will cover the basics of thresholding and provide practical examples to help you understand how to apply these techniques in your projects.

  1. Simple Thresholding

It is the basic form of thresholding where each pixel in the image is compared to a predefined threshold value. Now, what does this actually mean ?

It compares each pixel’s intensity value to a fixed threshold value. If the pixel’s value is higher than the threshold, it is set to a maximum value (255, which represents white in grayscale). If it is lower than the threshold, it is set to 0 (which represents black). This process creates a binary image where pixels are either white or black, depending on whether they are above or below the threshold.

If the pixel value is greater than the threshold, it is set to a maximum value (often 255, white); otherwise, it is set to a minimum value (often 0, black).

Let us see an example:

import cv2
import numpy as np

# Load an image in grayscale
image = cv2.imread('girl.jpg', 0)

# Apply simple thresholding
_, thresholded = cv2.threshold(image, 127, 255, cv2.THRESH_BINARY)

# Display the original and thresholded images
cv2.imshow('Original Image', image)
cv2.imshow('Thresholded Image', thresholded)
cv2.waitKey(0)
cv2.destroyAllWindows()

Original Image Which I have used in my code:

Output:

Explanation:

cv2.threshold(image, 127, 255, cv2.THRESH_BINARY): Applies simple thresholding to the image. Pixels with values greater than 127 are set to 255 (white), and pixels with values less than or equal to 127 are set to 0 (black).

2. Adaptive Thresholding

This thresholding is very useful when the image has varying lighting conditions. This means instead of using a global threshold value,

Oh wait, before we proceed what is the global threshold value?

a global threshold value is like a rule that decides if a pixel in an image should be considered as part of an object or background. This value is used to separate the object of interest from the background by comparing the intensity of each pixel to this fixed value. If a pixel’s intensity is higher than the threshold, it is considered part of the object; otherwise, it is considered part of the background. This helps in creating a clearer and more defined image of the object.

adaptive thresholding calculates the threshold for each pixel based on the local neighborhood of the pixel.

Let us see an example:

# Apply adaptive thresholding
adaptive_thresholded = cv2.adaptiveThreshold(image, 255, cv2.ADAPTIVE_THRESH_MEAN_C, cv2.THRESH_BINARY, 11, 2)

# Display the adaptive thresholded image
cv2.imshow('Adaptive Thresholded Image', adaptive_thresholded)
cv2.waitKey(0)
cv2.destroyAllWindows()

Output:

Explanation:

cv2.adaptiveThreshold(image, 255, cv2.ADAPTIVE_THRESH_MEAN_C, cv2.THRESH_BINARY, 11, 2): Applies adaptive thresholding using the mean of the neighborhood area. The threshold value is the mean of the neighborhood area minus the constant C (2 in this case).

3. Otsu’s Binarization

It is a global thresholding technique that automatically calculates the optimal threshold value based on the image histogram. Basically it assumes that the image contains two classes of pixels (foreground and background) and calculates the optimal threshold to separate these classes.

Example:

# Apply Otsu's binarization
_, otsu_thresholded = cv2.threshold(image, 0, 255, cv2.THRESH_BINARY + cv2.THRESH_OTSU)

# Display the Otsu thresholded image
cv2.imshow('Otsu Thresholded Image', otsu_thresholded)
cv2.waitKey(0)
cv2.destroyAllWindows()

Output:

Explanation:

cv2.THRESH_OTSU: Flag used with cv2.threshold to indicate Otsu’s binarization method.

4. Inverse Thresholding

It is similar to simple thresholding, but it inverts the output. Pixels with values greater than the threshold are set to 0, and pixels with values less than or equal to the threshold are set to the maximum value.

Example:

# Apply inverse thresholding
_, inverse_thresholded = cv2.threshold(image, 127, 255, cv2.THRESH_BINARY_INV)

# Display the inverse thresholded image
cv2.imshow('Inverse Thresholded Image', inverse_thresholded)
cv2.waitKey(0)
cv2.destroyAllWindows()

Output:

Explanation:

cv2.THRESH_BINARY_INV: Flag used with cv2.threshold to indicate inverse thresholding.

5. Truncation Thresholding

Truncation thresholding sets the pixel value to the threshold if it exceeds the threshold value; otherwise, it remains unchanged.

# Apply truncation thresholding
_, truncated = cv2.threshold(image, 127, 255, cv2.THRESH_TRUNC)

# Display the truncated image
cv2.imshow('Truncated Image', truncated)
cv2.waitKey(0)
cv2.destroyAllWindows()

Output:

cv2.THRESH_TRUNC: Flag used with cv2.threshold to indicate truncation thresholding.

Real-Life Use of Threshold Image:

Thresholding images is used in various real-life applications, such as:

  1. Medical Imaging: In X-ray and MRI images, thresholding can help highlight specific tissues or abnormalities, making it easier for doctors to diagnose conditions.
  2. Quality Inspection: In manufacturing, thresholding can be used to identify defects in products by distinguishing between acceptable and unacceptable features.
  3. Object Detection: Thresholding is used in computer vision for object detection and tracking. It helps in separating objects from the background, which is useful in surveillance and autonomous vehicles.
  4. Document Processing: Thresholding can be used to enhance text in scanned documents, making it easier to recognize characters during OCR (optical character recognition).
  5. Satellite Imagery: Thresholding is used to analyze satellite images for various purposes such as land cover classification, urban planning, and environmental monitoring.

Conclusion,

In this tutorial, i have covered various image thresholding techniques using OpenCV in Python. Thresholding is a powerful tool in image processing that allows you to segment images based on pixel intensities. By using these techniques, you can enhance the quality of your images and extract useful information for further analysis. Experiment with different thresholding techniques and parameters to see how they affect the output, and apply them to your own image processing projects.

Author

Sona Avatar

Written by

Leave a Reply

Trending

CodeMagnet

Your Magnetic Resource, For Coding Brilliance

Programming Languages

Web Development

Data Science and Visualization

Career Section

<script async src="https://pagead2.googlesyndication.com/pagead/js/adsbygoogle.js?client=ca-pub-4205364944170772"
     crossorigin="anonymous"></script>