TExcelTAD
Home › Computer Vision: Images to Detection, Segmentation & Tracking › Edge Detection: Gradients, Sobel and Canny

Edge Detection: Gradients, Sobel and Canny

Most of what we recognise in a picture is in its edges: a line drawing of a face is still a face. An edge is where the brightness changes quickly, at an object boundary, a shadow, a texture or a crease. Edges compress an image (a few percent of the pixels), are largely independent of the overall brightness, and feed everything from lane detection and document scanning to the corner and HOG features of classical features. The tool is the derivative: a discrete gradient tells you how strong and in which direction the brightness changes. This lesson builds derivatives from finite differences, measures how noise and kernel choice affect them, and implements the Canny detector step by step, checked against cv2.Canny.

Derivatives as finite differences

An image is a sampled function, so its derivative is a difference of neighbours. Two simple choices:

∂I∂x≈I[x+1]−I[x](forward),∂I∂x≈I[x+1]−I[x−1]2(central)\frac{\partial I}{\partial x} \approx I[x + 1] - I[x] \quad \text{(forward)}, \qquad \frac{\partial I}{\partial x} \approx \frac{I[x + 1] - I[x - 1]}{2} \quad \text{(central)}

and the second derivative I[x+1]−2I[x]+I[x−1]I[x + 1] - 2I[x] + I[x - 1]. The catch is noise: subtracting two noisy values adds their variances. If each pixel has noise σ\sigma, the forward difference has noise 2 σ\sqrt{2}\,\sigma, the central difference σ/2\sigma/\sqrt{2}, and the second difference 6 σ\sqrt{6}\,\sigma. Smoothing first lowers the noise, at the price of a wider, lower edge response.

python · try it yourself
import numpy as np

rng = np.random.default_rng(0)
x = np.arange(40)
step = np.where(x >= 20, 100.0, 0.0)                     # an ideal edge of height 100 at x = 20
noisy = step + rng.normal(0, 5, x.size)                  # noise sigma 5
fwd = noisy[1:] - noisy[:-1]
cen = (noisy[2:] - noisy[:-2]) / 2
sm = np.convolve(noisy, [0.25, 0.5, 0.25], mode="same")  # smooth with [1, 2, 1] / 4 first
smc = (sm[2:] - sm[:-2]) / 2
for name, d, off in [("forward f(x+1)-f(x)", fwd, 0.5), ("central (f(x+1)-f(x-1))/2", cen, 1), ("smooth [1,2,1]/4, then central", smc, 1)]:
    flat = np.r_[d[2:15], d[25:-2]]                      # samples far from the edge
    print(f"{name:31s} peak {d.max():6.1f} at x={int(d.argmax()) + off:<5} noise std {flat.std():4.2f}  peak/noise {d.max() / flat.std():5.1f}")
second = noisy[2:] - 2 * noisy[1:-1] + noisy[:-2]
print("second difference around the edge (x=17..22):", second[16:22].round(1).tolist())
print("noise std of second difference far from edge:", round(float(np.r_[second[2:15], second[25:-2]].std()), 2))
forward f(x+1)-f(x)             peak   94.1 at x=19.5  noise std 4.81  peak/noise  19.6
central (f(x+1)-f(x-1))/2       peak   50.8 at x=20    noise std 2.60  peak/noise  19.6
smooth [1,2,1]/4, then central  peak   37.9 at x=19    noise std 1.54  peak/noise  24.6
second difference around the edge (x=17..22): [2.5, -0.5, 91.0, -86.7, -17.6, 15.2]
noise std of second difference far from edge: 8.18

The noise levels keep the ratios the rule predicts: forward, central and second difference should be in the ratio 2:1:3.52 : 1 : 3.5 and measure 4.81:2.60:8.184.81 : 2.60 : 8.18. (The absolute values are below the predicted 7.1, 3.5 and 12.2 because this short sample of about 25 points happens to be calm.) The central difference halves both the peak and the noise, so their ratio stays 19.6; smoothing first wins (24.6), and that is the idea behind Sobel. The second difference crosses zero at the edge (from +91.0 to −86.7-86.7 between x=19x = 19 and x=20x = 20): edges are maxima of the first derivative and zero crossings of the second.

