@babylonjs-toolkit/agent 1.2.16 → 1.2.21
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/README.md +3 -2
- package/package.json +1 -1
- package/skills/bt-blender/SKILL.md +448 -0
- package/skills/bt-blender/THIRD_PARTY_NOTICES.md +141 -0
- package/skills/bt-blender/references/art-style-and-genre.md +173 -0
- package/skills/bt-blender/references/characters-and-creatures.md +644 -0
- package/skills/bt-blender/references/environments.md +478 -0
- package/skills/bt-blender/references/game-engine-export.md +284 -0
- package/skills/bt-blender/references/geometry-nodes.md +447 -0
- package/skills/bt-blender/references/hard-surface.md +724 -0
- package/skills/bt-blender/references/procedural-generation.md +358 -0
- package/skills/bt-blender/references/rigging-and-animation.md +1080 -0
- package/skills/bt-blender/references/sculpting-and-retopology.md +544 -0
- package/skills/bt-blender/references/uv-and-pbr-materials.md +381 -0
- package/skills/bt-blender/references/vehicles.md +637 -0
- package/skills/bt-blender/scripts/blender/__pycache__/construction_kit.cpython-313.pyc +0 -0
- package/skills/bt-blender/scripts/blender/__pycache__/geometry_nodes_builders.cpython-313.pyc +0 -0
- package/skills/bt-blender/scripts/blender/__pycache__/image_measure.cpython-313.pyc +0 -0
- package/skills/bt-blender/scripts/blender/__pycache__/reference_traces.cpython-313.pyc +0 -0
- package/skills/bt-blender/scripts/blender/assembly_check.py +420 -0
- package/skills/bt-blender/scripts/blender/blueprint.py +293 -0
- package/skills/bt-blender/scripts/blender/character_blockout.py +462 -0
- package/skills/bt-blender/scripts/blender/construction_kit.py +1770 -0
- package/skills/bt-blender/scripts/blender/coverage_check.py +221 -0
- package/skills/bt-blender/scripts/blender/environment_kit.py +525 -0
- package/skills/bt-blender/scripts/blender/evidence_sheet.py +243 -0
- package/skills/bt-blender/scripts/blender/export_asset.py +623 -0
- package/skills/bt-blender/scripts/blender/geometry_nodes_builders.py +575 -0
- package/skills/bt-blender/scripts/blender/hard_surface_panels.py +374 -0
- package/skills/bt-blender/scripts/blender/hard_surface_trims.py +200 -0
- package/skills/bt-blender/scripts/blender/image_measure.py +917 -0
- package/skills/bt-blender/scripts/blender/materials_pbr.py +439 -0
- package/skills/bt-blender/scripts/blender/measure_stations.py +496 -0
- package/skills/bt-blender/scripts/blender/ortho_views.py +309 -0
- package/skills/bt-blender/scripts/blender/overlay_sheet.py +238 -0
- package/skills/bt-blender/scripts/blender/procedural_game_ready.py +258 -0
- package/skills/bt-blender/scripts/blender/procedural_generators.py +842 -0
- package/skills/bt-blender/scripts/blender/qa_check.py +729 -0
- package/skills/bt-blender/scripts/blender/reference_traces.py +344 -0
- package/skills/bt-blender/scripts/blender/retopology_tools.py +781 -0
- package/skills/bt-blender/scripts/blender/review_render.py +358 -0
- package/skills/bt-blender/scripts/blender/rigging_tools.py +1170 -0
- package/skills/bt-blender/scripts/blender/style_palette.py +190 -0
- package/skills/bt-blender/scripts/blender/tool_common.py +289 -0
- package/skills/bt-blender/scripts/blender/trace.py +283 -0
- package/skills/bt-blender/scripts/blender/uv_layout.py +555 -0
- package/skills/bt-blender/scripts/blender/vehicle_parts.py +370 -0
- package/skills/bt-blender/scripts/blender/view_consistency.py +133 -0
- package/skills/bt-blender/scripts/blender/world_gate.py +231 -0
- package/skills/bt-blender/scripts/bt-blender.mjs +333 -0
- package/skills/bt-blender/scripts/validate_gltf.mjs +204 -0
- package/skills/bt-execute/SKILL.md +2 -1
- package/skills/bt-gauntlet/SKILL.md +30 -20
- package/skills/bt-gauntlet/references/critic-rubrics.md +106 -7
- package/skills/bt-gauntlet/references/loop-templates.md +23 -3
- package/skills/bt-gauntlet/references/spec-composition.md +20 -1
- package/skills/bt-gauntlet/references/target-images.md +27 -0
- package/skills/bt-gauntlet/references/unity-pipeline.md +41 -4
- package/skills/bt-gauntlet/references/workspace.md +90 -6
- package/skills/bt-unwrap/scripts/blender/__pycache__/bt_unwrap.cpython-313.pyc +0 -0
- package/skills/bt-unwrap/scripts/blender/__pycache__/image_utils.cpython-313.pyc +0 -0
- package/skills/bt-unwrap/scripts/blender/__pycache__/mesh_tools.cpython-313.pyc +0 -0
- package/skills/bt-unwrap/scripts/blender/__pycache__/model_io.cpython-313.pyc +0 -0
- package/skills/bt-unwrap/scripts/blender/__pycache__/previews.cpython-313.pyc +0 -0
- package/skills/bt-unwrap/scripts/blender/__pycache__/rasterizer.cpython-313.pyc +0 -0
- package/skills/bt-unwrap/scripts/blender/__pycache__/reference_views.cpython-313.pyc +0 -0
- package/skills/bt-unwrap/scripts/blender/__pycache__/reference_warp.cpython-313.pyc +0 -0
- package/skills/bt-unwrap/scripts/blender/__pycache__/texture_bake.cpython-313.pyc +0 -0
- package/skills/bt-unwrap/scripts/blender/__pycache__/texture_compose.cpython-313.pyc +0 -0
- package/skills/bt-unwrap/scripts/blender/__pycache__/uv_layout.cpython-313.pyc +0 -0
|
@@ -0,0 +1,917 @@
|
|
|
1
|
+
"""
|
|
2
|
+
Image measurement for bt-blender: subject masks, silhouette extents, line and circle fits, luminance ramps,
|
|
3
|
+
station grading and simple drawing for evidence images.
|
|
4
|
+
|
|
5
|
+
Pure numpy: no bpy import, so it is cheap to import from any tool. Every image array here is in image order:
|
|
6
|
+
row 0 is the TOP of the image and column 0 its left edge, the way image editors report pixel positions.
|
|
7
|
+
A continuous pixel coordinate (column, row) has pixel (i, j) covering [i, i + 1) x [j, j + 1), so pixel
|
|
8
|
+
centres sit at +0.5.
|
|
9
|
+
"""
|
|
10
|
+
import numpy as np
|
|
11
|
+
|
|
12
|
+
# Station grading bands (percent of the reference value) and the absolute allowance, in metres.
|
|
13
|
+
MATCH_PERCENT = 3.0
|
|
14
|
+
CLOSE_PERCENT = 6.0
|
|
15
|
+
MATCH_ABSOLUTE_METRES = 0.01
|
|
16
|
+
|
|
17
|
+
# Corner radii are graded against their own tolerance: a radius fit is noisier than a width.
|
|
18
|
+
RADIUS_TOLERANCE_PERCENT = 15.0
|
|
19
|
+
|
|
20
|
+
# The border flood fill runs on a grid whose long side is at most this many cells.
|
|
21
|
+
FLOOD_GRID_LONG_SIDE = 512
|
|
22
|
+
|
|
23
|
+
# Share of the image's short side sampled along each border to find the background colour.
|
|
24
|
+
BORDER_SAMPLE_FRACTION = 0.02
|
|
25
|
+
|
|
26
|
+
# Rec. 709 luminance weights.
|
|
27
|
+
LUMINANCE_WEIGHTS = np.array([0.2126, 0.7152, 0.0722], dtype=np.float32)
|
|
28
|
+
|
|
29
|
+
# A corner fit needs at least this many arc points to mean anything.
|
|
30
|
+
MINIMUM_ARC_POINTS = 5
|
|
31
|
+
|
|
32
|
+
# Gauss-Newton refinement steps for the geometric circle fit.
|
|
33
|
+
CIRCLE_REFINE_STEPS = 25
|
|
34
|
+
|
|
35
|
+
# Profile points closer than this to a fitted flat (in pixels) belong to the flat, not to the corner arc.
|
|
36
|
+
FLAT_TOLERANCE_PIXELS = 1.0
|
|
37
|
+
|
|
38
|
+
# Share of a corner region, measured from its inner edges, used to fit the two flats beside the arc.
|
|
39
|
+
FLAT_SAMPLE_FRACTION = 0.3
|
|
40
|
+
|
|
41
|
+
# A luminance ramp ends where the deviation from the plateau falls below this share of its largest value.
|
|
42
|
+
RAMP_END_FRACTION = 0.1
|
|
43
|
+
|
|
44
|
+
# Rows whose largest luminance deviation is below this carry no usable shading.
|
|
45
|
+
MINIMUM_RAMP_CONTRAST = 0.04
|
|
46
|
+
|
|
47
|
+
# Central share of a span used as the luminance plateau.
|
|
48
|
+
PLATEAU_FRACTION = 0.3
|
|
49
|
+
|
|
50
|
+
# How far (0..1 per channel) a pixel may differ from the border colour and still count as background.
|
|
51
|
+
DEFAULT_BACKGROUND_TOLERANCE = 0.08
|
|
52
|
+
|
|
53
|
+
# A luminance ramp needs at least this many subject columns in its row.
|
|
54
|
+
MINIMUM_RAMP_COLUMNS = 8
|
|
55
|
+
|
|
56
|
+
# Drawn circles: at least this many segments, and this many per pixel of radius.
|
|
57
|
+
CIRCLE_MINIMUM_SEGMENTS = 16
|
|
58
|
+
CIRCLE_SEGMENTS_PER_PIXEL = 8
|
|
59
|
+
|
|
60
|
+
# Numeric guards: smallest length or size treated as non-zero, the circle refinement's convergence step,
|
|
61
|
+
# the smallest luminance change treated as a ramp, and a denominator offset for horizontal edges.
|
|
62
|
+
NUMERIC_FLOOR = 1e-12
|
|
63
|
+
CIRCLE_CONVERGENCE = 1e-9
|
|
64
|
+
MINIMUM_RAMP_TOTAL = 1e-6
|
|
65
|
+
DIVISION_GUARD = 1e-30
|
|
66
|
+
|
|
67
|
+
|
|
68
|
+
def linear_to_srgb(values: np.ndarray) -> np.ndarray:
|
|
69
|
+
"""
|
|
70
|
+
Applies the sRGB transfer curve: linear light to display-encoded values.
|
|
71
|
+
|
|
72
|
+
:param values: Linear values in 0..1 (any shape).
|
|
73
|
+
:returns: sRGB-encoded values in 0..1, same shape, float32.
|
|
74
|
+
"""
|
|
75
|
+
clipped = np.clip(values, 0.0, 1.0).astype(np.float32)
|
|
76
|
+
return np.where(clipped <= 0.0031308, clipped * 12.92, 1.055 * np.power(clipped, 1.0 / 2.4) - 0.055)
|
|
77
|
+
|
|
78
|
+
|
|
79
|
+
def luminance(rgba: np.ndarray) -> np.ndarray:
|
|
80
|
+
"""
|
|
81
|
+
Converts an RGB or RGBA image to luminance.
|
|
82
|
+
|
|
83
|
+
:param rgba: float array (height, width, 3 or 4).
|
|
84
|
+
:returns: float32 array (height, width).
|
|
85
|
+
"""
|
|
86
|
+
return (rgba[:, :, :3] * LUMINANCE_WEIGHTS).sum(axis=2).astype(np.float32)
|
|
87
|
+
|
|
88
|
+
|
|
89
|
+
def erode(mask: np.ndarray, iterations: int = 1) -> np.ndarray:
|
|
90
|
+
"""
|
|
91
|
+
Shrinks a boolean mask by one pixel per iteration (4-neighbourhood).
|
|
92
|
+
|
|
93
|
+
:param mask: Boolean (height, width).
|
|
94
|
+
:param iterations: How many pixels to remove from every edge.
|
|
95
|
+
:returns: The eroded mask.
|
|
96
|
+
"""
|
|
97
|
+
result = mask.copy()
|
|
98
|
+
for _ in range(iterations):
|
|
99
|
+
shrunk = result.copy()
|
|
100
|
+
shrunk[1:, :] &= result[:-1, :]
|
|
101
|
+
shrunk[:-1, :] &= result[1:, :]
|
|
102
|
+
shrunk[:, 1:] &= result[:, :-1]
|
|
103
|
+
shrunk[:, :-1] &= result[:, 1:]
|
|
104
|
+
result = shrunk
|
|
105
|
+
return result
|
|
106
|
+
|
|
107
|
+
|
|
108
|
+
def dilate(mask: np.ndarray, iterations: int = 1) -> np.ndarray:
|
|
109
|
+
"""
|
|
110
|
+
Grows a boolean mask by one pixel per iteration (4-neighbourhood).
|
|
111
|
+
|
|
112
|
+
:param mask: Boolean (height, width).
|
|
113
|
+
:param iterations: How many pixels to add to every edge.
|
|
114
|
+
:returns: The dilated mask.
|
|
115
|
+
"""
|
|
116
|
+
result = mask.copy()
|
|
117
|
+
for _ in range(iterations):
|
|
118
|
+
grown = result.copy()
|
|
119
|
+
grown[1:, :] |= result[:-1, :]
|
|
120
|
+
grown[:-1, :] |= result[1:, :]
|
|
121
|
+
grown[:, 1:] |= result[:, :-1]
|
|
122
|
+
grown[:, :-1] |= result[:, 1:]
|
|
123
|
+
result = grown
|
|
124
|
+
return result
|
|
125
|
+
|
|
126
|
+
|
|
127
|
+
def _block_reduce(mask: np.ndarray, factor: int) -> np.ndarray:
|
|
128
|
+
"""Downsamples a boolean mask by an integer factor; a cell is set when most of its pixels are."""
|
|
129
|
+
height, width = mask.shape
|
|
130
|
+
padded_height = -(-height // factor) * factor
|
|
131
|
+
padded_width = -(-width // factor) * factor
|
|
132
|
+
padded = np.zeros((padded_height, padded_width), dtype=np.float32)
|
|
133
|
+
padded[:height, :width] = mask
|
|
134
|
+
blocks = padded.reshape(padded_height // factor, factor, padded_width // factor, factor)
|
|
135
|
+
return blocks.mean(axis=(1, 3)) > 0.5
|
|
136
|
+
|
|
137
|
+
|
|
138
|
+
def connected_to_border(candidates: np.ndarray) -> np.ndarray:
|
|
139
|
+
"""
|
|
140
|
+
Flood-fills from the image border through candidate pixels. Runs on a reduced grid for speed, then
|
|
141
|
+
widens the result by one reduced cell so it reaches every full-resolution edge pixel.
|
|
142
|
+
|
|
143
|
+
:param candidates: Boolean (height, width): pixels the fill may pass through.
|
|
144
|
+
:returns: Boolean (height, width): the candidates reachable from the border.
|
|
145
|
+
"""
|
|
146
|
+
height, width = candidates.shape
|
|
147
|
+
factor = max(1, int(np.ceil(max(height, width) / FLOOD_GRID_LONG_SIDE)))
|
|
148
|
+
passable = _block_reduce(candidates, factor)
|
|
149
|
+
reached = np.zeros_like(passable)
|
|
150
|
+
reached[0, :], reached[-1, :] = passable[0, :], passable[-1, :]
|
|
151
|
+
reached[:, 0] |= passable[:, 0]
|
|
152
|
+
reached[:, -1] |= passable[:, -1]
|
|
153
|
+
while True:
|
|
154
|
+
grown = dilate(reached) & passable
|
|
155
|
+
if np.array_equal(grown, reached):
|
|
156
|
+
break
|
|
157
|
+
reached = grown
|
|
158
|
+
reached = dilate(reached)
|
|
159
|
+
full = np.repeat(np.repeat(reached, factor, axis=0), factor, axis=1)[:height, :width]
|
|
160
|
+
return candidates & full
|
|
161
|
+
|
|
162
|
+
|
|
163
|
+
def subject_mask(rgba: np.ndarray, background_tolerance: float = DEFAULT_BACKGROUND_TOLERANCE,
|
|
164
|
+
remove_specks: bool = True) -> np.ndarray:
|
|
165
|
+
"""
|
|
166
|
+
Separates the subject from its background. A transparent image uses its alpha. Otherwise the background
|
|
167
|
+
colour is the median of the image border, and only background-coloured pixels connected to the border
|
|
168
|
+
count as background, so light details enclosed by the subject (logos, highlights) stay subject.
|
|
169
|
+
|
|
170
|
+
:param rgba: float array (height, width, 4), values 0..1.
|
|
171
|
+
:param background_tolerance: Largest per-channel difference (0..1) from the background colour that
|
|
172
|
+
still counts as background.
|
|
173
|
+
:param remove_specks: Open the mask (erode, then dilate) to drop single-pixel noise. The opening also
|
|
174
|
+
nicks every convex corner by one pixel, so a tracer that keeps only the largest region turns it off.
|
|
175
|
+
:returns: Boolean (height, width), True on the subject.
|
|
176
|
+
"""
|
|
177
|
+
alpha = rgba[:, :, 3]
|
|
178
|
+
if alpha.min() < 0.5:
|
|
179
|
+
return alpha > 0.5
|
|
180
|
+
mask = ~connected_to_border(background_like(rgba, background_tolerance))
|
|
181
|
+
# An opening removes single-pixel specks of noise without moving the outline.
|
|
182
|
+
return dilate(erode(mask)) if remove_specks else mask
|
|
183
|
+
|
|
184
|
+
|
|
185
|
+
def background_like(rgba: np.ndarray, background_tolerance: float = DEFAULT_BACKGROUND_TOLERANCE) -> np.ndarray:
|
|
186
|
+
"""
|
|
187
|
+
Pixels that look like the background, wherever they are: transparent pixels of an image with alpha, or
|
|
188
|
+
else pixels within the tolerance of the border colour (the median of the image border). Inside a subject
|
|
189
|
+
these are openings, or light details the same colour as the background.
|
|
190
|
+
|
|
191
|
+
:param rgba: float array (height, width, 4), values 0..1.
|
|
192
|
+
:param background_tolerance: Largest per-channel difference (0..1) from the border colour.
|
|
193
|
+
:returns: Boolean (height, width).
|
|
194
|
+
"""
|
|
195
|
+
alpha = rgba[:, :, 3]
|
|
196
|
+
if alpha.min() < 0.5:
|
|
197
|
+
return alpha <= 0.5
|
|
198
|
+
height, width = alpha.shape
|
|
199
|
+
border = max(2, int(min(width, height) * BORDER_SAMPLE_FRACTION))
|
|
200
|
+
strips = np.concatenate((rgba[:border, :, :3].reshape(-1, 3), rgba[-border:, :, :3].reshape(-1, 3),
|
|
201
|
+
rgba[:, :border, :3].reshape(-1, 3), rgba[:, -border:, :3].reshape(-1, 3)))
|
|
202
|
+
background = np.median(strips, axis=0)
|
|
203
|
+
return np.abs(rgba[:, :, :3] - background).max(axis=2) <= background_tolerance
|
|
204
|
+
|
|
205
|
+
|
|
206
|
+
def apply_crop(mask: np.ndarray, crop) -> np.ndarray:
|
|
207
|
+
"""
|
|
208
|
+
Clears everything outside a crop box, so labels, rulers and floor lines outside it are ignored.
|
|
209
|
+
|
|
210
|
+
:param mask: Boolean (height, width).
|
|
211
|
+
:param crop: [left, top, right, bottom] in pixels (right / bottom exclusive), or None for no crop.
|
|
212
|
+
:returns: A cropped copy of the mask, same shape.
|
|
213
|
+
"""
|
|
214
|
+
if crop is None:
|
|
215
|
+
return mask.copy()
|
|
216
|
+
left, top, right, bottom = (int(round(value)) for value in crop)
|
|
217
|
+
cropped = np.zeros_like(mask)
|
|
218
|
+
cropped[max(0, top):bottom, max(0, left):right] = mask[max(0, top):bottom, max(0, left):right]
|
|
219
|
+
return cropped
|
|
220
|
+
|
|
221
|
+
|
|
222
|
+
def subject_bounds(mask: np.ndarray):
|
|
223
|
+
"""
|
|
224
|
+
Bounding box of the subject in continuous pixel coordinates.
|
|
225
|
+
|
|
226
|
+
:param mask: Boolean (height, width).
|
|
227
|
+
:returns: (left, top, right, bottom) with right / bottom exclusive, or None for an empty mask.
|
|
228
|
+
"""
|
|
229
|
+
columns = np.flatnonzero(mask.any(axis=0))
|
|
230
|
+
rows = np.flatnonzero(mask.any(axis=1))
|
|
231
|
+
if columns.size == 0:
|
|
232
|
+
return None
|
|
233
|
+
return float(columns[0]), float(rows[0]), float(columns[-1] + 1), float(rows[-1] + 1)
|
|
234
|
+
|
|
235
|
+
|
|
236
|
+
def extent_along_row(mask: np.ndarray, row: float):
|
|
237
|
+
"""
|
|
238
|
+
The subject's horizontal extent on one image row.
|
|
239
|
+
|
|
240
|
+
:param mask: Boolean (height, width).
|
|
241
|
+
:param row: Continuous row coordinate; the pixel row containing it is read.
|
|
242
|
+
:returns: (first column, end column) continuous (end exclusive), or None when the row is empty or
|
|
243
|
+
outside the image.
|
|
244
|
+
"""
|
|
245
|
+
index = int(np.floor(row))
|
|
246
|
+
if index < 0 or index >= mask.shape[0]:
|
|
247
|
+
return None
|
|
248
|
+
columns = np.flatnonzero(mask[index])
|
|
249
|
+
if columns.size == 0:
|
|
250
|
+
return None
|
|
251
|
+
return float(columns[0]), float(columns[-1] + 1)
|
|
252
|
+
|
|
253
|
+
|
|
254
|
+
def extent_along_column(mask: np.ndarray, column: float):
|
|
255
|
+
"""
|
|
256
|
+
The subject's vertical extent on one image column.
|
|
257
|
+
|
|
258
|
+
:param mask: Boolean (height, width).
|
|
259
|
+
:param column: Continuous column coordinate; the pixel column containing it is read.
|
|
260
|
+
:returns: (first row, end row) continuous (end exclusive), or None when the column is empty or outside.
|
|
261
|
+
"""
|
|
262
|
+
return extent_along_row(mask.T, column)
|
|
263
|
+
|
|
264
|
+
|
|
265
|
+
def grade_delta(reference_metres: float, model_metres: float) -> dict:
|
|
266
|
+
"""
|
|
267
|
+
Grades a model measurement against the reference: MATCH within 3 % or 1 cm, CLOSE within 6 %,
|
|
268
|
+
WRONG beyond.
|
|
269
|
+
|
|
270
|
+
:param reference_metres: The reference value, in metres.
|
|
271
|
+
:param model_metres: The model value, in metres.
|
|
272
|
+
:returns: {"delta_m", "delta_percent", "grade"}; the delta is model minus reference.
|
|
273
|
+
"""
|
|
274
|
+
delta = model_metres - reference_metres
|
|
275
|
+
percent = 100.0 * delta / reference_metres if abs(reference_metres) > NUMERIC_FLOOR else float("inf")
|
|
276
|
+
if abs(percent) <= MATCH_PERCENT or abs(delta) <= MATCH_ABSOLUTE_METRES:
|
|
277
|
+
grade = "MATCH"
|
|
278
|
+
elif abs(percent) <= CLOSE_PERCENT:
|
|
279
|
+
grade = "CLOSE"
|
|
280
|
+
else:
|
|
281
|
+
grade = "WRONG"
|
|
282
|
+
return {"delta_m": round(delta, 5), "delta_percent": round(percent, 2), "grade": grade}
|
|
283
|
+
|
|
284
|
+
|
|
285
|
+
def grade_radius(reference_metres: float, model_metres: float) -> dict:
|
|
286
|
+
"""
|
|
287
|
+
Grades a corner radius: MATCH within 15 % of the reference radius, WRONG beyond.
|
|
288
|
+
|
|
289
|
+
:param reference_metres: Reference radius in metres.
|
|
290
|
+
:param model_metres: Model radius in metres.
|
|
291
|
+
:returns: {"delta_m", "delta_percent", "grade"}.
|
|
292
|
+
"""
|
|
293
|
+
delta = model_metres - reference_metres
|
|
294
|
+
percent = 100.0 * delta / reference_metres if reference_metres > NUMERIC_FLOOR else float("inf")
|
|
295
|
+
grade = "MATCH" if abs(percent) <= RADIUS_TOLERANCE_PERCENT else "WRONG"
|
|
296
|
+
return {"delta_m": round(delta, 5), "delta_percent": round(percent, 2), "grade": grade}
|
|
297
|
+
|
|
298
|
+
|
|
299
|
+
def fit_line(points: np.ndarray):
|
|
300
|
+
"""
|
|
301
|
+
Total-least-squares line through 2D points.
|
|
302
|
+
|
|
303
|
+
:param points: (N, 2) array, N >= 2.
|
|
304
|
+
:returns: (point on the line, unit direction), both (2,) arrays.
|
|
305
|
+
"""
|
|
306
|
+
centroid = points.mean(axis=0)
|
|
307
|
+
_, _, axes = np.linalg.svd(points - centroid)
|
|
308
|
+
return centroid, axes[0]
|
|
309
|
+
|
|
310
|
+
|
|
311
|
+
def distance_to_line(points: np.ndarray, line_point: np.ndarray, line_direction: np.ndarray) -> np.ndarray:
|
|
312
|
+
"""
|
|
313
|
+
Perpendicular distance of 2D points from a line.
|
|
314
|
+
|
|
315
|
+
:param points: (N, 2) array.
|
|
316
|
+
:param line_point: A point on the line.
|
|
317
|
+
:param line_direction: The line's unit direction.
|
|
318
|
+
:returns: (N,) distances.
|
|
319
|
+
"""
|
|
320
|
+
offsets = points - line_point
|
|
321
|
+
return np.abs(offsets[:, 0] * line_direction[1] - offsets[:, 1] * line_direction[0])
|
|
322
|
+
|
|
323
|
+
|
|
324
|
+
def fit_circle(points: np.ndarray) -> dict:
|
|
325
|
+
"""
|
|
326
|
+
Fits a circle to 2D points: an algebraic (Kasa) fit as the start, refined by Gauss-Newton on the
|
|
327
|
+
geometric distance. The algebraic fit alone under-estimates the radius of a partial arc.
|
|
328
|
+
|
|
329
|
+
:param points: (N, 2) array, N >= 3, not all on one line.
|
|
330
|
+
:returns: {"center": (x, y), "radius", "rms"} in the points' units.
|
|
331
|
+
:raises ValueError: when fewer than three points are given.
|
|
332
|
+
"""
|
|
333
|
+
if len(points) < 3:
|
|
334
|
+
raise ValueError("a circle fit needs at least three points")
|
|
335
|
+
x, y = points[:, 0], points[:, 1]
|
|
336
|
+
design = np.column_stack((x, y, np.ones_like(x)))
|
|
337
|
+
solution, *_ = np.linalg.lstsq(design, -(x * x + y * y), rcond=None)
|
|
338
|
+
center = np.array([-solution[0] / 2.0, -solution[1] / 2.0])
|
|
339
|
+
radius = float(np.sqrt(max(center @ center - solution[2], NUMERIC_FLOOR)))
|
|
340
|
+
for _ in range(CIRCLE_REFINE_STEPS):
|
|
341
|
+
offsets = points - center
|
|
342
|
+
distances = np.maximum(np.linalg.norm(offsets, axis=1), NUMERIC_FLOOR)
|
|
343
|
+
residuals = distances - radius
|
|
344
|
+
jacobian = np.column_stack((-offsets[:, 0] / distances, -offsets[:, 1] / distances, -np.ones_like(x)))
|
|
345
|
+
step, *_ = np.linalg.lstsq(jacobian, -residuals, rcond=None)
|
|
346
|
+
center = center + step[:2]
|
|
347
|
+
radius = radius + float(step[2])
|
|
348
|
+
if np.abs(step).max() < CIRCLE_CONVERGENCE:
|
|
349
|
+
break
|
|
350
|
+
rms = float(np.sqrt(np.mean((np.linalg.norm(points - center, axis=1) - radius) ** 2)))
|
|
351
|
+
return {"center": (float(center[0]), float(center[1])), "radius": abs(radius), "rms": rms}
|
|
352
|
+
|
|
353
|
+
|
|
354
|
+
def _top_profile(mask: np.ndarray, columns: np.ndarray) -> np.ndarray:
|
|
355
|
+
"""(column centre, top edge row) for every given column that holds subject pixels."""
|
|
356
|
+
points = []
|
|
357
|
+
for column in columns:
|
|
358
|
+
rows = np.flatnonzero(mask[:, column])
|
|
359
|
+
if rows.size:
|
|
360
|
+
points.append((column + 0.5, float(rows[0])))
|
|
361
|
+
return np.array(points, dtype=np.float64).reshape(-1, 2)
|
|
362
|
+
|
|
363
|
+
|
|
364
|
+
def _right_profile(mask: np.ndarray, rows: np.ndarray) -> np.ndarray:
|
|
365
|
+
"""(right edge column, row centre) for every given row that holds subject pixels."""
|
|
366
|
+
points = []
|
|
367
|
+
for row in rows:
|
|
368
|
+
columns = np.flatnonzero(mask[row])
|
|
369
|
+
if columns.size:
|
|
370
|
+
points.append((float(columns[-1] + 1), row + 0.5))
|
|
371
|
+
return np.array(points, dtype=np.float64).reshape(-1, 2)
|
|
372
|
+
|
|
373
|
+
|
|
374
|
+
def _top_right_corner(mask: np.ndarray, region) -> dict:
|
|
375
|
+
"""Corner fit for the top-right corner of a mask; see corner_radius for the contract."""
|
|
376
|
+
left, top, right, bottom = (int(round(value)) for value in region)
|
|
377
|
+
region_columns = np.arange(max(0, left), min(mask.shape[1], right))
|
|
378
|
+
region_rows = np.arange(max(0, top), min(mask.shape[0], bottom))
|
|
379
|
+
if region_columns.size < 4 or region_rows.size < 4:
|
|
380
|
+
return None
|
|
381
|
+
top_points = _top_profile(mask[:bottom], region_columns)
|
|
382
|
+
side_points = _right_profile(mask[:, :right], region_rows)
|
|
383
|
+
if len(top_points) < 3 or len(side_points) < 3:
|
|
384
|
+
return None
|
|
385
|
+
flat_columns = max(2, int(len(top_points) * FLAT_SAMPLE_FRACTION))
|
|
386
|
+
flat_rows = max(2, int(len(side_points) * FLAT_SAMPLE_FRACTION))
|
|
387
|
+
top_line = fit_line(top_points[:flat_columns])
|
|
388
|
+
side_line = fit_line(side_points[-flat_rows:])
|
|
389
|
+
flats = _flats_corner(top_line, side_line, top_points[:flat_columns], side_points[-flat_rows:])
|
|
390
|
+
profile = np.unique(np.concatenate((top_points, side_points)), axis=0)
|
|
391
|
+
away_from_flats = ((distance_to_line(profile, *top_line) > FLAT_TOLERANCE_PIXELS)
|
|
392
|
+
& (distance_to_line(profile, *side_line) > FLAT_TOLERANCE_PIXELS))
|
|
393
|
+
arc = profile[away_from_flats]
|
|
394
|
+
if len(arc) < MINIMUM_ARC_POINTS:
|
|
395
|
+
return {"radius_px": 0.0, "center": None, "rms_px": 0.0, "arc_points": int(len(arc)), **flats}
|
|
396
|
+
circle = fit_circle(arc)
|
|
397
|
+
return {"radius_px": circle["radius"], "center": circle["center"], "rms_px": circle["rms"],
|
|
398
|
+
"arc_points": int(len(arc)), **flats}
|
|
399
|
+
|
|
400
|
+
|
|
401
|
+
def _flats_corner(top_line: tuple, side_line: tuple, top_flat: np.ndarray, side_flat: np.ndarray) -> dict:
|
|
402
|
+
"""
|
|
403
|
+
The sharp corner the two fitted flats meet at, and the angle between them inside the shape: what an
|
|
404
|
+
equal-depth radius is measured from.
|
|
405
|
+
|
|
406
|
+
:returns: {"corner": (column, row) or None when the flats are parallel, "interior_angle_degrees"}.
|
|
407
|
+
"""
|
|
408
|
+
(top_point, top_direction), (side_point, side_direction) = top_line, side_line
|
|
409
|
+
system = np.column_stack((top_direction, -side_direction))
|
|
410
|
+
if abs(np.linalg.det(system)) < NUMERIC_FLOOR:
|
|
411
|
+
return {"corner": None, "interior_angle_degrees": None}
|
|
412
|
+
along_top = np.linalg.solve(system, side_point - top_point)[0]
|
|
413
|
+
corner = top_point + along_top * top_direction
|
|
414
|
+
toward_top, toward_side = top_flat.mean(axis=0) - corner, side_flat.mean(axis=0) - corner
|
|
415
|
+
cosine = toward_top @ toward_side / max(np.linalg.norm(toward_top) * np.linalg.norm(toward_side), NUMERIC_FLOOR)
|
|
416
|
+
return {"corner": (float(corner[0]), float(corner[1])),
|
|
417
|
+
"interior_angle_degrees": float(np.degrees(np.arccos(np.clip(cosine, -1.0, 1.0))))}
|
|
418
|
+
|
|
419
|
+
|
|
420
|
+
def corner_radius(mask: np.ndarray, quadrant: str, region=None) -> dict:
|
|
421
|
+
"""
|
|
422
|
+
Measures the radius of one rounded corner of a silhouette: the outer profile beside the corner is
|
|
423
|
+
split into the two flats (fitted as lines, so a leaning side still works) and the arc between them,
|
|
424
|
+
and a circle is fitted to the arc.
|
|
425
|
+
|
|
426
|
+
:param mask: Boolean (height, width) silhouette, row 0 at the top.
|
|
427
|
+
:param quadrant: "top_right", "top_left", "bottom_right" or "bottom_left".
|
|
428
|
+
:param region: Optional [left, top, right, bottom] box (pixels) to search in; default is the matching
|
|
429
|
+
quarter of the subject's bounding box.
|
|
430
|
+
:returns: {"radius_px", "center" (column, row) or None, "rms_px", "arc_points", "corner" (column, row)
|
|
431
|
+
where the fitted flats meet, or None, "interior_angle_degrees" between the flats}. A radius of 0 means
|
|
432
|
+
the corner is sharper than the image resolves. None when the region holds no usable outline.
|
|
433
|
+
:raises ValueError: for an unknown quadrant.
|
|
434
|
+
"""
|
|
435
|
+
flips = {"top_right": (False, False), "top_left": (False, True),
|
|
436
|
+
"bottom_right": (True, False), "bottom_left": (True, True)}
|
|
437
|
+
if quadrant not in flips:
|
|
438
|
+
raise ValueError(f"unknown corner quadrant '{quadrant}'; use one of {sorted(flips)}")
|
|
439
|
+
flip_rows, flip_columns = flips[quadrant]
|
|
440
|
+
height, width = mask.shape
|
|
441
|
+
bounds = subject_bounds(mask)
|
|
442
|
+
if bounds is None:
|
|
443
|
+
return None
|
|
444
|
+
if region is None:
|
|
445
|
+
left, top, right, bottom = bounds
|
|
446
|
+
middle_column, middle_row = (left + right) / 2.0, (top + bottom) / 2.0
|
|
447
|
+
region = [middle_column if not flip_columns else left, top if not flip_rows else middle_row,
|
|
448
|
+
right if not flip_columns else middle_column, middle_row if not flip_rows else bottom]
|
|
449
|
+
left, top, right, bottom = region
|
|
450
|
+
oriented = mask
|
|
451
|
+
if flip_rows:
|
|
452
|
+
oriented = oriented[::-1, :]
|
|
453
|
+
top, bottom = height - bottom, height - top
|
|
454
|
+
if flip_columns:
|
|
455
|
+
oriented = oriented[:, ::-1]
|
|
456
|
+
left, right = width - right, width - left
|
|
457
|
+
result = _top_right_corner(oriented, (left, top, right, bottom))
|
|
458
|
+
if result is None:
|
|
459
|
+
return result
|
|
460
|
+
for key in ("center", "corner"):
|
|
461
|
+
if result.get(key) is not None:
|
|
462
|
+
column, row = result[key]
|
|
463
|
+
result[key] = (width - column if flip_columns else column, height - row if flip_rows else row)
|
|
464
|
+
return result
|
|
465
|
+
|
|
466
|
+
|
|
467
|
+
def luminance_ramp(gray_row: np.ndarray, mask_row: np.ndarray) -> dict:
|
|
468
|
+
"""
|
|
469
|
+
Reads how shading changes across a surface on one image row. A rounded roll shades as a gradual ramp
|
|
470
|
+
roughly as wide as its radius; a faceted or sharp edge changes in one or two pixels.
|
|
471
|
+
|
|
472
|
+
:param gray_row: Luminance values along the row.
|
|
473
|
+
:param mask_row: Boolean subject mask along the row.
|
|
474
|
+
:returns: {"left_ramp_px", "right_ramp_px", "left_step_fraction", "right_step_fraction"}. A step
|
|
475
|
+
fraction near 1 means the whole change happens in one pixel step (a crease); a small one means a
|
|
476
|
+
smooth ramp. None when the row has no subject or no usable shading contrast.
|
|
477
|
+
"""
|
|
478
|
+
columns = np.flatnonzero(mask_row)
|
|
479
|
+
if columns.size < MINIMUM_RAMP_COLUMNS:
|
|
480
|
+
return None
|
|
481
|
+
# Skip one pixel at each silhouette edge: it is blended with the background by anti-aliasing.
|
|
482
|
+
span = gray_row[columns[0] + 1:columns[-1]]
|
|
483
|
+
plateau_half = max(1, int(len(span) * PLATEAU_FRACTION / 2))
|
|
484
|
+
middle = len(span) // 2
|
|
485
|
+
plateau = float(np.median(span[middle - plateau_half:middle + plateau_half + 1]))
|
|
486
|
+
deviation = np.abs(span - plateau)
|
|
487
|
+
if deviation.max() < MINIMUM_RAMP_CONTRAST:
|
|
488
|
+
return None
|
|
489
|
+
result = {}
|
|
490
|
+
for side, ordered in (("left", span[:middle]), ("right", span[middle:][::-1])):
|
|
491
|
+
side_deviation = np.abs(ordered - plateau)
|
|
492
|
+
largest = side_deviation.max()
|
|
493
|
+
if largest < MINIMUM_RAMP_CONTRAST:
|
|
494
|
+
result[f"{side}_ramp_px"], result[f"{side}_step_fraction"] = 0, None
|
|
495
|
+
continue
|
|
496
|
+
inside = np.flatnonzero(side_deviation < largest * RAMP_END_FRACTION)
|
|
497
|
+
ramp_end = int(inside[0]) if inside.size else len(ordered)
|
|
498
|
+
ramp = ordered[:ramp_end + 1]
|
|
499
|
+
steps = np.abs(np.diff(ramp))
|
|
500
|
+
total = abs(float(ramp[0]) - float(ramp[-1]))
|
|
501
|
+
result[f"{side}_ramp_px"] = ramp_end
|
|
502
|
+
result[f"{side}_step_fraction"] = round(float(steps.max()) / total, 3) if total > MINIMUM_RAMP_TOTAL else None
|
|
503
|
+
return result
|
|
504
|
+
|
|
505
|
+
|
|
506
|
+
def gaussian_blur(values: np.ndarray, sigma_pixels: float) -> np.ndarray:
|
|
507
|
+
"""
|
|
508
|
+
Separable Gaussian blur of a 2D array, edges extended.
|
|
509
|
+
|
|
510
|
+
:param values: (height, width) float array.
|
|
511
|
+
:param sigma_pixels: Standard deviation in pixels; 0 or less returns a copy.
|
|
512
|
+
:returns: The blurred array.
|
|
513
|
+
"""
|
|
514
|
+
if sigma_pixels <= 0:
|
|
515
|
+
return values.astype(np.float32).copy()
|
|
516
|
+
radius = int(np.ceil(3.0 * sigma_pixels))
|
|
517
|
+
offsets = np.arange(-radius, radius + 1, dtype=np.float32)
|
|
518
|
+
kernel = np.exp(-0.5 * (offsets / sigma_pixels) ** 2)
|
|
519
|
+
kernel /= kernel.sum()
|
|
520
|
+
padded = np.pad(values.astype(np.float32), radius, mode="edge")
|
|
521
|
+
rows_blurred = sum(weight * padded[:, index:index + values.shape[1]] for index, weight in enumerate(kernel))
|
|
522
|
+
return sum(weight * rows_blurred[index:index + values.shape[0], :] for index, weight in enumerate(kernel))
|
|
523
|
+
|
|
524
|
+
|
|
525
|
+
def fill_polygon(height: int, width: int, polygon: np.ndarray) -> np.ndarray:
|
|
526
|
+
"""
|
|
527
|
+
Rasterises a closed polygon (even-odd rule, sampled at pixel centres).
|
|
528
|
+
|
|
529
|
+
:param height: Mask height in pixels.
|
|
530
|
+
:param width: Mask width in pixels.
|
|
531
|
+
:param polygon: (N, 2) array of (column, row) vertices in continuous pixel coordinates.
|
|
532
|
+
:returns: Boolean (height, width) mask.
|
|
533
|
+
"""
|
|
534
|
+
rows, columns = np.mgrid[0:height, 0:width]
|
|
535
|
+
sample_columns, sample_rows = columns + 0.5, rows + 0.5
|
|
536
|
+
inside = np.zeros((height, width), dtype=bool)
|
|
537
|
+
previous = polygon[-1]
|
|
538
|
+
for current in polygon:
|
|
539
|
+
spans_row = (current[1] > sample_rows) != (previous[1] > sample_rows)
|
|
540
|
+
crossing = (previous[0] - current[0]) * (sample_rows - current[1]) / (previous[1] - current[1] + DIVISION_GUARD) + current[0]
|
|
541
|
+
inside ^= spans_row & (sample_columns < crossing)
|
|
542
|
+
previous = current
|
|
543
|
+
return inside
|
|
544
|
+
|
|
545
|
+
|
|
546
|
+
def draw_segment(image: np.ndarray, start, end, color, thickness: int = 1) -> None:
|
|
547
|
+
"""
|
|
548
|
+
Draws a straight segment into an RGB(A) float image in place.
|
|
549
|
+
|
|
550
|
+
:param image: (height, width, 3 or 4) float array.
|
|
551
|
+
:param start: (column, row) start point.
|
|
552
|
+
:param end: (column, row) end point.
|
|
553
|
+
:param color: RGB tuple 0..1.
|
|
554
|
+
:param thickness: Line thickness in pixels.
|
|
555
|
+
"""
|
|
556
|
+
length = max(abs(end[0] - start[0]), abs(end[1] - start[1]), 1.0)
|
|
557
|
+
steps = np.linspace(0.0, 1.0, int(length * 2) + 2)
|
|
558
|
+
columns = start[0] + (end[0] - start[0]) * steps
|
|
559
|
+
rows = start[1] + (end[1] - start[1]) * steps
|
|
560
|
+
_stamp(image, columns, rows, color, thickness)
|
|
561
|
+
|
|
562
|
+
|
|
563
|
+
def draw_circle(image: np.ndarray, center, radius: float, color, thickness: int = 1) -> None:
|
|
564
|
+
"""
|
|
565
|
+
Draws a circle outline into an RGB(A) float image in place.
|
|
566
|
+
|
|
567
|
+
:param image: (height, width, 3 or 4) float array.
|
|
568
|
+
:param center: (column, row) centre.
|
|
569
|
+
:param radius: Radius in pixels.
|
|
570
|
+
:param color: RGB tuple 0..1.
|
|
571
|
+
:param thickness: Line thickness in pixels.
|
|
572
|
+
"""
|
|
573
|
+
angles = np.linspace(0.0, 2.0 * np.pi, max(CIRCLE_MINIMUM_SEGMENTS, int(radius * CIRCLE_SEGMENTS_PER_PIXEL)))
|
|
574
|
+
_stamp(image, center[0] + radius * np.cos(angles), center[1] + radius * np.sin(angles), color, thickness)
|
|
575
|
+
|
|
576
|
+
|
|
577
|
+
def _stamp(image: np.ndarray, columns: np.ndarray, rows: np.ndarray, color, thickness: int) -> None:
|
|
578
|
+
"""Paints square dots of the given thickness at continuous pixel positions, clipped to the image."""
|
|
579
|
+
height, width = image.shape[:2]
|
|
580
|
+
half = thickness // 2
|
|
581
|
+
for row_offset in range(-half, thickness - half):
|
|
582
|
+
for column_offset in range(-half, thickness - half):
|
|
583
|
+
pixel_rows = np.floor(rows).astype(int) + row_offset
|
|
584
|
+
pixel_columns = np.floor(columns).astype(int) + column_offset
|
|
585
|
+
keep = (pixel_rows >= 0) & (pixel_rows < height) & (pixel_columns >= 0) & (pixel_columns < width)
|
|
586
|
+
image[pixel_rows[keep], pixel_columns[keep], :3] = color
|
|
587
|
+
|
|
588
|
+
|
|
589
|
+
# ---------------------------------------------------------------------------------------------------------
|
|
590
|
+
# Connected regions, outlines and polylines: shared by trace, overlay-sheet and coverage-check.
|
|
591
|
+
# ---------------------------------------------------------------------------------------------------------
|
|
592
|
+
|
|
593
|
+
# Corner-lattice steps of a traced outline, clockwise on screen (row 0 at the top): right, down, left, up.
|
|
594
|
+
OUTLINE_DIRECTIONS = ((1, 0), (0, 1), (-1, 0), (0, -1))
|
|
595
|
+
|
|
596
|
+
# Query points per block when measuring point-to-segment distances (bounds the points x segments work array).
|
|
597
|
+
DISTANCE_BLOCK_POINTS = 256
|
|
598
|
+
|
|
599
|
+
|
|
600
|
+
def mask_runs(mask: np.ndarray) -> np.ndarray:
|
|
601
|
+
"""
|
|
602
|
+
Run-length encodes a boolean mask row by row.
|
|
603
|
+
|
|
604
|
+
:param mask: Boolean (height, width).
|
|
605
|
+
:returns: int64 (N, 3) array of (row, first column, end column) with the end exclusive, in row order.
|
|
606
|
+
"""
|
|
607
|
+
height, width = mask.shape
|
|
608
|
+
padded = np.zeros((height, width + 2), dtype=np.int8)
|
|
609
|
+
padded[:, 1:-1] = mask
|
|
610
|
+
changes = np.diff(padded, axis=1)
|
|
611
|
+
start_rows, start_columns = np.nonzero(changes == 1)
|
|
612
|
+
_, end_columns = np.nonzero(changes == -1)
|
|
613
|
+
return np.column_stack((start_rows, start_columns, end_columns)).astype(np.int64)
|
|
614
|
+
|
|
615
|
+
|
|
616
|
+
def _find_root(parents: list, index: int) -> int:
|
|
617
|
+
"""Union-find root with path halving."""
|
|
618
|
+
while parents[index] != index:
|
|
619
|
+
parents[index] = parents[parents[index]]
|
|
620
|
+
index = parents[index]
|
|
621
|
+
return index
|
|
622
|
+
|
|
623
|
+
|
|
624
|
+
def _run_roots(runs: np.ndarray) -> np.ndarray:
|
|
625
|
+
"""Component root per run: runs on neighbouring rows that share a column are joined (4-connectivity)."""
|
|
626
|
+
parents = list(range(len(runs)))
|
|
627
|
+
row_starts = np.searchsorted(runs[:, 0], np.arange(int(runs[:, 0].max()) + 2)) if len(runs) else []
|
|
628
|
+
for row in range(1, len(row_starts) - 1):
|
|
629
|
+
previous = range(row_starts[row - 1], row_starts[row])
|
|
630
|
+
current = range(row_starts[row], row_starts[row + 1])
|
|
631
|
+
if not previous or not current:
|
|
632
|
+
continue
|
|
633
|
+
upper, lower = previous.start, current.start
|
|
634
|
+
while upper < previous.stop and lower < current.stop:
|
|
635
|
+
if runs[upper, 1] < runs[lower, 2] and runs[lower, 1] < runs[upper, 2]:
|
|
636
|
+
upper_root, lower_root = _find_root(parents, upper), _find_root(parents, lower)
|
|
637
|
+
if upper_root != lower_root:
|
|
638
|
+
parents[max(upper_root, lower_root)] = min(upper_root, lower_root)
|
|
639
|
+
if runs[upper, 2] < runs[lower, 2]:
|
|
640
|
+
upper += 1
|
|
641
|
+
else:
|
|
642
|
+
lower += 1
|
|
643
|
+
return np.array([_find_root(parents, index) for index in range(len(runs))], dtype=np.int64)
|
|
644
|
+
|
|
645
|
+
|
|
646
|
+
def component_regions(mask: np.ndarray, minimum_area_px: int = 1) -> list:
|
|
647
|
+
"""
|
|
648
|
+
The 4-connected regions of a mask, largest first.
|
|
649
|
+
|
|
650
|
+
:param mask: Boolean (height, width).
|
|
651
|
+
:param minimum_area_px: Regions smaller than this many pixels are left out.
|
|
652
|
+
:returns: [{"area_px", "bbox": [left, top, right, bottom] (right / bottom exclusive), "centroid":
|
|
653
|
+
[column, row], "touches_border"}] sorted by area, largest first.
|
|
654
|
+
"""
|
|
655
|
+
runs = mask_runs(mask)
|
|
656
|
+
if not len(runs):
|
|
657
|
+
return []
|
|
658
|
+
roots = _run_roots(runs)
|
|
659
|
+
height, width = mask.shape
|
|
660
|
+
lengths = runs[:, 2] - runs[:, 1]
|
|
661
|
+
regions = []
|
|
662
|
+
for root in np.unique(roots):
|
|
663
|
+
own = runs[roots == root]
|
|
664
|
+
own_lengths = lengths[roots == root]
|
|
665
|
+
area = int(own_lengths.sum())
|
|
666
|
+
if area < minimum_area_px:
|
|
667
|
+
continue
|
|
668
|
+
centre_columns = (own[:, 1] + own[:, 2]) / 2.0
|
|
669
|
+
regions.append({
|
|
670
|
+
"area_px": area,
|
|
671
|
+
"bbox": [int(own[:, 1].min()), int(own[:, 0].min()), int(own[:, 2].max()), int(own[:, 0].max()) + 1],
|
|
672
|
+
"centroid": [round(float((centre_columns * own_lengths).sum() / area), 2),
|
|
673
|
+
round(float(((own[:, 0] + 0.5) * own_lengths).sum() / area), 2)],
|
|
674
|
+
"touches_border": bool(own[:, 0].min() == 0 or own[:, 0].max() == height - 1
|
|
675
|
+
or own[:, 1].min() == 0 or own[:, 2].max() == width)})
|
|
676
|
+
return sorted(regions, key=lambda region: -region["area_px"])
|
|
677
|
+
|
|
678
|
+
|
|
679
|
+
def largest_component(mask: np.ndarray) -> np.ndarray:
|
|
680
|
+
"""
|
|
681
|
+
Keeps only the largest 4-connected region of a mask (stray specks, labels and shadows fall away).
|
|
682
|
+
|
|
683
|
+
:param mask: Boolean (height, width).
|
|
684
|
+
:returns: Boolean mask of the largest region (empty when the mask is empty).
|
|
685
|
+
"""
|
|
686
|
+
runs = mask_runs(mask)
|
|
687
|
+
result = np.zeros_like(mask, dtype=bool)
|
|
688
|
+
if not len(runs):
|
|
689
|
+
return result
|
|
690
|
+
roots = _run_roots(runs)
|
|
691
|
+
lengths = runs[:, 2] - runs[:, 1]
|
|
692
|
+
areas = np.bincount(roots, weights=lengths)
|
|
693
|
+
for row, first, end in runs[roots == int(np.argmax(areas))]:
|
|
694
|
+
result[row, first:end] = True
|
|
695
|
+
return result
|
|
696
|
+
|
|
697
|
+
|
|
698
|
+
def hole_mask(mask: np.ndarray) -> np.ndarray:
|
|
699
|
+
"""
|
|
700
|
+
The holes of a mask: background regions (4-connected) that do not reach the image border.
|
|
701
|
+
|
|
702
|
+
:param mask: Boolean (height, width).
|
|
703
|
+
:returns: Boolean mask of every hole pixel.
|
|
704
|
+
"""
|
|
705
|
+
background = ~mask
|
|
706
|
+
runs = mask_runs(background)
|
|
707
|
+
holes = np.zeros_like(mask, dtype=bool)
|
|
708
|
+
if not len(runs):
|
|
709
|
+
return holes
|
|
710
|
+
roots = _run_roots(runs)
|
|
711
|
+
height, width = mask.shape
|
|
712
|
+
on_border = (runs[:, 0] == 0) | (runs[:, 0] == height - 1) | (runs[:, 1] == 0) | (runs[:, 2] == width)
|
|
713
|
+
border_roots = set(np.unique(roots[on_border]).tolist())
|
|
714
|
+
for (row, first, end), root in zip(runs, roots):
|
|
715
|
+
if int(root) not in border_roots:
|
|
716
|
+
holes[row, first:end] = True
|
|
717
|
+
return holes
|
|
718
|
+
|
|
719
|
+
|
|
720
|
+
def _boundary_edges(mask: np.ndarray) -> dict:
|
|
721
|
+
"""Directed pixel-edge boundary of a mask, clockwise on screen: {start corner: [end corners]}."""
|
|
722
|
+
padded = np.pad(mask, 1)
|
|
723
|
+
inside = padded[1:-1, 1:-1]
|
|
724
|
+
edges = {}
|
|
725
|
+
sides = ((padded[:-2, 1:-1], (0, 0), (1, 0)), (padded[1:-1, 2:], (1, 0), (1, 1)),
|
|
726
|
+
(padded[2:, 1:-1], (1, 1), (0, 1)), (padded[1:-1, :-2], (0, 1), (0, 0)))
|
|
727
|
+
for neighbour, start_offset, end_offset in sides:
|
|
728
|
+
rows, columns = np.nonzero(inside & ~neighbour)
|
|
729
|
+
for row, column in zip(rows.tolist(), columns.tolist()):
|
|
730
|
+
start = (column + start_offset[0], row + start_offset[1])
|
|
731
|
+
edges.setdefault(start, []).append((column + end_offset[0], row + end_offset[1]))
|
|
732
|
+
return edges
|
|
733
|
+
|
|
734
|
+
|
|
735
|
+
def _next_corner(edges: dict, corner: tuple, heading: tuple) -> tuple:
|
|
736
|
+
"""Takes the outgoing edge at a corner, turning right first where two loops touch, so loops never cross."""
|
|
737
|
+
candidates = edges[corner]
|
|
738
|
+
if len(candidates) > 1:
|
|
739
|
+
def turn(end):
|
|
740
|
+
step = (end[0] - corner[0], end[1] - corner[1])
|
|
741
|
+
return -(heading[0] * step[1] - heading[1] * step[0])
|
|
742
|
+
candidates.sort(key=turn)
|
|
743
|
+
end = candidates.pop(0)
|
|
744
|
+
if not candidates:
|
|
745
|
+
del edges[corner]
|
|
746
|
+
return end
|
|
747
|
+
|
|
748
|
+
|
|
749
|
+
def signed_area(points: np.ndarray) -> float:
|
|
750
|
+
"""Shoelace area of a closed polygon (positive for clockwise on screen)."""
|
|
751
|
+
columns, rows = points[:, 0], points[:, 1]
|
|
752
|
+
return 0.5 * float(np.dot(columns, np.roll(rows, -1)) - np.dot(rows, np.roll(columns, -1)))
|
|
753
|
+
|
|
754
|
+
|
|
755
|
+
def _drop_collinear(points: np.ndarray) -> np.ndarray:
|
|
756
|
+
"""Removes corners where a closed lattice polyline goes straight on."""
|
|
757
|
+
before = points - np.roll(points, 1, axis=0)
|
|
758
|
+
after = np.roll(points, -1, axis=0) - points
|
|
759
|
+
turning = (before[:, 0] * after[:, 1] - before[:, 1] * after[:, 0]) != 0
|
|
760
|
+
return points[turning]
|
|
761
|
+
|
|
762
|
+
|
|
763
|
+
def outline_loops(mask: np.ndarray) -> list:
|
|
764
|
+
"""
|
|
765
|
+
Every closed boundary of a mask, traced along pixel edges, so a loop's extent is exactly the pixels'
|
|
766
|
+
extent (continuous pixel coordinates, pixel (i, j) covers [i, i + 1) x [j, j + 1)).
|
|
767
|
+
|
|
768
|
+
:param mask: Boolean (height, width).
|
|
769
|
+
:returns: [(N, 2) float arrays of (column, row) corners], largest enclosed area first. Outer boundaries
|
|
770
|
+
run clockwise on screen, hole boundaries counter-clockwise.
|
|
771
|
+
"""
|
|
772
|
+
edges = _boundary_edges(mask)
|
|
773
|
+
loops = []
|
|
774
|
+
while edges:
|
|
775
|
+
start = next(iter(edges))
|
|
776
|
+
corner, heading, points = start, (1, 0), [start]
|
|
777
|
+
while True:
|
|
778
|
+
end = _next_corner(edges, corner, heading)
|
|
779
|
+
heading = (end[0] - corner[0], end[1] - corner[1])
|
|
780
|
+
corner = end
|
|
781
|
+
if corner == start:
|
|
782
|
+
break
|
|
783
|
+
points.append(corner)
|
|
784
|
+
loops.append(_drop_collinear(np.array(points, dtype=np.float64)))
|
|
785
|
+
return sorted(loops, key=lambda loop: -abs(signed_area(loop)))
|
|
786
|
+
|
|
787
|
+
|
|
788
|
+
def _simplify_open(points: np.ndarray, tolerance: float) -> np.ndarray:
|
|
789
|
+
"""Ramer-Douglas-Peucker on an open polyline, iterative; keeps both ends."""
|
|
790
|
+
keep = np.zeros(len(points), dtype=bool)
|
|
791
|
+
keep[0] = keep[-1] = True
|
|
792
|
+
stack = [(0, len(points) - 1)]
|
|
793
|
+
while stack:
|
|
794
|
+
first, last = stack.pop()
|
|
795
|
+
if last - first < 2:
|
|
796
|
+
continue
|
|
797
|
+
chord = points[last] - points[first]
|
|
798
|
+
length = float(np.hypot(*chord))
|
|
799
|
+
offsets = points[first + 1:last] - points[first]
|
|
800
|
+
if length < NUMERIC_FLOOR:
|
|
801
|
+
distances = np.hypot(offsets[:, 0], offsets[:, 1])
|
|
802
|
+
else:
|
|
803
|
+
distances = np.abs(offsets[:, 0] * chord[1] - offsets[:, 1] * chord[0]) / length
|
|
804
|
+
farthest = int(np.argmax(distances))
|
|
805
|
+
if distances[farthest] > tolerance:
|
|
806
|
+
middle = first + 1 + farthest
|
|
807
|
+
keep[middle] = True
|
|
808
|
+
stack.extend(((first, middle), (middle, last)))
|
|
809
|
+
return points[keep]
|
|
810
|
+
|
|
811
|
+
|
|
812
|
+
def simplify_polyline(points: np.ndarray, tolerance: float, closed: bool = True) -> np.ndarray:
|
|
813
|
+
"""
|
|
814
|
+
Simplifies a polyline (Ramer-Douglas-Peucker): no removed point lies farther than `tolerance` from the
|
|
815
|
+
result. A closed loop is split at its first point and the point farthest from it, so both halves keep
|
|
816
|
+
their extremes.
|
|
817
|
+
|
|
818
|
+
:param points: (N, 2) array.
|
|
819
|
+
:param tolerance: Largest allowed deviation, in the points' units; 0 or less returns a copy.
|
|
820
|
+
:param closed: True for a closed loop (the last point joins the first).
|
|
821
|
+
:returns: The simplified (M, 2) array (a closed loop is returned without repeating its first point).
|
|
822
|
+
"""
|
|
823
|
+
if tolerance <= 0 or len(points) < 4:
|
|
824
|
+
return points.copy()
|
|
825
|
+
if not closed:
|
|
826
|
+
return _simplify_open(points, tolerance)
|
|
827
|
+
farthest = int(np.argmax(np.hypot(*(points - points[0]).T)))
|
|
828
|
+
first_half = _simplify_open(points[:farthest + 1], tolerance)
|
|
829
|
+
second_half = _simplify_open(np.vstack((points[farthest:], points[:1])), tolerance)
|
|
830
|
+
return np.vstack((first_half, second_half[1:-1]))
|
|
831
|
+
|
|
832
|
+
|
|
833
|
+
def polyline_boundary(points: np.ndarray, station_index: int, station: float, closed: bool = True):
|
|
834
|
+
"""
|
|
835
|
+
Where a polyline crosses a station line, read along the other coordinate.
|
|
836
|
+
|
|
837
|
+
:param points: (N, 2) array.
|
|
838
|
+
:param station_index: 0 when the station is a value of the first coordinate, 1 for the second.
|
|
839
|
+
:param station: The station value.
|
|
840
|
+
:param closed: True when the last point joins the first.
|
|
841
|
+
:returns: (smallest, largest) crossing of the other coordinate, or None when the line misses it.
|
|
842
|
+
"""
|
|
843
|
+
starts = points if closed else points[:-1]
|
|
844
|
+
ends = np.roll(points, -1, axis=0) if closed else points[1:]
|
|
845
|
+
other_index = 1 - station_index
|
|
846
|
+
start_values, end_values = starts[:, station_index], ends[:, station_index]
|
|
847
|
+
spans = (np.minimum(start_values, end_values) <= station) & (station <= np.maximum(start_values, end_values))
|
|
848
|
+
crossings = []
|
|
849
|
+
for start, end in zip(starts[spans], ends[spans]):
|
|
850
|
+
run = end[station_index] - start[station_index]
|
|
851
|
+
if abs(run) < NUMERIC_FLOOR:
|
|
852
|
+
crossings.extend((start[other_index], end[other_index]))
|
|
853
|
+
else:
|
|
854
|
+
share = (station - start[station_index]) / run
|
|
855
|
+
crossings.append(start[other_index] + share * (end[other_index] - start[other_index]))
|
|
856
|
+
if not crossings:
|
|
857
|
+
return None
|
|
858
|
+
return float(min(crossings)), float(max(crossings))
|
|
859
|
+
|
|
860
|
+
|
|
861
|
+
def resample_polyline(points: np.ndarray, step: float, closed: bool = True) -> np.ndarray:
|
|
862
|
+
"""
|
|
863
|
+
Points evenly spaced along a polyline by arc length, at most `step` apart, so every stretch of it weighs the
|
|
864
|
+
same in a measurement. Works in any dimension (pixel outlines, world curves).
|
|
865
|
+
|
|
866
|
+
:param points: (N, D) array.
|
|
867
|
+
:param step: Largest spacing between samples, in the points' units.
|
|
868
|
+
:param closed: True for a closed loop (the result does not repeat its first point).
|
|
869
|
+
:returns: (M, D) samples; the polyline's own end points are kept for an open polyline.
|
|
870
|
+
"""
|
|
871
|
+
path = np.vstack((points, points[:1])) if closed else np.asarray(points, dtype=np.float64)
|
|
872
|
+
lengths = np.linalg.norm(np.diff(path, axis=0), axis=1)
|
|
873
|
+
keep = np.concatenate(([True], lengths > NUMERIC_FLOOR))
|
|
874
|
+
path, lengths = path[keep], lengths[lengths > NUMERIC_FLOOR]
|
|
875
|
+
along = np.concatenate(([0.0], np.cumsum(lengths)))
|
|
876
|
+
total = float(along[-1])
|
|
877
|
+
if total < NUMERIC_FLOOR:
|
|
878
|
+
return path[:1].copy()
|
|
879
|
+
intervals = max(1, int(np.ceil(total / step)))
|
|
880
|
+
samples = np.linspace(0.0, total, intervals + (0 if closed else 1), endpoint=not closed)
|
|
881
|
+
return np.column_stack([np.interp(samples, along, path[:, axis]) for axis in range(path.shape[1])])
|
|
882
|
+
|
|
883
|
+
|
|
884
|
+
def distances_to_segments(points: np.ndarray, starts: np.ndarray, ends: np.ndarray) -> np.ndarray:
|
|
885
|
+
"""
|
|
886
|
+
The distance from every point to the nearest of a set of segments, in any dimension.
|
|
887
|
+
|
|
888
|
+
:param points: (N, D) query points.
|
|
889
|
+
:param starts: (S, D) segment start points.
|
|
890
|
+
:param ends: (S, D) segment end points.
|
|
891
|
+
:returns: (N,) distances, in the points' units.
|
|
892
|
+
"""
|
|
893
|
+
directions = ends - starts
|
|
894
|
+
lengths = np.maximum(np.einsum("ij,ij->i", directions, directions), DIVISION_GUARD)
|
|
895
|
+
distances = np.empty(len(points), dtype=np.float64)
|
|
896
|
+
for first in range(0, len(points), DISTANCE_BLOCK_POINTS):
|
|
897
|
+
block = points[first:first + DISTANCE_BLOCK_POINTS]
|
|
898
|
+
offsets = block[:, None, :] - starts[None, :, :]
|
|
899
|
+
along = np.clip(np.einsum("psd,sd->ps", offsets, directions) / lengths, 0.0, 1.0)
|
|
900
|
+
gaps = offsets - along[:, :, None] * directions[None, :, :]
|
|
901
|
+
distances[first:first + len(block)] = np.sqrt(np.einsum("psd,psd->ps", gaps, gaps).min(axis=1))
|
|
902
|
+
return distances
|
|
903
|
+
|
|
904
|
+
|
|
905
|
+
def draw_polyline(image: np.ndarray, points: np.ndarray, color, thickness: int = 1, closed: bool = True) -> None:
|
|
906
|
+
"""
|
|
907
|
+
Draws a polyline into an RGB(A) float image in place.
|
|
908
|
+
|
|
909
|
+
:param image: (height, width, 3 or 4) float array.
|
|
910
|
+
:param points: (N, 2) (column, row) points.
|
|
911
|
+
:param color: RGB tuple 0..1.
|
|
912
|
+
:param thickness: Line thickness in pixels.
|
|
913
|
+
:param closed: Also draw the segment from the last point back to the first.
|
|
914
|
+
"""
|
|
915
|
+
count = len(points)
|
|
916
|
+
for index in range(count if closed else count - 1):
|
|
917
|
+
draw_segment(image, points[index], points[(index + 1) % count], color, thickness)
|