21 May Image Thresholding (Binary, Otsu, Adaptive) with OpenCV
Thresholding is a fundamental image processing technique that converts grayscale images into binary images (black and white) by classifying pixels as either “foreground” or “background” based on their intensity values. Thresholding converts grayscale images into binary images (black & white).
OpenCV provides several thresholding methods:
- Simple Binary Thresholding
The most basic form where pixels above a threshold value are set to one value, and those below to another.
- Otsu’s Thresholding
Automatically determines the optimal threshold value by analyzing the image histogram (works best with bimodal histograms).
- Adaptive Thresholding
Calculates different thresholds for different regions of the image, useful for varying lighting conditions.
Other Thresholding Variants
OpenCV also provides:
- cv2.THRESH_BINARY_INV – Inverse binary thresholding
- cv2.THRESH_TRUNC – Truncates values above threshold
- cv2.THRESH_TOZERO – Sets below-threshold pixels to zero
- cv2.THRESH_TOZERO_INV – Inverse of above
When to Use Each Method
- Binary: When you know the exact threshold value for your application
- Otsu’s: When the image has a bimodal histogram and you want automatic thresholding
- Adaptive: When lighting conditions vary across the image
Thresholding is commonly used as a preprocessing step for tasks like edge detection, object detection, and OCR.
Let us see an example of implementing Binary, Otsu, and Adaptive thresholding methods with OpenCV:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 |
# Image Thresholding (Binary, Otsu, Adaptive) import cv2 # Load image in grayscale image = cv2.imread(r'C:\Users\hp\Downloads\Astronaut.png', 0) # 0 for grayscale # Simple Binary Thresholding _, binary = cv2.threshold(image, 127, 255, cv2.THRESH_BINARY) # Otsu's Thresholding (automatic threshold) _, otsu = cv2.threshold(image, 0, 255, cv2.THRESH_BINARY + cv2.THRESH_OTSU) # Adaptive Thresholding (useful for uneven lighting) adaptive = cv2.adaptiveThreshold(image, 255, cv2.ADAPTIVE_THRESH_GAUSSIAN_C, cv2.THRESH_BINARY, 11, 2) # Display results cv2.imshow("Binary Threshold", binary) cv2.imshow("Otsu Threshold", otsu) cv2.imshow("Adaptive Threshold", adaptive) cv2.waitKey(0) cv2.destroyAllWindows() |
Output
If you liked the tutorial, spread the word and share the link and our website Studyopedia with others.
For Videos, Join Our YouTube Channel: Join Now
Read More:
- Apply Sepia Tone filter with OpenCV
- Generative AI Tutorial
- Machine Learning Tutorial
- Deep Learning Tutorial
- Ollama Tutorial
- Retrieval Augmented Generation (RAG) Tutorial
- Copilot Tutorial
- Gemini Tutorial
- ChatGPT Tutorial
No Comments