Sub topic 2
Edges as an Alternative Input: Canny
This chapter assumes you can load and save images with cv2, index NumPy arrays, and convert an image to grayscale. It also assumes you have seen thresholding. You will learn when to feed cv2.findContours an edge map instead of a thresholded mask, how the Canny detector works inside, and how to avoid the errors that edge-based contours usually bring.
Why use edges instead of a threshold
Thresholding works when the object and the background differ in overall brightness. It fails when they do not. A gray part on a gray table, a shape with a gradient fill, or a scene with uneven lighting can all produce a threshold mask that is half full or full of noise.
An edge map records where brightness changes sharply, not how bright a region is. A boundary between two similar grays can still be a clear step. So edges can recover outlines that a single global threshold cannot.
The cost is that edges describe lines, not filled regions. This changes what findContours returns, as the later sections show.
How Canny works
cv2.Canny runs four stages. Knowing them tells you which parameter to change when the result looks wrong.
- Smoothing. A Gaussian blur reduces noise. OpenCV's
Cannydoes not blur for you, so you blur first. - Gradient. A Sobel filter measures how fast brightness changes at each pixel. This gives a gradient magnitude (edge strength) and a direction.
- Non-maximum suppression. Each pixel is compared with its two neighbors along the gradient direction. It survives only if it is the local maximum. This thins thick ridges to lines about one pixel wide.
- Hysteresis thresholding. Two thresholds,
threshold1(low) andthreshold2(high), decide which pixels remain. - Magnitude above the high threshold: a strong edge, always kept.
- Magnitude below the low threshold: discarded.
- Between the two: kept only if connected to a strong edge.
Hysteresis is the reason Canny edges are continuous. A weak but real stretch of an edge survives because it touches a strong stretch. An isolated weak response, which is likely noise, does not.
Running Canny
The output is a single-channel uint8 image. Edge pixels are 255 and everything else is 0. That is a binary image, so it can go straight into findContours.
import cv2
img = cv2.imread("shapes.png")
if img is None:
raise FileNotFoundError("shapes.png not found")
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
blur = cv2.GaussianBlur(gray, (5, 5), 0)
edges = cv2.Canny(blur, 50, 150)
cv2.imwrite("edges.png", edges)
print("edge pixels:", int((edges > 0).sum()))The parameters
| Parameter | Meaning | Typical use |
|---|---|---|
| `threshold1` | Low hysteresis threshold | About one third to one half of `threshold2` |
| `threshold2` | High hysteresis threshold | Raise it to keep fewer, stronger edges |
| `apertureSize` | Sobel kernel size (3, 5 or 7) | Default 3 is usually enough |
| `L2gradient` | Use the exact L2 norm for magnitude | Default `False` uses the faster L1 sum |
The common ratio between the thresholds is 1:2 or 1:3. If the output has too much clutter, raise both. If outlines have gaps, lower the low threshold so more weak pixels can connect to strong ones.
Choosing thresholds from the image
Fixed numbers such as 50 and 150 are guesses. A common automatic rule sets the thresholds around the median brightness of the image.
import cv2
import numpy as np
def auto_canny(gray, sigma=0.33):
v = float(np.median(gray))
low = int(max(0, (1.0 - sigma) * v))
high = int(min(255, (1.0 + sigma) * v))
return cv2.Canny(gray, low, high)
img = cv2.imread("shapes.png", cv2.IMREAD_GRAYSCALE)
blur = cv2.GaussianBlur(img, (5, 5), 0)
edges = auto_canny(blur)
print("edge pixels:", int((edges > 0).sum()))This is a heuristic. It adapts to overall exposure, but it does not know what you want to keep. Treat it as a starting point and check the result visually.
Feeding edges to findContours
You can pass the edge map directly, but the result differs from a filled mask in one important way. An edge is a thin line. findContours traces the boundary of each white region, so a one-pixel line is traced on both sides. A closed outline gives two contours: an outer one just outside the line and an inner one just inside it.
import cv2
img = cv2.imread("shapes.png")
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
blur = cv2.GaussianBlur(gray, (5, 5), 0)
edges = cv2.Canny(blur, 50, 150)
contours, hierarchy = cv2.findContours(edges, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
print("external contours:", len(contours))
contours_all, hierarchy_all = cv2.findContours(edges, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)
print("all contours:", len(contours_all))With RETR_EXTERNAL you get the outside of each closed outline. With RETR_TREE you also get the inner boundary of every outline, so the count is roughly doubled. Later chapters cover retrieval modes in detail.
Two consequences follow:
- Areas are unreliable. The area of the outer contour of a thin outline is close to the true shape area, but the contour of an unclosed line has almost zero area.
- Perimeters of edge contours are roughly twice the true value when the contour wraps both sides of an open line.
Closing gaps before finding contours
The main failure of edge-based contours is a broken outline. If a single pixel is missing, the shape is an open curve. RETR_EXTERNAL then returns a contour that hugs the line rather than the shape, and the area of the enclosed region is lost.
A small dilation closes these gaps. It also thickens the lines, which is acceptable because you only need a connected boundary.
import cv2
img = cv2.imread("shapes.png")
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
blur = cv2.GaussianBlur(gray, (5, 5), 0)
edges = cv2.Canny(blur, 50, 150)
kernel = cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (3, 3))
closed = cv2.morphologyEx(edges, cv2.MORPH_CLOSE, kernel, iterations=2)
contours, _ = cv2.findContours(closed, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
print("contours after closing:", len(contours))
out = img.copy()
cv2.drawContours(out, contours, -1, (0, 255, 0), 2)
cv2.imwrite("edge_contours.png", out)MORPH_CLOSE is a dilation followed by an erosion. It fills gaps smaller than the kernel while keeping line thickness close to the original. The next chapter covers morphology in full. If the gaps are wider than a few pixels, increase the iterations or the kernel size, but expect nearby shapes to merge.
Another option is to fill the regions. After closing, findContours with RETR_EXTERNAL gives the outer boundaries. You can draw those with thickness=cv2.FILLED onto a blank mask to get a solid region mask for later measurements.
import cv2
import numpy as np
mask = np.zeros(closed.shape, dtype=np.uint8)
cv2.drawContours(mask, contours, -1, 255, thickness=cv2.FILLED)
print("filled pixels:", int((mask > 0).sum()))Choosing between threshold and Canny
| Situation | Better input |
|---|---|
| Clear brightness difference between object and background | Threshold |
| Uneven lighting that a single threshold cannot handle | Adaptive threshold, or Canny |
| Object and background have similar brightness but a sharp boundary | Canny |
| You need accurate area of filled shapes | Threshold, or Canny plus filling |
| Textured background with many small edges | Threshold, or heavy blur before Canny |
Common errors
- No blur before Canny. Sensor noise produces many short edge fragments. These become many tiny contours. Blur first, and filter small contours afterward.
- Thresholds too close together. If the low and high values are nearly equal, hysteresis has no effect and edges break up. Keep a ratio of at least 1:2.
- Passing a color image.
cv2.Cannyaccepts 8-bit images and treats multi-channel input differently from grayscale in some versions. Convert to grayscale yourself so the behavior is predictable. - Expecting filled areas.
contourAreaon an unclosed edge contour is near zero. Close and fill first. - Double contours. With
RETR_TREEorRETR_LIST, one outline can yield two contours. UseRETR_EXTERNALwhen you only want outer boundaries. - Reading the wrong return values. In OpenCV 4,
findContoursreturns(contours, hierarchy). In OpenCV 3 it returned three values, with the image first. Code copied from older tutorials fails with an unpacking error.
Summary of the workflow
- Convert to grayscale.
- Blur with a Gaussian kernel.
- Run
cv2.Cannywith thresholds in a 1:2 or 1:3 ratio. - Close small gaps with
MORPH_CLOSE. - Call
findContours, usingRETR_EXTERNALfor outer outlines. - Optionally fill the contours into a mask for accurate measurements.
Exercise
You run Canny on a photo of a coin and call findContours with RETR_EXTERNAL, but the largest contour has an area close to zero. The edge image shows the coin's outline with one small gap. What is happening, and what two steps fix it?
Show answer
The outline is not closed, so findContours traces the thin line itself rather than a region enclosing the coin, and the area of a one-pixel-wide line is almost zero. Close the gap with cv2.morphologyEx using MORPH_CLOSE and a small elliptical kernel, then call findContours again. If you need a solid region, draw the resulting contour onto a blank mask with thickness=cv2.FILLED before measuring.
Exercise
A scene has an average brightness of 120 and you use the median rule with sigma=0.33. What low and high thresholds does auto_canny produce?
Show answer
The low threshold is int(0.67 120) = 80 and the high threshold is int(1.33 120) = 159, because 1.33 * 120 is 159.6 and int truncates it. The ratio is about 1:2, which fits the usual guidance.