Sub topic 10
Canny Edge Detection and Hysteresis Thresholds
Assume you know basic Python, NumPy arrays, grayscale images, and OpenCV image loading. You should also understand that a grayscale image stores intensity values, usually from 0 to 255.
Canny edge detection converts an image into a binary edge map. Edge pixels are white, and non-edge pixels are black. It combines several operations:
- Smooth the image to reduce noise.
- Compute intensity gradients.
- Keep thin local maxima instead of thick gradient regions.
- Classify pixels with two thresholds.
- Keep weak edges only when they connect to strong edges.
The last step is called hysteresis. It prevents isolated noise responses from becoming edges while preserving faint parts of real contours.
How the two thresholds work
Canny uses a high threshold and a low threshold.
| Gradient strength | Classification | Final result |
|---|---|---|
| At least the high threshold | Strong edge | Keep |
| Between low and high | Weak edge | Keep only if connected to a strong edge |
| Below the low threshold | Non-edge | Remove |
A strong edge starts an edge chain. A weak edge joins that chain if it is connected through neighboring edge pixels. OpenCV follows these connections during hysteresis.
The thresholds describe gradient strength, not brightness. A threshold of 50 does not mean that pixels brighter than 50 become edges. It means that an intensity change with sufficient gradient strength can become an edge.
Pre-blur before Canny
Noise creates small, sharp intensity changes. Canny may interpret those changes as edges. A Gaussian blur reduces high-frequency noise before gradient computation.
Too little blur leaves noisy fragments. Too much blur removes narrow objects and rounds corners. A kernel such as (5, 5) is a practical starting point for many 8-bit images.
import cv2
image = cv2.imread("input.jpg")
if image is None:
raise FileNotFoundError("input.jpg could not be read")
gray = cv2.cvtColor(image, 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)
cv2.imwrite("edges.png", edges)
cv2.imwrite("edges_l2.png", edges_l2)cv2.Canny performs the gradient calculation, non-maximum suppression, and hysteresis internally. The arguments 50 and 150 are the low and high thresholds. L2gradient=True uses the more precise Euclidean gradient magnitude. The default uses a faster approximation.
Understanding the output
Inspect the result at several threshold pairs. Lower thresholds reveal faint contours but also increase noise. Higher thresholds produce cleaner maps but may break faint or low-contrast objects.
Exercise
An edge map contains many isolated specks after Canny. Which changes should you try first, and why?
Show answer
Increase or improve the pre-blur to suppress noise, then raise the low threshold or high threshold. Check whether real thin edges disappear before choosing the final values.