QuiddityML

Edge detection explained: image gradients, Sobel, and the Canny edge detector

How a gradient measures change at each pixel, what the Sobel filter computes on a 3 by 3 patch, the four steps of the Canny edge detector and how edge pixels become contours you can measure, with PyTorch and OpenCV code.

Computer VisionBy · 4 December 2026 · 11 min read

Edge detection finds the pixels where an image's brightness changes sharply. Those pixels often sit on the outline of an object, so edges are a common first step for measuring shapes, finding the borders of a document in a photo or cleaning up a mask. The hard part is that shadows, texture and sensor noise also change brightness sharply, and an edge detector has to keep the outlines while throwing most of the rest away.

What an image gradient is

A grayscale image is a grid of brightness values, often called intensities. Finding edges starts with the gradient. At each pixel it is a pair of numbers: how fast the intensity changes when you move one pixel right, and how fast it changes when you move one pixel down. The two numbers together form a small arrow that points in the direction where the image gets brighter fastest.

In a flat region the intensity barely changes, so the gradient is close to zero. On an edge the intensity jumps, so the gradient is large and points across the edge toward the brighter side.

A bright disc on a dark background with dots on the flat areas and arrows on the rim pointing inward toward the bright side.

Finite differences

An image has no continuous surface to take a derivative of, only a grid of values. So the change is estimated by subtracting neighboring pixels. Write $I(x, y)$ for the intensity at column $x$ and row $y$, and $\partial_x I$ for the change in intensity in the $x$ direction:

$$\partial_x I \approx I(x+1, y) - I(x-1, y)$$

This is a finite difference: the right neighbor minus the left neighbor. Sliding the three weights $[-1, 0, 1]$ along each row and multiplying and adding at each position gives the same result, so it is a tiny convolution. Dividing by 2 gives the change per pixel, since the two neighbors sit 2 pixels apart.

Raw differences make noise stronger. A pixel that noise pushed up by 10 creates a difference of 10 even on a flat wall. So the image is usually blurred a little before taking differences.

The kernel -1, 0, +1 with the reading I(x+1) minus I(x-1) and a warning that raw differences amplify noise, so blur first.

A gradient on one row

Take a row of intensities with one edge in the middle:

$$I = [30, 32, 31, 90, 150, 152, 151]$$

The central difference at position $x$ is

$$\partial_x I \approx \tfrac{1}{2}(I[x+1] - I[x-1])$$

Working through the middle positions:

  • at $x = 1$: $(31 - 30) / 2 = 0.5$
  • at $x = 2$: $(90 - 32) / 2 = 29$
  • at $x = 3$: $(150 - 31) / 2 = 59.5$
  • at $x = 4$: $(152 - 90) / 2 = 31$

The gradient is near 0 in the flat runs and peaks at $x = 3$, where the intensity jumps from about 31 to about 150. The two end pixels have only one neighbor each, so the code uses a one-sided difference there:

import torch

I = torch.tensor(
    [30, 32, 31, 90, 150, 152, 151],
    dtype=torch.float32)

# central differences, edges one-sided
gx = torch.zeros_like(I)
gx[1:-1] = (I[2:] - I[:-2]) / 2
gx[0] = I[1] - I[0]
gx[-1] = I[-1] - I[-2]
print(gx.round(decimals=1))
# tensor([ 2.0000,  0.5000, 29.0000, 59.5000, 31.0000,  0.5000, -1.0000])

The values from position 1 to 5 match the hand calculation.

The row 30, 32, 31, 90, 150, 152, 151 plotted as a step, and its gradient 2.0, 0.5, 29.0, 59.5, 31.0, 0.5, -1.0 plotted as a peak at x = 3.

A large gradient is not always an object edge

A large gradient means the image changed at that pixel. The change might be the outline of an object. It might also be the border of a shadow, a patterned surface or noise. The gradient measures change and does not say what caused it.

A scene with a bright box, its cast shadow and a checkered mat, and its gradient magnitude, where the box outline, the shadow outline, the mat pattern and noise all light up.

The Sobel filter

