Sub topic 2
Edges as an Alternative Input: Canny
This chapter assumes that you can load, save, and display images with OpenCV, and that you understand grayscale images and NumPy arrays. It also assumes basic Python.
A contour is a curve that follows a boundary in a binary image. Thresholding creates that binary image by assigning pixels to foreground or background. Canny edge detection offers another input: instead of a filled foreground region, it creates thin lines at strong intensity changes.
What Canny produces
The Canny algorithm detects likely edges in several stages:
- It smooths the image to reduce noise.
- It calculates the strength and direction of intensity changes.
- It keeps thin local maxima through non-maximum suppression.
- It uses two thresholds to classify strong and weak edges.
- It connects weak edges that touch strong edges.
The result is usually a black image containing white, one-pixel-wide edge lines. You can pass this result to cv2.findContours.
Choosing Canny thresholds
Canny uses a low threshold and a high threshold. A pixel stronger than the high threshold becomes a strong edge. A weaker pixel can still become an edge if it connects to a strong edge and is above the low threshold.
The thresholds have no universal correct values. They depend on image contrast, noise, lighting, and object size.
| Setting | Effect |
|---|---|
| Lower thresholds | Detect more edges, including noise |
| Higher thresholds | Detect fewer, stronger edges |
| Larger blur | Removes noise but can erase small boundaries |
A common starting point is a ratio of 1:2 or 1:3 between the low and high thresholds.
Using Canny with contours
The following example reads an image, creates an edge map, and extracts external contours.
import cv2
image = cv2.imread("shapes.png")
if image is None:
raise FileNotFoundError("Could not read shapes.png")
gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
blurred = cv2.GaussianBlur(gray, (5, 5), 0)
edges = cv2.Canny(blurred, 50, 150)
contours, hierarchy = cv2.findContours(
edges,
cv2.RETR_EXTERNAL,
cv2.CHAIN_APPROX_SIMPLE,
)
output = image.copy()
cv2.drawContours(output, contours, -1, (0, 255, 0), 2)
cv2.imwrite("edges.png", edges)
cv2.imwrite("contours_from_edges.png", output)
print("contours found:", len(contours))Canny is useful when object boundaries are clear but filling the objects with thresholding is difficult. However, an object boundary has two sides. Depending on the image, Canny may produce two nearby contours around a thick border. A thresholded filled mask often produces one outer contour instead.
Common errors
- Too many contours: Increase the blur, raise the thresholds, or filter contours by area.
- Missing boundaries: Lower one or both thresholds, reduce blur, or improve image contrast.
- Broken contours: Use morphological closing after Canny to connect small gaps.
- Unexpected duplicate contours: Remember that both sides of a thick line may be detected.
- Wrong contour count: Use
RETR_TREEwhen nested boundaries matter, rather than assuming every contour is an independent object.
Canny detects changes, not objects. A shadow, texture edge, or text stroke can be as important to Canny as the boundary of the object you want. The later contour-processing steps cannot recover a boundary that the edge detector missed.
Exercise
Why might a thresholded mask be preferable to a Canny edge map for measuring the area of a solid object?
Show answer
A thresholded mask fills the object, so its outer contour encloses the object region directly. Canny usually returns boundary lines, possibly including both sides of an edge, which can produce duplicate or incomplete contours.