Sub topic 1
Preparing a binary image: grayscale, blur and thresholding
Prerequisites
This chapter assumes you can load and save images with cv2, index NumPy arrays, and read pixel values. You should know that a grayscale image stores one brightness value per pixel, from 0 (black) to 255 (white).
Grayscale, blur and thresholding
cv2.findContours expects a binary image: a single-channel image where the shapes are white (255) and the background is black (0). Getting there takes three steps. Convert to grayscale, smooth out sensor noise with a Gaussian blur, and then apply a threshold that splits pixels into foreground and background.
import cv2
img = cv2.imread("shapes.png")
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
blur = cv2.GaussianBlur(gray, (5, 5), 0)
_, binary = cv2.threshold(blur, 0, 255, cv2.THRESH_BINARY_INV + cv2.THRESH_OTSU)The THRESH_OTSU flag picks the threshold value automatically. THRESH_BINARY_INV turns dark shapes on a light background into white foreground.
Edges as an alternative input: Canny
Instead of a filled mask, you can pass edge pixels to findContours. cv2.Canny finds edges using two hysteresis thresholds. Edges give you outlines, but they can break into gaps, so the filled threshold is usually the safer input.
edges = cv2.Canny(blur, 50, 150)Cleaning masks with morphological operations
Thresholding often leaves specks and small holes. Opening (erode, then dilate) removes specks. Closing (dilate, then erode) fills small holes.
kernel = cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (3, 3))
clean = cv2.morphologyEx(binary, cv2.MORPH_OPEN, kernel)
clean = cv2.morphologyEx(clean, cv2.MORPH_CLOSE, kernel)Finding contours with cv2.findContours
cv2.findContours returns a list of contours, where each contour is an array of boundary points. Pass the cleaned mask and choose a retrieval mode. cv2.RETR_EXTERNAL returns only outermost contours.
contours, hierarchy = cv2.findContours(clean, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
print("contours found:", len(contours))Choosing a contour approximation method
The approximation flag controls how many points each contour stores.
| Flag | Points stored | Typical use |
|---|---|---|
| `cv2.CHAIN_APPROX_NONE` | Every boundary pixel | Exact outlines, slower and larger |
| `cv2.CHAIN_APPROX_SIMPLE` | Only the end points of straight runs | Most shape tasks, smaller and faster |
Exercise
Why does the pipeline use THRESHBINARYINV when the shapes are dark on a light background?
Show answer
It inverts the output so the dark shapes become white (255), which is the foreground that findContours traces.