Canny edge detector

Also known as: Canny algorithm

On this page 7

The Canny edge detector is a multi-stage edge detection algorithm that smooths an image, computes intensity gradients, thins candidate edges to single-pixel width and keeps only edges confirmed by two thresholds with hysteresis. Computer vision practitioners still treat it as the reference classical method for turning a grayscale image into a clean binary edge map, even in pipelines dominated by deep learning within artificial intelligence.

John Canny introduced the method in 1986 together with three explicit design criteria: good detection (few missed and few false edges), good localization (edges drawn close to their true position) and a single response per edge. The Canny algorithm is an engineered approximation of the operator that best satisfies these criteria for step edges in Gaussian noise, which explains why it remains a default baseline in libraries such as OpenCV.

How the Canny algorithm processes an image

The Canny edge detector works as a fixed sequence of five stages, and each stage removes a specific kind of error left by the previous one. The output is a binary image in which edge pixels are set and all other pixels are zero.

The following table summarizes what each stage does and which problem it solves.

StageOperationProblem it solves
Gaussian smoothingConvolve with a Gaussian kernel of width sigmaSuppresses pixel noise that creates false gradients
Gradient computationSobel or similar derivative filters in x and yMeasures edge strength and direction
Non-maximum suppressionKeep pixels that are local maxima along the gradient directionThins thick ridges to one-pixel edges
Double thresholdingClassify pixels as strong, weak or rejectedSeparates real edges from residual noise
Hysteresis trackingKeep weak pixels only if connected to strong onesPreserves continuous contours without noise fragments
The five stages of the Canny edge detector

The gradient magnitude is usually computed as the square root of Gx squared plus Gy squared, and the direction as the arctangent of Gy over Gx, quantized into four bins (0, 45, 90 and 135 degrees). Non-maximum suppression compares each pixel with its two neighbors along that direction and discards it unless it is the largest, which produces the characteristic thin contours.

Key parameters and how they shape the result

Three parameters control almost all of the behavior of the Canny edge detector: the Gaussian sigma, the low threshold and the high threshold. Some implementations also expose the size of the Sobel aperture and a flag for the exact L2 gradient norm.

ParameterTypical rangeEffect when increased
Gaussian sigma1.0 to 2.0 pixelsFewer noisy edges, but fine detail and corners blur
High thresholdOften 2 to 3 times the low valueFewer seed edges, so weak but real contours may vanish
Low thresholdAbout 0.4 to 0.5 of the high valueShorter edge chains, more gaps in contours
Sobel aperture3, 5 or 7Smoother gradients, coarser localization
L2 gradient flagOn or offMore accurate magnitude at slightly higher cost
Main Canny parameters and their effects

Threshold values depend on the bit depth and contrast of the image, so a pair that works on one dataset rarely transfers unchanged. A widely used heuristic sets the thresholds around the median pixel intensity, for example 0.66 and 1.33 times the median, which adapts them to overall brightness. Otsu thresholding of the gradient magnitude is another automatic tuning strategy.

Canny compared with other edge detection methods

The Canny edge detector differs from simple gradient operators because it post-processes the gradient rather than thresholding it directly. That extra work gives thinner, more continuous edges at a moderate computational cost.

MethodOutput qualityMain limitation
Sobel operatorThick, noisy gradient mapNo thinning and no linking of edge pixels
Laplacian of GaussianClosed zero-crossing contoursMany false edges in flat noisy regions
Canny edge detectorThin, connected, well-localized edgesManual threshold tuning, fixed scale
Learned edge detectorsSemantically meaningful boundariesNeed training data and GPU inference
Comparison of common edge detection approaches

Deep networks such as holistically nested edge detection learn which boundaries matter to humans, for example object outlines rather than texture. Canny, by contrast, responds to any sharp intensity change, including shadows and printed patterns. For measurement tasks this neutrality is an advantage, because the result is deterministic and explainable.

Where Canny is used in practice

The Canny edge detector appears wherever a pipeline needs reliable geometric contours before a higher-level step. Typical consumers of its output are the Hough transform for lines and circles, contour detection for shape analysis and document scanners that locate page borders.

  • Industrial inspection: measuring part dimensions and detecting cracks or burrs on a production line.
  • Lane detection: extracting road markings before fitting lines in driver assistance prototypes.
  • Document capture: finding the four page edges for perspective correction before OCR.
  • Preprocessing for learning: providing edge maps as conditioning input for generative image models.
  • Medical imaging: outlining organ or vessel boundaries as a first segmentation step.

Its speed matters in these settings. On a modern CPU, optimized implementations process a full HD frame in a few milliseconds, which makes the algorithm suitable for real-time video on embedded hardware without a neural accelerator.

Limitations and common mistakes

The Canny edge detector is robust but not universal. Its most important weakness is that it operates at a single scale chosen by sigma, so it cannot simultaneously capture fine texture edges and broad soft boundaries. Corners are also rounded and broken because non-maximum suppression assumes a single dominant gradient direction.

SymptomLikely causeFix
Speckled noise edgesSigma too small or thresholds too lowIncrease smoothing or raise the high threshold
Broken contoursLow threshold too highLower the low threshold to strengthen hysteresis
Missing faint boundariesHigh threshold too high for image contrastNormalize contrast or use median-based thresholds
Edges shifted from true positionExcessive Gaussian blurReduce sigma and accept slightly more noise
Inconsistent results across imagesFixed absolute thresholdsAdapt thresholds per image
Typical symptoms, causes and fixes

A frequent practical mistake is running Canny on a color image converted carelessly to grayscale, which can erase boundaries between regions of equal luminance but different hue. Another is expecting semantic object boundaries: the detector finds intensity changes, not objects, so it should be followed by a model or rule that interprets the edges.

Put simply

The Canny edge detector draws the outlines in a picture. First it blurs the image a little, so tiny specks do not count. Then it looks for places where brightness changes sharply. It keeps only the sharpest line along each change, so outlines stay thin.

Finally it uses two bars. Strong edges pass the high bar and are kept at once. Weaker edges are kept only if they touch a strong edge. It is like tracing a drawing with a pencil and lifting the pencil only where the line truly ends.

In practice

A quality engineer at a metal stamping plant needs to check the diameter of punched holes in steel brackets moving past a camera at about 20 parts per second. The camera delivers 1280 by 1024 grayscale frames under diffuse backlighting, so holes appear as bright discs on a dark part.

The inspection software applies a Gaussian blur with sigma 1.4 and runs the Canny edge detector with a low threshold of 50 and a high threshold of 150. The thin edge map feeds a circular Hough transform that fits each hole. Because the edges are one pixel wide and continuous, the fitted diameter is repeatable to roughly a tenth of a pixel.

When a worn punch begins to leave burrs, the edge contours show small bulges that change the fitted circle. The system flags brackets whose diameter drifts beyond plus or minus 0.05 millimeters, and the line is stopped for tool maintenance before defective parts reach the customer.