A bare $[-1, 0, 1]$ difference reads only two pixels, so one noisy pixel can produce a large false gradient. The Sobel filter fixes part of that. It is a 3 by 3 kernel that measures the change in one direction while averaging over three rows (or three columns) in the other direction. The kernel for change along $x$ is

$$G_x = \begin{bmatrix} -1 & 0 & 1 \\ -2 & 0 & 2 \\ -1 & 0 & 1 \end{bmatrix}$$

Each row of $G_x$ is a finite difference. The rows are weighted 1, 2 and 1, so the middle row counts most and the rows above and below smooth the result. The kernel for change along $y$, called $G_y$, is the same pattern turned on its side. The Scharr filter has the same layout with weights 3, 10 and 3.

The Sobel and Scharr kernels for x and y, with the note that both estimate a derivative in one direction while averaging in the other.

Sobel on a 3 by 3 patch

Take a patch with a vertical edge, dark on the left and bright on the right:

$$P = \begin{bmatrix} 20 & 25 & 200 \\ 22 & 24 & 210 \\ 21 & 26 & 205 \end{bmatrix}$$

Applying $G_x$ means multiplying each patch value by the matching kernel weight and adding the products. The left column gives $-1 \cdot 20 - 2 \cdot 22 - 1 \cdot 21 = -85$. The right column gives $1 \cdot 200 + 2 \cdot 210 + 1 \cdot 205 = 825$, and the center column has weight 0. So

$$g_x = -85 + 0 + 825 = 740$$

The same steps with $G_y$ compare the bottom row with the top row:

$$g_y = -270 + 0 + 278 = 8$$

That is close to 0 because the three rows are almost the same. A large $g_x$ with a small $g_y$ means the brightness changes from left to right, so the edge runs up and down.

The patch, both Sobel kernels and every weighted term, giving g_x = 740 and g_y = 8.

Magnitude and orientation

The two numbers $g_x$ and $g_y$ at a pixel combine into the strength and the direction of the change:

$$\text{magnitude} = \sqrt{g_x^2 + g_y^2}$$

$$\text{orientation} = \operatorname{atan2}(g_y, g_x)$$

The magnitude is how strong the change is. The orientation is the angle of the direction of steepest change, which points across the edge. atan2 is the two-argument arctangent. Code uses it instead of $\arctan(g_y / g_x)$ because it works when $g_x = 0$ and it keeps track of which way the arrow points. In an image the $y$ axis points down, so an orientation of 90 degrees means the image gets brighter downward.

Two gradients: brighter to the right gives 0 degrees with g_y = 0, and brighter downward gives 90 degrees with g_x = 0.

For the patch above, with $g_x = 740$ and $g_y = 8$:

  • magnitude: $\sqrt{740^2 + 8^2} = \sqrt{547600 + 64} \approx 740.0$
  • orientation: $\operatorname{atan2}(8, 740) \approx 0.011$ radians, about 0.6 degrees

The gradient points almost straight across the edge, from dark to bright. The edge itself runs at a right angle to the gradient, so it is nearly vertical.

The 3 by 3 patch with the edge marked between the middle and right columns and the gradient arrow pointing right, tipped 0.6 degrees down, with the magnitude 740.0 and orientation 0.011 worked out.

Non-maximum suppression

A map of gradient magnitudes marks each edge as a ridge several pixels wide, because the pixels next to the edge also see part of the jump. Non-maximum suppression (NMS) thins each ridge to a line one pixel wide. It keeps a value only where it is at least as large as its two neighbors, and sets every other value to zero:

$$[2,\ 9,\ 4,\ 7,\ 3] \rightarrow [0,\ 9,\ 0,\ 7,\ 0]$$

For edges, the two neighbors it compares against are the ones across the edge, along the gradient direction.

A response curve with two peaks, and the same signal after non-maximum suppression with only the two peak values kept.

NMS over a small ridge

Take a row of gradient magnitudes across an edge. The gradient direction is horizontal, so the neighbors are left and right:

$$[5, 30, 70, 95, 72, 28, 4]$$

Position $i$ is kept only if $mag[i] \geq mag[i-1]$ and $mag[i] \geq mag[i+1]$:

  • position 2 (value 70): its right neighbor 95 is larger, so it becomes 0
  • position 3 (value 95): both neighbors are smaller, so it stays 95
  • position 4 (value 72): its left neighbor 95 is larger, so it becomes 0

