The original article recorded contour areas about twenty times the region area. The current checkout lacks that input mask and complete old tracer, so this remains a historical observation. The checks below separate termination state, repeated laps and area calculation.
A termination test must match the state definition. The two simplified loops below alone cannot establish a three-line ordering error as the cause.
What the tracer is actually doing
The input is a binary mask: some pixels belong to the target region, the rest are background. Turning that into vector graphics means extracting each connected region’s boundary as an ordered list of points and joining them into a polygon.
Moore-neighbourhood tracing follows a region’s boundary, much like following a wall around a maze. On a pixel grid, the procedure is:
A row-major scan can select the first foreground pixel. Moore tracing also needs the backtracking neighbour that defines the next scan start; this is not necessarily the motion direction from the previous foreground pixel.
Keep a consistent neighbour order and backtracking state. A fixed scan start can select an incorrect boundary at concave corners. Inspect the state update together with the neighbour-search implementation.
7 0 1 neighbour indices (clockwise)
6 · 2 · is the current pixel
5 4 3
Each step therefore needs a pair of state values: position and direction. The direction comes from the previous step and determines where the next scan begins. The termination test used this state incorrectly.
The termination condition in Moore-neighbourhood tracing
Moore tracing searches the boundary pixel’s eight-neighbourhood and continues from its backtracking state. The stopping question concerns repetition of that state.
The question is when to stop. The naive answer is “when you return to the start”, which is not enough — some shapes pass through the start pixel mid-walk. A dumbbell with a thin neck does it, so does a one-pixel-wide spur that the tracer walks out along and back. Stopping there yields half a contour.
Jacob’s criterion compares re-entry into the start with its initial entry, not with the first departure direction. An implementation can instead define closure using a directed edge or complete scan state, with separate handling for isolated pixels and other degenerate inputs.
The original loop illustration follows. It omits initialisation and the meaning of the direction returned by findNextBoundaryPixel, so it cannot identify the faulty step on its own.
Direction definitions and test placement
The loop body looked roughly like this:
while (true) {
// check whether we are back at the start with a matching direction
if (x === startX && y === startY && dir === startDir) break;
next = findNextBoundaryPixel(x, y, dir);
x = next.x; y = next.y;
dir = next.dir; // direction updated only after the check
points.push([x, y]);
}
After a move, x,y,dir at the next loop’s start equal the just-updated state. Moving the same test to the previous iteration’s end generally changes initialisation or point-appending details; it does not convert an arrival direction into a departure direction.
Log initial state, every scan state and the stopping reason. An initial match can make the old loop exit immediately; a state that never matches needs cycle detection and an explicit failure at the iteration cap.
Repeated laps and accumulated area
Repeated laps repeat shoelace contributions. Twenty same-direction laps around a unit square have algebraic area 20, while retaining the same bounding box as one lap.
What matters is where it stops. The tracer is ultimately killed by the point cap, which leaves it at an arbitrary position on the contour rather than at the start. The resulting point list is therefore not closed — a stretch of real boundary sits between its last point and its first.
A capped point sequence closes with a chord. Its area also includes accumulated completed laps, so the discrepancy cannot be attributed entirely to the last closing edge.
The original twentyfold description concerned a thin arm mask. Without its input and old state trace, that remains a historical account. The repeated-square example establishes a possible accumulation mechanism, rather than the incident’s cause.
A top-edge-only trace also requires inspection of states and stopping reasons. Revisiting the start, matching a direction and traversing a complete boundary are separate conditions; a screenshot alone cannot establish a shared cause.
Original proposed fix and current implementation
The original proposed reorder is retained below. A valid repair must also define directions, initialisation, isolated-pixel handling and cap failures:
while (true) {
next = findNextBoundaryPixel(x, y, dir);
x = next.x; y = next.y;
dir = next.dir; // update direction first
// then check: position and *departure* direction must both match
if (x === startX && y === startY && dir === startDir) break;
points.push([x, y]);
}
The current browser tool’s svgPathForLabel walks directed pixel-cell edges and tracks used edges; it does not use this Moore loop. Distinguish pixel-centre and cell-edge coordinates when checking closure, area and coverage.
Shoelace input conditions
Area comes from the shoelace formula: pair up consecutive vertices, sum the cross products, halve the result.
let area = 0;
for (let i = 0; i < pts.length; i++) {
const [x1, y1] = pts[i];
const [x2, y2] = pts[(i + 1) % pts.length]; // last point wraps to first
area += x1 * y2 - x2 * y1;
}
area = Math.abs(area) / 2;
Shoelace closes the last vertex to the first without requiring an explicit duplicate endpoint. A valid polygon’s closing edge normally has nonzero length. Check whether that edge belongs to the intended contour.
If the point list is not closed, the first-to-last edge may be long. The shoelace formula still computes the polygon’s algebraic area; it does not check whether that edge follows the original region.
Worse, if that artificial edge makes the polygon self-intersecting, the formula returns signed areas that partly cancel. The result can be too large, too small, or close enough to correct to hide the problem entirely. Twentyfold is simply the number I happened to get; there is no rule to it.
Why the unit tests missed it
Rectangles and circles are useful baseline cases. Whether they trigger a stopping error depends on initialisation and scanning; they are not categorically immune.
Add lines, branches, concavities and repeated-state cases, recording full transitions. Shape thickness alone cannot establish a correct stopping rule.
What actually triggers it are long thin shapes with branches — a character’s arm, strands of hair, folds in clothing. Those have many one-pixel protrusions that the tracer must walk into and back out of, producing a far more complicated direction sequence.
Tests need to include pathological shapes: one-pixel lines, thin-necked dumbbells, regions with holes, and single-pixel regions. Passing rectangles and circles establishes behavior for those inputs.
Holes: the shoelace formula’s sign does the work for you
Everything above concerns outer contours. Real character layers frequently have holes — gaps in a sleeve, cut-outs for eyes, the inner ring of a letter O. Moore-neighbourhood tracing finds only the outer contour, so holes need separate handling or the computed area includes them.
The shoelace formula gives a signed area determined by winding direction. If a clockwise outer contour gives a positive value, tracing holes counter-clockwise gives negative values. Their sum is the net area.
area = shoelace(outer) # clockwise, positive
for hole in holes:
area += shoelace(hole) # counter-clockwise, negative -- add, don't subtract
With classified outer rings and holes, consistent coordinates and winding, signed areas can be summed. The snippet requires shoelace to preserve sign. Applying the absolute value used in the earlier JavaScript first would prevent hole subtraction.
SVG evenodd uses crossing parity; nonzero uses signed winding. Equal-direction simple outer and hole rings can make them differ, but self-intersections or repeated traversal can do so too. A difference does not uniquely diagnose hole direction.
Define foreground and background connectivity
One choice has to be settled before tracing begins: whether pixel adjacency means 4-connectivity (edges only) or 8-connectivity (including diagonals).
For conventional inside/outside separation in digital images, use complementary foreground/background connectivity such as 8/4 or 4/8. The checkerboard illustrates discrete adjacency ambiguity; it is not itself a simple continuous Jordan curve.
The fix is to make them complementary: 8-connectivity for foreground and 4 for background, or the reverse. Diagonally touching foreground counts as connected while diagonally touching background does not, and the contradiction disappears.
Eight-connectivity groups corner-touching pixels, whereas four-connectivity separates them. Contour output also depends on corner branching rules and need not be one simple ring. Record the diagonal-connectivity choice for line art.
So the configuration should expose one switch with the other derived from it, rather than two independent parameters — the latter lets a user configure exactly the contradictory combination above, and the symptom (contours occasionally merging or breaking for no apparent reason) is very hard to diagnose.
How to catch this sooner
The bug passed my initial visual checks because the output still formed coherent shapes with plausible point counts.
Bounding boxes are one inexpensive necessary check. Also check state closure, repeated edges, raster coverage and area: repeated laps or incorrect interior walks can keep the same box.
Compare boxes under the same coordinate convention. Pixel centres and cell edges may differ by one unit and need a declared conversion. Matching boxes pass only that check, not every boundary property.
We can check geometric output against independently computed invariants. Area, bounding boxes, point-count bounds, and closure can all be checked automatically alongside a visual inspection.
Establishing a common cause for top-edge truncation and area error requires their inputs and state logs, followed by before/after reproduction.
Vary noise in the soft mask threshold lab and observe components. The original 0.12 is an example slider setting; connectivity also depends on the image, threshold and random state.