Sobel and Scharr: smoothed derivatives in 2-D

The Sobel kernels combine a central difference in one direction with [1,2,1][1, 2, 1] smoothing in the other:

Sx=[−101−202−101]=[121][−101],Sy=SxTS_x = \begin{bmatrix} -1 & 0 & 1 \\ -2 & 0 & 2 \\ -1 & 0 & 1 \end{bmatrix} = \begin{bmatrix} 1 \\ 2 \\ 1 \end{bmatrix} \begin{bmatrix} -1 & 0 & 1 \end{bmatrix}, \qquad S_y = S_x^{\mathsf T}

From the two responses gx,gyg_x, g_y come the gradient magnitude and direction:

∥∇I∥=gx2+gy2,θ=atan2⁡(gy,gx)\lVert \nabla I \rVert = \sqrt{g_x^2 + g_y^2}, \qquad \theta = \operatorname{atan2}(g_y, g_x)

The gradient points towards brighter pixels, perpendicular to the edge. Because image yy points down, θ=90∘\theta = 90^{\circ} means "brighter below". Slide the Sobel kernels over the same small image as in image filtering and compare with the Laplacian:

Input image (0–9)111111111111111111115511188881115511188881115511188881115511188881115511111111115511111911111111111191111111111119111111111111911111111111191111Kernel−101−202−101productsdoneFeature map 10 × 10700−7−701212−12−122100−21−2101616−16−162800−28−2801616−16−162800−28−2801616−16−162100−21−2101616−16−16780−15−701212−12−120168−16−8044−4−408160−16−80000008160−16−80000008160−16−800red > 0, blue < 0; max |value| 28

Sobel x responds to the left and right sides of the bright square, with opposite signs (red where the image gets brighter to the right, blue where it gets darker), and is zero on its top and bottom edges; Sobel y is the same turned by 90 degrees; the diagonal line answers to both. The Laplacian responds to every edge and to the line, with a positive and a negative band around each: the zero crossing between them is the edge.

python · try it yourself
import numpy as np
import cv2
cv2.setLogLevel(0)

img = np.zeros((101, 101), np.float32)
cv2.circle(img, (50, 50), 30, 1.0, -1)                   # a bright disc of radius 30
img = cv2.GaussianBlur(img, (0, 0), 2)
sx = np.array([[-1, 0, 1], [-2, 0, 2], [-1, 0, 1]], np.float32)
gx = cv2.Sobel(img, cv2.CV_32F, 1, 0, ksize=3); gy = cv2.Sobel(img, cv2.CV_32F, 0, 1, ksize=3)
print("cv2.Sobel == filter2D with the Sobel x kernel:", np.allclose(gx, cv2.filter2D(img, -1, sx), atol=1e-6))
mag = np.hypot(gx, gy); ang = np.degrees(np.arctan2(gy, gx))
for name, (r, c) in [("right edge", (50, 80)), ("bottom edge", (80, 50)), ("left edge", (50, 20)), ("top edge", (20, 50)), ("lower right", (71, 71)), ("centre", (50, 50))]:
    print(f"{name:11s} (x={c}, y={r}): gx {gx[r, c]:6.3f} gy {gy[r, c]:6.3f} magnitude {mag[r, c]:5.3f} direction {ang[r, c]:7.1f} deg")

