Before deep learning, and still today for many industrial tasks, computer vision relies on classic image processing: grayscale conversion, blurring, thresholding, edge detection and contours. This tutorial builds a small shape detector with OpenCV and shows why each step matters.
What You Will Learn
- Create and read images as NumPy arrays
- Grayscale and Gaussian blur
- Otsu thresholding and morphology
- Canny edge detection
- Find contours and recognise shapes
Prerequisites
Introduction to OpenCV, NumPy.
Create a Noisy Test Image
import cv2
import numpy as np
img = np.zeros((200, 300, 3), np.uint8) # black canvas (BGR)
cv2.rectangle(img, (20, 30), (100, 120), (255, 255, 255), -1)
cv2.circle(img, (180, 80), 40, (255, 255, 255), -1)
cv2.fillPoly(img, [np.array([[230, 170], [290, 170], [260, 110]], np.int32)], (255, 255, 255))
rng = np.random.default_rng(0)
noisy = np.clip(img.astype(int) + rng.normal(0, 80, img.shape), 0, 255).astype(np.uint8)
cv2.imwrite("shapes.png", noisy)
Explanation: An image is just a NumPy array of shape (height, width, channels). OpenCV uses BGR channel order. We draw a rectangle, a circle and a triangle, then add heavy random noise to simulate a poor camera.
Threshold With and Without Blur
gray = cv2.cvtColor(noisy, cv2.COLOR_BGR2GRAY)
t1, th_raw = cv2.threshold(gray, 0, 255, cv2.THRESH_BINARY + cv2.THRESH_OTSU)
c_raw, _ = cv2.findContours(th_raw, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
blur = cv2.GaussianBlur(gray, (5, 5), 0)
t2, th = cv2.threshold(blur, 0, 255, cv2.THRESH_BINARY + cv2.THRESH_OTSU)
th = cv2.morphologyEx(th, cv2.MORPH_OPEN, np.ones((3, 3), np.uint8)) # remove specks
cnts, _ = cv2.findContours(th, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
print(t1, t2, "without blur", len(c_raw), "with blur+open", len(cnts))
126.0 124.0 without blur 459 with blur+open 3
Explanation: Otsu picks the threshold automatically (≈125) by separating the two brightness groups. Thresholding the raw noisy image produces 459 contours – every noise speck becomes an “object”. A 5×5 Gaussian blur averages out the noise and a morphological opening (erode then dilate) removes leftover specks, leaving exactly the 3 real shapes.
Recognise the Shapes
for c in sorted(cnts, key=lambda c: cv2.boundingRect(c)[0]): # left to right
approx = cv2.approxPolyDP(c, 0.04 * cv2.arcLength(c, True), True)
n = len(approx)
name = "triangle" if n == 3 else "rectangle" if n == 4 else "circle"
print(name, n, cv2.boundingRect(c), int(cv2.contourArea(c)))
rectangle 4 (20, 30, 81, 91) 7199 circle 8 (141, 41, 79, 79) 4908 triangle 3 (231, 112, 59, 59) 1797
Explanation: approxPolyDP simplifies each outline to a polygon; the number of corners identifies the shape (many corners ≈ circle). boundingRect gives (x, y, width, height) and contourArea the size in pixels – the rectangle’s 81×91 box matches what we drew. Draw results with cv2.drawContours(img, cnts, -1, (0, 255, 0), 2).
Edge Detection
e_raw = cv2.Canny(gray, 50, 150)
e_blur = cv2.Canny(blur, 50, 150)
print("edge pixels raw", int((e_raw > 0).sum()), "blurred", int((e_blur > 0).sum()))
edge pixels raw 21844 blurred 3732
Explanation: Canny finds strong intensity changes using two thresholds (50 and 150) with hysteresis. On the raw image noise creates 21,844 edge pixels; after blurring only about 3,700 remain, mostly the true outlines. Always smooth before edge detection.
Cheat Sheet
| Task | OpenCV function |
|---|---|
| Read / save | cv2.imread, cv2.imwrite |
| Colour conversion | cv2.cvtColor(img, cv2.COLOR_BGR2GRAY / COLOR_BGR2HSV) |
| Resize / rotate | cv2.resize, rotation |
| Blur | cv2.GaussianBlur, cv2.medianBlur (salt-and-pepper noise) |
| Threshold | cv2.threshold (Otsu), cv2.adaptiveThreshold (uneven lighting) |
| Morphology | cv2.erode, cv2.dilate, cv2.morphologyEx |
| Edges | cv2.Canny, cv2.Sobel |
| Contours | cv2.findContours, cv2.contourArea, cv2.approxPolyDP |
| Colour masks | cv2.inRange on HSV images |
Series
Computer vision series: OpenCV Intro · Image Processing · Image Classification · Data Augmentation · CNN · Transfer Learning · Object Detection (YOLO) · Image Segmentation · OCR · Face Detection
Interview Questions
Q: Why blur before thresholding or edge detection?
Blurring removes high-frequency noise that would otherwise create false edges and contours.
Q: What does Otsu’s method do?
Chooses the threshold that best separates foreground and background brightness levels.
Q: Erosion vs dilation?
Erosion shrinks white regions and removes specks; dilation grows them and fills gaps.
Practice Exercises
- Count coins in a photo using blur, threshold and contours.
- Detect only red objects using an HSV mask with cv2.inRange.
Summary
Grayscale → blur → threshold (Otsu) → morphology → contours is the classic pipeline for finding objects; Canny finds edges. Blurring makes the difference between 459 false objects and the 3 real ones.
Next: Image Classification
Machine Learning Tutorials, Courses and Certifications