WebMCP Ready
❖ WebGL & GPU Image Processing

Raster-to-Vector Tracing: Edge Detection, Polygon Simplification & Potrace

Transforming a pixelated raster bitmap into an infinitely scalable, resolution-independent SVG graphic is one of the classic challenges in computer vision. Naively tracing pixel steps produces jagged staircase outlines; over-smoothing erodes sharp geometric corners and typographic serifs. Raster-to-Vector Tracing: Edge Detection, Polygon Simplification & Potrace explores the algorithmic pipeline: bilateral filtering, Canny edge detection, marching squares contour tracing, Douglas-Peucker polygon reduction, and Peter Selinger's landmark Potrace Bézier fitting algorithm.

The Vectorization Pipeline: Four Critical Stages

Algorithmic vectorization bridges discrete pixel matrices with continuous parametric geometry through a structured four-stage processing pipeline:

  1. Image Pre-Processing & Thresholding: Binarizes grayscale or color imagery into high-contrast black-and-white silhouette masks using adaptive thresholding (Otsu's method).
  2. Contour Extraction (Boundary Tracing): Identifies closed boundary loops surrounding connected pixel components using the Moore-Neighbor tracing or Marching Squares algorithm.
  3. Polygon Simplification: Replaces thousands of single-pixel step edges with optimal linear polygon segments using the Douglas-Peucker algorithm.
  4. Smooth Curve Fitting: Detects sharp corner vertices and fits smooth cubic Bézier splines across smooth spans using least-squares polynomial regression.

Algorithmic Stages in Modern Vector Tracing

Pipeline Stage Primary Algorithm Input Data Output Representation
Thresholding Otsu's Global Binarization 8-bit Grayscale Bitmap 1-bit Binary Mask
Contour Tracing Moore-Neighbor / Marching Squares Binary Pixel Matrix Raw Pixel-Step Boundary Loops
Polygon Reduction Douglas-Peucker Recursive Pruning Dense Pixel Loops Simplified Linear Polygon
Curve Fitting Potrace Least-Squares Bézier Fitting Corner-Tagged Polygon Cubic Bézier SVG Path ()

Canny Edge Detection & Gradient Hysteresis

When vectorizing continuous-tone photographs rather than clean black-and-white logos, extracting crisp geometric edges requires Canny Edge Detection:

  • Non-Maximum Suppression: After computing horizontal and vertical Sobel gradients, the algorithm checks whether the gradient magnitude at a pixel is greater than its two neighbors along the gradient normal direction. If not, the value is suppressed to zero, thinning wide blurry edges down to a crisp 1-pixel line.
  • Hysteresis Thresholding: Uses two threshold limits: $T_{\text{high}}$ and $T_{\text{low}}$. Edge pixels exceeding $T_{\text{high}}$ are marked as strong; pixels below $T_{\text{low}}$ are discarded. Pixels between the thresholds are preserved only if they are topologically connected to a strong edge pixel, eliminating noise speckles while preserving faint continuous lines.

The Douglas-Peucker Polygon Simplification Algorithm

A raw traced pixel contour contains thousands of redundant vertices along straight edges. The Douglas-Peucker algorithm simplifies this polygon recursively based on perpendicular distance tolerance $\epsilon$:

d = \frac{|(y_2 - y_1)x_0 - (x_2 - x_1)y_0 + x_2 y_1 - y_2 x_1|}{\sqrt{(y_2 - y_1)^2 + (x_2 - x_1)^2}}
  1. Draw a straight line segment connecting the first vertex $P_1$ and last vertex $P_n$ of the polygon curve.
  2. Locate the intermediate vertex $P_k$ that has the maximum perpendicular distance $d_{\max}$ from this line.
  3. If $d_{\max} > \epsilon$, vertex $P_k$ is retained, and the algorithm recursively splits the curve into two sub-curves ($P_1 \to P_k$ and $P_k \to P_n$).
  4. If $d_{\max} \le \epsilon$, all intermediate vertices are discarded, reducing the segment to a single straight chord.

The Potrace Algorithm: Transforming Pixels into Organic Béziers

Published in 2001 by Peter Selinger, Potrace remains the gold standard engine for converting bitmap outlines into smooth, production-ready vector graphics:

  • Tolerance Envelope Optimization: Potrace finds the polygon with the minimum number of vertices that stays completely within a tolerance corridor of half a pixel from the original bitmap boundary, using a dynamic programming path optimization.
  • Corner Thresholding: Vertices where the interior polygon angle is sharper than a threshold parameter (typically $\alpha_{\max} = 1.34$ radians) are locked as sharp corner vertices.
  • Least-Squares Bézier Fitting: Across all non-corner curved spans, Potrace calculates the optimal cubic Bézier control points by minimizing the squared Euclidean distance between the parametric curve $B(t)$ and the underlying polygon vertices.

Color Vectorization: Multi-Layer Quantization & Chink Prevention

To vectorize color images, the engine first applies K-Means color quantization to segment the image into discrete color layers (e.g., 16 colors). Each color is isolated into a separate binary mask and vectorized via Potrace independently.

To eliminate microscopic gaps (white seams or "chinks") between adjacent vector shapes caused by curve fitting approximations, professional tracing engines apply a 0.5-pixel morphological dilation (stroke expansion) to lower color layers before layering them in painter's algorithm order, producing perfectly seamless multi-color SVG illustrations.

Topological Consistency & Hole Detection in Complex Outlines

A critical challenge in raster vectorization is preserving topological hierarchy—specifically distinguishing between exterior solid boundaries and interior transparent cutouts (such as the counter holes in typographic letters like 'O', 'B', and 'P').

The vectorizer constructs a Contour Hierarchy Tree where root nodes represent outer boundaries and child nodes represent nested holes. When serializing the contours to an SVG path string, the engine relies on the Non-Zero Winding Rule or the Even-Odd Rule (fill-rule="evenodd"). By orienting outer boundary paths in a clockwise direction and interior hole cutouts in a counter-clockwise direction, the renderer automatically carves out negative space without requiring separate Boolean clipping paths.

Additionally, real-world bitmap scans inevitably contain sensor dust, paper grain, and stray compression artifacts. Production tracing engines apply an area-threshold Despeckling Filter prior to curve fitting. Any closed contour enclosing an area smaller than a specified pixel threshold (e.g., fewer than 4 square pixels) is classified as visual noise and automatically excised from the AST, ensuring pristine, artifact-free vector output.

❖

Written by Imagemodifier Graphics Engineering Team

Specializing in low-level HTML5 Canvas 2D pipelines, WebGL 2.0 fragment shaders, Bézier curve vector mathematics, and WebAssembly SIMD image compression algorithms.