yy, xx = np.mgrid[0:64, 0:64].astype(np.float32)          # how accurate is the direction? test on stripes
for P in [5, 10]:
    t = np.deg2rad(22.5)
    stripes = np.sin(2 * np.pi * (xx * np.cos(t) + yy * np.sin(t)) / P).astype(np.float32)
    out = []
    for name, (a, b) in [("central", (cv2.filter2D(stripes, -1, np.array([[-0.5, 0, 0.5]], np.float32)), cv2.filter2D(stripes, -1, np.array([[-0.5], [0], [0.5]], np.float32)))),
                         ("Sobel", (cv2.Sobel(stripes, cv2.CV_32F, 1, 0), cv2.Sobel(stripes, cv2.CV_32F, 0, 1))),
                         ("Scharr", (cv2.Scharr(stripes, cv2.CV_32F, 1, 0), cv2.Scharr(stripes, cv2.CV_32F, 0, 1)))]:
        th = np.degrees(np.arctan2(b, a))[8:-8, 8:-8]; m = np.hypot(a, b)[8:-8, 8:-8]
        e = (th - 22.5 + 90) % 180 - 90                    # angle error, ignoring the sign of the gradient
        out.append(f"{name} {np.abs(e[m > 0.5 * m.max()]).mean():4.2f}")
    print(f"stripes at 22.5 deg, period {P:2d} px, mean direction error in deg: " + " | ".join(out))
print("Scharr x kernel = column", cv2.getDerivKernels(1, 0, -1)[1].ravel().tolist(), "x row", cv2.getDerivKernels(1, 0, -1)[0].ravel().tolist())
cv2.Sobel == filter2D with the Sobel x kernel: True
right edge  (x=80, y=50): gx -1.502 gy  0.000 magnitude 1.502 direction   180.0 deg
bottom edge (x=50, y=80): gx  0.000 gy -1.502 magnitude 1.502 direction   -90.0 deg
left edge   (x=20, y=50): gx  1.502 gy  0.000 magnitude 1.502 direction     0.0 deg
top edge    (x=50, y=20): gx  0.000 gy  1.502 magnitude 1.502 direction    90.0 deg
lower right (x=71, y=71): gx -1.063 gy -1.063 magnitude 1.503 direction  -135.0 deg
centre      (x=50, y=50): gx  0.000 gy  0.000 magnitude 0.000 direction     0.0 deg
stripes at 22.5 deg, period  5 px, mean direction error in deg: central 4.26 | Sobel 2.00 | Scharr 0.31
stripes at 22.5 deg, period 10 px, mean direction error in deg: central 0.97 | Sobel 0.48 | Scharr 0.11
Scharr x kernel = column [3.0, 10.0, 3.0] x row [-1.0, 0.0, 1.0]

On the disc, the gradient at the right edge points left (180 degrees, towards the brighter inside), at the bottom edge up (−90-90 degrees), at the lower right diagonally inwards (−135-135 degrees), and the magnitude is the same all around (1.502, 1.503 on the diagonal): Sobel is close to rotation-invariant at this scale. Its magnitude is not in "grey levels per pixel": a unit step gives 4 (the sum of the positive weights), a unit ramp 8, so compare magnitudes only between results of the same kernel.

Fine detail is where the kernels differ. On stripes at 22.5 degrees with a 5-pixel period, the plain central difference misjudges the direction by 4.26 degrees on average, Sobel by 2.00, and Scharr by 0.31; at a 10-pixel period all errors shrink. Scharr's weights [3,10,3][3, 10, 3] were optimised for rotational symmetry, which matters when you use the direction: Canny's non-maximum suppression, HOG histograms, optical flow.

Laplacian of Gaussian: edges and blobs at a scale

The Laplacian ∇2I=∂2I/∂x2+∂2I/∂y2\nabla^2 I = \partial^2 I/\partial x^2 + \partial^2 I/\partial y^2 is rotation-invariant but very noisy, so it is applied after a Gaussian blur: the Laplacian of Gaussian (LoG). The blur's σ\sigma sets the scale: small σ\sigma finds fine edges and noise, large σ\sigma only big structures. Multiplying by σ2\sigma^2 makes responses at different scales comparable (scale normalisation), and then a disc of radius rr gives its strongest response at σ=r/2\sigma = r/\sqrt{2}, the basis of blob detection and of SIFT's difference-of-Gaussians.

python · try it yourself
import numpy as np
import cv2
from skimage import data
cv2.setLogLevel(0)