The result is $[0, 0, 0, 95, 0, 0, 0]$, a single pixel at the peak. In code, on a 1D row of magnitudes:

def nms_1d(mag):
    out = [0] * len(mag)
    for i in range(1, len(mag) - 1):
        if mag[i] >= mag[i - 1] and mag[i] >= mag[i + 1]:
            out[i] = mag[i]
    return out

print(nms_1d([5, 30, 70, 95, 72, 28, 4]))
# [0, 0, 0, 95, 0, 0, 0]

A bar chart of 5, 30, 70, 95, 72, 28, 4 and the same chart after suppression with only the 95 left.

The same name is used in object detection, for a different cleanup. A detector often outputs several overlapping boxes for one object, each with a confidence score. NMS there keeps the highest-scoring box and removes the other boxes that overlap it heavily. In both uses NMS has no learned parameters. It is a fixed rule applied after the main computation.

Four nested boxes around one car with scores 0.6 to 0.9, reduced to the single 0.9 box.

The Canny edge detector

Raw gradient magnitudes give noisy edge evidence: thick ridges, broken outlines and specks from noise and texture. The Canny edge detector turns that evidence into clean edge curves in four steps:

  1. Smooth. A Gaussian blur keeps noise from creating false edges.
  2. Compute gradients. A Sobel filter gives a magnitude and an orientation at every pixel.
  3. Thin. Non-maximum suppression along the gradient direction cuts each ridge to one pixel wide.
  4. Link. Two thresholds decide which thin edge pixels to keep.

Each step removes a specific kind of false edge.

The four Canny steps run on one noisy image: the blurred image, wide gradient ridges, thin lines with short noise lines, and clean outlines after linking, with 332 pixels kept and 297 weak noise pixels dropped.

The first three steps on a noisy shape: the blur removes most of the grain, the gradient magnitude shows the outline as a wide bright band, and thinning turns the band into a line one pixel wide.

A noisy shape, the same shape after a Gaussian blur, its gradient magnitude with wide ridges and the thinned outline one pixel wide.

Linking with two thresholds

After thinning, many pixels still have a small magnitude from noise or texture. A single cutoff has a problem. Set it high and faint parts of a real outline disappear. Set it low and noise specks survive.

Canny uses two thresholds, a low one and a high one. This step is often called hysteresis thresholding:

  • a pixel above the high threshold is a definite edge
  • a pixel between the two thresholds is kept only if it connects, through other kept pixels, to a definite edge
  • a pixel below the low threshold is dropped

This keeps faint stretches of a real contour, because they touch the strong parts of the same contour. It drops isolated weak responses, because they touch no strong pixel.

Outlines where solid green segments are above the high threshold, dashed amber segments are kept because they connect to them, and red dots are isolated responses that get dropped.

Two-threshold linking traced

Take a 1D slice of magnitudes after thinning, with $low = 20$ and $high = 50$:

$$[8, 25, 30, 60, 40, 15, 45, 12]$$

  • position 3 (value 60): above 50, so it is a definite edge
  • positions 2 and 4 (values 30 and 40): between the thresholds and touching position 3, so both are kept
  • position 1 (value 25): touches position 2, which is now kept, so it is kept
  • position 6 (value 45): between the thresholds, but its neighbors 15 and 12 are both below 20
  • positions 0, 5 and 7: below 20, so they are dropped

Positions 1 to 4 are kept as one connected segment. Position 6 came close to the high threshold, but with no definite edge to connect to, it is dropped.

The eight magnitudes classified as dropped, weak and kept, or strong, with the result 0, 25, 30, 60, 40, 0, 0, 0.

Canny in code

OpenCV, imported as cv2, is a widely used image-processing library. cv2.Canny runs the gradient, thinning and linking steps in one call:

import cv2
import numpy as np

gray = np.zeros((100, 100), dtype=np.uint8)
# one vertical edge
gray[:, 50:] = 255

edges = cv2.Canny(
    gray, threshold1=50, threshold2=150,
    apertureSize=3)
