Contour detection

Also known as: contour tracing

On this page 7

Contour detection is the process in computer vision of finding the continuous boundary curves that separate objects or regions from their surroundings and returning each boundary as an ordered sequence of points. Also called contour tracing, it turns a pixel mask or edge map into explicit geometry that software can measure, simplify, compare and filter, which makes it a basic building block of classical image analysis and of many artificial intelligence pipelines.

Contour detection differs from edge detection in one essential way: an edge detector marks individual pixels with a strong intensity change, while a contour detector links boundary pixels into connected curves with a defined order, topology and often a parent-child hierarchy. The output is therefore a shape description rather than a raster of candidate pixels.

How contour detection traces object boundaries

Contour detection works by following the border between foreground and background pixels in a binary image, step by step, until the trace returns to its starting point. The classic approach is the Suzuki-Abe border following algorithm from 1985, which scans the image row by row, starts a trace at every unvisited border pixel and walks around the region using a fixed neighborhood rule.

The typical pipeline has four stages. The image is first converted to grayscale and smoothed to suppress noise. It is then binarized, either with a global or adaptive threshold or with an edge detector such as the Canny edge detector followed by morphological closing. The tracing algorithm then extracts the borders, and a final stage filters and simplifies the resulting curves.

The table below summarizes what each stage contributes and what usually goes wrong there.

StagePurposeTypical failure
PreprocessingReduce noise with Gaussian or median blurOver-blurring merges nearby objects
BinarizationSeparate foreground from backgroundUneven lighting breaks shapes apart
Border followingTrace closed point sequencesNoise creates thousands of tiny contours
Post-processingFilter by area, simplify, classifyWrong thresholds discard valid objects
Stages of a classical contour detection pipeline

The neighborhood rule matters. 8-connectivity treats diagonal pixels as neighbors and produces fewer, smoother contours, while 4-connectivity considers only horizontal and vertical neighbors. Outer borders and hole borders must use complementary connectivity so that the topology stays consistent.

Contour representations and hierarchy

A detected contour can be stored in several forms, and the choice affects memory use and downstream accuracy. A dense representation keeps every boundary pixel, while a compressed form stores only the endpoints of straight horizontal, vertical and diagonal runs. Polygon approximation with the Ramer-Douglas-Peucker algorithm reduces a curve further to a few vertices within a chosen tolerance.

Most implementations also return a contour hierarchy, a tree that records which contours lie inside others. This distinguishes an outer border from the hole borders inside it, which is essential for shapes such as washers, letters like O and B, or nested markers. The following table compares common retrieval and storage options.

OptionWhat it returnsWhen to use it
External onlyOutermost borders, no holesCounting separate objects
Full treeAll borders with nesting levelsShapes with holes, document markers
Two-levelOuter borders and their direct holesSimple parts inspection
Dense pointsEvery boundary pixelPrecise perimeter or curvature analysis
Compressed runsEndpoints of straight segmentsGeneral use with lower memory
Common contour retrieval and storage options

From the stored points, software computes shape descriptors: area, perimeter, bounding box, centroid from image moments, convex hull, convexity defects, circularity and Hu moment invariants, which stay stable under translation, scale and rotation. These descriptors are what make contours useful for measurement and recognition.

Contour detection sits between low-level pixel operations and full scene understanding, and it is often confused with its neighbors in the Computer vision toolbox. The comparison below clarifies the output and typical role of each technique.

TechniqueOutputKey difference
Contour detectionOrdered closed curves per regionExplicit geometry with topology
Edge detectionBinary map of high-gradient pixelsNo linking, gaps and spurs remain
Connected-component labelingLabel image of pixel regionsRegion interior, not boundary order
Image segmentationClass or region label per pixelAssigns meaning, not curves
Hough transformParameters of lines or circlesFits predefined models only
How contour detection relates to neighboring techniques

In deep learning, the term also covers learned contour detection, in which a neural network predicts boundary probability maps. Models such as holistically-nested edge detection and later encoder-decoder networks produce far cleaner object boundaries than gradient filters, especially on textured natural images. Their output is still a probability raster, so a classical tracing step is usually applied afterward to obtain point sequences. Instance segmentation networks such as Mask R-CNN likewise output masks that are commonly converted to polygons through contour tracing.

Practical use and parameter choices

Contour detection performs best when the scene is controlled and high-contrast: industrial inspection, document scanning, medical slide analysis, robotics pick-and-place and annotation tooling. In these settings it is fast, deterministic and explainable, often running in a few milliseconds per frame on a standard CPU.

The decisive settings are the thresholding method, the morphology kernel and the minimum contour area used to reject noise. The decision table below links common situations to a recommended configuration.

SituationRecommended choiceReason
Uniform backlightGlobal or Otsu thresholdClean bimodal histogram
Uneven room lightingAdaptive thresholdCompensates local brightness
Textured backgroundLearned boundary modelGradients alone are unreliable
Small dust particlesArea filter of 50-200 pixelsRemoves noise contours
Broken outlinesMorphological closingBridges small gaps before tracing
Choosing a contour detection configuration

A reliable practice is to tune thresholds on representative images from the real camera and lighting, not on clean samples. Logging the number of contours per frame is a simple health metric: a sudden jump usually signals a lighting or focus problem.

Limitations and common mistakes

The main weakness of contour detection is its dependence on a good binary image. Every error in thresholding or edge extraction passes directly into the traced curves. Typical problems include the following.

  • Touching objects merge into one contour unless they are separated first, for example with the watershed algorithm.
  • Occlusion and shadows create false boundaries or cut real ones.
  • Low resolution makes perimeter and curvature measurements unreliable for objects only a few pixels wide.
  • Feeding a grayscale image instead of a strict binary mask produces unpredictable results in most libraries.
  • Ignoring the hierarchy causes hole borders to be counted as objects.

Contours also carry no semantic meaning on their own. A contour says where a boundary is, not what the object is, so recognition still requires a classifier, rule set or learned model built on top of the extracted shapes.

A non-technical view

Imagine tracing the outline of each cookie on a baking tray with a pen. You start at one point and follow the edge until you return. Contour detection does the same for a computer. It finds the outline of each shape in a picture.

The result is a list of points around every object. With that list, a program can measure size, count items or check shape. It sees outlines, not meaning. It knows where a cookie ends, but not that it is a cookie.

A concrete example

A packaging line checks metal washers moving under a camera on a backlit conveyor. Each frame is blurred, binarized with an Otsu threshold and passed to contour detection with the full hierarchy enabled. Every washer then yields one outer contour and one inner hole contour.

The software filters out contours smaller than 150 pixels, then checks three values for each part: outer area, hole circularity and the distance between the two centroids. A washer with an off-center or oval hole fails the test and is pushed off the belt by an air jet.

The system processes about 40 parts per second on an ordinary industrial PC. Because each rejection is tied to a measured value, quality engineers can explain every rejected part and adjust tolerances without retraining any model.