img = data.camera().astype(np.float32)
for s in [1, 2, 4]:
    log = s ** 2 * cv2.Laplacian(cv2.GaussianBlur(img, (0, 0), s), cv2.CV_32F, ksize=3)
    zc_h = (np.sign(log[:, :-1]) != np.sign(log[:, 1:])) & (np.abs(log[:, :-1] - log[:, 1:]) > 20)
    zc_v = (np.sign(log[:-1, :]) != np.sign(log[1:, :])) & (np.abs(log[:-1, :] - log[1:, :]) > 20)
    zc = np.zeros(img.shape, bool); zc[:, :-1] |= zc_h; zc[:-1, :] |= zc_v
    print(f"sigma {s}: zero crossings with contrast > 20: {int(zc.sum()):6d} pixels ({zc.mean() * 100:.1f} %)")

blob = np.zeros((101, 101), np.float32); cv2.circle(blob, (50, 50), 8, 1.0, -1)
resp = {s: float(-s ** 2 * cv2.Laplacian(cv2.GaussianBlur(blob, (0, 0), s), cv2.CV_32F, ksize=3)[50, 50]) for s in np.arange(2, 10.5, 0.5)}
best = max(resp, key=resp.get)
print("disc radius 8: scale-normalised LoG at the centre peaks at sigma", float(best), "| r / sqrt(2) =", round(8 / np.sqrt(2), 2))
print({float(k): round(v, 3) for k, v in resp.items() if k in (2, 4, 5, 5.5, 6, 7, 9)})
sigma 1: zero crossings with contrast > 20:  28902 pixels (11.0 %)
sigma 2: zero crossings with contrast > 20:  10828 pixels (4.1 %)
sigma 4: zero crossings with contrast > 20:   4362 pixels (1.7 %)
disc radius 8: scale-normalised LoG at the centre peaks at sigma 5.5 | r / sqrt(2) = 5.66
{2.0: 0.035, 4.0: 2.207, 5.0: 2.84, 5.5: 2.916, 6.0: 2.892, 7.0: 2.68, 9.0: 2.092}

Doubling σ\sigma from 1 to 2 to 4 cuts the strong zero crossings from 11.0 % to 4.1 % to 1.7 % of the pixels: grass texture and noise vanish first, the outline of the photographer last. For the disc of radius 8 the response peaks at σ=5.5\sigma = 5.5 on the 0.5 grid, next to the predicted 5.66; at σ=2\sigma = 2 the disc is "all inside" and the centre response is almost zero. That is how a detector can report not only where a blob is but how big.

The Canny edge detector

John Canny (1986) asked what an optimal edge detector should do: find all real edges (good detection), place them where they are (good localisation), and mark each edge once (a single response). His answer is still the default edge detector:

1. smoothGaussian blur 2. gradientSobel: |g|, theta 3. thin (NMS)local max only 4. hysteresistwo thresholds 409060 across the edge:keep 90 only green strong, red weaklinked weak: keptlone weak: dropped output: thin, connected edges,one pixel wide
  1. Smooth with a Gaussian (cv2.Canny does not do this itself; you blur first).
  2. Gradient with Sobel. OpenCV uses the L1 magnitude ∣gx∣+∣gy∣\lvert g_x \rvert + \lvert g_y \rvert unless L2gradient=True.
  3. Non-maximum suppression (NMS): quantise the direction to 0, 45, 90 or 135 degrees and keep a pixel only if its magnitude is at least that of both neighbours along that direction. A blurry edge several pixels wide becomes a line one pixel wide.
  4. Hysteresis: pixels above high are edges; pixels above low are edges only if they connect (8-neighbourhood) to an edge pixel. A faint stretch of a strong edge survives, an isolated faint pixel (noise) does not.
python · try it yourself
import numpy as np
import cv2
from scipy import ndimage
from skimage import data
cv2.setLogLevel(0)

