Skip to content
Tutorials Center
My learning

Topics

Lesson 24 of 54 ยท Edges, Contours and Shapes

Canny Edge Detection

Understand cv2.Canny: Gaussian blur, gradients, non-maximum suppression and hysteresis. Learn how to pick thresholds, and run the four stages in NumPy.

Sobel tells you how strong the brightness change is at every pixel, but its answer is thick and messy: an edge shows up as a smear several pixels wide, and noise produces faint speckles everywhere. For finding contours, lines and shapes you usually want something cleaner: thin, one-pixel-wide lines that are mostly continuous. That is what the Canny edge detector produces, and cv2.Canny is probably the most used edge function in OpenCV.

Canny is not one filter but a small pipeline of four stages. Knowing the stages makes the two threshold parameters stop being magic numbers, and tells you what to do when the result is too noisy or has gaps. This lesson walks through the stages, shows the real call, and then runs a simplified version of every stage in NumPy.

cv2.Canny itself is shown as read-only code because opencv-python cannot run in the browser. The stand-ins implement the same four ideas in NumPy on a tiny synthetic image. They are honest teaching versions: OpenCV's implementation uses faster code and slightly different rounding, so exact pixel positions can differ.

The real call

Python
import cv2

gray = cv2.imread("coins.png", cv2.IMREAD_GRAYSCALE)
blurred = cv2.GaussianBlur(gray, (5, 5), 1.4)

edges = cv2.Canny(blurred, 50, 150)                # threshold1=50, threshold2=150
edges = cv2.Canny(blurred, 50, 150, apertureSize=3, L2gradient=True)

The result is a single-channel 8-bit image that contains only the values 0 and 255. The second and third arguments are the two hysteresis thresholds; OpenCV accepts them in either order and uses the smaller as the low one. apertureSize is the Sobel kernel size used for the gradients (3, 5 or 7, default 3). L2gradient=True uses the accurate magnitude sqrt(gxยฒ + gyยฒ); the default is the cheaper |gx| + |gy|, which changes what a given threshold means. The input must be an 8-bit single-channel image, so convert color images to gray first.

Four stages of Canny

Smooth Blur away the noise.
Gradient Strength and direction.
Thin Keep only local peaks.
Link Two thresholds, hysteresis.
1 / 2

Stage 1: smooth

Every derivative amplifies noise, so Canny starts with a Gaussian blur. Without it, a grainy photo produces thousands of tiny edge fragments. In OpenCV, cv2.Canny does not blur for you, so do it yourself with cv2.GaussianBlur (see Blurring and Noise Reduction). A 5x5 blur is a good default; blur more when the image is noisy, less when edges are fine details.

Stage 2: gradients

Next come the Sobel gradients gx and gy from Gradients, Sobel and Laplacian, turned into a magnitude and an angle for every pixel. The angle matters because the next stage needs to know which way the edge points.

Stage 3: non-maximum suppression

A gradient magnitude image shows an edge as a ridge several pixels wide. Non-maximum suppression thins it: for each pixel, compare its magnitude with its two neighbors along the gradient direction (across the edge). If it is not the largest of the three, set it to zero. Only the crest of the ridge survives, so the edge becomes one pixel wide. The angle is rounded to one of four directions (horizontal, vertical and the two diagonals) to choose the neighbors.

Stage 4: double threshold and hysteresis

After thinning, you must decide which ridge pixels are real edges. A single threshold forces a bad trade-off: set it high and real edges break into gaps where they fade; set it low and noise survives. Canny uses two:

  • magnitude at or above the high threshold: a strong edge, kept for sure;
  • magnitude between low and high: a weak edge, kept only if it connects (through neighbors) to a strong edge;
  • magnitude below low: dropped.

This is hysteresis: a faint stretch of a real contour survives because it is attached to a strong part, while an isolated faint speck, which is probably noise, does not.

Python The four Canny stages in NumPy

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Follow the numbers down the pipeline. Blurring cuts the noise (in a flat corner the standard deviation drops from about 6 to about 1.6). The gradient is nonzero almost everywhere (575 pixels), because noise leaves tiny gradients even in flat regions. Thresholding the raw magnitude at the low level still leaves 165 pixels, a ridge three or four pixels wide; thinning reduces that to 48 pixels. Of those, 44 are strong and 4 are weak ones that hysteresis kept because they touch a strong pixel. The text picture shows a closed ring, one or two pixels thick, with no speckles from the noise.

Choosing the thresholds

There is no universal pair, because "strong" depends on image contrast and on the gradient formula you choose. These rules work in practice:

  • Start with a ratio of about 1:2 or 1:3 (for example 50 and 150, or 100 and 200).
  • Lower the high threshold to get more edges in a low-contrast image; raise it to remove clutter.
  • If real contours have gaps, lower the low threshold (it controls how far an edge may continue); if edges grow stray tails, raise it.
  • A popular automatic rule derives both from the median brightness: low = 0.66 * median, high = 1.33 * median. It is a heuristic, not a guarantee, but it adapts to dark and bright photos.
  • Blur first and tune the blur together with the thresholds, not separately.
Python Hysteresis and threshold choices

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Row 3 is a strong line whose strength fades from 500 to 150. With a low threshold of 100 the whole line survives (12 pixels), because every pixel is connected to the strong start. With low=200 the tail below 200 is cut off after seven pixels, and with low=250 only five remain. When the high threshold is 600, nothing is strong, so nothing is kept at all, a reminder that hysteresis needs at least one strong seed. The faint speck at row 0 (strength 260) is never kept, since it has no strong neighbor, even though its strength is above two of the low thresholds. The last two lines show how the median rule scales the thresholds with brightness.

Typical problems

  • Too many tiny edges: increase the blur or both thresholds.
  • Broken outlines: lower the low threshold, or close small gaps afterwards with cv2.dilate or cv2.morphologyEx (see Morphological Operations).
  • Edges missing in shadows: apply contrast work such as histogram equalization first.
  • Different results across OpenCV versions or settings: check apertureSize and L2gradient, since they change what the thresholds mean.

The output of Canny is the perfect input for the next lesson: Finding and Drawing Contours turns edge pixels into shapes you can measure.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What is the job of non-maximum suppression in Canny?

    For each pixel it compares the magnitude with its two neighbors along the gradient direction and keeps it only if it is the local maximum, leaving the crest of each ridge.
  2. 2. A pixel's gradient magnitude lies between the low and high thresholds. When is it kept?

    That is hysteresis. Weak pixels survive only if a chain of weak pixels links them to a strong pixel, which keeps faded parts of real edges but drops isolated noise.
  3. 3. Which pair of thresholds follows the usual rule of thumb?

    The high threshold is usually two to three times the low one, such as 50 and 150. Equal values remove the benefit of hysteresis, and (0, 255) makes everything weak and almost nothing strong.
  4. 4. Does cv2.Canny blur the image for you?

    cv2.Canny computes gradients, thins and links edges, but does not blur. Call cv2.GaussianBlur first or noise will create many small false edges.

Summary

  • Canny = smooth, gradient, non-maximum suppression, double threshold with hysteresis.
  • cv2.Canny(gray, low, high) returns a 0/255 image; blur before calling it.
  • Non-maximum suppression gives one-pixel-wide edges by comparing neighbors across the edge.
  • Strong pixels are kept; weak pixels are kept only if connected to a strong one; the rest are dropped.
  • Use a high:low ratio of about 2:1 to 3:1, tune on your own images, and remember apertureSize and L2gradient change what the numbers mean.

Next lesson: Finding and Drawing Contours.