How to Apply Threshold in OpenCV for Computer Vision
Use OpenCV's
cv2.threshold() function to convert grayscale images into binary images by setting a pixel intensity cutoff. This function takes the source image, threshold value, max value, and thresholding type as inputs and outputs the thresholded image and the used threshold value.Syntax
The cv2.threshold() function syntax is:
src: Grayscale input image.thresh: Threshold value to classify pixel intensities.maxval: Value assigned to pixels exceeding the threshold.type: Thresholding type (e.g., binary, binary inverse).
The function returns a tuple: the used threshold and the thresholded image.
python
retval, dst = cv2.threshold(src, thresh, maxval, type)Example
This example loads a grayscale image, applies a binary threshold at 127, and shows the original and thresholded images.
python
import cv2 # Load image in grayscale img = cv2.imread('input.jpg', cv2.IMREAD_GRAYSCALE) # Apply binary threshold retval, thresh_img = cv2.threshold(img, 127, 255, cv2.THRESH_BINARY) # Save thresholded image cv2.imwrite('thresholded.jpg', thresh_img) print(f'Threshold used: {retval}')
Output
Threshold used: 127.0
Common Pitfalls
Common mistakes include:
- Using a color image instead of grayscale, which causes errors or unexpected results.
- Choosing an inappropriate threshold value, leading to poor segmentation.
- Confusing threshold types, such as using
THRESH_BINARY_INVwhenTHRESH_BINARYis intended.
Always convert images to grayscale before thresholding and experiment with threshold values for best results.
python
import cv2 # Wrong: Using color image img_color = cv2.imread('input.jpg') retval, thresh_wrong = cv2.threshold(img_color, 127, 255, cv2.THRESH_BINARY) # This will fail or give wrong output # Right: Convert to grayscale first img_gray = cv2.cvtColor(img_color, cv2.COLOR_BGR2GRAY) retval, thresh_right = cv2.threshold(img_gray, 127, 255, cv2.THRESH_BINARY)
Quick Reference
| Threshold Type | Description |
|---|---|
| cv2.THRESH_BINARY | Pixel > thresh set to maxval, else 0 |
| cv2.THRESH_BINARY_INV | Pixel > thresh set to 0, else maxval |
| cv2.THRESH_TRUNC | Pixel > thresh set to thresh, else unchanged |
| cv2.THRESH_TOZERO | Pixel > thresh unchanged, else 0 |
| cv2.THRESH_TOZERO_INV | Pixel > thresh set to 0, else unchanged |
Key Takeaways
Always convert images to grayscale before applying threshold in OpenCV.
Choose the threshold value carefully to get meaningful segmentation results.
Use the correct threshold type to match your desired output.
The cv2.threshold function returns both the threshold used and the thresholded image.
Experiment with different threshold types for different image processing tasks.