Thresholding is a foundational technique in computer vision and image processing used to segment objects from the background. It works by comparing each pixel value of a grayscale image against a specified threshold value. Based on this comparison, pixels are assigned new values, usually 0 (black) or 255 (white).In OpenCV with Python, the function cv2.threshold is used for thresholding.
In thresholding, for every pixel at position (x,y) with an intensity value f(x,y):
If f(x,y) < T, set the pixel to 0 (black).
If f(x,y) β₯ T, set it to the maximum value (typically 255, white).
Here, T is the threshold value, and the process is usually performed on a grayscale version of the image
Technique
Description
cv2.THRESH_BINARY
Above threshold -> 255, below -> 0.
cv2.THRESH_BINARY_INV
Above threshold -> 0, below -> 255 (inverse of binary).
cv2.THRESH_TRUNC
Above threshold -> set to threshold, below -> unchanged.
cv2.THRESH_TOZERO
Below threshold -> 0, above -> unchanged.
cv2.THRESH_TOZERO_INV
Above threshold -> 0, below -> unchanged (inverse of TOZERO).
Step-by-Step Implementation
Let's implement the various types of simple thresholding techniques,