print(edges.shape, edges.dtype)         # (100, 100) uint8
print(np.unique(edges))                 # [  0 255]
# 100, one clean edge column
print(np.count_nonzero(edges[:, 49:51]))

threshold1 is the low threshold and threshold2 the high one, and apertureSize=3 sets the Sobel kernel to 3 by 3. The result is a binary edge map with 255 on the edge pixels and 0 elsewhere, one pixel wide along each boundary. The 100 nonzero pixels are one per row along the vertical edge. cv2.Canny does not blur the image for you, so blur noisy input first.

What cv2.Canny runs inside: Sobel gradient, non-maximum suppression and hysteresis, giving a binary edge map one pixel wide, with the blur done outside the call.

What the thresholds trade

The blur's sigma and the two thresholds trade completeness against clutter. Loose settings (a small sigma and low thresholds) find faint edges and also a lot of texture and noise. Tight settings find only the strong edges and miss some real ones, such as a door frame with little contrast.

A landscape scene with loose settings, where the grass and leaves turn into clutter, and tight settings, where only the main outlines remain and some details are missing.

From edge pixels to contours

An edge map is still an image: a grid of 0s and 255s. A contour is an ordered chain of points that traces one boundary. Turning edge pixels into contours follows pixels that touch, chaining them into curves, so the output is a list of boundaries instead of a binary map.

Scattered edge pixels around an oval turned into one ordered chain numbered 1 to 24.

OpenCV's findContours walks the boundary of the white region in a binary image and returns its points in order:

import cv2
import numpy as np

mask = np.zeros((80, 80), dtype=np.uint8)
cv2.rectangle(
    mask, (20, 20), (60, 50),
    color=255, thickness=-1)

contours, _ = cv2.findContours(
    mask, cv2.RETR_EXTERNAL,
    cv2.CHAIN_APPROX_SIMPLE)
c = contours[0]
# (4, 1, 2), four corner points
print(c.shape)
# 1200.0  (40 * 30)
print(cv2.contourArea(c))
# 140.0  (perimeter)
print(cv2.arcLength(c, closed=True))

RETR_EXTERNAL returns only the outer boundaries. CHAIN_APPROX_SIMPLE collapses straight runs to their end points, so the rectangle comes back as 4 corner points instead of one point per boundary pixel. The rectangle is 40 pixels wide and 30 tall between its corner points, which gives an area of 1200 and a perimeter of 140.

The boundary of a rectangle collapsed to 4 corner points, with area 1200 and perimeter 140.

With a contour you can measure an object's area and perimeter, simplify its boundary to a few points or compare its shape with another one. A contour is a list of points, so it is the first result in this pipeline that is something other than another image.

Four uses of a contour: measuring perimeter and area, simplifying to a few points, matching a shape and defining a region outline.

When to use edge detection, and common mistakes

Edge detection works well when the objects you care about differ a lot in brightness from their background and the lighting is fairly even, as with documents on a desk, parts on a conveyor or shapes in a scan. With busy backgrounds, heavy texture or changing light it finds many edges that are not object boundaries, and a model trained on examples often does better.

  • Running Canny on a noisy image without a blur. The gradient step reacts to noise, so the edge map fills with short false edges.
  • Treating every edge as an object boundary. Shadows, texture and reflections produce strong edges too.
  • Picking thresholds once and reusing them everywhere. Thresholds that work on one camera or lighting setup can miss edges or add clutter on another. Check them on a few images from each source.
  • Expecting closed outlines. Edge maps often have gaps. Contours, or a small dilation of the edge map, help when you need closed shapes.
  • Mixing up the gradient direction and the edge direction. The gradient points across the edge. The edge runs at a right angle to it.

The finite difference and Sobel kernels are convolutions with fixed weights. Image convolution explained covers the sliding window, padding and stride. The blur in Canny's first step is a Gaussian blur, which Image blurring and denoising covers along with the box and median filters. Thresholding a single brightness value, as opposed to linking edges with two thresholds, is in Classical image processing.

QuiddityML teaches edge detection, from image gradients to the Canny detector and contours, in the classical image processing unit of its Computer Vision track. The exercises there include writing the central-difference gradient from scratch and implementing non-maximum suppression on a row of magnitudes (QuiddityML).