@floless/app 0.117.1 → 0.119.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,1039 @@
1
+ #!/usr/bin/env python3
2
+ """Separate ink by CLASS, then centerline only what is left -- Stage 0d.
3
+
4
+ The ordering is the whole point, and it was wrong before. Skeletonising all residual ink
5
+ produces clean, confident centerlines through every letter, hatch mark and stamp: geometry
6
+ that looks plausible and is wrong, which is worse than geometry that is missing. A reviewer
7
+ can see a gap. Nobody can see that a tidy polyline is actually the stem of a '4'.
8
+
9
+ So: detect and mask glyphs, hatch and stamps FIRST; thin what remains; walk the skeleton into
10
+ a graph; fit each chain to a line, an arc, or a simplified polyline. Circles leave as
11
+ kind:"arc" + d, never 36-gons -- the contract has always permitted arcs, and the 36-gon
12
+ existed only because the old scorer read `pts`.
13
+
14
+ Thinning is hand-rolled Zhang-Suen over a 256-entry lookup on the 8-neighbour bit pattern.
15
+ `opencv-python-headless` ships no `ximgproc.thinning`, and the alternatives were real costs:
16
+ `opencv-contrib-python` conflicts with the pinned headless wheel, and scikit-image drags in
17
+ scipy. The LUT form measured 1.7 s on an A4 at 300 DPI against 11.3 s for the naive vectorised
18
+ form -- 6.6x -- and is asserted identical to an explicit implementation of the published
19
+ algorithm. No new dependency.
20
+
21
+ Nothing here is validated for QUALITY: that needs the Stage 0b labels, which do not exist.
22
+ `--selftest` proves the stages do what they claim on synthetic input; the corpus run reports
23
+ diagnostics, not a score.
24
+ """
25
+
26
+ import argparse
27
+ import hashlib
28
+ import json
29
+ import math
30
+ import os
31
+ import re
32
+ import sys
33
+ import time
34
+
35
+ import cv2
36
+ import numpy as np
37
+
38
+ sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
39
+ from rectify_and_trace import (apply_affine, build_ink, measure_skew, # noqa: E402
40
+ rotation_matrix, warp)
41
+
42
+ TRACE_VERSION = "0d.1"
43
+
44
+ # Bit i of the neighbour code is Zhang-Suen's P(i+2), clockwise from North.
45
+ _KERNEL = np.array([[128, 1, 2],
46
+ [64, 0, 4],
47
+ [32, 16, 8]], np.float32)
48
+
49
+
50
+ def _build_thinning_luts():
51
+ lut = [np.zeros(256, bool), np.zeros(256, bool)]
52
+ for code in range(256):
53
+ P = [(code >> i) & 1 for i in range(8)]
54
+ P2, P3, P4, P5, P6, P7, P8, P9 = P
55
+ B = sum(P)
56
+ seq = P + [P2]
57
+ A = sum(1 for a, b in zip(seq, seq[1:]) if a == 0 and b == 1)
58
+ base = 2 <= B <= 6 and A == 1
59
+ lut[0][code] = base and (P2 * P4 * P6 == 0) and (P4 * P6 * P8 == 0)
60
+ lut[1][code] = base and (P2 * P4 * P8 == 0) and (P2 * P6 * P8 == 0)
61
+ return lut
62
+
63
+
64
+ _THIN_LUT = _build_thinning_luts()
65
+
66
+
67
+ def thin(mask, max_iter=200):
68
+ """Zhang-Suen thinning to a single-pixel skeleton, via the neighbour-code lookup.
69
+
70
+ Every Zhang-Suen condition -- the neighbour count B, the 0->1 transition count A, and the
71
+ two corner products -- is a pure function of the 8-neighbour bit pattern, so one
72
+ convolution plus one 256-entry lookup replaces ~25 array operations per sub-iteration.
73
+ Work is confined to the ink bounding box because a drawing is mostly paper.
74
+ """
75
+ img = (mask > 0).astype(np.uint8)
76
+ ys, xs = np.nonzero(img)
77
+ if not len(ys):
78
+ return img * 255, 0
79
+ y0, y1 = max(0, ys.min() - 1), min(img.shape[0], ys.max() + 2)
80
+ x0, x1 = max(0, xs.min() - 1), min(img.shape[1], xs.max() + 2)
81
+ sub = img[y0:y1, x0:x1].copy()
82
+ it = 0
83
+ while it < max_iter:
84
+ it += 1
85
+ changed = False
86
+ for step in (0, 1):
87
+ code = cv2.filter2D(sub, cv2.CV_16S, _KERNEL,
88
+ borderType=cv2.BORDER_CONSTANT).astype(np.uint8)
89
+ kill = _THIN_LUT[step][code] & (sub == 1)
90
+ if kill.any():
91
+ sub[kill] = 0
92
+ changed = True
93
+ if not changed:
94
+ break
95
+ out = np.zeros_like(img)
96
+ out[y0:y1, x0:x1] = sub
97
+ # `converged` matters: hitting the cap returns a PARTIALLY thinned mask that is not a
98
+ # skeleton, and tracing it yields plausible geometry with no signal that anything was
99
+ # wrong. Convergence needs roughly half the stroke thickness in iterations, so a very
100
+ # thick blob can exceed the cap.
101
+ return (out * 255).astype(np.uint8), it, it < max_iter
102
+
103
+
104
+ # ------------------------------------------------------------------------ class separation
105
+
106
+ def detect_glyphs(ink, max_extent, min_run=3, line_gap=None):
107
+ """Mask text as RUNS of glyph-sized components, never as isolated small components.
108
+
109
+ Size alone cannot separate a letter from a bolt-hole circle, a tick mark or an arrowhead
110
+ -- they are all small. What distinguishes lettering is that it comes in LINES: several
111
+ similar-height components sitting side by side on a shared baseline. Requiring a run of
112
+ `min_run` therefore keeps small structural marks out of the text mask, which matters
113
+ because anything masked here is geometry the tracer will never emit.
114
+ """
115
+ line_gap = line_gap if line_gap is not None else max_extent
116
+ n, labels, stats, cent = cv2.connectedComponentsWithStats(ink, connectivity=8)
117
+ cand = []
118
+ for i in range(1, n):
119
+ w, h = stats[i, cv2.CC_STAT_WIDTH], stats[i, cv2.CC_STAT_HEIGHT]
120
+ if max(w, h) > max_extent or max(w, h) < 3:
121
+ continue
122
+ cand.append((i, float(cent[i][0]), float(cent[i][1]), int(w), int(h),
123
+ int(stats[i, cv2.CC_STAT_LEFT]), int(stats[i, cv2.CC_STAT_TOP])))
124
+ boxes, used, keep_labels = [], set(), []
125
+ # Group by baseline: same-ish height, vertically aligned centroid, horizontally adjacent.
126
+ cand.sort(key=lambda c: (round(c[2] / max(1, max_extent // 2)), c[1]))
127
+ for k, c in enumerate(cand):
128
+ if c[0] in used:
129
+ continue
130
+ run = [c]
131
+ used.add(c[0])
132
+ for d in cand[k + 1:]:
133
+ if d[0] in used:
134
+ continue
135
+ last = run[-1]
136
+ if (abs(d[2] - last[2]) <= 0.6 * max(last[4], d[4])
137
+ and 0 <= d[1] - last[1] <= line_gap + last[3]
138
+ and 0.4 <= (d[4] + 1) / (last[4] + 1) <= 2.5):
139
+ run.append(d)
140
+ used.add(d[0])
141
+ if len(run) >= min_run:
142
+ x0 = min(r[5] for r in run)
143
+ y0 = min(r[6] for r in run)
144
+ x1 = max(r[5] + r[3] for r in run)
145
+ y1 = max(r[6] + r[4] for r in run)
146
+ boxes.append([x0, y0, x1, y1])
147
+ keep_labels.extend(r[0] for r in run)
148
+ else:
149
+ for r in run:
150
+ used.discard(r[0])
151
+ # Mask the glyph COMPONENTS, never the run's bounding rectangle. A text label's box is full
152
+ # of things that are not text: the leader that points at it, the dimension line it sits on,
153
+ # the member outline behind it. Clearing the rectangle deletes all of them permanently --
154
+ # exactly the failure that made hatch delete every line crossing a hatched area, and the
155
+ # same fix applies. The box is still REPORTED, because an excluded-class region is what the
156
+ # scorer and the editor's unvectorized_regions want.
157
+ mask = np.zeros_like(ink)
158
+ if keep_labels:
159
+ sel = np.zeros(n, dtype=bool)
160
+ sel[np.asarray(keep_labels, dtype=np.int64)] = True
161
+ mask = np.where(sel[labels], 255, 0).astype(np.uint8)
162
+ return cv2.bitwise_and(ink, mask), boxes
163
+
164
+
165
+ def detect_hatch(ink, cell, min_strokes, max_len, angle_tol_deg=8.0, stroke_pad=1,
166
+ min_purity=0.78, protect_min=236):
167
+ """Mask hatch as the STROKES themselves, in cells holding many mutually parallel ones.
168
+
169
+ A single short diagonal is a tick; forty of them at one angle inside one cell is a fill
170
+ pattern. Parallelism is the discriminator, so the evidence is an angle histogram per cell.
171
+
172
+ Two things this deliberately does NOT do, both measured failures:
173
+
174
+ * It does not mask the CELL. Masking an 80 px square because hatch was found in it
175
+ deletes every structural line that happens to cross the hatched area -- and a hatch
176
+ region almost always has a boundary and often a dimension line running through it.
177
+ Only the qualifying strokes are masked, and `stroke_pad` is deliberately SMALL. That
178
+ is a real trade-off, not a tuning detail: padding wide enough to erase a hatch stroke
179
+ cleanly also erases the same width out of every line it crosses. At 300 DPI, hatch at
180
+ ~1.5 mm spacing crossed by a 5 px-wide mask loses a third of the crossing line; a 3 px
181
+ mask loses a fifth, and the healing pass below closes what is left. Erring narrow keeps
182
+ some hatch ink; erring wide destroys structural geometry. Losing the drawing is far
183
+ worse than keeping some hatch.
184
+ * It does not run on raw ink. Lettering is dozens of short, roughly parallel strokes per
185
+ cell, so on the full mask this classified text as hatch: measured on `aisc-min`, 60% of
186
+ the resulting hatch mask was in fact glyphs, and the mask claimed 73% of all ink on the
187
+ sheet. It runs on the residual AFTER glyphs and stamps are removed.
188
+ """
189
+ raw = cv2.HoughLinesP(ink, 1, np.pi / 720.0, threshold=18,
190
+ minLineLength=8, maxLineGap=2)
191
+ if raw is None or not len(raw):
192
+ return np.zeros_like(ink), []
193
+ rows = np.asarray(raw, float).reshape(-1, 4)
194
+ h, w = ink.shape
195
+ buckets = {}
196
+ for x0, y0, x1, y1 in rows:
197
+ L = math.hypot(x1 - x0, y1 - y0)
198
+ if L > max_len:
199
+ continue
200
+ cx, cy = int((x0 + x1) / 2 // cell), int((y0 + y1) / 2 // cell)
201
+ ang = math.degrees(math.atan2(y1 - y0, x1 - x0)) % 180.0
202
+ buckets.setdefault((cx, cy), []).append((ang, (x0, y0, x1, y1)))
203
+ mask = np.zeros_like(ink)
204
+ boxes = []
205
+ for (cx, cy), items in sorted(buckets.items()):
206
+ if len(items) < min_strokes:
207
+ continue
208
+ angs = np.array([a for a, _ in items])
209
+ best_n, best_a = 0, None
210
+ for a in angs:
211
+ d = np.abs(((angs - a + 90.0) % 180.0) - 90.0)
212
+ n = int((d <= angle_tol_deg).sum())
213
+ if n > best_n:
214
+ best_n, best_a = n, a
215
+ if best_n < min_strokes:
216
+ continue
217
+ # ANGLE PURITY: hatch runs in ONE direction; lettering does not. A text row is also
218
+ # dozens of short mutually-parallel strokes -- its verticals alone satisfy a count test
219
+ # -- but it also carries horizontals and diagonals, so the dominant direction holds a
220
+ # smaller share. Measured: synthetic hatch 0.96, a text row 0.85.
221
+ #
222
+ # Note what was tried and REJECTED, because the obvious idea is wrong: spacing
223
+ # regularity. Lettering sits on an even pitch and measured MORE regular than hatch
224
+ # (0.07 vs 0.68). Stroke-length uniformity fails the same way (text 0.17, hatch 0.64).
225
+ if best_n / len(items) < min_purity:
226
+ continue
227
+ keep = np.abs(((angs - best_a + 90.0) % 180.0) - 90.0) <= angle_tol_deg
228
+ for (a, (x0, y0, x1, y1)), k in zip(items, keep):
229
+ if not k:
230
+ continue
231
+ cv2.line(mask, (int(round(x0)), int(round(y0))), (int(round(x1)), int(round(y1))),
232
+ 255, stroke_pad * 2 + 1)
233
+ bx0, by0 = max(0, cx * cell), max(0, cy * cell)
234
+ boxes.append([bx0, by0, min(w, bx0 + cell), min(h, by0 + cell)])
235
+
236
+ # PROTECT long straight strokes. Dense structural linework -- a schedule's rules, a stack
237
+ # of dimension lines, a run of parallel members -- also presents as many short mutually
238
+ # parallel Hough segments per cell, so it satisfies the hatch test. Measured across three
239
+ # corpus sheets, 47-73% of the hatch mask was landing on connected components over 30 mm
240
+ # long, which is not hatch by any definition. Nothing that is part of a detected long
241
+ # straight stroke may be masked as fill.
242
+ protect = np.zeros_like(ink)
243
+ # protect_min is a PHYSICAL length (~20 mm), not a multiple of the hatch cutoff. Derived as
244
+ # 4x max_len it came to 480 px, so a 370 px (31 mm) member line was NOT protected and the
245
+ # hatch mask ate it.
246
+ long_raw = cv2.HoughLinesP(ink, 1, np.pi / 720.0, threshold=60,
247
+ minLineLength=max(protect_min, 60), maxLineGap=6)
248
+ if long_raw is not None and len(long_raw):
249
+ for x0, y0, x1, y1 in np.asarray(long_raw, float).reshape(-1, 4):
250
+ cv2.line(protect, (int(round(x0)), int(round(y0))),
251
+ (int(round(x1)), int(round(y1))), 255, stroke_pad * 2 + 3)
252
+ mask = cv2.bitwise_and(mask, cv2.bitwise_not(protect))
253
+ return cv2.bitwise_and(ink, mask), boxes
254
+
255
+
256
+ def detect_stamps(ink, min_area, min_fill, min_side):
257
+ """Mask seals, logos and barcodes: large components that are mostly solid AND two-dimensional.
258
+
259
+ Structural linework is thin -- a member outline fills a few percent of its bounding box. A
260
+ component that fills a third of a large box is a filled graphic, not a drawn stroke.
261
+
262
+ Fill ratio ALONE is not enough, and getting that wrong silently deletes the drawing: a long
263
+ thick stroke fills its own bounding box completely, so a 500x9 bar scores fill = 1.0 and is
264
+ masked as a stamp. Requiring both sides of the box to be substantial is what separates a
265
+ blob from a bar.
266
+ """
267
+ n, labels, stats, _ = cv2.connectedComponentsWithStats(ink, connectivity=8)
268
+ mask = np.zeros_like(ink)
269
+ boxes = []
270
+ for i in range(1, n):
271
+ w, h = stats[i, cv2.CC_STAT_WIDTH], stats[i, cv2.CC_STAT_HEIGHT]
272
+ area, box = stats[i, cv2.CC_STAT_AREA], float(w * h)
273
+ if box < min_area or box <= 0 or min(w, h) < min_side:
274
+ continue
275
+ if area / box >= min_fill:
276
+ x0, y0 = int(stats[i, cv2.CC_STAT_LEFT]), int(stats[i, cv2.CC_STAT_TOP])
277
+ mask[y0:y0 + h, x0:x0 + w] |= (labels[y0:y0 + h, x0:x0 + w] == i).astype(
278
+ np.uint8) * 255
279
+ boxes.append([x0, y0, x0 + int(w), y0 + int(h)])
280
+ return mask, boxes
281
+
282
+
283
+ # ------------------------------------------------------------------- skeleton -> polylines
284
+
285
+ _N8 = [(-1, -1), (-1, 0), (-1, 1), (0, -1), (0, 1), (1, -1), (1, 0), (1, 1)]
286
+
287
+
288
+ def skeleton_to_chains(skel, min_len=6):
289
+ """Walk a single-pixel skeleton into polyline chains split at junctions.
290
+
291
+ Chains are cut at every pixel with three or more skeleton neighbours, so a junction is a
292
+ shared vertex rather than a place where one arbitrary branch wins. That is what lets the
293
+ downstream graph have real connectivity instead of a pile of overlapping strokes.
294
+ """
295
+ ys, xs = np.nonzero(skel)
296
+ pts = set(zip(ys.tolist(), xs.tolist()))
297
+ if not pts:
298
+ return []
299
+ nbr = {p: [q for q in ((p[0] + dy, p[1] + dx) for dy, dx in _N8) if q in pts] for p in pts}
300
+ deg = {p: len(v) for p, v in nbr.items()}
301
+ nodes = {p for p in pts if deg[p] != 2}
302
+ chains, seen = [], set()
303
+
304
+ def walk(start, first):
305
+ chain = [start, first]
306
+ prev, cur = start, first
307
+ while deg.get(cur, 0) == 2 and cur not in nodes:
308
+ nxt = next((q for q in nbr[cur] if q != prev), None)
309
+ if nxt is None or nxt in chain[:-1]:
310
+ break
311
+ prev, cur = cur, nxt
312
+ chain.append(cur)
313
+ return chain
314
+
315
+ for s in sorted(nodes):
316
+ for f in sorted(nbr[s]):
317
+ if (s, f) in seen:
318
+ continue
319
+ chain = walk(s, f)
320
+ seen.add((s, f))
321
+ seen.add((chain[-1], chain[-2]))
322
+ chains.append(chain)
323
+ # closed loops have no node at all: seed them from any unvisited degree-2 pixel
324
+ visited = {p for c in chains for p in c}
325
+ for s in sorted(pts - visited):
326
+ if deg[s] != 2:
327
+ continue
328
+ chain = walk(s, sorted(nbr[s])[0])
329
+ if chain[-1] != s:
330
+ chain.append(s)
331
+ chains.append(chain)
332
+ visited.update(chain)
333
+ out = []
334
+ for c in chains:
335
+ poly = [(float(x), float(y)) for y, x in c]
336
+ if len(poly) >= 2 and _plen(poly) >= min_len:
337
+ out.append(poly)
338
+ return out
339
+
340
+
341
+ def _dir_at(poly, from_start, span):
342
+ """Unit direction leaving one end of a chain, averaged over `span` of arc length.
343
+
344
+ Averaged rather than taken from the first segment: a skeleton's last pixel or two wobble,
345
+ and a direction read off one 1 px step is mostly noise."""
346
+ pts = poly if from_start else poly[::-1]
347
+ acc = 0.0
348
+ ax, ay = pts[0]
349
+ for (x0, y0), (x1, y1) in zip(pts, pts[1:]):
350
+ acc += math.dist((x0, y0), (x1, y1))
351
+ if acc >= span:
352
+ bx, by = x1, y1
353
+ break
354
+ else:
355
+ bx, by = pts[-1]
356
+ d = math.hypot(bx - ax, by - ay)
357
+ return ((bx - ax) / d, (by - ay) / d) if d > 1e-9 else (0.0, 0.0)
358
+
359
+
360
+ def merge_through_junctions(chains, join_radius, max_turn_deg=28.0, span=12.0):
361
+ """Re-join chains that pass STRAIGHT THROUGH a junction into one stroke.
362
+
363
+ skeleton_to_chains deliberately cuts at every junction, which is right for topology and
364
+ wrong for representation: a grid line crossed by ten others becomes eleven elements. On the
365
+ corpus that is the single biggest driver of element count -- each reference line was traced
366
+ as ~6 pieces -- and it also costs junction F1, because every cut invents two stroke ends
367
+ that the drawing does not have.
368
+
369
+ At each junction the incident chain-ends are paired by DIRECTION: two ends whose outgoing
370
+ tangents are near-opposite are the same physical stroke continuing. A T-junction's stem has
371
+ no opposed partner and is correctly left alone. Pairing is greedy on the straightest
372
+ candidate first, which is deterministic and cannot pair one end twice.
373
+ """
374
+ ends = [] # (point, chain index, which end)
375
+ for i, c in enumerate(chains):
376
+ if math.dist(c[0], c[-1]) <= 1e-9:
377
+ continue # a closed loop has nothing to join
378
+ ends.append((c[0], i, 0))
379
+ ends.append((c[-1], i, 1))
380
+ # bucket ends by cell so junction lookup is not quadratic
381
+ cell = max(join_radius, 1e-6)
382
+ buckets = {}
383
+ for k, (p, i, e) in enumerate(ends):
384
+ buckets.setdefault((int(p[0] // cell), int(p[1] // cell)), []).append(k)
385
+
386
+ partner = {}
387
+ used = set()
388
+ cands = []
389
+ for k, (p, i, e) in enumerate(ends):
390
+ cx, cy = int(p[0] // cell), int(p[1] // cell)
391
+ for ox in (-1, 0, 1):
392
+ for oy in (-1, 0, 1):
393
+ for k2 in buckets.get((cx + ox, cy + oy), ()):
394
+ if k2 <= k:
395
+ continue
396
+ q, j, e2 = ends[k2]
397
+ if i == j or math.dist(p, q) > join_radius:
398
+ continue
399
+ d1 = _dir_at(chains[i], e == 0, span)
400
+ d2 = _dir_at(chains[j], e2 == 0, span)
401
+ # both point AWAY from the junction, so continuing straight through means
402
+ # they are opposed
403
+ dot = d1[0] * d2[0] + d1[1] * d2[1]
404
+ turn = math.degrees(math.acos(max(-1.0, min(1.0, -dot))))
405
+ if turn <= max_turn_deg:
406
+ cands.append((turn, k, k2))
407
+ for turn, k, k2 in sorted(cands, key=lambda t: (t[0], t[1], t[2])):
408
+ if k in used or k2 in used:
409
+ continue
410
+ used.add(k)
411
+ used.add(k2)
412
+ partner[k] = k2
413
+ partner[k2] = k
414
+
415
+ end_of = {}
416
+ for k, (p, i, e) in enumerate(ends):
417
+ end_of[(i, e)] = k
418
+
419
+ def walk(k0):
420
+ """Concatenate the run of chains reachable by entering at end `k0`."""
421
+ run, k = [], k0
422
+ while True:
423
+ i, e = ends[k][1], ends[k][2]
424
+ if i in seen:
425
+ break
426
+ seen.add(i)
427
+ piece = chains[i] if e == 0 else chains[i][::-1] # enter at this end
428
+ if run and math.dist(run[-1], piece[0]) <= join_radius:
429
+ run.extend(piece[1:])
430
+ else:
431
+ run.extend(piece)
432
+ nxt = partner.get(end_of[(i, 1 - e)])
433
+ if nxt is None:
434
+ break
435
+ k = nxt
436
+ return run
437
+
438
+ seen = set()
439
+ out = []
440
+ for i, c in enumerate(chains):
441
+ if math.dist(c[0], c[-1]) <= 1e-9: # a closed loop joins nothing
442
+ seen.add(i)
443
+ out.append(c)
444
+ # Start from FREE ends, so every open run is emitted once and whole. Starting anywhere
445
+ # would enter a run in its middle and emit it as two halves.
446
+ for k in range(len(ends)):
447
+ if k in partner or ends[k][1] in seen:
448
+ continue
449
+ run = walk(k)
450
+ if len(run) >= 2:
451
+ out.append(run)
452
+ for i in range(len(chains)): # closed rings of paired chains
453
+ if i in seen:
454
+ continue
455
+ run = walk(end_of[(i, 0)])
456
+ if len(run) >= 2:
457
+ out.append(run)
458
+ return out
459
+
460
+
461
+ def _plen(poly):
462
+ return sum(math.dist(a, b) for a, b in zip(poly, poly[1:]))
463
+
464
+
465
+ def _max_dev_from_line(poly):
466
+ (x0, y0), (x1, y1) = poly[0], poly[-1]
467
+ L = math.hypot(x1 - x0, y1 - y0)
468
+ if L < 1e-9:
469
+ return float("inf")
470
+ return max(abs((x1 - x0) * (y0 - p[1]) - (x0 - p[0]) * (y1 - y0)) / L for p in poly)
471
+
472
+
473
+ def _fit_circle(poly):
474
+ """Algebraic (Kasa) circle fit. Returns (cx, cy, r, max radial deviation)."""
475
+ a = np.asarray(poly, float)
476
+ x, y = a[:, 0], a[:, 1]
477
+ A = np.column_stack([x, y, np.ones(len(x))])
478
+ b = x * x + y * y
479
+ try:
480
+ sol, *_ = np.linalg.lstsq(A, b, rcond=None)
481
+ except np.linalg.LinAlgError:
482
+ return None
483
+ cx, cy = sol[0] / 2.0, sol[1] / 2.0
484
+ r2 = sol[2] + cx * cx + cy * cy
485
+ if r2 <= 0:
486
+ return None
487
+ r = math.sqrt(r2)
488
+ dev = float(np.max(np.abs(np.hypot(x - cx, y - cy) - r)))
489
+ return cx, cy, r, dev
490
+
491
+
492
+ def _arc_path(cx, cy, r, poly):
493
+ """SVG `d` for the arc a chain traces. A closed ring becomes two half-arcs, because a
494
+ single elliptical arc command cannot express a full circle (start and end coincide, and
495
+ the spec then draws nothing)."""
496
+ a0 = math.atan2(poly[0][1] - cy, poly[0][0] - cx)
497
+ a1 = math.atan2(poly[-1][1] - cy, poly[-1][0] - cx)
498
+ closed = math.dist(poly[0], poly[-1]) <= max(1.5, r * 0.08)
499
+ if closed:
500
+ x0, y0 = cx + r, cy
501
+ return (f"M{x0:.2f} {y0:.2f} A{r:.2f} {r:.2f} 0 1 1 {cx - r:.2f} {cy:.2f} "
502
+ f"A{r:.2f} {r:.2f} 0 1 1 {x0:.2f} {y0:.2f} Z")
503
+ # Sweep AND span come from the traced points, by accumulating the angle actually swept
504
+ # around the centre. Deriving the span from the two ENDPOINTS cannot work: the wrapped
505
+ # endpoint delta is <= pi by construction, so `large` was always 0 and every fitted arc
506
+ # over 180 degrees was emitted as its complementary minor branch -- a visibly wrong bow
507
+ # drawn confidently. Verified: a 270-degree arc emitted "A r r 0 0 1", i.e. the 90-degree
508
+ # one.
509
+ swept = 0.0
510
+ prev = a0
511
+ for px, py in poly[1:]:
512
+ cur = math.atan2(py - cy, px - cx)
513
+ d = (cur - prev + math.pi) % (2 * math.pi) - math.pi
514
+ swept += d
515
+ prev = cur
516
+ sweep = 1 if swept > 0 else 0
517
+ large = 1 if abs(swept) > math.pi else 0
518
+ return (f"M{poly[0][0]:.2f} {poly[0][1]:.2f} A{r:.2f} {r:.2f} 0 {large} {sweep} "
519
+ f"{poly[-1][0]:.2f} {poly[-1][1]:.2f}")
520
+
521
+
522
+ def fit_chain(poly, line_tol, arc_tol, min_arc_r, max_arc_r, simplify_eps):
523
+ """One skeleton chain -> a line, an arc, or a simplified polyline."""
524
+ if _max_dev_from_line(poly) <= line_tol:
525
+ return {"kind": "line", "pts": [poly[0], poly[-1]]}
526
+ fit = _fit_circle(poly)
527
+ if fit:
528
+ cx, cy, r, dev = fit
529
+ chord = math.dist(poly[0], poly[-1])
530
+ # A short chain hugs any circle, so a fit is only believed when the chain actually
531
+ # subtends a real arc: enough length relative to the radius to have curved.
532
+ if (min_arc_r <= r <= max_arc_r and dev <= arc_tol
533
+ and _plen(poly) >= max(0.35 * r, 3 * line_tol)
534
+ and (chord < 1.9 * r)):
535
+ # Parameters, not a finished `d`: the path is built AFTER the inverse
536
+ # transform, so the arc lands in the same frame as every other element.
537
+ return {"kind": "arc", "cx": cx, "cy": cy, "r": r, "poly": poly}
538
+ approx = cv2.approxPolyDP(np.asarray(poly, np.float32).reshape(-1, 1, 2),
539
+ simplify_eps, False)
540
+ pts = [(float(p[0][0]), float(p[0][1])) for p in approx]
541
+ if len(pts) < 2:
542
+ pts = [poly[0], poly[-1]]
543
+ return {"kind": "polyline", "pts": pts}
544
+
545
+
546
+ # ------------------------------------------------------------------------------- pipeline
547
+
548
+ def run(bgr, args):
549
+ t0 = time.perf_counter()
550
+ h, w = bgr.shape[:2]
551
+ # Every threshold below is derived from the sheet's own resolution, so the same physical
552
+ # question is asked whatever DPI the scan arrived at.
553
+ dpi = float(args.dpi)
554
+ px = lambda mm: _px(mm, dpi) # noqa: E731
555
+ min_area = max(1, int(round(px(args.min_area_mm2 ** 0.5) ** 2)))
556
+ ink, _, _, red_px = build_ink(bgr, min_area, args.strip_colour,
557
+ dpi=dpi, block_mm=args.ink_block_mm,
558
+ method=args.ink_method)
559
+ t_ink = time.perf_counter()
560
+
561
+ angle, _ = measure_skew(ink)
562
+ M, ow, oh = rotation_matrix(w, h, angle)
563
+ Minv = cv2.invertAffineTransform(M)
564
+ ink_d = warp(ink, M, (ow, oh), 0)
565
+ t_rect = time.perf_counter()
566
+
567
+ # ---- CLASS SEPARATION FIRST. Everything masked here is geometry the tracer will never
568
+ # emit, which is the trade: a missed stroke is visible to a reviewer, a confident
569
+ # centerline through a letter is not.
570
+ # SEQUENTIAL, on the shrinking residual, not three independent passes over the same ink.
571
+ # Running them independently let the hatch detector see lettering -- which is dozens of
572
+ # short roughly-parallel strokes per cell and therefore reads exactly like a fill pattern.
573
+ # Measured on `aisc-min`, 60% of the hatch mask was glyphs.
574
+ glyph_mask, glyph_boxes = detect_glyphs(ink_d, int(px(args.text_max_extent_mm)),
575
+ args.text_min_run)
576
+ rest = cv2.bitwise_and(ink_d, cv2.bitwise_not(glyph_mask))
577
+ stamp_mask, stamp_boxes = detect_stamps(rest, int(px(args.stamp_min_area_mm2 ** 0.5) ** 2),
578
+ args.stamp_min_fill,
579
+ int(px(args.stamp_min_side_mm)))
580
+ rest = cv2.bitwise_and(rest, cv2.bitwise_not(stamp_mask))
581
+ hatch_mask, hatch_boxes = detect_hatch(rest, int(px(args.hatch_cell_mm)),
582
+ args.hatch_min_strokes,
583
+ int(px(args.hatch_max_len_mm)),
584
+ min_purity=args.hatch_min_purity,
585
+ protect_min=int(px(args.protect_min_mm)))
586
+ structural = cv2.bitwise_and(rest, cv2.bitwise_not(hatch_mask))
587
+ # Masking hatch pixel-by-pixel punches a nick in every structural line a hatch stroke
588
+ # crossed, and each nick becomes a break in the traced geometry. Closing reclaims ONLY
589
+ # pixels that were masked out and that structural ink is continuous across -- it heals the
590
+ # holes we made without inventing ink anywhere else.
591
+ heal = max(0, int(round(px(args.heal_mm))))
592
+ if heal > 0:
593
+ k = np.ones((heal | 1, heal | 1), np.uint8)
594
+ closed = cv2.morphologyEx(structural, cv2.MORPH_CLOSE, k)
595
+ # Reclaim only HATCH pixels. A stamp is a solid blob deliberately removed; letting a
596
+ # close reinstate part of one puts it straight back into the skeleton. Glyph pixels are
597
+ # not reclaimed either -- with components masked rather than rectangles, a line behind
598
+ # text is no longer being cut in the first place.
599
+ structural = cv2.bitwise_or(structural, cv2.bitwise_and(closed, hatch_mask))
600
+ t_class = time.perf_counter()
601
+
602
+ skel, iters, converged = thin(structural)
603
+ t_thin = time.perf_counter()
604
+
605
+ min_chain = px(args.min_chain_len_mm)
606
+ chains = skeleton_to_chains(skel, min_chain)
607
+ n_raw_chains = len(chains)
608
+ if args.merge_through:
609
+ chains = merge_through_junctions(chains, max(2.0, min_chain))
610
+ elements = [fit_chain(c, px(args.line_tol_mm), px(args.arc_tol_mm), px(args.min_arc_r_mm),
611
+ px(args.max_arc_r_mm), px(args.simplify_eps_mm)) for c in chains]
612
+ t_fit = time.perf_counter()
613
+
614
+ # Published in the ORIGINAL raster frame -- the frame the model, the editor and the raster
615
+ # backdrop all use. Scoring against a deskewed mask was the 0a defect.
616
+ def back(pts):
617
+ return [[round(p[0], 2), round(p[1], 2)] for p in apply_affine(Minv, pts)]
618
+
619
+ out_elements = []
620
+ for el in elements:
621
+ if el["kind"] == "arc":
622
+ # Deskew is a rotation plus a translation, so it maps a circle to a circle of the
623
+ # SAME radius: transforming the centre and the traced points and rebuilding the
624
+ # path is exact. Emitting the deskewed `d` and labelling the frame would have left
625
+ # arcs in a different coordinate system from the lines beside them in one document
626
+ # -- correct-looking output that is silently misplaced on any skewed sheet.
627
+ (cx, cy), = apply_affine(Minv, [(el["cx"], el["cy"])])
628
+ out_elements.append({"kind": "arc",
629
+ "d": _arc_path(cx, cy, el["r"], apply_affine(Minv, el["poly"]))})
630
+ else:
631
+ out_elements.append({"kind": el["kind"], "pts": back(el["pts"])})
632
+ for i, e in enumerate(out_elements):
633
+ e["id"] = f"e{i + 1}"
634
+
635
+ def boxes_back(boxes, reason):
636
+ out = []
637
+ for x0, y0, x1, y1 in boxes:
638
+ q = apply_affine(Minv, [(x0, y0), (x1, y0), (x1, y1), (x0, y1)])
639
+ xs = [p[0] for p in q]
640
+ ys = [p[1] for p in q]
641
+ out.append({"bbox": [round(min(xs), 1), round(min(ys), 1),
642
+ round(max(xs), 1), round(max(ys), 1)], "reason": reason})
643
+ return out
644
+
645
+ verts = sum(len(e.get("pts", [])) for e in out_elements)
646
+ ink_px = int(ink_d.sum() // 255)
647
+ return {
648
+ "method": "opencv/centerline",
649
+ "trace_version": TRACE_VERSION,
650
+ "image": {"w": w, "h": h},
651
+ "output_frame": "original",
652
+ "opencv": cv2.__version__,
653
+ "script_sha256": hashlib.sha256(
654
+ open(os.path.abspath(__file__), "rb").read()).hexdigest()[:16],
655
+ "skew_deg": round(angle, 3),
656
+ "deskew_canvas": [int(ow), int(oh)],
657
+ "params": vars(args) | {"image": None, "out": None, "debug_prefix": None},
658
+ "ink_px": ink_px,
659
+ "red_markup_px": red_px,
660
+ "class_ink_px": {
661
+ "glyph": int(glyph_mask.sum() // 255),
662
+ "hatch": int(hatch_mask.sum() // 255),
663
+ "stamp": int(stamp_mask.sum() // 255),
664
+ "structural": int(structural.sum() // 255),
665
+ },
666
+ "class_ink_frac": {k: round(v / ink_px, 4) if ink_px else None for k, v in (
667
+ ("glyph", int(glyph_mask.sum() // 255)),
668
+ ("hatch", int(hatch_mask.sum() // 255)),
669
+ ("stamp", int(stamp_mask.sum() // 255)),
670
+ ("structural", int(structural.sum() // 255)))},
671
+ "thin_iterations": iters,
672
+ "thin_converged": converged,
673
+ "skeleton_px": int(skel.sum() // 255),
674
+ "chains": len(chains),
675
+ "chains_before_merge": n_raw_chains,
676
+ "elements_by_kind": {k: sum(1 for e in out_elements if e["kind"] == k)
677
+ for k in ("line", "arc", "polyline")},
678
+ "vertices": verts,
679
+ "unvectorized_regions": (boxes_back(glyph_boxes, "unsupported-class:glyph")
680
+ + boxes_back(hatch_boxes, "unsupported-class:hatch")
681
+ + boxes_back(stamp_boxes, "unsupported-class:stamp")),
682
+ "timings_s": {"ink": round(t_ink - t0, 3), "rectify": round(t_rect - t_ink, 3),
683
+ "classify": round(t_class - t_rect, 3), "thin": round(t_thin - t_class, 3),
684
+ "fit": round(t_fit - t_thin, 3), "total": round(t_fit - t0, 3)},
685
+ "elements": out_elements,
686
+ }, (ink_d, glyph_mask, hatch_mask, stamp_mask, structural, skel)
687
+
688
+
689
+ # ------------------------------------------------------------------------------- selftest
690
+
691
+ def _synthetic_sheet():
692
+ """A page carrying one of everything: structural lines, a circle, a run of lettering, a
693
+ hatch patch and a solid stamp."""
694
+ img = np.full((900, 1200, 3), 255, np.uint8)
695
+ for y in (150, 700):
696
+ cv2.line(img, (100, y), (1100, y), (0, 0, 0), 3)
697
+ cv2.line(img, (300, 150), (300, 700), (0, 0, 0), 3)
698
+ cv2.circle(img, (850, 400), 40, (0, 0, 0), 3)
699
+ for i, ch in enumerate("SECTION A-A TYP"):
700
+ cv2.putText(img, ch, (120 + i * 26, 800), cv2.FONT_HERSHEY_SIMPLEX, 0.8, (0, 0, 0), 2)
701
+ cv2.line(img, (252, 752), (252, 848), (0, 0, 0), 3) # through a gap in the text row
702
+ for x in range(430, 1000, 16): # hatch: parallel, evenly spaced ~1.4mm at 300 DPI
703
+ cv2.line(img, (x, 230), (x - 50, 330), (0, 0, 0), 2)
704
+ # a structural line running straight THROUGH the hatched area. Masking hatch by cell
705
+ # deletes this, which is how class separation stops being a filter and starts being data
706
+ # loss -- a hatched region nearly always has a boundary or a dimension line crossing it.
707
+ cv2.line(img, (330, 280), (700, 280), (0, 0, 0), 3)
708
+ cv2.rectangle(img, (950, 720), (1120, 840), (0, 0, 0), -1) # solid stamp
709
+ return img
710
+
711
+
712
+ def selftest():
713
+ fails = []
714
+
715
+ def check(name, cond, detail=""):
716
+ if cond:
717
+ print(f" ok {name}")
718
+ else:
719
+ print(f" FAIL {name} -> {detail}")
720
+ fails.append(name)
721
+
722
+ # --- thinning matches an explicit implementation of the published algorithm
723
+ def zs_reference(mask):
724
+ img = (mask > 0).astype(np.uint8)
725
+ while True:
726
+ changed = False
727
+ for step in (0, 1):
728
+ p = np.pad(img, 1)
729
+ P2, P3, P4 = p[0:-2, 1:-1], p[0:-2, 2:], p[1:-1, 2:]
730
+ P5, P6, P7 = p[2:, 2:], p[2:, 1:-1], p[2:, 0:-2]
731
+ P8, P9 = p[1:-1, 0:-2], p[0:-2, 0:-2]
732
+ B = P2 + P3 + P4 + P5 + P6 + P7 + P8 + P9
733
+ seq = (P2, P3, P4, P5, P6, P7, P8, P9, P2)
734
+ A = np.zeros_like(B)
735
+ for a, b in zip(seq, seq[1:]):
736
+ A += ((a == 0) & (b == 1)).astype(np.uint8)
737
+ cond = ((P2 * P4 * P6 == 0) & (P4 * P6 * P8 == 0)) if step == 0 else \
738
+ ((P2 * P4 * P8 == 0) & (P2 * P6 * P8 == 0))
739
+ kill = (img == 1) & (B >= 2) & (B <= 6) & (A == 1) & cond
740
+ if kill.any():
741
+ img = img & ~kill
742
+ changed = True
743
+ if not changed:
744
+ return (img * 255).astype(np.uint8)
745
+
746
+ rng = np.random.default_rng(3)
747
+ same = True
748
+ for _ in range(5):
749
+ m = np.zeros((90, 120), np.uint8)
750
+ for _ in range(10):
751
+ cv2.line(m, (int(rng.integers(0, 120)), int(rng.integers(0, 90))),
752
+ (int(rng.integers(0, 120)), int(rng.integers(0, 90))),
753
+ 255, int(rng.integers(1, 7)))
754
+ cv2.circle(m, (60, 45), 20, 255, 4)
755
+ same &= np.array_equal(thin(m.copy())[0], zs_reference(m))
756
+ check("thin: LUT equals an explicit Zhang-Suen implementation", same)
757
+
758
+ bar = np.zeros((60, 200), np.uint8)
759
+ cv2.line(bar, (10, 30), (190, 30), 255, 9)
760
+ sk, _, _ = thin(bar)
761
+ cols = [int((sk[:, x] > 0).sum()) for x in range(20, 180)]
762
+ check("thin: a 9px bar reduces to ONE pixel per column", set(cols) == {1}, set(cols))
763
+
764
+ # --- class separation on a synthetic sheet
765
+ ap = argparse.Namespace(**_defaults())
766
+ doc, masks = run(_synthetic_sheet(), ap)
767
+ ink_d, glyph, hatch, stamp, structural, skel = masks
768
+ check("classify: lettering is masked", int(glyph.sum()) > 0, int(glyph.sum() // 255))
769
+ check("classify: hatch is masked", int(hatch.sum()) > 0, int(hatch.sum() // 255))
770
+ check("classify: the solid stamp is masked", int(stamp.sum()) > 0, int(stamp.sum() // 255))
771
+ check("classify: structural ink survives",
772
+ doc["class_ink_frac"]["structural"] > 0.2, doc["class_ink_frac"])
773
+
774
+ # The load-bearing claim of the whole stage: no traced element may sit inside a masked
775
+ # class region. If it does, class separation ran too late to matter.
776
+ def elem_pts(e):
777
+ return e.get("pts") or []
778
+ inside = 0
779
+ for e in doc["elements"]:
780
+ for x, y in elem_pts(e):
781
+ xi, yi = int(round(x)), int(round(y))
782
+ if 0 <= yi < glyph.shape[0] and 0 <= xi < glyph.shape[1] and glyph[yi, xi]:
783
+ inside += 1
784
+ check("classify BEFORE centerline: no traced vertex lands on masked lettering",
785
+ inside == 0, inside)
786
+
787
+ # Masking hatch by CELL deletes any structural line crossing the hatched area. This asserts
788
+ # the line at y=280 running through the hatch patch survives to become an element.
789
+ # What class separation must guarantee is that the line's INK survives into the structural
790
+ # mask. Two things this deliberately does NOT demand:
791
+ #
792
+ # * 100% of the ink. The hatch strokes physically OVERLAP the line -- 35 crossings at
793
+ # 3 px each out of 370 px -- so masking hatch and keeping every pixel of the line are
794
+ # contradictory. ~84% is the arithmetic ceiling here, not a shortfall.
795
+ # * traced continuity. Whether the tracer emits one stroke or fragments between crossings
796
+ # is a TRACING property, reported separately as `fragmentation`. Asserting it here made
797
+ # the check pass or fail on how much hatch happened to be detected, which is the
798
+ # opposite of what a `classify:` check is for.
799
+ #
800
+ # What must not regress is WHOLESALE loss: cell-masking takes this to ~15%, and removing the
801
+ # angle-purity gate lets a text row take the line with it. Both are caught at this bar.
802
+ band_ink = int(ink_d[276:285, 330:700].sum() // 255)
803
+ band_structural = int(structural[276:285, 330:700].sum() // 255)
804
+ check("classify: a structural line CROSSING hatch keeps its ink except at the crossings",
805
+ band_structural >= 0.75 * band_ink, f"{band_structural} of {band_ink}")
806
+
807
+ # The angle-purity gate only bites under LOCAL thresholding, which recovers enough of the
808
+ # light ink to make a text row look like a fill pattern. Pinning it under the default would
809
+ # be vacuous, so this fixture runs the configuration where it is load-bearing: without the
810
+ # gate, the line through the text row loses most of its ink to the hatch mask (measured 52
811
+ # of 96 px traced, against 86 with the gate).
812
+ ad = dict(_defaults())
813
+ ad["ink_method"] = "adaptive"
814
+ doc_ad, m_ad = run(_synthetic_sheet(), argparse.Namespace(**ad))
815
+ ink_ad, glyph_ad, hatch_ad, stamp_ad, struct_ad, _ = m_ad
816
+ tb_ink = int(ink_ad[752:848, 248:257].sum() // 255)
817
+ tb_struct = int(struct_ad[752:848, 248:257].sum() // 255)
818
+ check("classify (adaptive): a line through a TEXT row is not swallowed as hatch",
819
+ tb_struct >= 0.8 * tb_ink, f"{tb_struct} of {tb_ink}")
820
+
821
+ check("classify: the class masks are disjoint (sequential residual)",
822
+ int(cv2.bitwise_and(glyph, hatch).sum()) == 0
823
+ and int(cv2.bitwise_and(glyph, stamp).sum()) == 0
824
+ and int(cv2.bitwise_and(hatch, stamp).sum()) == 0,
825
+ (int(cv2.bitwise_and(glyph, hatch).sum() // 255),
826
+ int(cv2.bitwise_and(glyph, stamp).sum() // 255),
827
+ int(cv2.bitwise_and(hatch, stamp).sum() // 255)))
828
+
829
+ check("trace: the circle leaves as an arc, not a 36-gon",
830
+ doc["elements_by_kind"]["arc"] >= 1, doc["elements_by_kind"])
831
+ check("trace: no element carries both d and pts",
832
+ all(not (e.get("d") and e.get("pts")) for e in doc["elements"]))
833
+
834
+ # An arc must land in the SAME frame as the lines beside it. Detection runs deskewed, so
835
+ # on a skewed sheet an arc emitted in the deskew frame is silently misplaced by the whole
836
+ # rotation -- roughly 50 px here -- and a ZERO-SKEW fixture can never catch it. The property
837
+ # asserted is the one that actually matters and does not care how many pieces the circle
838
+ # fits as: every emitted arc must land ON THE INK of the sheet it was traced from.
839
+ plain = np.full((900, 1200, 3), 255, np.uint8)
840
+ cv2.circle(plain, (600, 450), 60, (0, 0, 0), 3)
841
+ cv2.line(plain, (80, 120), (1120, 120), (0, 0, 0), 3) # gives the deskew a signal
842
+ cv2.line(plain, (80, 780), (1120, 780), (0, 0, 0), 3)
843
+ Mrot, ow2, oh2 = rotation_matrix(1200, 900, -4.0)
844
+ rot = cv2.warpAffine(plain, Mrot, (ow2, oh2), flags=cv2.INTER_NEAREST,
845
+ borderMode=cv2.BORDER_CONSTANT, borderValue=(255, 255, 255))
846
+ d3, _ = run(rot, argparse.Namespace(**_defaults()))
847
+ ink3, _, _, _ = build_ink(rot, 12, False)
848
+ dt = cv2.distanceTransform(255 - ink3, cv2.DIST_L2, 3)
849
+ arcs, worst = 0, 0.0
850
+ for e in d3["elements"]:
851
+ if e["kind"] != "arc":
852
+ continue
853
+ arcs += 1
854
+ n = [float(v) for v in re.findall(r"-?\d+\.?\d*", e["d"])]
855
+ for (ax, ay) in ((n[0], n[1]), (n[7], n[8])):
856
+ yi = int(min(max(round(ay), 0), dt.shape[0] - 1))
857
+ xi = int(min(max(round(ax), 0), dt.shape[1] - 1))
858
+ worst = max(worst, float(dt[yi, xi]))
859
+ check("trace: every arc on a SKEWED sheet lands on the ink (original frame)",
860
+ arcs >= 1 and worst <= 4.0, f"{arcs} arcs, worst anchor {worst:.1f}px off the ink "
861
+ f"(skew detected {d3['skew_deg']})")
862
+
863
+ # Deriving the arc span from the two ENDPOINTS makes `large` always 0, so every fitted arc
864
+ # over 180 degrees is emitted as its complementary minor branch -- a confidently drawn,
865
+ # visibly wrong bow.
866
+ flags = []
867
+ for lo, hi in ((0.0, 0.5 * math.pi), (0.0, 1.5 * math.pi), (1.5 * math.pi, 0.0)):
868
+ pp = [(150 + 60 * math.cos(a), 150 + 60 * math.sin(a))
869
+ for a in np.linspace(lo, hi, 80)]
870
+ f = _fit_circle(pp)
871
+ flags.append(tuple(_arc_path(f[0], f[1], f[2], pp).split()[5:7]))
872
+ check("trace: a major arc sets the SVG large-arc flag, a minor one does not",
873
+ flags == [("0", "1"), ("1", "1"), ("1", "0")], flags)
874
+
875
+ check("trace: straight strokes fit as lines",
876
+ doc["elements_by_kind"]["line"] >= 3, doc["elements_by_kind"])
877
+
878
+ # A stroke must produce ONE centerline, not two offset outlines -- the defect that
879
+ # withdrew recall_linework. A 9px-wide bar traced by this pipeline is one chain.
880
+ img = np.full((200, 600, 3), 255, np.uint8)
881
+ cv2.line(img, (50, 100), (550, 100), (0, 0, 0), 9)
882
+ d2, _ = run(img, argparse.Namespace(**_defaults()))
883
+ check("trace: a wide bar yields ONE centerline, not two outlines",
884
+ len(d2["elements"]) == 1, [e["kind"] for e in d2["elements"]])
885
+ e = d2["elements"][0] if d2["elements"] else None
886
+ ys = [p[1] for p in (e or {}).get("pts", [])]
887
+ check("trace: that centerline runs down the middle of the bar",
888
+ e is not None and e["kind"] == "line" and ys and all(abs(y - 100) <= 2 for y in ys),
889
+ (e and e["kind"], ys))
890
+
891
+ # skeleton -> graph must split at junctions, so a '+' is four chains sharing a vertex
892
+ plus = np.zeros((200, 200), np.uint8)
893
+ cv2.line(plus, (20, 100), (180, 100), 255, 3)
894
+ cv2.line(plus, (100, 20), (100, 180), 255, 3)
895
+ sk, _, _ = thin(plus)
896
+ chains = skeleton_to_chains(sk)
897
+ check("skeleton: a '+' splits into 4 chains at the junction", len(chains) == 4,
898
+ len(chains))
899
+ ends = [c[0] for c in chains] + [c[-1] for c in chains]
900
+ at_centre = sum(1 for p in ends if math.dist(p, (100, 100)) <= 3)
901
+ check("skeleton: all 4 chains share the junction vertex", at_centre == 4, at_centre)
902
+
903
+ # Re-joining chains that pass STRAIGHT THROUGH a junction. Splitting at every junction is
904
+ # right for topology and wrong for representation: a grid line crossed by ten others became
905
+ # eleven elements. That was the biggest driver of element count, and of the invented stroke
906
+ # ends that dragged junction F1 down.
907
+ def _merged(im):
908
+ sk_, _, _ = thin(im)
909
+ ch_ = skeleton_to_chains(sk_)
910
+ return len(ch_), len(merge_through_junctions(ch_, 6.0))
911
+
912
+ cross = np.zeros((300, 300), np.uint8)
913
+ cv2.line(cross, (20, 150), (280, 150), 255, 3)
914
+ cv2.line(cross, (150, 20), (150, 280), 255, 3)
915
+ check("merge: a '+' crossing becomes 2 strokes, not 4", _merged(cross) == (4, 2),
916
+ _merged(cross))
917
+
918
+ tee = np.zeros((300, 300), np.uint8)
919
+ cv2.line(tee, (20, 150), (280, 150), 255, 3)
920
+ cv2.line(tee, (150, 150), (150, 280), 255, 3)
921
+ # the flange runs through; the stem has no opposed partner and must stay its own stroke
922
+ check("merge: a 'T' keeps its stem separate", _merged(tee) == (3, 2), _merged(tee))
923
+
924
+ ell = np.zeros((300, 300), np.uint8)
925
+ cv2.line(ell, (40, 150), (150, 150), 255, 3)
926
+ cv2.line(ell, (150, 150), (150, 260), 255, 3)
927
+ check("merge: a 90-degree corner is NOT merged into one stroke",
928
+ _merged(ell) == (2, 2), _merged(ell))
929
+
930
+ grid = np.zeros((400, 400), np.uint8)
931
+ for _y in (100, 200, 300):
932
+ cv2.line(grid, (30, _y), (370, _y), 255, 3)
933
+ for _x in (100, 200, 300):
934
+ cv2.line(grid, (_x, 30), (_x, 370), 255, 3)
935
+ check("merge: a 3x3 grid is 6 lines, not 24 fragments", _merged(grid) == (24, 6),
936
+ _merged(grid))
937
+
938
+ # ...and the PIPELINE must actually use it. The checks above call the function directly, so
939
+ # they stay green even if run() never invokes it.
940
+ check("merge: the pipeline applies it (chains drop against chains_before_merge)",
941
+ doc["chains"] < doc["chains_before_merge"],
942
+ (doc["chains_before_merge"], doc["chains"]))
943
+
944
+ print(f"\nselftest: {len(fails)} failure(s)")
945
+ return 1 if fails else 0
946
+
947
+
948
+ # Every length here is PHYSICAL, in millimetres, and converted to pixels from the sheet's --dpi
949
+ # at run time. They used to be absolute pixel counts, which silently encodes one scan resolution:
950
+ # a 240 px hatch cell is 20 mm at 300 DPI and 40 mm at 150 DPI, so the same sheet scanned twice
951
+ # was asked two different questions. The values below are the previous pixel defaults expressed
952
+ # at 300 DPI, so behaviour at 300 DPI is unchanged and every other resolution is now correct
953
+ # instead of silently mis-scaled.
954
+ _MM = {
955
+ "min_area_mm2": 0.086, # was 12 px^2 speckle cutoff
956
+ "text_max_extent_mm": 3.9, # was 46 px -- largest glyph
957
+ "hatch_cell_mm": 20.3, # was 240 px -- evidence window
958
+ "hatch_max_len_mm": 10.2, # was 120 px -- longest stroke that can be fill
959
+ "protect_min_mm": 20.0, # strokes longer than this are never masked as fill
960
+ "stamp_min_area_mm2": 28.7, # was 4000 px^2
961
+ "stamp_min_side_mm": 3.4, # was 40 px -- a stamp is a blob, not a bar
962
+ "min_chain_len_mm": 0.51, # was 6 px
963
+ "heal_mm": 0.59, # was 7 px
964
+ "line_tol_mm": 0.135, # was 1.6 px
965
+ "arc_tol_mm": 0.135, # was 1.6 px
966
+ "min_arc_r_mm": 0.42, # was 5 px
967
+ "max_arc_r_mm": 33.9, # was 400 px
968
+ "simplify_eps_mm": 0.10, # was 1.2 px
969
+ }
970
+
971
+
972
+ def _px(mm, dpi):
973
+ return mm / 25.4 * float(dpi)
974
+
975
+
976
+ def _defaults():
977
+ # ink_method: ADAPTIVE. A single global Otsu cut discards the light linework a drawing
978
+ # carries alongside its heavy linework -- measured, it recovered 79% of a real sheet's
979
+ # strokes against 99.5% for the local threshold, lifting centerline F1 from 0.588 to 0.727.
980
+ return {"strip_colour": False, "dpi": 300.0, "ink_block_mm": 12.0,
981
+ "ink_method": "adaptive", "text_min_run": 3,
982
+ "hatch_min_strokes": 10, "hatch_min_purity": 0.78, "stamp_min_fill": 0.35,
983
+ "merge_through": True, "image": None, "out": None, "debug_prefix": None,
984
+ **_MM}
985
+
986
+
987
+ def main():
988
+ ap = argparse.ArgumentParser(description=__doc__,
989
+ formatter_class=argparse.RawDescriptionHelpFormatter)
990
+ ap.add_argument("image", nargs="?")
991
+ ap.add_argument("--out")
992
+ ap.add_argument("--selftest", action="store_true")
993
+ d = _defaults()
994
+ ap.add_argument("--strip-colour", action="store_true")
995
+ ap.add_argument("--dpi", type=float, default=d["dpi"],
996
+ help="the sheet's resolution; EVERY length below is physical and derived "
997
+ "from it, so a wrong value reads the sheet at the wrong scale")
998
+ ap.add_argument("--ink-method", choices=["adaptive", "otsu"], default=d["ink_method"],
999
+ help="adaptive is local and finds the light linework a global cut discards; "
1000
+ "otsu is the older global behaviour")
1001
+ ap.add_argument("--ink-block-mm", type=float, default=d["ink_block_mm"])
1002
+ ap.add_argument("--text-min-run", type=int, default=d["text_min_run"],
1003
+ help="glyph-sized components in a row before it counts as lettering")
1004
+ ap.add_argument("--hatch-min-strokes", type=int, default=d["hatch_min_strokes"])
1005
+ ap.add_argument("--hatch-min-purity", type=float, default=d["hatch_min_purity"],
1006
+ help="share of strokes that must share the dominant direction")
1007
+ ap.add_argument("--stamp-min-fill", type=float, default=d["stamp_min_fill"])
1008
+ ap.add_argument("--no-merge-through", dest="merge_through", action="store_false",
1009
+ default=True, help="keep every junction split as its own element")
1010
+ for _k, _v in sorted(_MM.items()):
1011
+ ap.add_argument(f"--{_k.replace('_', '-')}", type=float, default=_v,
1012
+ help=f"physical size in {'mm^2' if _k.endswith('mm2') else 'mm'}")
1013
+ ap.add_argument("--debug-prefix")
1014
+ args = ap.parse_args()
1015
+
1016
+ if args.selftest:
1017
+ sys.exit(selftest())
1018
+ if not args.image or not args.out:
1019
+ sys.exit("both an image and --out are required (or pass --selftest)")
1020
+ bgr = cv2.imread(args.image, cv2.IMREAD_COLOR)
1021
+ if bgr is None:
1022
+ sys.exit(f"cannot read {args.image}")
1023
+ doc, masks = run(bgr, args)
1024
+ if args.debug_prefix:
1025
+ names = ("ink", "glyph", "hatch", "stamp", "structural", "skeleton")
1026
+ for name, m in zip(names, masks):
1027
+ cv2.imwrite(f"{args.debug_prefix}_{name}.png", m)
1028
+ with open(args.out, "w", encoding="utf-8") as f:
1029
+ json.dump(doc, f)
1030
+ k = doc["elements_by_kind"]
1031
+ print(f"{args.out}: {len(doc['elements'])} elements "
1032
+ f"({k['line']} line, {k['arc']} arc, {k['polyline']} polyline), "
1033
+ f"{doc['vertices']} vertices, structural ink "
1034
+ f"{doc['class_ink_frac']['structural']:.0%}, {doc['timings_s']['total']}s",
1035
+ file=sys.stderr)
1036
+
1037
+
1038
+ if __name__ == "__main__":
1039
+ main()