Canny Edge Detection
The Canny edge detector is the gold standard algorithm for edge detection. It produces clean, thin edges with minimal noise by combining multiple processing steps into one optimised pipeline.
10 min•By Priygop Team•Updated 2026
How Canny Works
The Canny edge detector works in 5 steps:
- 1Gaussian blur — reduce noise before detecting edges
- 2Sobel gradients — compute edge strength in x and y directions
- 3Non-maximum suppression — thin edges to 1 pixel wide
- 4Double threshold — classify strong, weak, and non-edges
- 5Hysteresis — keep weak edges only if connected to strong edges
The two threshold parameters control sensitivity:
- threshold1 (low): minimum gradient to consider a potential edge
- threshold2 (high): minimum gradient to consider a definite edge
- Pixels between thresholds: kept only if connected to definite edges
Rule of thumb: threshold2 / threshold1 ≈ 2:1 to 3:1
Diagram
Loading diagram…
Machine Learning follows a structured pipeline from data to deployment
Canny Edge Detection
Canny Edge Detection
import cv2
import numpy as np
image = cv2.imread("photo.jpg")
gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
# Always blur slightly before Canny to reduce noise
blurred = cv2.GaussianBlur(gray, (5, 5), 0)
# Canny(image, threshold1, threshold2)
# threshold1 < threshold2 — ratio of about 1:2 or 1:3
edges_loose = cv2.Canny(blurred, 50, 150) # More edges (sensitive)
edges_medium = cv2.Canny(blurred, 100, 200) # Balanced
edges_strict = cv2.Canny(blurred, 150, 300) # Fewer, stronger edges only
# Count detected edge pixels
print(f"Loose edges: {edges_loose.sum() // 255:,} pixels")
print(f"Medium edges: {edges_medium.sum() // 255:,} pixels")
print(f"Strict edges: {edges_strict.sum() // 255:,} pixels")
# Overlay edges on original image
result = image.copy()
result[edges_medium > 0] = [0, 255, 0] # Colour edges green
cv2.imwrite("canny_edges.jpg", edges_medium)
cv2.imwrite("canny_overlay.jpg", result)
print("Canny edge detection complete")