I7 · Computer Vision in Practice

Edge and Contour Detection

An edge is a place where image brightness changes sharply, often at the boundary of an object. Edge detectors such as Sobel compute the brightness gradient at each pixel, and the Canny detector, published by John Canny in 1986, turns gradients into thin, connected edge lines. A contour is a closed curve tracing the boundary of a region in a binary image; from contours you can count objects and measure their area, perimeter, position and shape.

10 min Intermediate · Sublevel Advanced Jump to the activity

What you need: The earlier topics of this module.

Definition

A coin-counting machine, a robot picking parts from a bin and an app that measures a wound all need to find where one object ends and another begins. Edges and contours give the outline of things.

An edge is a place where image brightness changes sharply, often at the boundary of an object. Edge detectors such as Sobel compute the brightness gradient at each pixel, and the Canny detector, published by John Canny in 1986, turns gradients into thin, connected edge lines. A contour is a closed curve tracing the boundary of a region in a binary image; from contours you can count objects and measure their area, perimeter, position and shape.

In simple words

Run your finger across a photo of a white plate on a dark table. Where your finger crosses from dark to bright, that is an edge. Tracing your finger all the way round the plate's outline draws its contour.

Overview

  • Edges are places where brightness changes sharply, usually object boundaries.
  • Contours are connected curves along the boundary of a shape in a binary image.
  • The Canny detector (John Canny, 1986) is the standard edge detector.
  • Blurring first reduces false edges caused by noise.
  • Contour properties such as area, perimeter and bounding box measure objects.
  • Classical edge and contour methods are fast and need no training data.

Why it matters

Edges and contours power document scanners that find page corners, lane detection, industrial measurement, cell counting in medical labs and coin or seed counters, often in real time on cheap hardware.

Key terms

Gradient
The rate and direction of brightness change at a pixel.
Sobel operator
A pair of 3 × 3 kernels estimating horizontal and vertical gradients.
Canny edge detector
A multi-step method: blur, gradients, thinning and two thresholds to keep connected edges.
Binary image
An image with only two values, such as object (1) and background (0).
Contour
The boundary curve around a connected region.
Connected components
Separate groups of touching foreground pixels, each one an object.

Types

Edge and contour methods come in several types. These are the main ones and their uses.

1. Gradient-based edge detection (Sobel, Prewitt)

Estimating the brightness gradient in x and y with small kernels.

  • How it works: The gradient magnitude √(Gx² + Gy²) is large at edges and its direction shows the edge's orientation.
  • Example: Highlighting road lane markings in a dashboard camera frame.
  • When to use it: Use it when you need edge strength and direction, for example as features.

2. Canny edge detector

A multi-step detector producing thin, connected edges.

  • How it works: It blurs, computes gradients, thins edges by non-maximum suppression and keeps edges using two thresholds with hysteresis.
  • Example: cv2.Canny(gray, 50, 150) outlining the shapes of tools on a workbench.
  • When to use it: Use it as the default edge detector before finding contours or lines.

3. Laplacian and zero-crossing detection

Finding edges where the second derivative of brightness changes sign.

  • How it works: The Laplacian of Gaussian (LoG) blurs and takes the second derivative in one step; edges are at zero crossings.
  • Example: Detecting blobs such as cells in microscope images.
  • When to use it: Use it for blob detection and when edges in all directions matter equally.

4. Contour finding and analysis

Tracing the outlines of regions in a binary image and measuring them.

  • How it works: cv2.findContours returns point lists; contourArea, arcLength, boundingRect, aspect ratio and extent describe each shape.
  • Example: Counting tablets on a tray and rejecting broken ones by their area.
  • When to use it: Use it for counting, measuring and inspecting objects in controlled settings such as factories.

5. Shape fitting (Hough transform and polygons)

Detecting lines, circles and simple polygons from edges.

  • How it works: The Hough transform votes for lines or circles that pass through many edge points; approxPolyDP simplifies contours into polygons.
  • Example: Finding the four corners of a document to straighten it; detecting coins as circles.
  • When to use it: Use it when objects have simple geometric shapes.

Explained in detail

From gradients to edges

The Sobel operator applies two kernels: one measures how brightness changes from left to right (Gx), the other from top to bottom (Gy). The edge strength at a pixel is the gradient magnitude √(Gx² + Gy²), and the edge direction is the angle atan2(Gy, Gx). Thresholding the magnitude gives a rough edge map, but the lines are thick and noise creates false edges. Canny improves this in four steps: blur with a Gaussian to suppress noise; compute gradients; thin each edge to one pixel by keeping only local maxima along the gradient direction; then use two thresholds, keeping strong edges and only those weak edges connected to strong ones, called hysteresis.

