OpenCV cv2.threshold() Function

Learn via video courses
Topics Covered

Overview

Thresholding is one of the most common (and fundamental) segmentation techniques in computer vision, and it allows us to separate the foreground (i.e., the objects of interest) from the background of the image. Each pixel value is compared to the supplied threshold value when assigning pixel values about it. If the pixel value exceeds the threshold, the image is segmented by changing this value to maximum; otherwise, it is set to 0.

Syntax of OpenCV cv2.threshold() Method

The cv2.threshold() method is used to apply a fixed-level threshold to an input image, which means that it will convert all pixel values below a certain threshold value to a specified value and all pixel values above that threshold value to another specified value.

cv2.threshold(src, thresholdValue, maxValue, threshold type)

Parameters of OpenCV cv2.threshold() Method

The cv2.threshold() method in OpenCV requires several parameters to work properly. Here are the important points about the parameters needed:

ParameterDescription
srcThe source image, which should be grayscale, will be used. Grayscale images are images that are black and white.
thresholdValueThis is the threshold value, which will be either above or below the pixel value. The threshold value will change based on the pixels.
maxValueThis will be the maximum value that can be assigned to a pixel.
threshold typeThe threshold type is the method or technique that will be used on the image.

Return Value of OpenCV cv2.threshold() Method

The cv2.threshold() method in OpenCV returns the following:

  • retval: The threshold value used for the operation.
  • dst: The output image after the thresholding operation has been applied.
  • thresh The threshold value that was passed as an argument to the method.
  • type: The thresholding type that was used for the operation, which is specified as an argument to the method.

Exceptions of OpenCV cv2.threshold() Function

The cv2.threshold() function in OpenCV may raise exceptions in the following cases:

  • TypeError: This exception is raised if the src argument is not a numpy array or if the thresh and maxval arguments are not of the same data type as the src array.
  • ValueError: This exception is raised if the thresh or maxval arguments are outside the valid range of values for the data type of the src array.
  • cv2.error: This exception is raised if the method encounters an internal error during the thresholding operation.
  • cv2.UnsupportedError: This exception is raised if the thresholding type specified by the type argument is not supported by the OpenCV library.

Methods of Thresholding an Image

Thresholding is an essential image-processing technique that is widely used for image segmentation, object detection, and feature extraction. OpenCV provides several methods for thresholding an image, and here are the two most commonly used methods:

1. Basic Thresholding

Simple thresholding, in which you must manually enter a threshold value, T. Binary Thresholding is the most fundamental Thresholding approach. The same threshold value is used for each pixel. If the pixel value is less than the threshold, it is set to zero, otherwise, it is set to the maximum value.

OpenCV provides several binary thresholding methods, some of which are:

cv2.THRESH_BINARY: This is the most basic thresholding method, where all pixel values above a specified threshold are set to a maximum value, and all pixel values below the threshold are set to 0.

cv2.THRESH_BINARY_INV: This method is the inverse of the cv2.THRESH_BINARY method, where all pixel values above the specified threshold are set to 0, and all pixel values below the threshold are set to a maximum value.

cv2.THRESH_TRUNC: In this method, all pixel values above the specified threshold are set to the threshold value, and all pixel values below the threshold are left unchanged.

cv2.THRESH_TOZERO: This method sets all pixel values below the specified threshold to 0 and leaves all pixel values above the threshold unchanged.

cv2.THRESH_TOZERO_INV: This method sets all pixel values above the specified threshold to 0 and leaves all pixel values below the threshold unchanged.

These methods can be used in conjunction with the cv2.threshold() function in OpenCV to perform binary thresholding operations on an input image.

2.Otsu Thresholding

  • With simple thresholding, we had to manually enter a T threshold value. We might be able to hardcode this value for basic images in controlled lighting circumstances.
  • Otsu's method eliminates the need to choose a value by determining it automatically.
  • Imagine an image with only two different image values (bimodal image), with a histogram consisting of only two peaks. A good threshold would be in between those two figures. Similarly, Otsu's technique uses the image histogram to obtain an ideal global threshold value.
  • The algorithm then selects the best threshold value and returns it as the first output.
  • Otsu's approach makes no assumptions about which pixels belong in the foreground and which in the background; it just attempts to best separate the histogram's peaks.

How does the OpenCV cv2.threshold() Method Work?

The cv2.threshold() method in OpenCV is used for thresholding, which is a process of converting a grayscale or color image into a binary image. The method works as follows:

  • If the input image is a color image, it is first converted to a grayscale image.
  • A threshold value is specified as an argument to the method. This value can be chosen based on the thresholding method that is used.
  • The method compares each pixel value in the input image to the specified threshold value. If the pixel value is greater than or equal to the threshold value, the pixel value is set to a maximum value specified by the maxval argument. If the pixel value is less than the threshold value, the pixel value is set to 0.
  • The output image is then returned as a binary image with pixel values of either 0 or maxval.
  • The method also returns the threshold value that was used and the output image.
  • If the cv2.THRESH_OTSU flag is specified as an argument, Otsu's thresholding method is automatically applied, which calculates the optimal threshold value based on the image histogram.

Examples

The cv2.threshold() method is used for image thresholding, which converts a grayscale or color image into a binary image.

The method can be used to apply various thresholding techniques such as binary thresholding, adaptive thresholding, Otsu's thresholding, and Gaussian thresholding.

Example usage of the method includes setting a threshold value and a maximum value for binary thresholding, using the cv2.THRESH_OTSU flag for Otsu's thresholding, and specifying a block size and a constant value for adaptive thresholding.

Example 1

Let’s compare different thresholding techniques:

Output:

different thresholding techniques

Example 2

Let’s have an intuitive understanding of Otsu's Binarization. The input image contains noise.

Otsu's approach, as we know, uses the image histogram to establish an ideal global threshold value. To accomplish this, the cv.threshold() function is utilized, with cv.THRESH OTSU set as an extra flag. The algorithm then picks the most suitable threshold value and returns it as the first output.

Global thresholding with a value of 127 is used in the first scenario. In the second situation, Otsu's thresholding is directly implemented. In the third scenario, the image is initially filtered using a 5x5 Gaussian kernel to reduce noise before being subjected to Otsu thresholding. Examine how noise filtering improves the outcome.

Output:

otsu thresholding

Conclusion

  • The function applies a fixed-level threshold to each array element (or to a multiple-channel array).
  • The cv2.threshold() function is often used to extract a bi-level (binary) image from a grayscale image (compare could also be used for this) or to remove noise, that is, to filter out pixels with too tiny or too big values.
  • Applies to enhance contrast and OCR accuracy in Optical Character Recognition (OCR).

See also

OpenCV thresholding documentation

https://docs.opencv.org/4.x/d7/d4d/tutorial_py_thresholding.html

OpenCV threshold types documentation

https://docs.opencv.org/4.x/d7/d1b/group__imgproc__misc.html#gaa9e58d2860d4afa658ef70a9b1115576