Skip to content
OpenCV

Threshold

Apply binary, adaptive, and Otsu thresholding.

By EZ4Code Team
thresholdbinarize

Code

import cv2

img = cv2.imread("doc.png", cv2.IMREAD_GRAYSCALE)

# Simple binary threshold
_, binary = cv2.threshold(img, 127, 255, cv2.THRESH_BINARY)

# Inverted binary
_, inv = cv2.threshold(img, 127, 255, cv2.THRESH_BINARY_INV)

# Otsu picks the optimal threshold automatically
_, otsu = cv2.threshold(img, 0, 255, cv2.THRESH_BINARY + cv2.THRESH_OTSU)

# Adaptive threshold handles uneven lighting
adaptive = cv2.adaptiveThreshold(img, 255, cv2.ADAPTIVE_THRESH_GAUSSIAN_C,
                                 cv2.THRESH_BINARY, 11, 2)

# Truncate and to-zero variants
_, trunc = cv2.threshold(img, 127, 255, cv2.THRESH_TRUNC)
_, tozero = cv2.threshold(img, 127, 255, cv2.THRESH_TOZERO)

cv2.imwrite("otsu.png", otsu)

Explanation

threshold() converts a grayscale image to binary using a fixed cutoff, with THRESH_BINARY_INV, TRUNC, and TOZERO offering different mappings. Otsu's method derives the cutoff from the histogram automatically, ideal for bimodal images. Adaptive threshold computes a local cutoff per block, handling uneven illumination.

More OpenCV Snippets