From binary images to contours

To measure objects, first separate them from the background, for example by thresholding. Each group of touching foreground pixels is a connected component, and its outline is a contour. In OpenCV, cv2.findContours returns the list of contours; cv2.contourArea gives each area, cv2.arcLength the perimeter and cv2.boundingRect the enclosing box. Shape measures such as circularity, 4π × area ÷ perimeter², which is 1 for a perfect circle, help tell coins from screws or healthy cells from irregular ones.

MeasurementUse
Count of contoursCounting coins, seeds, cells or pills
AreaMeasuring leaf damage or wound size, rejecting tiny noise blobs
Bounding boxLocating objects to crop or label
Four-corner approximationFinding a page or card for document scanning
CircularityTelling round objects from long or irregular ones
  • Touching objects merge into one contour; techniques such as the distance transform and watershed separate them.
  • Lighting matters more than the algorithm: an even, contrasting background makes contour methods very reliable.
  • Deep-learning segmentation now handles cluttered scenes, but edges and contours remain fast, explainable and easy to run on small devices.

Morphological operations clean binary images before contours are found. Erosion shrinks white regions and removes tiny specks; dilation grows them and fills small gaps; opening, an erosion followed by a dilation, removes noise while keeping object size; closing, a dilation followed by an erosion, fills holes inside objects. A typical seed-counting pipeline thresholds the image, applies an opening to remove dust, then finds contours and keeps only those within the expected size range for a single seed.

How it works

  1. Convert to grayscale and blur lightly to reduce noise.
  2. For edges, apply Sobel or Canny and tune the thresholds.
  3. For objects, threshold to a binary image and clean it with small morphological operations.
  4. Find contours, filter out tiny ones by area and measure the rest.
  5. Draw the results on the image to check them visually.

In code

edges_contours.py
import numpy as np
from scipy import ndimage

# A 30 x 30 image with three bright objects on a dark background
img = np.zeros((30, 30))
yy, xx = np.mgrid[:30, :30]
img[(yy - 8) ** 2 + (xx - 8) ** 2 <= 16] = 1.0      # a coin, radius 4
img[(yy - 20) ** 2 + (xx - 20) ** 2 <= 36] = 1.0    # a bigger coin, radius 6
img[4:7, 18:28] = 1.0                               # a long thin screw

gx = ndimage.sobel(img, axis=1)
gy = ndimage.sobel(img, axis=0)
magnitude = np.hypot(gx, gy)
print("Edge pixels (gradient magnitude > 1):", int((magnitude > 1).sum()))

labels, count = ndimage.label(img > 0.5)               # connected components
print("Objects found:", count)
for i, box in enumerate(ndimage.find_objects(labels), start=1):
    region = labels[box] == i
    area = int(region.sum())
    h, w = region.shape
    aspect = max(h, w) / min(h, w)           # 1.0 for round or square shapes
    extent = area / (h * w)                  # 1.0 for a rectangle, lower for a circle (about 0.79 when large)
    kind = "long and thin" if aspect > 2 else "round"
    print(f"object {i}: area={area:3d}  box={w}x{h}  aspect={aspect:.2f}  extent={extent:.2f}  -> {kind}")

Output

Edge pixels (gradient magnitude > 1): 220
Objects found: 3
object 1: area= 49  box=9x9  aspect=1.00  extent=0.60  -> round
object 2: area= 30  box=10x3  aspect=3.33  extent=1.00  -> long and thin
object 3: area=113  box=13x13  aspect=1.00  extent=0.67  -> round

Try it yourself

Counting seeds for germination tests

An agricultural lab counts hundreds of seeds on trays every day.

The Canny edge detector

Put the steps in order.

  1. 1Blur the image with a Gaussian
  2. 2Keep strong edges and connected weak edges (hysteresis)
  3. 3Thin edges to one pixel (non-maximum suppression)
  4. 4Compute gradient magnitude and direction

Common mistakes

  • Skipping the blur, so noise produces many false edges.
  • Counting every contour, including tiny specks of noise.
  • Expecting touching objects to be separated automatically.

Check yourself

Question 1

1. What is an edge in an image?

Question 2

2. Why does Canny use two thresholds?

Question 3

3. Circularity is close to 1 for…

Summary

  • Edges are sharp brightness changes, found from gradients with Sobel or Canny.
  • Contours outline connected regions in a binary image.
  • Contours let you count objects and measure area, perimeter, position and shape.

Finished reading?

Sources: Richard Szeliski, Computer Vision: Algorithms and Applications (2nd ed.) · OpenCV documentation and tutorials