Image thresholding — computer vision in the browser

Thresholding turns a grayscale image into black-and-white by comparing each pixel to a cutoff — the simplest segmentation step in computer vision. This OpenCV demo contrasts a fixed global threshold with adaptive thresholding, which adjusts the cutoff per region. Run it live and change the parameters.

Image thresholding — example output

Example code (Python / OpenCV)

import cv2
import numpy as np

# Horizontal gradient 0..255
grad = np.tile(np.linspace(0, 255, 400, dtype=np.uint8), (300, 1))
cv2.imshow("gray", grad)

_, binary = cv2.threshold(grad, 127, 255, cv2.THRESH_BINARY)
cv2.imshow("global (127)", binary)

adaptive = cv2.adaptiveThreshold(grad, 255, cv2.ADAPTIVE_THRESH_MEAN_C,
                                 cv2.THRESH_BINARY, 11, 2)
cv2.imshow("adaptive", adaptive)
print("Fixed global vs adaptive thresholding on a gradient.")

More computer-vision techniques →