Do you think IIT Guwahati certified course can help you in your career?
No
Introduction
Are you interested in image processing and computer vision? Do you want to learn about an essential OpenCV function that helps image thresholding? If so, let's dive into the world of OpenCV and explore the cv2.threshold() function.
We will discuss two thresholding techniques: Simple Thresholding and Adaptive Thresholding. Additionally, we will examine the different advantages and disadvantages of OpenCV.
Image Thresholding
Before understanding the term “ImageThresholding”, let us first understand the term “Image Segmentation.”
Image segmentation involves dividing an image into distinct sub-regions or individual objects. The extent of subdivision varies depending on the specific problem at hand. In other words, the segmentation process should stop once the objects or regions of interest have been identified.
Image segmentation splits an image into different parts based on color or other features. For example, a picture of a cat sitting on a couch can be segmented into two parts: the cat and the couch. The image is divided into two parts by assigning different values to the pixels, based on whether they belong to the cat or the couch.
Thresholding is an easy and effective method for performing basic segmentation on an image, converting it into a “binaryimage” consisting of pixels that are either 0 or 1 (or 255 when defined as integers).
Basics of cv2.threshold() Function
The cv2.threshold() function is an essential feature within computer vision and image processing libraries, such as OpenCV, enabling the application of image thresholding. Image thresholding is a method used to separate an image into distinct segments based on the intensity values of its pixels.
OpenCV's cv. threshold() function executes image thresholding by organizing pixel values based on a set threshold, returning the thresholded picture and threshold value.
Parameters
In this syntax, we pass four parameters. Those are:
Source: The source image is typically grayscale.
Threshold_value: The value operated to categorize pixels.
Maximum_value: The maximum value set to pixels.
Thresholding_techniques: The method used for thresholding, such as binary, inverse binary, truncate, threshold to zero, or inverse threshold to zero.
Example
Following is a simple example of the use of the cv2.threshold() function.
Code
import cv2
from matplotlib import pyplot as plt
# Load the image in grayscale
image = cv2.imread('/content/download.png', 1)
# Convert image to grayscale
gray_image = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
# Apply thresholding
retval, thresholded_image = cv2.threshold(gray_image, 62, 255, cv2.THRESH_BINARY)
# Display the original image
plt.subplot(1, 2, 1)
plt.imshow(cv2.cvtColor(image, cv2.COLOR_BGR2RGB))
plt.axis('off')
plt.title('Original Image')
# Display the thresholded image
plt.subplot(1, 2, 2)
plt.imshow(thresholded_image, cmap='gray')
plt.axis('off')
plt.title('Thresholded Image')
plt.tight_layout()
plt.show()
Output
Explanation
This cv2.threshold() function is applied to the grayscale image. The function requires the following inputs:
The grayscale image used as the input for thresholding is called gray_image.
The cutoff number (threshold value) is 62. Pixels with intensity values below the threshold are set to 0 (black), while those with values equal to or higher than the threshold are set to 255 (white).
The thresholded pixels can have a maximum value of 255.
cv2.THRESH_BINARY: According to the thresholding type, it thresholds the pixels using a binary approach, putting values below the threshold to 0 and those that are equal to or higher than the threshold to the maximum specified value.
Simple thresholding with cv2.threshold()
Simple thresholding using cv2.threshold() is a method to convert a grayscale image into a binary image. Each pixel's intensity is compared with a threshold value. Pixels above or equal to the threshold are assigned to the maximum value, creating the foreground, while pixels below are set to zero, representing the background. Modifying the threshold and maximum values allows control over the thresholding outcome.
Code
# Import necessary libraries
import cv2
import matplotlib.pyplot as plt
# Reading input image as a grayscale image
img = cv2.imread('/content/download.png', 0)
# Different types of thresholding techniques are applied to the input image
thresh_types = [cv2.THRESH_BINARY, cv2.THRESH_BINARY_INV, cv2.THRESH_TRUNC, cv2.THRESH_TOZERO, cv2.THRESH_TOZERO_INV]
titles = ['BINARY,' 'BINARY_INV,' 'TRUNC,' 'TOZERO,' 'TOZERO_INV']
images = []
# Binary thresholding technique
for thresh_type, title in zip(thresh_types, titles):
_, thresh = cv2.threshold(img, 127, 255, thresh_type)
images.append(thresh)
# Display the original image and the thresholded images
plt.figure(figsize=(12, 8))
# Display the original image
plt.subplot(2, 3, 1)
plt.imshow(img, cmap='gray')
plt.title('Original Image')
plt.axis("off")
# Display the thresholded images
for i in range(5):
plt.subplot(2, 3, i + 2)
plt.imshow(images[i], cmap='gray')
plt.title(titles[i])
plt.axis("off")
plt.tight_layout()
plt.show()
Output
Explanation
In this code, we have functions like:
cv2.THRESH_BINARY
This thresholding technique sets a pixel to 0 (black) if its intensity is below the threshold and 255 (white) if the intensity is equal to or greater than the threshold.
cv2.THRESH_TRUNC
It is much similar to "cv2.THRESH_TRUNC". In this thresholding process, any pixel value higher than the assigned threshold will remain unchanged, while all other pixels will be unaffected.
cv2.THRESH_TOZERO
This technique sets pixel values to 0 (black) if they are below the threshold and leaves them unchanged if they are equal to or above the threshold.
cv2.THRESH_TOZERO_INV
This technique modifies pixel values based on a threshold, inverting the behavior of cv2.THRESH_TOZERO.
Adaptive thresholding with cv2.threshold()
Adaptive thresholding is a technique that calculates the threshold value for smaller regions within an image. As a result, different regions can have distinct threshold values to note variations in lighting conditions in a particular image. This method is valuable when images show non-uniform lighting or variable contrast levels.
Code
import cv2
import numpy as np
import matplotlib.pyplot as plt
# Load the input image
img = cv2.imread('/content/download.png', cv2.IMREAD_GRAYSCALE)
# Apply median blur to reduce noise
img_blur = cv2.medianBlur(img, 5)
# Apply global thresholding
_, th1 = cv2.threshold(img_blur, 127, 255, cv2.THRESH_BINARY)
# Apply adaptive thresholding with the mean method
th2 = cv2.adaptiveThreshold(img_blur, 255, cv2.ADAPTIVE_THRESH_MEAN_C, cv2.THRESH_BINARY, 11, 2)
# Apply adaptive thresholding with the Gaussian method
th3 = cv2.adaptiveThreshold(img_blur, 255, cv2.ADAPTIVE_THRESH_GAUSSIAN_C, cv2.THRESH_BINARY, 11, 2)
# Set up the figure for plotting
fig, axs = plt.subplots(2, 2, figsize=(10, 8))
# Display the original image
axs[0, 0].imshow(img, cmap='gray')
axs[0, 0].set_title('Original Image')
# Display the global thresholding result
axs[0, 1].imshow(th1, cmap='gray')
axs[0, 1].set_title('Global Thresholding')
# Display the adaptive thresholding with mean method result
axs[1, 0].imshow(th2, cmap='gray')
axs[1, 0].set_title('Adaptive Mean Thresholding')
# Display the adaptive thresholding with Gaussian method result
axs[1, 1].imshow(th3, cmap='gray')
axs[1, 1].set_title('Adaptive Gaussian Thresholding')
# Remove axis labels
for ax in axs.flat:
ax.axis('off')
# Adjust the spacing between subplots
plt.tight_layout()
# Show the plot
plt.show()
Output
Explanation
We have used "cv2.ADAPTIVE_THRESH_MEAN_C"; the threshold value is the mean of the neighborhood area minus the constant C and "cv2.ADAPTIVE_THRESH_GAUSSIAN_C", the threshold value for each pixel is determined by taking a weighted sum of the neighboring pixel values.
Advantages of OpenCV cv2.threshold function
The advantages of OpenCV are:
Users may quickly comprehend and use the cv2.threshold function because of its simple design.
The cv2.threshold function lets users change the thresholding parameters to suit their needs.
The function seamlessly integrates with other functions and modules in OpenCV, creating a comprehensive framework for image processing and computer vision tasks.
Disadvantages of OpenCV cv2.threshold() function
The disadvantages of OpenCV are:
The cv2.threshold function offers a range of thresholding methods and options, but it may not cover all possible scenarios.
The function usually requires manually selecting a threshold value, which can be subjective and time-consuming.
The cv2 threshold function is sensitive to noise in the image.
Frequently Asked Questions
What is the purpose of the cv2.threshold function in OpenCV?
The cv2.threshold function in OpenCV converts a grayscale image into a binary image using a threshold value for each pixel.
Can the cv2.threshold function be applied to color images as well?
Typically, users apply the cv2.threshold function in OpenCV to grayscale images as it does not directly support color images.
What is the return value of the cv2.threshold function?
The cv2.threshold function in the OpenCV library returns a tuple consisting of the threshold value used and the thresholded image array.
What is the limitation of the cv2.threshold function?
cv2.threshold function can perform basic thresholding operations, such as simple and adaptive thresholding, and may not manage complex image segmentation tasks or uneven lighting conditions.
What are the use cases of the cv2.threshold function?
The cv2.threshold() function can be used in object detection, text extraction, image segmentation, and biomedical image analysis.
Conclusion
In this article, we have discussed image segmentation and image threshold. This article has examined the syntax and parameters of the cv2.threshold() function. We have even discussed simple thresholding with cv2.threshold() in depth with the help of an example. We have learned about adaptive thresholding with cv2.threshold() in depth with the help of an example in this article. In the end, this article talks about the advantages and disadvantages of OpenCV.
Do check out the link to learn more about such topic
You can find more informative articles or blogs on our platform. You can also practice more coding problems and prepare for interview questions from well-known companies on your platform, Coding Ninjas Studio.