Sub topic 10
Canny edge detection and hysteresis thresholds
This chapter assumes you can read an image with cv2.imread, convert it to grayscale, and use NumPy arrays. It also assumes you have met Gaussian smoothing and Sobel gradients from the earlier chapters. Here you will see how cv2.Canny combines those pieces into a thin, connected edge map. You will also see why it takes two thresholds and why you should blur the image first.
What Canny produces
A Sobel gradient magnitude image shows where intensity changes, but its edges are thick and blurry. Many pixels near a real edge have a large gradient. If you threshold the magnitude directly, you get bands several pixels wide, and noise produces scattered specks.
cv2.Canny returns a binary uint8 image. Edge pixels are 255 and everything else is 0. Edges are about one pixel wide, and weak responses survive only if they connect to strong ones.
The four stages
Canny works in four stages. OpenCV runs the last three inside cv2.Canny. The first stage you do yourself.
- Smooth. Blur the image to suppress noise. Without this, Sobel responds to every noisy pixel.
- Compute gradients. Apply Sobel in x and y, then compute magnitude and direction. Direction is rounded to one of four sectors: horizontal, vertical, and the two diagonals.
- Non-maximum suppression. For each pixel, compare its magnitude with its two neighbours along the gradient direction. If it is not the largest of the three, set it to zero. This thins a wide ridge to a single-pixel line.
- Hysteresis thresholding. Use two thresholds to decide which surviving pixels are edges.
Hysteresis thresholds
Hysteresis uses a low threshold and a high threshold. Each pixel left after suppression falls into one of three classes:
| Gradient magnitude | Classification | Outcome |
|---|---|---|
| Above the high threshold | Strong edge | Always kept |
| Between low and high | Weak edge | Kept only if connected to a strong edge |
| Below the low threshold | Not an edge | Discarded |
Connected means touching a kept pixel through its eight neighbours, directly or through a chain of other weak pixels. Chains that never reach a strong pixel are dropped.
A single threshold forces a bad trade. Set it high and edges break wherever the contrast dips slightly. Set it low and noise appears everywhere. Two thresholds let strong evidence start an edge, while weaker evidence can extend it along a contour. A faint stretch of a real edge is kept because it is attached to a strong stretch. An isolated faint speck is not.
A common starting point is a high threshold two to three times the low one. The function call below follows that ratio.
Calling cv2.Canny
import cv2
import numpy as np
img = cv2.imread("input.jpg")
if img is None:
raise FileNotFoundError("input.jpg could not be read")
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
blur = cv2.GaussianBlur(gray, (5, 5), 0)
edges = cv2.Canny(blur, 50, 150)
edges_l2 = cv2.Canny(blur, 50, 150, L2gradient=True)
print(edges.shape, edges.dtype) # (height, width) uint8
print("edge pixels:", np.count_nonzero(edges))
print("with L2 norm:", np.count_nonzero(edges_l2))The signature is cv2.Canny(image, threshold1, threshold2, apertureSize=3, L2gradient=False). These are the parts that matter:
imagemust be an 8-bit single-channel image. OpenCV also accepts 8-bit color input in recent versions, but it computes the gradient per channel and takes the strongest response. Converting to grayscale yourself keeps the behaviour predictable.threshold1,threshold2are the two hysteresis thresholds. OpenCV uses the smaller as the low value and the larger as the high value, so the order you pass them does not matter.apertureSizeis the Sobel kernel size. It defaults to 3 and must be odd, from 3 to 7. Larger values respond to broader, smoother edges.L2gradientchooses how magnitude is computed. WithFalse, OpenCV uses the cheaper L1 norm,|gx| + |gy|. WithTrue, it uses the L2 norm,sqrt(gx² + gy²). The L2 norm is more accurate, and it gives smaller values for diagonal edges than L1 does. Because the two norms scale differently, thresholds tuned for one do not transfer exactly to the other.
Why the pre-blur matters
Sobel is a derivative filter, so it amplifies high-frequency content. Sensor noise is high-frequency. Without smoothing, a noisy flat region produces many small gradients, and some exceed the thresholds. Those become short, scattered edge fragments.
A Gaussian blur removes most of that noise before differentiation. The cost is that real edges also soften and can shift slightly. The blur size is a trade-off:
- A small blur such as
(3, 3)keeps fine detail and lets more noise through. - A large blur such as
(9, 9)removes texture and fine structure, so only large contours remain.
cv2.Canny does not blur the image for you. The original algorithm includes a Gaussian step, but the OpenCV function does not, so you must call cv2.GaussianBlur yourself.
Choosing thresholds
You can set thresholds by hand, but a useful automatic starting point derives them from the image median. This adapts to overall brightness and contrast.
import cv2
import numpy as np
def auto_canny(gray_blurred, sigma=0.33):
"""Pick Canny thresholds around the median intensity."""
median = float(np.median(gray_blurred))
low = int(max(0, (1.0 - sigma) * median))
high = int(min(255, (1.0 + sigma) * median))
return cv2.Canny(gray_blurred, low, high)
img = cv2.imread("input.jpg", cv2.IMREAD_GRAYSCALE)
if img is None:
raise FileNotFoundError("input.jpg could not be read")
blur = cv2.GaussianBlur(img, (5, 5), 0)
edges = auto_canny(blur)
print("edge pixels:", np.count_nonzero(edges))This heuristic is a starting point and not a guarantee. It uses image brightness, which is only loosely related to edge strength. An image with a bright background and faint edges can get thresholds that are too high. Always check the result visually.
A more principled alternative is to use the Otsu threshold as the high value and half of it as the low value. Otsu's method is covered later in this tutorial. It works well when the image has a clear foreground and background.
Tuning by observation
Tune in a consistent order so you know which change caused which effect.
- Fix the blur first. Pick the smallest kernel that removes the noise you see.
- Set the high threshold. Raise it until background noise stops forming strong edges.
- Set the low threshold. Lower it until real contours connect, and stop before noise attaches to them.
The effect of each knob is predictable:
| Change | Typical effect |
|---|---|
| Raise the high threshold | Fewer starting points, so fewer edges overall |
| Lower the high threshold | More edges, more noise |
| Raise the low threshold | Edges break into fragments |
| Lower the low threshold | Edges extend further and link up, and may leak into texture |
| Larger blur | Smoother, fewer fine edges |
| Larger `apertureSize` | Responds to broader edges |
Edge cases and common mistakes
- Passing a float or 16-bit image.
cv2.Cannyrequires 8-bit input. Convert withcv2.normalizeandastype(np.uint8)first, or you will get an assertion error. - Skipping the blur. This is the most common cause of speckled output.
- Forgetting that the output is binary. There is no soft edge strength in the result. If you need magnitudes, compute them with Sobel as in the previous chapter.
- Expecting closed contours. Canny can leave small gaps. If you need closed shapes, apply a morphological closing to the edge map, or use a contour method that tolerates gaps.
- Using thresholds on the wrong scale. Sobel on 8-bit data can give magnitudes well above 255 for strong edges, and Canny handles this internally. Do not rescale your image to try to fit the thresholds. Adjust the thresholds instead.
- Swapping thresholds between norms. After switching
L2gradient, recheck the result. - Low contrast images. If edges are faint, thresholds that work elsewhere will find nothing. Consider contrast adjustment before blurring, or set lower thresholds.
Checking your result
A quick numeric check helps when you cannot view images. The fraction of edge pixels is a rough sanity signal.
import cv2
import numpy as np
gray = cv2.imread("input.jpg", cv2.IMREAD_GRAYSCALE)
if gray is None:
raise FileNotFoundError("input.jpg could not be read")
blur = cv2.GaussianBlur(gray, (5, 5), 0)
for low, high in [(20, 60), (50, 150), (100, 200)]:
edges = cv2.Canny(blur, low, high)
fraction = np.count_nonzero(edges) / edges.size
print(f"low={low:3d} high={high:3d} edge fraction={fraction:.3%}")For many natural photographs, a few percent edge pixels looks reasonable, and tens of percent usually means noise. Treat these as rough guides, since the right value depends on the scene. A page of text will have a very different fraction from a sky photograph.
Exercise
You run cv2.Canny(blur, 50, 150) and see long contours broken into many short dashes, but almost no noise in the flat regions. Which parameter should you change first, and in which direction? Explain why.
Show answer
Lower the low threshold (for example from 50 to 30). Contours break into dashes when parts of an edge fall below the low threshold, so those pixels are discarded even though they are attached to strong edge pixels. A lower low threshold lets weak pixels connected to a strong pixel survive. The high threshold is already producing clean starting points with little noise, so leave it alone.
Exercise
Why does cv2.Canny give a one-pixel-wide edge, while thresholding a Sobel magnitude image gives a wide band?
Show answer
Canny applies non-maximum suppression before hysteresis. For each pixel it compares the gradient magnitude with the two neighbours along the gradient direction and keeps the pixel only if it is the local maximum. This reduces a ridge several pixels wide to a single-pixel line. Plain thresholding keeps every pixel above the cutoff, including all the pixels on both sides of the ridge peak.