Morphological operations — computer vision in the browser

Morphological operations reshape binary regions with a small kernel: erosion shrinks, dilation grows, opening removes specks and closing fills gaps — the standard clean-up for masks and scanned text in computer vision. This fetches a document photo, thresholds it, and shows all four (cv2.morphologyEx). Run it live.

Morphological operations — example output

Example code (Python / OpenCV)

"""
Morphological operations

Morphological operations reshape binary regions with a small kernel: erosion shrinks, dilation grows, opening removes specks and closing fills gaps — the standard clean-up for masks and scanned text in computer vision. This fetches a document photo, thresholds it, and shows all four (cv2.morphologyEx). Run it live.
"""

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)
_, bw = cv2.threshold(gray, 0, 255, cv2.THRESH_BINARY_INV + cv2.THRESH_OTSU)
k = np.ones((3, 3), np.uint8)

cv2.imshow("binary", bw)
cv2.imshow("erode", cv2.erode(bw, k))
cv2.imshow("dilate", cv2.dilate(bw, k))
cv2.imshow("open (denoise)", cv2.morphologyEx(bw, cv2.MORPH_OPEN, k))
cv2.imshow("close (fill)", cv2.morphologyEx(bw, cv2.MORPH_CLOSE, k))

More computer-vision techniques →