← Back

Freeman Chain Code

Encodes a boundary as a sequence of 8-directional steps. A compact representation used as input to higher-level shape analysis and simplification.

How it works

A chain code traces a pixel boundary by recording the direction of each step rather than absolute coordinates. With an 8-connected neighbourhood, only 3 bits per step are needed — far more compact than storing (x, y) pairs.

Starting from a known pixel, follow the boundary clockwise. At each step record the direction to the next boundary pixel using the numbering below, then advance. The resulting sequence of digits is the chain code. The starting point and a single (x, y) anchor are sufficient to reconstruct the full outline.

3
2
1
4
·P
0
5
6
7
function chainCode(boundary, start): code = [] pos = start // Direction vectors: 0=E, 1=NE, 2=N, 3=NW, 4=W, 5=SW, 6=S, 7=SE repeat: for dir in [0,1,2,3,4,5,6,7]: next = step(pos, dir) if next in boundary: code.append(dir) pos = next break until pos == start return code
Difference chain code. Storing direction differences (mod 8) between consecutive steps makes the code rotationally invariant — the same shape rotated 90° produces the same difference code. This is useful for shape matching and recognition.

Draw and trace

Draw a filled shape on the pixel grid. The algorithm traces its boundary and generates the chain code below. Each coloured step in the code corresponds to a highlighted segment on the boundary.

— draw a shape then press Trace —

Click or drag to paint pixels. Press Trace to run the algorithm.

Step-by-step

Watch the tracer advance one step at a time around the boundary. The amber cell is the current position; the arrow shows the direction about to be appended to the code.

Step 0 / 0
Press Next to begin.