Thresholding is a technique used to convert an image into a binary format (black & white) by comparing pixel values with a threshold. OpenCV provides several thresholding methods such as Binary, Adaptive, and Otsu’s thresholding.
In binary thresholding, if the pixel value is greater than a threshold, it is set to white (255), otherwise black (0).
import cv2
img = cv2.imread("sample.jpg", cv2.IMREAD_GRAYSCALE)
# Apply binary thresholding
_, binary = cv2.threshold(img, 127, 255, cv2.THRESH_BINARY)
cv2.imshow("Binary Threshold", binary)
cv2.waitKey(0)
cv2.destroyAllWindows()
Adaptive thresholding calculates thresholds for smaller regions of the image, making it useful for images with varying lighting conditions.
adaptive = cv2.adaptiveThreshold(img, 255, cv2.ADAPTIVE_THRESH_MEAN_C,
cv2.THRESH_BINARY, 11, 2)
cv2.imshow("Adaptive Threshold", adaptive)
cv2.waitKey(0)
cv2.destroyAllWindows()
Otsu’s method automatically calculates the best threshold value by minimizing variance between foreground and background.
# Otsu’s thresholding
_, otsu = cv2.threshold(img, 0, 255, cv2.THRESH_BINARY + cv2.THRESH_OTSU)
cv2.imshow("Otsu Threshold", otsu)
cv2.waitKey(0)
cv2.destroyAllWindows()
✅ In this lesson, you learned about Binary, Adaptive, and Otsu’s thresholding.
These techniques are essential for image segmentation, document processing, and object recognition.
👉 Next, we will explore image filtering techniques (blur, Gaussian, median, bilateral).
