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.
Example code (Python / OpenCV)
"""
Image thresholding
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.
"""
import cv2
import requests
import numpy as np
# A real photo, fetched live from the web — nothing is uploaded
url = "https://images.unsplash.com/photo-1695131020187-d3dcdab5016b?w=480&q=70"
# no-cache: always fetch a fresh copy so a stale browser-cache entry can't break decoding
resp = requests.get(url, headers={"Cache-Control": "no-cache"})
img = cv2.imdecode(np.frombuffer(resp.content, np.uint8), cv2.IMREAD_COLOR)
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
cv2.imshow("gray", gray)
_, glob = cv2.threshold(gray, 127, 255, cv2.THRESH_BINARY) # fixed cutoff
_, otsu = cv2.threshold(gray, 0, 255, cv2.THRESH_BINARY + cv2.THRESH_OTSU) # auto cutoff
adap = cv2.adaptiveThreshold(gray, 255, cv2.ADAPTIVE_THRESH_GAUSSIAN_C,
cv2.THRESH_BINARY, 15, 8) # per-region
cv2.imshow("global 127", glob)
cv2.imshow("otsu", otsu)
cv2.imshow("adaptive", adap)