def canny(img, low, high):
    gx = cv2.Sobel(img, cv2.CV_32F, 1, 0, ksize=3)
    gy = cv2.Sobel(img, cv2.CV_32F, 0, 1, ksize=3)
    mag = np.abs(gx) + np.abs(gy)                                   # L1 magnitude, as cv2.Canny's default
    q = np.round(np.degrees(np.arctan2(gy, gx)) % 180 / 45).astype(int) % 4   # 0, 45, 90, 135 degrees
    H, W = mag.shape
    P = np.pad(mag, 1)
    keep = np.zeros(mag.shape, bool)
    for d, (dr, dc) in {0: (0, 1), 1: (1, 1), 2: (1, 0), 3: (1, -1)}.items():
        ahead = P[1 + dr:H + 1 + dr, 1 + dc:W + 1 + dc]              # neighbour along the gradient
        behind = P[1 - dr:H + 1 - dr, 1 - dc:W + 1 - dc]             # neighbour against it
        keep |= (q == d) & (mag > behind) & (mag >= ahead)
    thin = np.where(keep, mag, 0)
    weak = thin > low
    labels, n = ndimage.label(weak, structure=np.ones((3, 3)))       # 8-connected chains of weak pixels
    good = np.unique(labels[thin > high])                            # chains that contain a strong pixel
    return np.isin(labels, good[good > 0]), thin, weak

img = cv2.GaussianBlur(data.camera(), (5, 5), 1.4)
ours, thin, weak = canny(img, 50, 150)
ref = cv2.Canny(img, 50, 150) > 0
print("after NMS: candidate pixels", int((thin > 0).sum()), "| above low", int(weak.sum()), "| above high", int((thin > 150).sum()))
print("edge pixels: ours", int(ours.sum()), "| cv2.Canny", int(ref.sum()))
print("exact agreement (IoU):", round(float((ours & ref).sum() / (ours | ref).sum()), 3))
near = cv2.dilate(ref.astype(np.uint8), np.ones((3, 3), np.uint8)) > 0
print("share of our edge pixels within 1 px of OpenCV's:", round(float((ours & near).sum() / ours.sum()), 3))
after NMS: candidate pixels 62860 | above low 15699 | above high 5697
edge pixels: ours 7602 | cv2.Canny 7517
exact agreement (IoU): 0.989
share of our edge pixels within 1 px of OpenCV's: 0.998

Thirty lines reproduce OpenCV's result: the same pixels for 98.9 % of the union, and 99.8 % of ours within one pixel of OpenCV's. The rest are tie-breaking details of the direction quantisation and of NMS at plateaus. The counts show the funnel: 262,144 pixels, 62,860 local maxima, 15,699 above the low threshold, 5,697 strong seeds, and hysteresis grows those seeds into 7,602 edge pixels (2.9 % of the image), keeping only the weak pixels that connect to a strong one.

Choosing the thresholds

python · try it yourself
import numpy as np
import cv2
from skimage import data
cv2.setLogLevel(0)

img = cv2.GaussianBlur(data.camera(), (5, 5), 1.4)
raw = data.camera()
print("low high | edge pixels (blurred)  L2 gradient | no blur")
for lo, hi in [(20, 60), (50, 100), (50, 150), (100, 200), (150, 300), (300, 600)]:
    a = int((cv2.Canny(img, lo, hi) > 0).sum())
    b = int((cv2.Canny(img, lo, hi, L2gradient=True) > 0).sum())
    c = int((cv2.Canny(raw, lo, hi) > 0).sum())
    print(f"{lo:3d} {hi:4d} | {a:21d} {b:12d} | {c:7d}")
n, lab = cv2.connectedComponents(cv2.Canny(img, 50, 150))
print("connected edge chains at (50, 150):", n - 1)
low high | edge pixels (blurred)  L2 gradient | no blur
 20   60 |                 22960        17945 |   45798
 50  100 |                  9692         7632 |   35938
 50  150 |                  7517         6737 |   30980
100  200 |                  6038         5346 |   19686
150  300 |                  4624         3112 |    9452
300  600 |                   486            0 |    4576
connected edge chains at (50, 150): 99

