Sub topic 15
Putting It Together: A Filter, Edge, and Threshold Pipeline
This chapter assumes basic Python, NumPy array indexing and data types, grayscale images, and a working OpenCV installation. The goal is to build a pipeline that produces both an edge map and a foreground mask.
Choose the order of operations
Each stage prepares data for the next stage:
- Read the image as a grayscale array.
- Blur it to reduce small noise.
- Run Canny on the blurred image to find object boundaries.
- Use Otsu thresholding to create a binary foreground mask.
- Apply morphological opening and closing to clean the mask.
- Save and inspect every intermediate result.
The edge map answers “where does intensity change?” The threshold mask answers “which pixels belong to the foreground?” They are related, but they are not interchangeable.
A complete pipeline
This example saves each result so that you can inspect the effect of every stage. The assertions act as small tests: they catch unexpected shapes or data types before later processing hides the problem.
import cv2
from pathlib import Path
input_path = Path("input.jpg")
gray = cv2.imread(str(input_path), cv2.IMREAD_GRAYSCALE)
if gray is None:
raise FileNotFoundError(f"Could not read {input_path}")
blur = cv2.GaussianBlur(gray, (5, 5), 0)
# The lower threshold links weak edges to nearby strong edges.
# The upper threshold identifies strong candidate edges.
edges = cv2.Canny(blur, 50, 150, L2gradient=True)
# Otsu selects the threshold from the blurred image histogram.
otsu_value, mask = cv2.threshold(
blur, 0, 255, cv2.THRESH_BINARY + cv2.THRESH_OTSU
)
kernel = cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (5, 5))
opened = cv2.morphologyEx(mask, cv2.MORPH_OPEN, kernel)
clean_mask = cv2.morphologyEx(opened, cv2.MORPH_CLOSE, kernel)
assert gray.ndim == 2 and gray.dtype == "uint8"
assert edges.shape == gray.shape
assert clean_mask.shape == gray.shape
outputs = {
"gray.png": gray,
"blur.png": blur,
"edges.png": edges,
"mask.png": mask,
"clean_mask.png": clean_mask,
}
for filename, image in outputs.items():
if not cv2.imwrite(filename, image):
raise IOError(f"Could not write {filename}")
print(f"Otsu threshold: {otsu_value:.1f}")
print("Wrote:", ", ".join(outputs))Canny uses two hysteresis thresholds. Pixels above the high threshold become strong edges. Pixels between the thresholds become edges only when connected to strong edges. A lower threshold can recover faint boundaries, but it can also add noise. A higher threshold removes weak edges, but it may break real contours.
Otsu works well when foreground and background form two fairly distinct intensity groups. For uneven lighting, replace it with adaptive thresholding. If the object is dark on a light background, use cv2.THRESH_BINARY_INV so the object becomes white.
Check each result before tuning
| Result | Useful question | Typical adjustment |
|---|---|---|
| Blur | Is noise reduced without losing small features? | Change Gaussian kernel or sigma |
| Edges | Are contours continuous and specific? | Change Canny thresholds |
| Mask | Is the foreground separated? | Change threshold method or polarity |
| Clean mask | Are specks and holes reduced? | Change morphology kernel size |
Exercise
Exercise
An image has strong shadows, so Otsu creates an incomplete foreground mask. Which pipeline stage should you replace, and what should you try?
Show answer
Replace global Otsu thresholding with adaptive thresholding, then tune its block size and constant for the scale of the lighting variation.