@floless/app 0.117.1 → 0.118.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.
- package/dist/floless-server.cjs +65 -9
- package/dist/skills/floless-app-steel-takeoff/SKILL.md +63 -8
- package/dist/skills/floless-app-vectorize/SKILL.md +91 -29
- package/dist/skills/floless-app-vectorize/scripts/classify_and_trace.py +1039 -0
- package/dist/skills/floless-app-vectorize/scripts/rectify_and_trace.py +447 -0
- package/dist/skills/floless-app-vectorize/scripts/vision_to_contract.py +176 -9
- package/dist/skills/reading-structural-drawings/SKILL.md +35 -3
- package/dist/skills/steel-drawing-abbreviations/SKILL.md +1 -1
- package/dist/skills/steel-drawing-abbreviations/references/standard-us-abbreviations.md +5 -1
- package/dist/web/app.css +18 -6
- package/dist/web/app.js +244 -0
- package/dist/web/steel-3d-core.js +3 -3
- package/dist/web/steel-editor.html +20 -10
- package/dist/web/steel-filter-core.js +1 -1
- package/dist/web/vector-3d.html +33 -7
- package/dist/web/vector-editor.html +26 -2
- package/package.json +4 -2
|
@@ -0,0 +1,447 @@
|
|
|
1
|
+
#!/usr/bin/env python3
|
|
2
|
+
"""Rectify a scanned drawing and trace its linework deterministically with OpenCV.
|
|
3
|
+
|
|
4
|
+
The raster counterpart to extract_pdf.py: where a vector PDF has exact geometry to read,
|
|
5
|
+
a scan has ink to measure. This finds the ink, strips coloured pen markup and speckle,
|
|
6
|
+
corrects the scan skew, and measures straight strokes as real endpoint coordinates --
|
|
7
|
+
no model, no guessing, same output for the same input every time.
|
|
8
|
+
|
|
9
|
+
Emits {elements:[{kind:'line', pts:[[x,y],[x,y]]}]} in the image's native pixel frame,
|
|
10
|
+
which is the same frame vision_to_contract.py maps the model's 0..1000 output onto.
|
|
11
|
+
"""
|
|
12
|
+
|
|
13
|
+
import argparse
|
|
14
|
+
import hashlib
|
|
15
|
+
import json
|
|
16
|
+
import math
|
|
17
|
+
import os
|
|
18
|
+
import sys
|
|
19
|
+
import time
|
|
20
|
+
|
|
21
|
+
import cv2
|
|
22
|
+
import numpy as np
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
def build_ink(bgr, min_component_area, strip_colour=False, dpi=300.0,
|
|
26
|
+
block_mm=12.0, offset=10, method="otsu"):
|
|
27
|
+
"""Ink mask (255 = ink) with speckle removed, and optionally coloured pen markup.
|
|
28
|
+
|
|
29
|
+
`method="adaptive"` thresholds LOCALLY (a window sized in MILLIMETRES, not pixels) instead
|
|
30
|
+
of taking one global Otsu cut. It is measurably better at finding the drawing: a sheet
|
|
31
|
+
carries heavy and light linework together -- grid lines, existing work, joists drawn thin
|
|
32
|
+
and grey -- and one global cut lands between them and discards the light half. Measured on
|
|
33
|
+
a 42x30 in framing plan rendered at 150 DPI, Otsu cut at grey 156 and recovered only **79%**
|
|
34
|
+
of the sheet's real linework; the local threshold recovered **99.5%**, lifting centerline
|
|
35
|
+
F1 against that sheet's own CAD geometry from **0.579 to 0.742**.
|
|
36
|
+
|
|
37
|
+
It is NOT the default yet, deliberately. Recovering the light ink also thickens dense
|
|
38
|
+
lettering, and a text row of many short parallel strokes then reads as a fill pattern to
|
|
39
|
+
detect_hatch -- which masks it, taking any short structural stroke passing through with it
|
|
40
|
+
(measured: a 96 px line lost all 683 of its ink pixels). The real fix is a spacing-
|
|
41
|
+
regularity test in detect_hatch (hatch is evenly spaced, lettering is not); until that
|
|
42
|
+
lands, this stays opt-in via --ink-method adaptive.
|
|
43
|
+
|
|
44
|
+
Colour stripping is OFF by default and should stay that way unless you have looked at
|
|
45
|
+
the sheet. It is tempting -- red review markup is not part of the drawing -- but it is
|
|
46
|
+
not safe to automate: a pencil sketch scanned with a warm cast is strongly red-channel
|
|
47
|
+
dominant, and on this corpus a hue filter deleted 91% of one sketch's graphite while
|
|
48
|
+
still catching only ~28% of a genuine pen sheet's ink. No threshold on R-max(G,B)
|
|
49
|
+
separated the two. Losing the drawing is far worse than keeping the pen.
|
|
50
|
+
"""
|
|
51
|
+
gray = cv2.cvtColor(bgr, cv2.COLOR_BGR2GRAY)
|
|
52
|
+
blur = cv2.GaussianBlur(gray, (3, 3), 0)
|
|
53
|
+
if method == "adaptive":
|
|
54
|
+
blk = max(3, int(round(block_mm / 25.4 * float(dpi))) | 1) # OpenCV needs it odd
|
|
55
|
+
ink = cv2.adaptiveThreshold(blur, 255, cv2.ADAPTIVE_THRESH_GAUSSIAN_C,
|
|
56
|
+
cv2.THRESH_BINARY_INV, blk, offset)
|
|
57
|
+
else:
|
|
58
|
+
_, ink = cv2.threshold(blur, 0, 255, cv2.THRESH_BINARY_INV | cv2.THRESH_OTSU)
|
|
59
|
+
|
|
60
|
+
red = np.zeros_like(ink)
|
|
61
|
+
ink_black = ink
|
|
62
|
+
if strip_colour:
|
|
63
|
+
hsv = cv2.cvtColor(bgr, cv2.COLOR_BGR2HSV)
|
|
64
|
+
h, s, v = hsv[:, :, 0], hsv[:, :, 1], hsv[:, :, 2]
|
|
65
|
+
red = (((h <= 10) | (h >= 170)) & (s >= 60) & (v >= 50)).astype(np.uint8) * 255
|
|
66
|
+
red = cv2.dilate(red, np.ones((5, 5), np.uint8), iterations=1)
|
|
67
|
+
ink_black = cv2.bitwise_and(ink, cv2.bitwise_not(red))
|
|
68
|
+
|
|
69
|
+
# Drop scanner speckle: anything too small to be a drawn stroke.
|
|
70
|
+
n, labels, stats, _ = cv2.connectedComponentsWithStats(ink_black, connectivity=8)
|
|
71
|
+
keep = np.zeros(n, dtype=bool)
|
|
72
|
+
keep[1:] = stats[1:, cv2.CC_STAT_AREA] >= min_component_area
|
|
73
|
+
despeckled = np.where(keep[labels], 255, 0).astype(np.uint8)
|
|
74
|
+
return despeckled, ink, red, int(red.sum() // 255)
|
|
75
|
+
|
|
76
|
+
|
|
77
|
+
def measure_skew(ink, min_len=150.0, bin_deg=0.25):
|
|
78
|
+
"""Scan skew in degrees, folded into (-45, 45].
|
|
79
|
+
|
|
80
|
+
Estimated from LONG strokes only, and by histogram mode rather than median. Lettering
|
|
81
|
+
and revision clouds contribute many short strokes at arbitrary angles; a median over
|
|
82
|
+
all of them drags the estimate off true and tilts an already-square page. Structural
|
|
83
|
+
linework is what is long, so length is the filter that isolates it.
|
|
84
|
+
|
|
85
|
+
A 90-degree page orientation is not skew -- rotating a line 90 degrees does not change
|
|
86
|
+
the geometry -- so angles fold modulo 90.
|
|
87
|
+
"""
|
|
88
|
+
raw = cv2.HoughLinesP(ink, 1, np.pi / 1800.0, threshold=80,
|
|
89
|
+
minLineLength=min_len, maxLineGap=4)
|
|
90
|
+
if raw is None or not len(raw):
|
|
91
|
+
return 0.0, 0
|
|
92
|
+
rows = np.asarray(raw, dtype=float).reshape(-1, 4)
|
|
93
|
+
angles, weights = [], []
|
|
94
|
+
for x0, y0, x1, y1 in rows:
|
|
95
|
+
length = math.hypot(x1 - x0, y1 - y0)
|
|
96
|
+
if length < min_len:
|
|
97
|
+
continue
|
|
98
|
+
deg = math.degrees(math.atan2(y1 - y0, x1 - x0)) % 90.0
|
|
99
|
+
angles.append(deg - 90.0 if deg > 45.0 else deg)
|
|
100
|
+
weights.append(length)
|
|
101
|
+
if not angles:
|
|
102
|
+
return 0.0, 0
|
|
103
|
+
angles = np.array(angles)
|
|
104
|
+
weights = np.array(weights)
|
|
105
|
+
edges = np.arange(-45.0, 45.0 + bin_deg, bin_deg)
|
|
106
|
+
hist, _ = np.histogram(angles, bins=edges, weights=weights)
|
|
107
|
+
peak = edges[int(np.argmax(hist))] + bin_deg / 2.0
|
|
108
|
+
# Refine: length-weighted mean of the strokes inside the winning peak.
|
|
109
|
+
near = np.abs(angles - peak) <= bin_deg * 2
|
|
110
|
+
if near.sum() and weights[near].sum() > 0:
|
|
111
|
+
peak = float(np.average(angles[near], weights=weights[near]))
|
|
112
|
+
return float(peak), int(len(angles))
|
|
113
|
+
|
|
114
|
+
|
|
115
|
+
def rotation_matrix(w, h, angle):
|
|
116
|
+
"""Deskew transform into an EXPANDED canvas, so rotation cannot clip.
|
|
117
|
+
|
|
118
|
+
Rotating into the input-sized canvas silently loses the corner wedges -- at 1.9 degrees
|
|
119
|
+
on a 300 DPI sheet that is real border geometry, gone before anything downstream can
|
|
120
|
+
recover it. The canvas is grown to the rotated bounding box and the matrix carries the
|
|
121
|
+
matching translation.
|
|
122
|
+
|
|
123
|
+
Returns (M, out_w, out_h). Near-zero skew returns the identity so the common case is
|
|
124
|
+
untouched and costs nothing.
|
|
125
|
+
"""
|
|
126
|
+
if abs(angle) < 0.05:
|
|
127
|
+
return np.array([[1.0, 0.0, 0.0], [0.0, 1.0, 0.0]]), w, h
|
|
128
|
+
m = cv2.getRotationMatrix2D((w / 2.0, h / 2.0), angle, 1.0)
|
|
129
|
+
cos, sin = abs(m[0, 0]), abs(m[0, 1])
|
|
130
|
+
out_w = int(math.ceil(h * sin + w * cos))
|
|
131
|
+
out_h = int(math.ceil(h * cos + w * sin))
|
|
132
|
+
m[0, 2] += out_w / 2.0 - w / 2.0
|
|
133
|
+
m[1, 2] += out_h / 2.0 - h / 2.0
|
|
134
|
+
return m, out_w, out_h
|
|
135
|
+
|
|
136
|
+
|
|
137
|
+
def warp(img, m, size, border):
|
|
138
|
+
if m[0, 0] == 1.0 and m[0, 1] == 0.0 and m[0, 2] == 0.0 and m[1, 1] == 1.0:
|
|
139
|
+
return img
|
|
140
|
+
return cv2.warpAffine(img, m, size, flags=cv2.INTER_NEAREST,
|
|
141
|
+
borderMode=cv2.BORDER_CONSTANT, borderValue=border)
|
|
142
|
+
|
|
143
|
+
|
|
144
|
+
def apply_affine(m, pts):
|
|
145
|
+
"""Map points through a 2x3 affine. Used to bring every traced primitive back into the
|
|
146
|
+
ORIGINAL raster frame, which is the frame the model, the editor and the backdrop all use."""
|
|
147
|
+
return [(m[0, 0] * x + m[0, 1] * y + m[0, 2],
|
|
148
|
+
m[1, 0] * x + m[1, 1] * y + m[1, 2]) for x, y in pts]
|
|
149
|
+
|
|
150
|
+
|
|
151
|
+
def selftest():
|
|
152
|
+
"""Round-trip every transform this tool applies; fail loudly on sub-pixel drift."""
|
|
153
|
+
worst = 0.0
|
|
154
|
+
for (w, h) in ((2550, 3300), (10816, 4400), (777, 1001)):
|
|
155
|
+
for angle in (0.0, 0.04, -0.36, 1.934, -12.5, 44.9):
|
|
156
|
+
m, ow, oh = rotation_matrix(w, h, angle)
|
|
157
|
+
inv = cv2.invertAffineTransform(m)
|
|
158
|
+
pts = [(0, 0), (w - 1, 0), (0, h - 1), (w - 1, h - 1),
|
|
159
|
+
(w / 2.0, h / 2.0), (1.25, h - 3.75)]
|
|
160
|
+
back = apply_affine(inv, apply_affine(m, pts))
|
|
161
|
+
for (ax, ay), (bx, by) in zip(pts, back):
|
|
162
|
+
worst = max(worst, math.hypot(ax - bx, ay - by))
|
|
163
|
+
# An expanded canvas must contain every forward-mapped corner.
|
|
164
|
+
for x, y in apply_affine(m, [(0, 0), (w - 1, 0), (0, h - 1), (w - 1, h - 1)]):
|
|
165
|
+
assert -0.5 <= x <= ow + 0.5 and -0.5 <= y <= oh + 0.5, (
|
|
166
|
+
f"corner ({x:.2f},{y:.2f}) outside {ow}x{oh} canvas at {angle} deg -- would clip")
|
|
167
|
+
assert worst < 1e-6, f"round-trip error {worst:.3e} px exceeds sub-pixel tolerance"
|
|
168
|
+
print(f"selftest OK — max round-trip error {worst:.2e} px, no canvas clipping")
|
|
169
|
+
return 0
|
|
170
|
+
|
|
171
|
+
|
|
172
|
+
def merge_collinear(segs, angle_tol_deg=2.0, offset_tol=4.0, gap_tol=14.0):
|
|
173
|
+
"""Fuse fragments of one physical stroke that Hough returned as several pieces."""
|
|
174
|
+
buckets = {}
|
|
175
|
+
for x0, y0, x1, y1 in segs:
|
|
176
|
+
ang = math.degrees(math.atan2(y1 - y0, x1 - x0)) % 180.0
|
|
177
|
+
ux, uy = math.cos(math.radians(ang)), math.sin(math.radians(ang))
|
|
178
|
+
offset = -uy * x0 + ux * y0 # perpendicular distance to origin
|
|
179
|
+
key = (round(ang / angle_tol_deg), round(offset / offset_tol))
|
|
180
|
+
buckets.setdefault(key, []).append((ux, uy, x0, y0, x1, y1))
|
|
181
|
+
|
|
182
|
+
merged = []
|
|
183
|
+
for group in buckets.values():
|
|
184
|
+
ux, uy = group[0][0], group[0][1]
|
|
185
|
+
spans = []
|
|
186
|
+
for _, _, x0, y0, x1, y1 in group:
|
|
187
|
+
t0, t1 = ux * x0 + uy * y0, ux * x1 + uy * y1
|
|
188
|
+
lo, hi = (t0, t1) if t0 <= t1 else (t1, t0)
|
|
189
|
+
base = (x0, y0) if t0 <= t1 else (x1, y1)
|
|
190
|
+
spans.append((lo, hi, base, t0 if t0 <= t1 else t1))
|
|
191
|
+
spans.sort()
|
|
192
|
+
cur_lo, cur_hi, base, base_t = spans[0]
|
|
193
|
+
for lo, hi, b, bt in spans[1:]:
|
|
194
|
+
if lo <= cur_hi + gap_tol:
|
|
195
|
+
cur_hi = max(cur_hi, hi)
|
|
196
|
+
else:
|
|
197
|
+
merged.append(_span_to_seg(base, base_t, cur_lo, cur_hi, ux, uy))
|
|
198
|
+
cur_lo, cur_hi, base, base_t = lo, hi, b, bt
|
|
199
|
+
merged.append(_span_to_seg(base, base_t, cur_lo, cur_hi, ux, uy))
|
|
200
|
+
return merged
|
|
201
|
+
|
|
202
|
+
|
|
203
|
+
def _span_to_seg(base, base_t, lo, hi, ux, uy):
|
|
204
|
+
bx, by = base
|
|
205
|
+
ax, ay = bx + (lo - base_t) * ux, by + (lo - base_t) * uy
|
|
206
|
+
return (ax, ay, bx + (hi - base_t) * ux, by + (hi - base_t) * uy)
|
|
207
|
+
|
|
208
|
+
|
|
209
|
+
def trace_residual_contours(ink, segs, polys, cover_px, min_len, epsilon):
|
|
210
|
+
"""Follow the ink a straight-line detector cannot fit.
|
|
211
|
+
|
|
212
|
+
Hough answers "where are the straight strokes" and is silent on everything else. On
|
|
213
|
+
this corpus the leftovers are mostly tick marks, arrowheads, dashes, handwriting and
|
|
214
|
+
curves -- 336 of 429 residual components on the worst sheet were under 30px. Those are
|
|
215
|
+
traced by following the residual ink's own contours, so the vertices sit ON the ink
|
|
216
|
+
instead of being fitted to it, which is why this adds coverage without costing
|
|
217
|
+
precision.
|
|
218
|
+
"""
|
|
219
|
+
covered = np.zeros_like(ink)
|
|
220
|
+
for x0, y0, x1, y1 in segs:
|
|
221
|
+
cv2.line(covered, (int(round(x0)), int(round(y0))),
|
|
222
|
+
(int(round(x1)), int(round(y1))), 255, cover_px)
|
|
223
|
+
# Rings count as covered too. Marking only the straight segments left every detected
|
|
224
|
+
# circle's ink in the residual, so it was emitted a SECOND time as contour polylines --
|
|
225
|
+
# duplicate geometry that inflated both the element count and recall.
|
|
226
|
+
for poly in polys:
|
|
227
|
+
for a, b in zip(poly, poly[1:]):
|
|
228
|
+
cv2.line(covered, (int(round(a[0])), int(round(a[1]))),
|
|
229
|
+
(int(round(b[0])), int(round(b[1]))), 255, cover_px)
|
|
230
|
+
residual = cv2.bitwise_and(ink, cv2.bitwise_not(covered))
|
|
231
|
+
|
|
232
|
+
found = cv2.findContours(residual, cv2.RETR_LIST, cv2.CHAIN_APPROX_SIMPLE)
|
|
233
|
+
contours = found[0] if len(found) == 2 else found[1]
|
|
234
|
+
out = []
|
|
235
|
+
for c in contours:
|
|
236
|
+
if cv2.arcLength(c, False) < min_len:
|
|
237
|
+
continue
|
|
238
|
+
approx = cv2.approxPolyDP(c, epsilon, False)
|
|
239
|
+
pts = [(float(p[0][0]), float(p[0][1])) for p in approx]
|
|
240
|
+
if len(pts) >= 2:
|
|
241
|
+
out.append(pts)
|
|
242
|
+
return out, int(residual.sum() // 255)
|
|
243
|
+
|
|
244
|
+
|
|
245
|
+
def circles_on_ink(ink, circles, min_frac, tol=3.0, n=64):
|
|
246
|
+
"""Keep only detected circles whose ring actually lies on ink.
|
|
247
|
+
|
|
248
|
+
HoughCircles votes on gradient geometry, not on whether a circle is drawn there, so on
|
|
249
|
+
a text-heavy sheet it fires on letterforms -- O, D, 0, 8. Measured on `aisc-min` the
|
|
250
|
+
raw detections dropped precision from 0.997 to 0.802 while adding almost no recall.
|
|
251
|
+
Every candidate is therefore checked against the ink it claims to trace, which is the
|
|
252
|
+
same standard the rest of this tool is held to.
|
|
253
|
+
"""
|
|
254
|
+
if circles is None or not len(circles):
|
|
255
|
+
return [], 0
|
|
256
|
+
dt = cv2.distanceTransform(255 - ink, cv2.DIST_L2, 3)
|
|
257
|
+
h, w = ink.shape
|
|
258
|
+
kept, seen = [], 0
|
|
259
|
+
for cx, cy, r in np.asarray(circles, dtype=float).reshape(-1, 3):
|
|
260
|
+
seen += 1
|
|
261
|
+
hits = 0
|
|
262
|
+
for i in range(n):
|
|
263
|
+
a = 2 * math.pi * i / n
|
|
264
|
+
x, y = int(round(cx + r * math.cos(a))), int(round(cy + r * math.sin(a)))
|
|
265
|
+
if 0 <= x < w and 0 <= y < h and dt[y, x] <= tol:
|
|
266
|
+
hits += 1
|
|
267
|
+
if hits / n >= min_frac:
|
|
268
|
+
kept.append((cx, cy, r))
|
|
269
|
+
return kept, seen
|
|
270
|
+
|
|
271
|
+
|
|
272
|
+
def circle_to_polyline(cx, cy, r, n=36):
|
|
273
|
+
"""A detected circle as a closed vertex ring.
|
|
274
|
+
|
|
275
|
+
The contract's `arc` kind would be truer, but `d` and `pts` must never both be set
|
|
276
|
+
(renderers prefer `d`, which would shadow the vertices) and the rest of this tool
|
|
277
|
+
speaks `pts`. A 36-gon is well under a pixel off for bolt-hole radii; emitting real
|
|
278
|
+
arcs is a follow-up for when renderer and scorer agree on them.
|
|
279
|
+
"""
|
|
280
|
+
return [(cx + r * math.cos(2 * math.pi * i / n),
|
|
281
|
+
cy + r * math.sin(2 * math.pi * i / n)) for i in range(n + 1)]
|
|
282
|
+
|
|
283
|
+
|
|
284
|
+
def main():
|
|
285
|
+
ap = argparse.ArgumentParser(description=__doc__)
|
|
286
|
+
ap.add_argument("image", nargs="?")
|
|
287
|
+
ap.add_argument("--out")
|
|
288
|
+
ap.add_argument("--detector", choices=["hough", "lsd"], default="hough")
|
|
289
|
+
ap.add_argument("--min-len", type=float, default=40.0, help="shortest stroke to keep, px")
|
|
290
|
+
ap.add_argument("--min-area", type=int, default=12, help="speckle cutoff, px")
|
|
291
|
+
ap.add_argument("--dpi", type=float, default=300.0)
|
|
292
|
+
ap.add_argument("--ink-block-mm", type=float, default=12.0)
|
|
293
|
+
ap.add_argument("--ink-method", choices=["adaptive", "otsu"], default="otsu",
|
|
294
|
+
help="adaptive is local and finds far more light linework; see build_ink "
|
|
295
|
+
"for why it is not yet the default")
|
|
296
|
+
ap.add_argument("--strip-colour", action="store_true",
|
|
297
|
+
help="drop saturated (pen) ink -- unsafe on warm-cast scans, see build_ink")
|
|
298
|
+
ap.add_argument("--no-residual", dest="residual", action="store_false",
|
|
299
|
+
help="skip the contour pass over ink Hough could not fit")
|
|
300
|
+
ap.add_argument("--cover-px", type=int, default=7,
|
|
301
|
+
help="stroke width treated as explained by a traced segment")
|
|
302
|
+
ap.add_argument("--residual-min-len", type=float, default=25.0,
|
|
303
|
+
help="shortest residual contour to keep, px")
|
|
304
|
+
ap.add_argument("--circle-min-ink", type=float, default=0.8,
|
|
305
|
+
help="fraction of a detected circle's ring that must lie on ink to keep it")
|
|
306
|
+
ap.add_argument("--residual-eps", type=float, default=1.5,
|
|
307
|
+
help="approxPolyDP tolerance, px -- larger simplifies more, hugs ink less")
|
|
308
|
+
ap.add_argument("--debug-prefix", help="write intermediate masks for inspection")
|
|
309
|
+
ap.add_argument("--selftest", action="store_true",
|
|
310
|
+
help="round-trip the transforms and exit; no image needed")
|
|
311
|
+
args = ap.parse_args()
|
|
312
|
+
|
|
313
|
+
if args.selftest:
|
|
314
|
+
sys.exit(selftest())
|
|
315
|
+
|
|
316
|
+
if not args.image or not args.out:
|
|
317
|
+
sys.exit("both an image and --out are required (or pass --selftest)")
|
|
318
|
+
t0 = time.perf_counter()
|
|
319
|
+
bgr = cv2.imread(args.image, cv2.IMREAD_COLOR)
|
|
320
|
+
if bgr is None:
|
|
321
|
+
sys.exit(f"cannot read {args.image}")
|
|
322
|
+
h, w = bgr.shape[:2]
|
|
323
|
+
|
|
324
|
+
ink, raw_ink, red, red_px = build_ink(bgr, args.min_area, args.strip_colour,
|
|
325
|
+
dpi=args.dpi, block_mm=args.ink_block_mm,
|
|
326
|
+
method=args.ink_method)
|
|
327
|
+
t_ink = time.perf_counter()
|
|
328
|
+
|
|
329
|
+
angle, n_ang = measure_skew(ink)
|
|
330
|
+
M, ow, oh = rotation_matrix(w, h, angle)
|
|
331
|
+
Minv = cv2.invertAffineTransform(M)
|
|
332
|
+
ink_d = warp(ink, M, (ow, oh), 0)
|
|
333
|
+
gray_d = warp(cv2.cvtColor(bgr, cv2.COLOR_BGR2GRAY), M, (ow, oh), 255)
|
|
334
|
+
t_rect = time.perf_counter()
|
|
335
|
+
|
|
336
|
+
if args.detector == "hough":
|
|
337
|
+
raw = cv2.HoughLinesP(ink_d, 1, np.pi / 1800.0, threshold=60,
|
|
338
|
+
minLineLength=args.min_len, maxLineGap=6)
|
|
339
|
+
else:
|
|
340
|
+
lsd = cv2.createLineSegmentDetector()
|
|
341
|
+
raw = lsd.detect(cv2.bitwise_not(ink_d))[0]
|
|
342
|
+
# OpenCV 4 returns (N,1,4); OpenCV 5 returns (N,4). Accept either.
|
|
343
|
+
segs = []
|
|
344
|
+
if raw is not None and len(raw):
|
|
345
|
+
rows = np.asarray(raw, dtype=float).reshape(-1, 4)
|
|
346
|
+
for x0, y0, x1, y1 in rows:
|
|
347
|
+
if math.hypot(x1 - x0, y1 - y0) >= args.min_len:
|
|
348
|
+
segs.append((float(x0), float(y0), float(x1), float(y1)))
|
|
349
|
+
n_raw = len(segs)
|
|
350
|
+
segs = merge_collinear(segs)
|
|
351
|
+
t_lines = time.perf_counter()
|
|
352
|
+
|
|
353
|
+
circles = cv2.HoughCircles(gray_d, cv2.HOUGH_GRADIENT, dp=1, minDist=30,
|
|
354
|
+
param1=100, param2=40, minRadius=8, maxRadius=45)
|
|
355
|
+
kept_circles, n_candidates = circles_on_ink(ink_d, circles, args.circle_min_ink)
|
|
356
|
+
n_circles = len(kept_circles)
|
|
357
|
+
rings = [circle_to_polyline(cx, cy, r) for cx, cy, r in kept_circles]
|
|
358
|
+
t_circ = time.perf_counter()
|
|
359
|
+
|
|
360
|
+
curves, residual_px = ([], 0)
|
|
361
|
+
if args.residual:
|
|
362
|
+
curves, residual_px = trace_residual_contours(
|
|
363
|
+
ink_d, segs, rings, args.cover_px, args.residual_min_len, args.residual_eps)
|
|
364
|
+
|
|
365
|
+
# Detection ran in the deskewed frame; everything is published in the ORIGINAL raster
|
|
366
|
+
# frame. Scoring the model's original-frame coordinates against deskewed ink was the
|
|
367
|
+
# defect this stage exists to fix, and the editor's raster backdrop is original-frame too.
|
|
368
|
+
segs = [tuple(apply_affine(Minv, [(s[0], s[1]), (s[2], s[3])])[i][j]
|
|
369
|
+
for i in (0, 1) for j in (0, 1)) for s in segs]
|
|
370
|
+
curves = [apply_affine(Minv, c) for c in curves]
|
|
371
|
+
rings = [apply_affine(Minv, r) for r in rings]
|
|
372
|
+
t_end = time.perf_counter()
|
|
373
|
+
|
|
374
|
+
if args.debug_prefix:
|
|
375
|
+
cv2.imwrite(f"{args.debug_prefix}_ink.png", ink)
|
|
376
|
+
cv2.imwrite(f"{args.debug_prefix}_red.png", red)
|
|
377
|
+
overlay = cv2.cvtColor(255 - ink, cv2.COLOR_GRAY2BGR)
|
|
378
|
+
for x0, y0, x1, y1 in segs:
|
|
379
|
+
cv2.line(overlay, (int(x0), int(y0)), (int(x1), int(y1)), (0, 0, 255), 2)
|
|
380
|
+
# green = what the residual/ring passes added on top of Hough
|
|
381
|
+
for poly in curves + rings:
|
|
382
|
+
for a, b in zip(poly, poly[1:]):
|
|
383
|
+
cv2.line(overlay, (int(a[0]), int(a[1])), (int(b[0]), int(b[1])), (0, 160, 0), 2)
|
|
384
|
+
cv2.imwrite(f"{args.debug_prefix}_traced.png", overlay)
|
|
385
|
+
|
|
386
|
+
# Straight strokes, then detected rings, then whatever ink neither explained.
|
|
387
|
+
elements = []
|
|
388
|
+
for s in segs:
|
|
389
|
+
elements.append({"kind": "line", "pts": [(s[0], s[1]), (s[2], s[3])]})
|
|
390
|
+
for ring in rings:
|
|
391
|
+
elements.append({"kind": "polyline", "pts": ring})
|
|
392
|
+
for c in curves:
|
|
393
|
+
elements.append({"kind": "polyline", "pts": c})
|
|
394
|
+
for i, e in enumerate(elements):
|
|
395
|
+
e["id"] = f"e{i + 1}"
|
|
396
|
+
e["pts"] = [[round(p[0], 2), round(p[1], 2)] for p in e["pts"]]
|
|
397
|
+
|
|
398
|
+
out = {
|
|
399
|
+
"method": f"opencv/{args.detector}",
|
|
400
|
+
"image": {"w": w, "h": h},
|
|
401
|
+
"output_frame": "original",
|
|
402
|
+
"transform_version": "0a",
|
|
403
|
+
"script_sha256": hashlib.sha256(
|
|
404
|
+
open(os.path.abspath(__file__), "rb").read()).hexdigest()[:16],
|
|
405
|
+
"opencv": cv2.__version__,
|
|
406
|
+
"deskew_canvas": [int(ow), int(oh)],
|
|
407
|
+
"params": {"detector": args.detector, "min_len": args.min_len,
|
|
408
|
+
"min_area": args.min_area, "cover_px": args.cover_px,
|
|
409
|
+
"residual_min_len": args.residual_min_len,
|
|
410
|
+
"residual_eps": args.residual_eps,
|
|
411
|
+
"circle_min_ink": args.circle_min_ink,
|
|
412
|
+
"residual": bool(args.residual),
|
|
413
|
+
"strip_colour": bool(args.strip_colour)},
|
|
414
|
+
"skew_deg": round(angle, 3),
|
|
415
|
+
"skew_samples": n_ang,
|
|
416
|
+
"colour_stripped": bool(args.strip_colour),
|
|
417
|
+
"red_markup_px": red_px,
|
|
418
|
+
"ink_px": int(ink.sum() // 255),
|
|
419
|
+
"raw_ink_px": int(raw_ink.sum() // 255),
|
|
420
|
+
"segments_raw": n_raw,
|
|
421
|
+
"circles": n_circles,
|
|
422
|
+
"circle_candidates": n_candidates,
|
|
423
|
+
"residual_curves": len(curves),
|
|
424
|
+
"residual_px": residual_px,
|
|
425
|
+
"timings_s": {
|
|
426
|
+
"ink": round(t_ink - t0, 3),
|
|
427
|
+
"rectify": round(t_rect - t_ink, 3),
|
|
428
|
+
"lines": round(t_lines - t_rect, 3),
|
|
429
|
+
"circles": round(t_circ - t_lines, 3),
|
|
430
|
+
"residual": round(t_end - t_circ, 3),
|
|
431
|
+
"total": round(t_end - t0, 3),
|
|
432
|
+
},
|
|
433
|
+
"elements": elements,
|
|
434
|
+
}
|
|
435
|
+
# ORIGINAL-frame ink: output is published in that frame, and so are the model's
|
|
436
|
+
# coordinates. Writing the deskewed mask here is precisely what made the earlier
|
|
437
|
+
# comparison unfair to vision.extract.
|
|
438
|
+
cv2.imwrite(args.out + ".ink.png", ink)
|
|
439
|
+
with open(args.out, "w", encoding="utf-8") as f:
|
|
440
|
+
json.dump(out, f)
|
|
441
|
+
print(f"{args.out}: {len(segs)} segments (from {n_raw} raw), {n_circles} circles, "
|
|
442
|
+
f"{len(curves)} residual curves, skew {angle:+.2f}deg, "
|
|
443
|
+
f"{out['timings_s']['total']}s", file=sys.stderr)
|
|
444
|
+
|
|
445
|
+
|
|
446
|
+
if __name__ == "__main__":
|
|
447
|
+
main()
|