Raising the thresholds removes weak edges first, from 22,960 edge pixels at (20, 60) to 486 at (300, 600). The L2 magnitude is never larger than the L1 one, so the same thresholds keep fewer pixels with L2gradient=True (none at all at 600). Without the blur the counts are four times higher at (50, 150): Canny on a raw photo marks every grain of texture. Common rules: a high-to-low ratio of 2:1 to 3:1 (Canny's suggestion), thresholds tied to the image, such as 0.66 and 1.33 times the median grey level, and tuning on a few labelled images rather than by eye on the test set. The thresholds are in gradient units, so they depend on the kernel (apertureSize) and on the image's contrast; a fixed pair does not transfer between cameras.

Pitfalls

  • Forgetting to blur. cv2.Canny applies no Gaussian of its own; noise turns into edges.
  • uint8 derivatives. cv2.Sobel(img, cv2.CV_8U, 1, 0) clips all negative gradients to 0, so half of every edge disappears. Use CV_16S or CV_32F.
  • Image yy points down. Gradient directions and angles are mirrored compared with a maths textbook; atan2⁡(gy,gx)=90∘\operatorname{atan2}(g_y, g_x) = 90^{\circ} means brighter below.
  • Comparing magnitudes across kernels. Sobel, Scharr and central differences have different gains (a unit step gives 4, 16 and 0.5); normalise before you compare or threshold.
  • Edges are not boundaries. Edge detectors also fire on texture, shadows and reflections, and leave gaps where an object and its background have similar brightness. Turning edges into object outlines needs more: morphology and contours, or a learned segmenter.

Practice

  1. Compute gxg_x with the Sobel kernel at the centre of the patch [[10, 10, 50], [10, 10, 50], [10, 10, 50]].
Answer

Correlation with SxS_x: (−1)(10)+1(50)+(−2)(10)+2(50)+(−1)(10)+1(50)=40+80+40=160(-1)(10) + 1(50) + (-2)(10) + 2(50) + (-1)(10) + 1(50) = 40 + 80 + 40 = 160. The step of 40 grey levels gives 4×40=1604 \times 40 = 160, the Sobel gain of 4 for a step.

  1. At a pixel gx=−30g_x = -30 and gy=30g_y = 30. Give the magnitude, the direction, and the neighbours NMS compares with.
Answer

Magnitude 900+900≈42.4\sqrt{900 + 900} \approx 42.4 (L1: 60). Direction atan2⁡(30,−30)=135∘\operatorname{atan2}(30, -30) = 135^{\circ}: brighter towards the lower left. NMS compares with the neighbours along that diagonal, at (row + 1, col −- 1) and (row −- 1, col + 1).

  1. Why does Canny need two thresholds instead of one?
Answer

With one high threshold, real edges break into pieces wherever their contrast dips; with one low threshold, noise produces many short false edges. Hysteresis uses the high threshold to decide which edges exist and the low one to follow them as far as they go, so a weak pixel is kept only when it continues a strong edge.

Test yourself

Why does the Sobel kernel include the weights 1, 2, 1 across the derivative direction?

  1. To make the kernel symmetric
  2. They smooth the image perpendicular to the derivative, which lowers the noise of the result
  3. They double the resolution
  4. They make it a second derivative

What does non-maximum suppression do in Canny?

  1. Removes duplicate boxes
  2. Keeps a pixel only if its gradient magnitude is a local maximum along the gradient direction, thinning edges to one pixel
  3. Removes pixels below the low threshold
  4. Blurs the image

In hysteresis with low = 50 and high = 150, a pixel has magnitude 90. When is it an edge pixel?

  1. Always
  2. Never
  3. Only if it is connected through pixels above 50 to a pixel above 150
  4. Only if its neighbours are below 50

With scale normalisation, at which σ\sigma does the Laplacian of Gaussian respond most strongly to a disc of radius rr?

  1. σ=r\sigma = r
  2. σ=r/2\sigma = r/\sqrt{2}
  3. σ=2r\sigma = 2r
  4. σ=1\sigma = 1, independent of rr