Image thresholding is one of the most important image segmentation techniques in computer vision. It converts a grayscale image into a binary image by comparing each pixel’s intensity with a predefined threshold value. Pixels that satisfy the threshold condition become white (foreground), while the remaining pixels become black (background).
Thresholding is widely used in document scanning, Optical Character Recognition (OCR), medical image analysis, industrial inspection, object detection, fingerprint recognition, and many other computer vision applications. It simplifies complex images by separating objects of interest from the background, making further analysis much easier.
In this lesson, you will learn the concept of thresholding, understand how binary thresholding works, explore different thresholding types available in OpenCV, and implement thresholding using the cv2.threshold() function.
Thresholding is a pixel-level image processing technique where each pixel is compared with a threshold value. Based on this comparison, the pixel is assigned a new value. The result is usually a binary image consisting of only black and white pixels.
For example, suppose the threshold value is 127.
This simple process makes it easy to distinguish objects from their background.
Many computer vision algorithms work better on binary images than on grayscale or color images. Thresholding reduces unnecessary information and highlights the most relevant regions.
Some common applications include:
Thresholding is applied primarily to grayscale images because each pixel contains only one intensity value ranging from 0 to 255.
| Pixel Value | Meaning |
|---|---|
| 0 | Black |
| 64 | Dark Gray |
| 127 | Medium Gray |
| 192 | Light Gray |
| 255 | White |
OpenCV provides the cv2.threshold() function to apply thresholding.
Syntax:
retval, output = cv2.threshold(
src,
thresh,
maxval,
type
)
Parameters:
Binary thresholding is the simplest thresholding technique. Every pixel is compared with the threshold value.
If the pixel value is greater than the threshold, it becomes white. Otherwise, it becomes black.
import cv2
image = cv2.imread(
"sample.jpg",
cv2.IMREAD_GRAYSCALE
)
_, binary = cv2.threshold(
image,
127,
255,
cv2.THRESH_BINARY
)
cv2.imshow("Binary Threshold", binary)
cv2.waitKey(0)
cv2.destroyAllWindows()
OpenCV provides several thresholding methods.
| Threshold Type | Description |
|---|---|
| THRESH_BINARY | Pixels become either black or white. |
| THRESH_BINARY_INV | Inverse of binary thresholding. |
| THRESH_TRUNC | Values above the threshold become the threshold value. |
| THRESH_TOZERO | Values below the threshold become zero. |
| THRESH_TOZERO_INV | Values above the threshold become zero. |
_, binary_inv = cv2.threshold(
image,
127,
255,
cv2.THRESH_BINARY_INV
)
This produces the opposite result of binary thresholding: pixels above the threshold become black, while pixels below the threshold become white.
Choosing an appropriate threshold often depends on the image histogram. A histogram shows the distribution of pixel intensity values within an image.
If the histogram has two distinct peaks representing the foreground and background, selecting a threshold between the peaks usually produces good segmentation results.
For images with uneven lighting, however, a single threshold value may not be sufficient. In such cases, adaptive thresholding or Otsu’s thresholding provides better results.
In this lesson, you learned the fundamentals of image thresholding, explored binary thresholding, understood different thresholding types, and implemented thresholding using the cv2.threshold() function. You also learned how pixel intensity and image histograms influence threshold selection. In the next part, you will explore Adaptive Thresholding and Otsu’s Thresholding, which automatically handle images with varying illumination and complex intensity distributions.
In the previous lesson, you learned that binary thresholding uses a single threshold value for the entire image. While this approach is simple and fast, it performs poorly when different parts of the image have different lighting conditions. Shadows, reflections, or uneven illumination can cause objects to merge with the background or disappear completely.
To solve this problem, OpenCV provides Adaptive Thresholding. Instead of using one global threshold, adaptive thresholding calculates a different threshold value for each small region of the image. This allows the algorithm to handle varying brightness levels much more effectively.
Consider a scanned document where one side is brighter than the other due to uneven lighting. A single threshold value may correctly separate text from the background in the bright region but fail in the darker region.
Adaptive thresholding analyzes the local neighborhood around each pixel and computes an appropriate threshold for that area, resulting in much better segmentation.
Instead of using one threshold value for the entire image, the algorithm divides the image into many small blocks. Each block receives its own threshold based on the surrounding pixel intensities.
As a result:
OpenCV provides the cv2.adaptiveThreshold() function for local thresholding.
Syntax:
cv2.adaptiveThreshold(
src,
maxValue,
adaptiveMethod,
thresholdType,
blockSize,
C
)
The threshold value is calculated as the average of all pixel values within the local neighborhood.
import cv2
image = cv2.imread(
"sample.jpg",
cv2.IMREAD_GRAYSCALE
)
adaptive_mean = cv2.adaptiveThreshold(
image,
255,
cv2.ADAPTIVE_THRESH_MEAN_C,
cv2.THRESH_BINARY,
11,
2
)
Instead of using a simple average, this method calculates a weighted average using a Gaussian distribution. Pixels closer to the center receive higher importance than pixels farther away.
adaptive_gaussian = cv2.adaptiveThreshold(
image,
255,
cv2.ADAPTIVE_THRESH_GAUSSIAN_C,
cv2.THRESH_BINARY,
11,
2
)
Adaptive Gaussian thresholding generally produces smoother and more accurate results than Adaptive Mean thresholding.
One challenge with binary thresholding is selecting an appropriate threshold value manually. Otsu’s Thresholding solves this problem by automatically determining the optimal threshold based on the image histogram.
Otsu’s algorithm assumes that the image contains two classes of pixels: foreground and background. It calculates the threshold that minimizes the variance within each class while maximizing the separation between them.
import cv2
image = cv2.imread(
"sample.jpg",
cv2.IMREAD_GRAYSCALE
)
threshold, otsu = cv2.threshold(
image,
0,
255,
cv2.THRESH_BINARY + cv2.THRESH_OTSU
)
print("Optimal Threshold:", threshold)
Notice that the threshold value is set to 0. OpenCV ignores this value because Otsu’s algorithm calculates the optimal threshold automatically.
| Method | Best Used For |
|---|---|
| Binary Thresholding | Images with uniform lighting. |
| Adaptive Mean | Documents with uneven illumination. |
| Adaptive Gaussian | Images containing shadows and gradual brightness changes. |
| Otsu’s Thresholding | Images with clearly separated foreground and background. |
| Feature | Binary | Adaptive | Otsu |
|---|---|---|---|
| Manual Threshold | Yes | No | No |
| Handles Uneven Lighting | No | Yes | Limited |
| Processing Speed | Fast | Moderate | Fast |
| Best For | Simple Images | Uneven Illumination | Bimodal Histograms |
In this lesson, you explored Adaptive Thresholding and Otsu’s Thresholding, two powerful techniques that overcome the limitations of simple binary thresholding. Adaptive thresholding calculates local thresholds for different image regions, while Otsu’s method automatically selects the optimal global threshold using the image histogram. These methods are essential for robust image segmentation under varying lighting conditions and form the basis of many computer vision applications.
In real-world computer vision applications, thresholding is rarely applied directly to an image. Images often contain noise, uneven lighting, shadows, or compression artifacts that reduce segmentation quality. To improve results, thresholding is usually combined with preprocessing techniques such as grayscale conversion, image smoothing, histogram equalization, and morphological operations.
A well-designed thresholding workflow produces cleaner binary images, making it easier for subsequent algorithms to detect objects, recognize text, extract contours, or measure image features.
A standard image thresholding workflow consists of the following steps:
cv2.imread().Noise can negatively affect thresholding results. Applying Gaussian Blur before thresholding often produces cleaner binary images by smoothing small intensity variations.
import cv2
image = cv2.imread(
"sample.jpg",
cv2.IMREAD_GRAYSCALE
)
blurred = cv2.GaussianBlur(
image,
(5,5),
0
)
_, binary = cv2.threshold(
blurred,
127,
255,
cv2.THRESH_BINARY
)
cv2.imshow("Binary Image", binary)
cv2.waitKey(0)
cv2.destroyAllWindows()
This preprocessing step is especially useful when working with scanned documents, handwritten text, or noisy camera images.
One of the most effective combinations is Gaussian Blur followed by Otsu’s Thresholding. The blur reduces noise, allowing Otsu’s algorithm to determine a more reliable threshold value.
blurred = cv2.GaussianBlur(
image,
(5,5),
0
)
_, otsu = cv2.threshold(
blurred,
0,
255,
cv2.THRESH_BINARY + cv2.THRESH_OTSU
)
This approach is commonly used in document analysis and Optical Character Recognition (OCR).
| Scenario | Recommended Method |
|---|---|
| Uniform lighting | Binary Thresholding |
| Uneven lighting | Adaptive Thresholding |
| Unknown threshold value | Otsu’s Thresholding |
| Noisy grayscale image | Gaussian Blur + Otsu’s Thresholding |
| Scanned documents | Adaptive Gaussian Thresholding |
Thresholding is a key preprocessing step in many computer vision systems because it simplifies images and separates foreground objects from the background.
blockSize and C in adaptive thresholding.Thresholding compares intensity values. Grayscale images contain a single intensity channel, making the comparison straightforward and computationally efficient.
Smoothing filters such as Gaussian Blur reduce random noise and small intensity fluctuations, improving the quality of the binary image after thresholding.
Not necessarily. Adaptive Thresholding is more effective for uneven lighting, but Binary Thresholding is faster and works well when illumination is uniform.
Yes. Otsu’s Thresholding is commonly combined with Gaussian Blur and other noise reduction techniques to improve segmentation accuracy.
blockSize and C values in Adaptive Thresholding.In this lesson, you learned the principles of image thresholding and explored three major thresholding techniques available in OpenCV: Binary Thresholding, Adaptive Thresholding, and Otsu’s Thresholding. You understood how thresholding simplifies images by separating foreground objects from the background, learned how preprocessing with Gaussian Blur improves segmentation quality, and discovered practical applications in OCR, medical imaging, industrial inspection, and object detection. These techniques form the foundation of image segmentation and prepare you for more advanced image processing tasks. In the next lesson, you will learn image filtering techniques such as averaging, Gaussian blur, median filtering, and bilateral filtering for noise reduction and image enhancement.