@babylonjs-toolkit/agent 1.2.0 → 1.2.2
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 +31 -21
- package/lib/claude-settings.js +146 -1
- package/lib/doctor.js +21 -4
- package/lib/install.js +67 -4
- package/package.json +1 -1
- package/scripts/hooks/block-sleep.js +138 -0
- package/skills/bt-atlas/SKILL.md +22 -5
- package/skills/bt-design/references/3d-hero-docs.md +10 -3
- package/skills/bt-design/references/3d-hero-scroll.md +30 -5
- package/skills/bt-execute/SKILL.md +89 -120
- package/skills/bt-execute/scripts/dashboard.mjs +279 -19
- package/skills/bt-execute/templates/dashboard/data-schema.md +36 -15
- package/skills/bt-gauntlet/SKILL.md +4 -4
- package/skills/bt-gauntlet/references/spec-composition.md +4 -2
- package/skills/bt-gauntlet/references/target-images.md +28 -4
- package/skills/bt-gauntlet/references/unity-pipeline.md +30 -8
- package/skills/bt-hero/SKILL.md +3 -3
- package/skills/bt-landing/SKILL.md +1 -1
- package/skills/bt-plan/SKILL.md +52 -62
- package/skills/bt-prototype/SKILL.md +3 -3
- package/skills/bt-unwrap/SKILL.md +396 -0
- 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
- package/skills/bt-unwrap/scripts/blender/bt_unwrap.py +678 -0
- package/skills/bt-unwrap/scripts/blender/image_utils.py +264 -0
- package/skills/bt-unwrap/scripts/blender/mesh_tools.py +508 -0
- package/skills/bt-unwrap/scripts/blender/model_io.py +135 -0
- package/skills/bt-unwrap/scripts/blender/previews.py +205 -0
- package/skills/bt-unwrap/scripts/blender/rasterizer.py +217 -0
- package/skills/bt-unwrap/scripts/blender/reference_views.py +945 -0
- package/skills/bt-unwrap/scripts/blender/reference_warp.py +571 -0
- package/skills/bt-unwrap/scripts/blender/texture_bake.py +390 -0
- package/skills/bt-unwrap/scripts/blender/texture_compose.py +596 -0
- package/skills/bt-unwrap/scripts/blender/uv_layout.py +605 -0
- package/skills/bt-unwrap/scripts/bt-unwrap.mjs +165 -0
|
@@ -0,0 +1,945 @@
|
|
|
1
|
+
"""
|
|
2
|
+
Reference images for bt-unwrap: find the view images in a folder, cut each subject out of its background,
|
|
3
|
+
work out which way the model faces by matching silhouettes, line every image up with the mesh, and build
|
|
4
|
+
per-view depth buffers so a reference only paints surfaces it can actually see.
|
|
5
|
+
|
|
6
|
+
"Orthographic" references made by image generators are nearly always perspective renders: parts further
|
|
7
|
+
from the camera look smaller, and the camera is often a little above the model. Each reference therefore
|
|
8
|
+
gets a fitted camera: its direction (solved within a few degrees of the named view, or anywhere around
|
|
9
|
+
the model for three-quarter views), a perspective strength, its in-plane rotation, scale and offset.
|
|
10
|
+
"""
|
|
11
|
+
import math
|
|
12
|
+
import os
|
|
13
|
+
import re
|
|
14
|
+
from dataclasses import dataclass, field
|
|
15
|
+
from typing import Optional
|
|
16
|
+
|
|
17
|
+
import numpy as np
|
|
18
|
+
|
|
19
|
+
import image_utils
|
|
20
|
+
import mesh_tools
|
|
21
|
+
import rasterizer
|
|
22
|
+
import uv_layout
|
|
23
|
+
|
|
24
|
+
IMAGE_EXTENSIONS = (".png", ".jpg", ".jpeg", ".webp", ".tga", ".tif", ".tiff", ".bmp")
|
|
25
|
+
VIEW_KEYWORDS = {
|
|
26
|
+
"front": {"front", "fwd", "frontview"},
|
|
27
|
+
"rear": {"rear", "back", "rearview", "backview"},
|
|
28
|
+
"left": {"left", "lhs", "leftside", "leftview"},
|
|
29
|
+
"right": {"right", "rhs", "rightside", "rightview"},
|
|
30
|
+
"top": {"top", "plan", "overhead", "topview"},
|
|
31
|
+
"bottom": {"bottom", "under", "underside", "bottomview"},
|
|
32
|
+
}
|
|
33
|
+
OPPOSITE_VIEWS = ({"front", "rear"}, {"left", "right"}, {"top", "bottom"})
|
|
34
|
+
# Words that mark an image as something other than a view of the whole model: never used.
|
|
35
|
+
PARTIAL_VIEW_KEYWORDS = {"detail", "details", "turnaround", "sheet", "closeup", "close", "cutaway", "crop",
|
|
36
|
+
"cropped", "zoom", "interior", "exploded"}
|
|
37
|
+
# Words that mark an angled view of the whole model; its camera direction is solved from the silhouette.
|
|
38
|
+
OBLIQUE_KEYWORDS = {"three", "quarter", "threequarter", "iso", "isometric", "perspective", "persp", "oblique",
|
|
39
|
+
"angle", "angled"}
|
|
40
|
+
THREE_QUARTER_PATTERN = re.compile(r"3[_\- ]?4")
|
|
41
|
+
OBLIQUE_ANY = "oblique" # name for an angled view whose file name gives no direction
|
|
42
|
+
# Compass names for oblique cameras, by yaw sector (0 = front, 90 = left, 180 = rear, -90 = right).
|
|
43
|
+
COMPASS_NAMES = ((0.0, "front"), (45.0, "front_left"), (90.0, "left"), (135.0, "rear_left"),
|
|
44
|
+
(180.0, "rear"), (-135.0, "rear_right"), (-90.0, "right"), (-45.0, "front_right"))
|
|
45
|
+
|
|
46
|
+
BORDER_SAMPLE_FRACTION = 0.02 # outer strip used to estimate the background color
|
|
47
|
+
FLOOD_GRID_LONG_SIDE = 700 # background flood fill runs on a grid about this size
|
|
48
|
+
BBOX_MINIMUM_PIXELS_FRACTION = 0.002 # a row / column needs this share of subject pixels to count
|
|
49
|
+
SCORE_CANVAS_SIZE = 256 # long side of the silhouette comparison
|
|
50
|
+
COARSE_CANVAS_SIZE = 128 # long side used while searching camera directions coarsely
|
|
51
|
+
SCORE_CANVAS_MARGIN = 0.15 # empty border around the subject in the comparison canvas
|
|
52
|
+
HORIZONTAL_VIEWS = ("front", "rear", "left", "right")
|
|
53
|
+
|
|
54
|
+
# Silhouettes are scored on stand-in meshes: vertices snapped to a grid of about one comparison pixel, so
|
|
55
|
+
# even a multi-million-triangle mesh scores quickly and without holes. The coarse stand-in serves the
|
|
56
|
+
# small canvas, the fine one the full canvas.
|
|
57
|
+
COARSE_PROXY_CELLS = 100
|
|
58
|
+
FINE_PROXY_CELLS = 150
|
|
59
|
+
PROXY_MINIMUM_TRIANGLES = 30_000 # smaller meshes are scored as they are
|
|
60
|
+
|
|
61
|
+
# Perspective strength: how much smaller the farthest point of the model looks than the nearest one
|
|
62
|
+
# (0 = true orthographic, 0.5 = the far end appears at 1 / 1.5 of its size).
|
|
63
|
+
PERSPECTIVE_START = 0.3
|
|
64
|
+
PERSPECTIVE_LIMIT = 1.6
|
|
65
|
+
PERSPECTIVE_PER_DEGREE = 0.025 # perspective step that goes with a 1-degree direction step
|
|
66
|
+
# Camera direction search. A straight view may sit a few degrees off its axis (AI "orthographic" images are
|
|
67
|
+
# often taken from slightly above); a three-quarter view is searched around the model.
|
|
68
|
+
STRAIGHT_TILT_LIMIT = 12.0 # degrees a straight view's camera may move off its named axis
|
|
69
|
+
STRAIGHT_TILT_MINIMUM_GAIN = 0.004 # ...and only when that matches the silhouette at least this much better
|
|
70
|
+
OBLIQUE_TILT_LIMIT = 20.0 # degrees a three-quarter camera may move from its coarse start
|
|
71
|
+
OBLIQUE_YAW_STEP = 15.0
|
|
72
|
+
OBLIQUE_FRONT_REAR_WINDOW = 80.0 # yaw searched each side of a named front or rear
|
|
73
|
+
OBLIQUE_PITCH_STEPS = {"level": (-15.0, 0.0, 15.0, 30.0, 45.0, 60.0), "top": (30.0, 45.0, 60.0),
|
|
74
|
+
"bottom": (-60.0, -45.0, -30.0, -15.0)}
|
|
75
|
+
OBLIQUE_STARTS = 2 # best coarse candidates refined further
|
|
76
|
+
OBLIQUE_DISTINCT_DEGREES = 20.0 # coarse candidates closer than this count as the same start
|
|
77
|
+
OBLIQUE_DUPLICATE_DEGREES = 15.0 # an angled view this close to a better-matching view adds nothing
|
|
78
|
+
COARSE_PATTERN_STEPS = (4.0, 1.0) # degrees: first and last compass-search step on the small canvas
|
|
79
|
+
FINE_PATTERN_STEPS = (0.5, 0.5) # ...and on the full canvas
|
|
80
|
+
# Scale / offset corrections that absorb an AI image's slightly different proportions: largest values and
|
|
81
|
+
# the first and last search steps.
|
|
82
|
+
REFINE_LIMITS = (0.08, 0.08, 0.06, 0.06)
|
|
83
|
+
REFINE_STEPS = ((0.02, 0.0025), (0.02, 0.0025), (0.01, 0.00125), (0.01, 0.00125))
|
|
84
|
+
IDENTITY_REFINE = (1.0, 1.0, 0.0, 0.0)
|
|
85
|
+
|
|
86
|
+
|
|
87
|
+
@dataclass
|
|
88
|
+
class ViewFrame:
|
|
89
|
+
"""How the model projects into one reference: rotation, perspective and the fitted extents."""
|
|
90
|
+
|
|
91
|
+
quarter_turns: int
|
|
92
|
+
perspective: float
|
|
93
|
+
depth_range: tuple # (nearest, farthest) model depth along the view
|
|
94
|
+
center: tuple # principal point in view-plane meters (center of the model's extents)
|
|
95
|
+
extents: tuple # (min_x, max_x, min_y, max_y) of the projected model
|
|
96
|
+
|
|
97
|
+
|
|
98
|
+
@dataclass
|
|
99
|
+
class ReferenceSource:
|
|
100
|
+
"""A reference image to load: the view it shows and, for an angled view, what its name says."""
|
|
101
|
+
|
|
102
|
+
view: str # front, rear, left, right, top, bottom, or an angled-view name
|
|
103
|
+
path: str
|
|
104
|
+
oblique: bool = False # an angled view: its camera direction is solved from the silhouette
|
|
105
|
+
named_views: tuple = () # view words in an angled view's name, e.g. ("front", "right")
|
|
106
|
+
|
|
107
|
+
|
|
108
|
+
@dataclass
|
|
109
|
+
class ReferenceImage:
|
|
110
|
+
"""One reference view and everything learned about it."""
|
|
111
|
+
|
|
112
|
+
view: str
|
|
113
|
+
path: str
|
|
114
|
+
pixels: np.ndarray # float32 (height, width, 4), row 0 at the bottom
|
|
115
|
+
mask: np.ndarray # bool (height, width): subject pixels
|
|
116
|
+
bbox: tuple # (x0, y0, x1, y1) of the subject in pixels, bottom-up
|
|
117
|
+
quarter_turns: Optional[int] = None # fixed in-plane rotation; None = detect
|
|
118
|
+
iou: float = 0.0 # silhouette match after alignment, 0..1
|
|
119
|
+
refine: tuple = IDENTITY_REFINE # scale x, scale y, offset x, offset y (fractions of bbox)
|
|
120
|
+
frame: Optional[ViewFrame] = None
|
|
121
|
+
used: bool = False
|
|
122
|
+
note: str = ""
|
|
123
|
+
depth: Optional[np.ndarray] = field(default=None, repr=False)
|
|
124
|
+
warp: Optional[object] = field(default=None, repr=False) # reference_warp.WarpField: local alignment
|
|
125
|
+
agreement: Optional[object] = field(default=None, repr=False) # reference_warp.AgreementMap: where to trust it
|
|
126
|
+
direction: Optional[np.ndarray] = None # unit vector from the model toward the camera (oriented frame)
|
|
127
|
+
oblique: bool = False # an angled view whose camera direction is solved
|
|
128
|
+
named_views: tuple = () # view words in an angled view's file name
|
|
129
|
+
camera_tilt: float = 0.0 # degrees the solved camera sits off the named straight axis
|
|
130
|
+
overlay: str = "" # alignment overlay image, when previews are on
|
|
131
|
+
|
|
132
|
+
def report(self) -> dict:
|
|
133
|
+
"""Summary for the JSON report."""
|
|
134
|
+
return {
|
|
135
|
+
"view": self.view, "path": self.path, "used": self.used, "note": self.note,
|
|
136
|
+
"angled_view": self.oblique,
|
|
137
|
+
"silhouette_iou": round(self.iou, 3),
|
|
138
|
+
"camera_yaw_pitch_degrees": [round(value, 1) for value in direction_angles(self.direction)],
|
|
139
|
+
"camera_tilt_degrees": round(self.camera_tilt, 1),
|
|
140
|
+
"quarter_turns": self.frame.quarter_turns if self.frame else self.quarter_turns,
|
|
141
|
+
"perspective": round(self.frame.perspective, 3) if self.frame else None,
|
|
142
|
+
"refine_scale": [round(self.refine[0], 3), round(self.refine[1], 3)],
|
|
143
|
+
"refine_offset": [round(self.refine[2], 3), round(self.refine[3], 3)],
|
|
144
|
+
"subject_bbox": [round(value, 1) for value in self.bbox],
|
|
145
|
+
"local_warp": self.warp.report() if self.warp is not None else None,
|
|
146
|
+
"consistency": self.agreement.report() if self.agreement is not None else None,
|
|
147
|
+
}
|
|
148
|
+
|
|
149
|
+
|
|
150
|
+
def discover_references(directory: Optional[str], explicit: list, include_oblique: bool = True) -> tuple:
|
|
151
|
+
"""
|
|
152
|
+
Finds the reference images. Explicit --ref entries come first; the rest are matched by file name in the
|
|
153
|
+
folder. A name with one view word is a straight view (01_front_ortho.png, car_left_side.jpg, top.webp);
|
|
154
|
+
the best-named file per view wins. A name with a three-quarter word (three_quarter, 3-4, iso, angle,
|
|
155
|
+
perspective) or with two neighbouring view words (front_left, top_rear) is an angled view, and every one
|
|
156
|
+
is kept. Detail, close-up, cutaway and turnaround-sheet images are skipped: they do not show the whole model.
|
|
157
|
+
|
|
158
|
+
:param directory: Folder to scan, or None.
|
|
159
|
+
:param explicit: (name, path) pairs from --ref. A name is a view (front, rear, left, right, top, bottom), a
|
|
160
|
+
combination of neighbouring views for an angled view (front_left, top_rear_right ...) or 'oblique'
|
|
161
|
+
for an angled view whose camera direction is unknown.
|
|
162
|
+
:param include_oblique: Use angled views (False skips them).
|
|
163
|
+
:returns: (list of ReferenceSource, list of notes about skipped files).
|
|
164
|
+
:raises ValueError: for an unknown view name or a missing file / folder.
|
|
165
|
+
"""
|
|
166
|
+
sources = []
|
|
167
|
+
notes = []
|
|
168
|
+
for name, path in explicit:
|
|
169
|
+
if not os.path.isfile(path):
|
|
170
|
+
raise ValueError(f"--ref {name}={path}: file not found")
|
|
171
|
+
source = _source_from_view_name(name, path)
|
|
172
|
+
if source.oblique and not include_oblique:
|
|
173
|
+
notes.append(f"skipped {path}: angled view, and --no-oblique is set")
|
|
174
|
+
continue
|
|
175
|
+
sources.append(source)
|
|
176
|
+
if directory:
|
|
177
|
+
if not os.path.isdir(directory):
|
|
178
|
+
raise ValueError(f"--refs folder not found: {directory}")
|
|
179
|
+
sources.extend(_scan_folder(directory, {source.view for source in sources if not source.oblique},
|
|
180
|
+
{source.path for source in sources}, include_oblique, notes))
|
|
181
|
+
return _unique_view_names(sources), notes
|
|
182
|
+
|
|
183
|
+
|
|
184
|
+
def _source_from_view_name(name: str, path: str) -> ReferenceSource:
|
|
185
|
+
"""Turns a --ref view name into a source; raises ValueError for a name that is not a view."""
|
|
186
|
+
lowered = name.strip().lower()
|
|
187
|
+
if lowered in VIEW_KEYWORDS:
|
|
188
|
+
return ReferenceSource(view=lowered, path=path)
|
|
189
|
+
if lowered in (OBLIQUE_ANY, "any", "angle", "angled"):
|
|
190
|
+
return ReferenceSource(view=OBLIQUE_ANY, path=path, oblique=True)
|
|
191
|
+
parts = [part for part in re.split(r"[^a-z]+", lowered) if part]
|
|
192
|
+
if len(parts) >= 2 and all(part in VIEW_KEYWORDS for part in parts) and not _names_opposite_views(parts):
|
|
193
|
+
return ReferenceSource(view="_".join(_ordered_views(parts)), path=path, oblique=True,
|
|
194
|
+
named_views=tuple(_ordered_views(parts)))
|
|
195
|
+
raise ValueError(f"--ref view '{name}' is not a view: use front, rear, left, right, top, bottom, a "
|
|
196
|
+
f"neighbouring pair such as front_left or top_rear, or oblique")
|
|
197
|
+
|
|
198
|
+
|
|
199
|
+
def _scan_folder(directory: str, explicit_views: set, explicit_paths: set, include_oblique: bool,
|
|
200
|
+
notes: list) -> list:
|
|
201
|
+
"""Matches the images in a folder to views by file name; see discover_references."""
|
|
202
|
+
straight = {}
|
|
203
|
+
angled = []
|
|
204
|
+
for name in sorted(os.listdir(directory)):
|
|
205
|
+
stem, extension = os.path.splitext(name)
|
|
206
|
+
path = os.path.join(directory, name)
|
|
207
|
+
if extension.lower() not in IMAGE_EXTENSIONS or path in explicit_paths:
|
|
208
|
+
continue
|
|
209
|
+
lowered = stem.lower()
|
|
210
|
+
tokens = set(re.split(r"[^a-z0-9]+", lowered))
|
|
211
|
+
if tokens & PARTIAL_VIEW_KEYWORDS:
|
|
212
|
+
notes.append(f"skipped {name}: not a view of the whole model")
|
|
213
|
+
continue
|
|
214
|
+
views = [view for view, keywords in VIEW_KEYWORDS.items() if tokens & keywords]
|
|
215
|
+
if _names_opposite_views(views):
|
|
216
|
+
notes.append(f"skipped {name}: names opposite views ({', '.join(views)})")
|
|
217
|
+
continue
|
|
218
|
+
angled_name = bool(tokens & OBLIQUE_KEYWORDS) or bool(THREE_QUARTER_PATTERN.search(lowered)) or len(views) > 1
|
|
219
|
+
if angled_name:
|
|
220
|
+
if not include_oblique:
|
|
221
|
+
notes.append(f"skipped {name}: angled view, and --no-oblique is set")
|
|
222
|
+
continue
|
|
223
|
+
ordered = tuple(_ordered_views(views))
|
|
224
|
+
angled.append(ReferenceSource(view="_".join(ordered) or OBLIQUE_ANY, path=path, oblique=True,
|
|
225
|
+
named_views=ordered))
|
|
226
|
+
elif len(views) == 1:
|
|
227
|
+
straight.setdefault(views[0], []).append(name)
|
|
228
|
+
|
|
229
|
+
sources = []
|
|
230
|
+
for view, names in straight.items():
|
|
231
|
+
if view in explicit_views:
|
|
232
|
+
notes.append(f"skipped {', '.join(names)}: --ref already gives the {view} view")
|
|
233
|
+
continue
|
|
234
|
+
names.sort(key=lambda candidate: ("ortho" not in candidate.lower(), len(candidate)))
|
|
235
|
+
sources.append(ReferenceSource(view=view, path=os.path.join(directory, names[0])))
|
|
236
|
+
for extra in names[1:]:
|
|
237
|
+
notes.append(f"skipped {extra}: {names[0]} already covers the {view} view")
|
|
238
|
+
return sources + angled
|
|
239
|
+
|
|
240
|
+
|
|
241
|
+
def _names_opposite_views(views) -> bool:
|
|
242
|
+
"""True when the view words include both members of an opposite pair (front and rear, ...)."""
|
|
243
|
+
named = set(views)
|
|
244
|
+
return any(pair <= named for pair in OPPOSITE_VIEWS)
|
|
245
|
+
|
|
246
|
+
|
|
247
|
+
def _ordered_views(views) -> list:
|
|
248
|
+
"""View words in a fixed order (top / bottom, front / rear, left / right), so names are predictable."""
|
|
249
|
+
order = ("top", "bottom", "front", "rear", "left", "right")
|
|
250
|
+
return sorted(set(views), key=order.index)
|
|
251
|
+
|
|
252
|
+
|
|
253
|
+
def _unique_view_names(sources: list) -> list:
|
|
254
|
+
"""Gives repeated angled-view names a number (oblique, oblique_2 ...); straight views are unique already."""
|
|
255
|
+
seen = {}
|
|
256
|
+
for source in sources:
|
|
257
|
+
count = seen.get(source.view, 0) + 1
|
|
258
|
+
seen[source.view] = count
|
|
259
|
+
if count > 1:
|
|
260
|
+
source.view = f"{source.view}_{count}"
|
|
261
|
+
return sources
|
|
262
|
+
|
|
263
|
+
|
|
264
|
+
def load_reference(source: ReferenceSource, background_tolerance: float,
|
|
265
|
+
quarter_turns: Optional[int]) -> ReferenceImage:
|
|
266
|
+
"""
|
|
267
|
+
Loads a reference and separates the subject from the background. A transparent background is used
|
|
268
|
+
directly; otherwise the background color is taken from the image border.
|
|
269
|
+
|
|
270
|
+
:param source: The image and the view it shows.
|
|
271
|
+
:param background_tolerance: How far (0..1 per channel) a pixel may differ from the background color and
|
|
272
|
+
still count as background.
|
|
273
|
+
:param quarter_turns: Fixed in-plane rotation, or None to detect it (top / bottom views).
|
|
274
|
+
:returns: The loaded reference. An angled view's camera direction is a first guess until alignment.
|
|
275
|
+
:raises RuntimeError: when no subject can be found.
|
|
276
|
+
"""
|
|
277
|
+
pixels = image_utils.load_image_array(source.path)
|
|
278
|
+
height, width = pixels.shape[:2]
|
|
279
|
+
alpha = pixels[:, :, 3]
|
|
280
|
+
if alpha.min() < 0.5:
|
|
281
|
+
mask = alpha > 0.5
|
|
282
|
+
else:
|
|
283
|
+
border = max(2, int(min(width, height) * BORDER_SAMPLE_FRACTION))
|
|
284
|
+
strips = np.concatenate((pixels[:border, :, :3].reshape(-1, 3), pixels[-border:, :, :3].reshape(-1, 3),
|
|
285
|
+
pixels[:, :border, :3].reshape(-1, 3), pixels[:, -border:, :3].reshape(-1, 3)))
|
|
286
|
+
background = np.median(strips, axis=0)
|
|
287
|
+
background_like = np.abs(pixels[:, :, :3] - background).max(axis=2) <= background_tolerance
|
|
288
|
+
# Only background-colored pixels connected to the image border are background. White logos and
|
|
289
|
+
# numbers on a light backdrop have the backdrop's color too, but they are enclosed by the subject.
|
|
290
|
+
mask = ~(background_like & _connected_to_border(background_like))
|
|
291
|
+
mask = image_utils.dilate_mask(image_utils.erode_mask(mask, 2), 2)
|
|
292
|
+
bbox = _subject_bbox(mask)
|
|
293
|
+
if bbox is None:
|
|
294
|
+
raise RuntimeError(f"no subject found in {source.path}; try a different --ref-bg-tolerance")
|
|
295
|
+
if source.oblique:
|
|
296
|
+
direction = _named_direction(source.named_views)
|
|
297
|
+
quarter_turns = 0
|
|
298
|
+
else:
|
|
299
|
+
direction = np.array(uv_layout.VIEW_DIRECTIONS[source.view], dtype=np.float64)
|
|
300
|
+
if source.view in HORIZONTAL_VIEWS and quarter_turns is None:
|
|
301
|
+
quarter_turns = 0
|
|
302
|
+
return ReferenceImage(view=source.view, path=source.path, pixels=pixels, mask=mask, bbox=bbox,
|
|
303
|
+
quarter_turns=quarter_turns, direction=direction, oblique=source.oblique,
|
|
304
|
+
named_views=source.named_views)
|
|
305
|
+
|
|
306
|
+
|
|
307
|
+
def _named_direction(named_views: tuple) -> np.ndarray:
|
|
308
|
+
"""First-guess camera direction for an angled view: the average of its named views (front if none)."""
|
|
309
|
+
total = np.zeros(3)
|
|
310
|
+
for view in named_views or ("front",):
|
|
311
|
+
total += np.array(uv_layout.VIEW_DIRECTIONS[view], dtype=np.float64)
|
|
312
|
+
if np.linalg.norm(total) < 1e-9:
|
|
313
|
+
total = np.array(uv_layout.VIEW_DIRECTIONS["front"], dtype=np.float64)
|
|
314
|
+
return total / np.linalg.norm(total)
|
|
315
|
+
|
|
316
|
+
|
|
317
|
+
def _connected_to_border(candidates: np.ndarray) -> np.ndarray:
|
|
318
|
+
"""
|
|
319
|
+
Flood-fills from the image border through candidate pixels. Runs on a reduced grid for speed, then
|
|
320
|
+
widens the result by one reduced cell so it reaches every full-resolution edge pixel.
|
|
321
|
+
|
|
322
|
+
:param candidates: Boolean (height, width) pixels the fill may pass through.
|
|
323
|
+
:returns: Boolean (height, width): candidates reachable from the border.
|
|
324
|
+
"""
|
|
325
|
+
height, width = candidates.shape
|
|
326
|
+
factor = max(1, int(round(max(height, width) / FLOOD_GRID_LONG_SIDE)))
|
|
327
|
+
small_height, small_width = max(1, height // factor), max(1, width // factor)
|
|
328
|
+
passable = image_utils.resize_image(candidates.astype(np.float32), small_width, small_height) > 0.5
|
|
329
|
+
reached = np.zeros_like(passable)
|
|
330
|
+
reached[0, :], reached[-1, :], reached[:, 0], reached[:, -1] = passable[0, :], passable[-1, :], \
|
|
331
|
+
passable[:, 0], passable[:, -1]
|
|
332
|
+
while True:
|
|
333
|
+
grown = reached.copy()
|
|
334
|
+
grown[1:, :] |= reached[:-1, :]
|
|
335
|
+
grown[:-1, :] |= reached[1:, :]
|
|
336
|
+
grown[:, 1:] |= reached[:, :-1]
|
|
337
|
+
grown[:, :-1] |= reached[:, 1:]
|
|
338
|
+
grown &= passable
|
|
339
|
+
if np.array_equal(grown, reached):
|
|
340
|
+
break
|
|
341
|
+
reached = grown
|
|
342
|
+
reached = image_utils.dilate_mask(reached, 1)
|
|
343
|
+
full = np.repeat(np.repeat(reached, factor, axis=0), factor, axis=1)
|
|
344
|
+
padded = np.zeros((height, width), dtype=bool)
|
|
345
|
+
padded[:min(height, full.shape[0]), :min(width, full.shape[1])] = full[:height, :width]
|
|
346
|
+
if full.shape[0] < height:
|
|
347
|
+
padded[full.shape[0]:, :] = True
|
|
348
|
+
if full.shape[1] < width:
|
|
349
|
+
padded[:, full.shape[1]:] = True
|
|
350
|
+
return candidates & padded
|
|
351
|
+
|
|
352
|
+
|
|
353
|
+
def _subject_bbox(mask: np.ndarray) -> Optional[tuple]:
|
|
354
|
+
"""Bounding box of the subject, ignoring rows / columns with only a few stray pixels."""
|
|
355
|
+
height, width = mask.shape
|
|
356
|
+
columns = np.flatnonzero(mask.sum(axis=0) >= max(2, height * BBOX_MINIMUM_PIXELS_FRACTION))
|
|
357
|
+
rows = np.flatnonzero(mask.sum(axis=1) >= max(2, width * BBOX_MINIMUM_PIXELS_FRACTION))
|
|
358
|
+
if columns.size == 0 or rows.size == 0:
|
|
359
|
+
return None
|
|
360
|
+
return float(columns[0]), float(rows[0]), float(columns[-1] + 1), float(rows[-1] + 1)
|
|
361
|
+
|
|
362
|
+
|
|
363
|
+
def direction_angles(direction: Optional[np.ndarray]) -> tuple:
|
|
364
|
+
"""Camera yaw (0 = front, 90 = left) and pitch (up positive) in degrees for a view direction."""
|
|
365
|
+
if direction is None:
|
|
366
|
+
return (0.0, 0.0)
|
|
367
|
+
yaw = math.degrees(math.atan2(direction[0], -direction[1]))
|
|
368
|
+
pitch = math.degrees(math.asin(max(-1.0, min(1.0, float(direction[2])))))
|
|
369
|
+
return (yaw, pitch)
|
|
370
|
+
|
|
371
|
+
|
|
372
|
+
def _heading_rotation(model_rotation_degrees: float) -> Optional[np.ndarray]:
|
|
373
|
+
"""Rotation that expresses a view direction in the coordinates of a model not yet turned."""
|
|
374
|
+
if not model_rotation_degrees:
|
|
375
|
+
return None
|
|
376
|
+
angle = math.radians(-model_rotation_degrees)
|
|
377
|
+
return np.array(((math.cos(angle), -math.sin(angle), 0.0), (math.sin(angle), math.cos(angle), 0.0),
|
|
378
|
+
(0.0, 0.0, 1.0)))
|
|
379
|
+
|
|
380
|
+
|
|
381
|
+
def view_coordinates(points: np.ndarray, direction: np.ndarray, quarter_turns: int,
|
|
382
|
+
model_rotation_degrees: float = 0.0) -> np.ndarray:
|
|
383
|
+
"""
|
|
384
|
+
Projects world points orthographically into a view's 2D image plane (meters): x to the image right, y up.
|
|
385
|
+
|
|
386
|
+
:param points: float array (..., 3).
|
|
387
|
+
:param direction: Unit vector from the model toward the camera.
|
|
388
|
+
:param quarter_turns: In-plane rotation of the image, in 90-degree steps.
|
|
389
|
+
:param model_rotation_degrees: Rotation about +Z the model WOULD get before viewing (used to score
|
|
390
|
+
heading candidates without moving the mesh).
|
|
391
|
+
:returns: float array (..., 2).
|
|
392
|
+
"""
|
|
393
|
+
right, up = uv_layout.view_axes(np.asarray(direction, dtype=np.float64))
|
|
394
|
+
rotation = _heading_rotation(model_rotation_degrees)
|
|
395
|
+
if rotation is not None:
|
|
396
|
+
right, up = rotation @ right, rotation @ up
|
|
397
|
+
across = points @ right
|
|
398
|
+
upward = points @ up
|
|
399
|
+
turns = quarter_turns % 4
|
|
400
|
+
if turns == 1:
|
|
401
|
+
across, upward = -upward, across
|
|
402
|
+
elif turns == 2:
|
|
403
|
+
across, upward = -across, -upward
|
|
404
|
+
elif turns == 3:
|
|
405
|
+
across, upward = upward, -across
|
|
406
|
+
return np.stack((across, upward), axis=-1)
|
|
407
|
+
|
|
408
|
+
|
|
409
|
+
def depth_along(points: np.ndarray, direction: np.ndarray, model_rotation_degrees: float = 0.0) -> np.ndarray:
|
|
410
|
+
"""
|
|
411
|
+
Distance of points toward a view's camera; larger is closer.
|
|
412
|
+
|
|
413
|
+
:param points: float array (..., 3).
|
|
414
|
+
:param direction: Unit vector from the model toward the camera.
|
|
415
|
+
:param model_rotation_degrees: As in view_coordinates.
|
|
416
|
+
:returns: float array (...).
|
|
417
|
+
"""
|
|
418
|
+
direction = np.asarray(direction, dtype=np.float64)
|
|
419
|
+
rotation = _heading_rotation(model_rotation_degrees)
|
|
420
|
+
if rotation is not None:
|
|
421
|
+
direction = rotation @ direction
|
|
422
|
+
return points @ direction
|
|
423
|
+
|
|
424
|
+
|
|
425
|
+
def build_view_frame(triangle_positions: np.ndarray, direction: np.ndarray, quarter_turns: int, perspective: float,
|
|
426
|
+
model_rotation_degrees: float = 0.0) -> ViewFrame:
|
|
427
|
+
"""
|
|
428
|
+
Measures how the model projects into a view for a given rotation and perspective strength.
|
|
429
|
+
|
|
430
|
+
:param triangle_positions: float array (count, 3, 3).
|
|
431
|
+
:param direction: Unit vector from the model toward the camera.
|
|
432
|
+
:param quarter_turns: In-plane rotation.
|
|
433
|
+
:param perspective: Perspective strength (see PERSPECTIVE_START).
|
|
434
|
+
:param model_rotation_degrees: Heading candidate, as in view_coordinates.
|
|
435
|
+
:returns: The frame, including the projected extents.
|
|
436
|
+
"""
|
|
437
|
+
return _frame_and_projection(triangle_positions, direction, quarter_turns, perspective, model_rotation_degrees)[0]
|
|
438
|
+
|
|
439
|
+
|
|
440
|
+
def _frame_and_projection(triangle_positions: np.ndarray, direction: np.ndarray, quarter_turns: int,
|
|
441
|
+
perspective: float, model_rotation_degrees: float = 0.0) -> tuple:
|
|
442
|
+
"""
|
|
443
|
+
Builds a view frame and projects the triangles with it in one pass.
|
|
444
|
+
|
|
445
|
+
:returns: (ViewFrame, float array (count, 3, 2) of projected corners in view-plane meters).
|
|
446
|
+
"""
|
|
447
|
+
flat = triangle_positions.reshape(-1, 3)
|
|
448
|
+
orthographic = view_coordinates(flat, direction, quarter_turns, model_rotation_degrees)
|
|
449
|
+
depth = depth_along(flat, direction, model_rotation_degrees)
|
|
450
|
+
center = ((orthographic[:, 0].min() + orthographic[:, 0].max()) / 2.0,
|
|
451
|
+
(orthographic[:, 1].min() + orthographic[:, 1].max()) / 2.0)
|
|
452
|
+
depth_range = (float(depth.max()), float(depth.min()))
|
|
453
|
+
projected = _apply_perspective(orthographic, depth, depth_range, perspective, center)
|
|
454
|
+
frame = ViewFrame(quarter_turns=quarter_turns, perspective=perspective, depth_range=depth_range, center=center,
|
|
455
|
+
extents=(projected[:, 0].min(), projected[:, 0].max(), projected[:, 1].min(),
|
|
456
|
+
projected[:, 1].max()))
|
|
457
|
+
return frame, projected.reshape(triangle_positions.shape[:-1] + (2,))
|
|
458
|
+
|
|
459
|
+
|
|
460
|
+
def project_with_frame(points: np.ndarray, direction: np.ndarray, frame: ViewFrame,
|
|
461
|
+
model_rotation_degrees: float = 0.0) -> np.ndarray:
|
|
462
|
+
"""
|
|
463
|
+
Projects world points into a view with the frame's rotation and perspective: points further from the
|
|
464
|
+
camera are pulled toward the principal point.
|
|
465
|
+
|
|
466
|
+
:param points: float array (..., 3).
|
|
467
|
+
:param direction: Unit vector from the model toward the camera.
|
|
468
|
+
:param frame: The fitted frame.
|
|
469
|
+
:param model_rotation_degrees: Heading candidate, as in view_coordinates.
|
|
470
|
+
:returns: float array (..., 2) in view-plane meters.
|
|
471
|
+
"""
|
|
472
|
+
coordinates = view_coordinates(points, direction, frame.quarter_turns, model_rotation_degrees)
|
|
473
|
+
if frame.perspective <= 0.0:
|
|
474
|
+
return coordinates
|
|
475
|
+
depth = depth_along(points, direction, model_rotation_degrees)
|
|
476
|
+
return _apply_perspective(coordinates, depth, frame.depth_range, frame.perspective, frame.center)
|
|
477
|
+
|
|
478
|
+
|
|
479
|
+
def _apply_perspective(coordinates: np.ndarray, depth: np.ndarray, depth_range: tuple, perspective: float,
|
|
480
|
+
center: tuple) -> np.ndarray:
|
|
481
|
+
"""Pulls projected points toward the principal point the further they are from the camera."""
|
|
482
|
+
if perspective <= 0.0:
|
|
483
|
+
return coordinates
|
|
484
|
+
nearest, farthest = depth_range
|
|
485
|
+
behind = (nearest - depth) / max(nearest - farthest, 1e-12)
|
|
486
|
+
shrink = 1.0 / (1.0 + perspective * np.clip(behind, 0.0, 1.0))
|
|
487
|
+
principal_point = np.array(center)
|
|
488
|
+
return principal_point + (coordinates - principal_point) * shrink[..., None]
|
|
489
|
+
|
|
490
|
+
|
|
491
|
+
def _nominal_mapping(coordinates_2d: np.ndarray, extents: tuple, bbox: tuple) -> np.ndarray:
|
|
492
|
+
"""Maps view-plane coordinates so the model's extents fill the reference subject's bounding box."""
|
|
493
|
+
minimum_x, maximum_x, minimum_y, maximum_y = extents
|
|
494
|
+
x0, y0, x1, y1 = bbox
|
|
495
|
+
pixel_x = x0 + (coordinates_2d[..., 0] - minimum_x) / max(maximum_x - minimum_x, 1e-12) * (x1 - x0)
|
|
496
|
+
pixel_y = y0 + (coordinates_2d[..., 1] - minimum_y) / max(maximum_y - minimum_y, 1e-12) * (y1 - y0)
|
|
497
|
+
return np.stack((pixel_x, pixel_y), axis=-1)
|
|
498
|
+
|
|
499
|
+
|
|
500
|
+
def _apply_refine(pixel_points: np.ndarray, bbox: tuple, refine: tuple) -> np.ndarray:
|
|
501
|
+
"""Scales about the bbox center and shifts by fractions of the bbox size."""
|
|
502
|
+
scale_x, scale_y, offset_x, offset_y = refine
|
|
503
|
+
x0, y0, x1, y1 = bbox
|
|
504
|
+
center_x, center_y = (x0 + x1) / 2.0, (y0 + y1) / 2.0
|
|
505
|
+
refined_x = center_x + (pixel_points[..., 0] - center_x) * scale_x + offset_x * (x1 - x0)
|
|
506
|
+
refined_y = center_y + (pixel_points[..., 1] - center_y) * scale_y + offset_y * (y1 - y0)
|
|
507
|
+
return np.stack((refined_x, refined_y), axis=-1)
|
|
508
|
+
|
|
509
|
+
|
|
510
|
+
def map_to_reference(reference: ReferenceImage, points: np.ndarray) -> np.ndarray:
|
|
511
|
+
"""
|
|
512
|
+
Maps world points of the oriented model to pixel coordinates in a reference image, using the fitted
|
|
513
|
+
alignment.
|
|
514
|
+
|
|
515
|
+
:param reference: An aligned reference (align_reference must have run).
|
|
516
|
+
:param points: float array (..., 3).
|
|
517
|
+
:returns: float array (..., 2) of pixel coordinates, bottom-up.
|
|
518
|
+
"""
|
|
519
|
+
coordinates_2d = project_with_frame(points, reference.direction, reference.frame)
|
|
520
|
+
nominal = _nominal_mapping(coordinates_2d, reference.frame.extents, reference.bbox)
|
|
521
|
+
return _apply_refine(nominal, reference.bbox, reference.refine)
|
|
522
|
+
|
|
523
|
+
|
|
524
|
+
class _ScoreCanvas:
|
|
525
|
+
"""Low-resolution window around a reference's subject, for fast silhouette comparisons."""
|
|
526
|
+
|
|
527
|
+
def __init__(self, reference: ReferenceImage, size: int = SCORE_CANVAS_SIZE):
|
|
528
|
+
x0, y0, x1, y1 = reference.bbox
|
|
529
|
+
margin_x = (x1 - x0) * SCORE_CANVAS_MARGIN
|
|
530
|
+
margin_y = (y1 - y0) * SCORE_CANVAS_MARGIN
|
|
531
|
+
self.reference = reference
|
|
532
|
+
self.origin_x, self.origin_y = x0 - margin_x, y0 - margin_y
|
|
533
|
+
span_x, span_y = (x1 - x0) + 2 * margin_x, (y1 - y0) + 2 * margin_y
|
|
534
|
+
self.pixels_per_unit = size / max(span_x, span_y)
|
|
535
|
+
self.width = max(8, int(round(span_x * self.pixels_per_unit)))
|
|
536
|
+
self.height = max(8, int(round(span_y * self.pixels_per_unit)))
|
|
537
|
+
grid_x, grid_y = np.meshgrid(np.arange(self.width) + 0.5, np.arange(self.height) + 0.5)
|
|
538
|
+
self.grid = np.stack((self.origin_x + grid_x / self.pixels_per_unit,
|
|
539
|
+
self.origin_y + grid_y / self.pixels_per_unit), axis=-1)
|
|
540
|
+
self.identity_mask = self._reference_mask(IDENTITY_REFINE)
|
|
541
|
+
|
|
542
|
+
def mesh_mask(self, pixel_points: np.ndarray) -> np.ndarray:
|
|
543
|
+
"""Rasterizes mesh triangles given in reference pixel coordinates."""
|
|
544
|
+
canvas_points = np.stack(((pixel_points[..., 0] - self.origin_x) * self.pixels_per_unit,
|
|
545
|
+
(pixel_points[..., 1] - self.origin_y) * self.pixels_per_unit), axis=-1)
|
|
546
|
+
return rasterizer.rasterize_mask(canvas_points, self.width, self.height)
|
|
547
|
+
|
|
548
|
+
def overlap(self, mesh_mask: np.ndarray, refine: tuple) -> float:
|
|
549
|
+
"""
|
|
550
|
+
Intersection over union of the mesh silhouette and the reference subject, with the mesh moved by
|
|
551
|
+
`refine`. The mesh stays put; the reference is sampled where the moved mesh would land.
|
|
552
|
+
"""
|
|
553
|
+
reference_mask = self.identity_mask if refine == IDENTITY_REFINE else self._reference_mask(refine)
|
|
554
|
+
union = np.logical_or(mesh_mask, reference_mask).sum()
|
|
555
|
+
return float(np.logical_and(mesh_mask, reference_mask).sum() / max(union, 1))
|
|
556
|
+
|
|
557
|
+
def _reference_mask(self, refine: tuple) -> np.ndarray:
|
|
558
|
+
"""The reference subject sampled on the canvas grid, moved by `refine`."""
|
|
559
|
+
sample_points = _apply_refine(self.grid, self.reference.bbox, refine)
|
|
560
|
+
return image_utils.sample_nearest(self.reference.mask, sample_points[..., 0].ravel(),
|
|
561
|
+
sample_points[..., 1].ravel()).reshape(self.height, self.width)
|
|
562
|
+
|
|
563
|
+
|
|
564
|
+
@dataclass
|
|
565
|
+
class _Pose:
|
|
566
|
+
"""One camera candidate for a reference, and how well the model's silhouette matches from it."""
|
|
567
|
+
|
|
568
|
+
direction: np.ndarray
|
|
569
|
+
quarter_turns: int
|
|
570
|
+
perspective: float
|
|
571
|
+
score: float = -1.0
|
|
572
|
+
|
|
573
|
+
|
|
574
|
+
class _PoseScorer:
|
|
575
|
+
"""Scores camera candidates for one reference on the silhouette stand-in mesh."""
|
|
576
|
+
|
|
577
|
+
def __init__(self, reference: ReferenceImage, proxy_positions: np.ndarray, canvas_size: int):
|
|
578
|
+
self.reference = reference
|
|
579
|
+
self.triangles = proxy_positions
|
|
580
|
+
self.canvas = _ScoreCanvas(reference, canvas_size)
|
|
581
|
+
|
|
582
|
+
def score(self, direction: np.ndarray, quarter_turns: int, perspective: float,
|
|
583
|
+
model_rotation_degrees: float = 0.0) -> float:
|
|
584
|
+
"""
|
|
585
|
+
Silhouette overlap of the model seen from a camera candidate, with the model's projected extents
|
|
586
|
+
stretched onto the subject's bounding box, discounted when that stretch changes the shape's aspect.
|
|
587
|
+
|
|
588
|
+
:returns: Score in 0..1; higher is a better match.
|
|
589
|
+
"""
|
|
590
|
+
frame, projected = _frame_and_projection(self.triangles, direction, quarter_turns, perspective,
|
|
591
|
+
model_rotation_degrees)
|
|
592
|
+
mesh_mask = self.canvas.mesh_mask(_nominal_mapping(projected, frame.extents, self.reference.bbox))
|
|
593
|
+
return self.canvas.overlap(mesh_mask, IDENTITY_REFINE) * _aspect_agreement(frame, self.reference.bbox) ** 0.25
|
|
594
|
+
|
|
595
|
+
def evaluate(self, pose: _Pose) -> _Pose:
|
|
596
|
+
"""Scores a pose in place and returns it."""
|
|
597
|
+
pose.score = self.score(pose.direction, pose.quarter_turns, pose.perspective)
|
|
598
|
+
return pose
|
|
599
|
+
|
|
600
|
+
|
|
601
|
+
def _aspect_agreement(frame: ViewFrame, bbox: tuple) -> float:
|
|
602
|
+
"""1.0 when the projected model and the subject have the same width-to-height ratio, lower otherwise."""
|
|
603
|
+
model_aspect = (frame.extents[1] - frame.extents[0]) / max(frame.extents[3] - frame.extents[2], 1e-12)
|
|
604
|
+
x0, y0, x1, y1 = bbox
|
|
605
|
+
image_aspect = (x1 - x0) / max(y1 - y0, 1e-12)
|
|
606
|
+
return min(model_aspect, image_aspect) / max(model_aspect, image_aspect)
|
|
607
|
+
|
|
608
|
+
|
|
609
|
+
def _search_refine(canvas: _ScoreCanvas, mesh_mask: np.ndarray) -> tuple:
|
|
610
|
+
"""
|
|
611
|
+
Finds small scale and offset corrections by coordinate search: each of scale x, scale y, offset x and
|
|
612
|
+
offset y is stepped either way while that helps, and the steps shrink until they reach their last size.
|
|
613
|
+
|
|
614
|
+
:returns: (best iou, best refine tuple).
|
|
615
|
+
"""
|
|
616
|
+
values = list(IDENTITY_REFINE)
|
|
617
|
+
best_iou = canvas.overlap(mesh_mask, IDENTITY_REFINE)
|
|
618
|
+
steps = [first for first, _ in REFINE_STEPS]
|
|
619
|
+
while any(step >= last for step, (_, last) in zip(steps, REFINE_STEPS)):
|
|
620
|
+
for index, (_, last) in enumerate(REFINE_STEPS):
|
|
621
|
+
if steps[index] < last:
|
|
622
|
+
continue
|
|
623
|
+
improved = False
|
|
624
|
+
for direction in (1.0, -1.0):
|
|
625
|
+
candidate = list(values)
|
|
626
|
+
candidate[index] += direction * steps[index]
|
|
627
|
+
if abs(candidate[index] - IDENTITY_REFINE[index]) > REFINE_LIMITS[index] + 1e-9:
|
|
628
|
+
continue
|
|
629
|
+
candidate_iou = canvas.overlap(mesh_mask, tuple(candidate))
|
|
630
|
+
if candidate_iou > best_iou + 1e-6:
|
|
631
|
+
values, best_iou, improved = candidate, candidate_iou, True
|
|
632
|
+
break
|
|
633
|
+
if not improved:
|
|
634
|
+
steps[index] /= 2.0
|
|
635
|
+
return best_iou, tuple(values)
|
|
636
|
+
|
|
637
|
+
|
|
638
|
+
def _quarter_turn_candidates(reference: ReferenceImage) -> list:
|
|
639
|
+
"""The in-plane rotations worth testing for a reference."""
|
|
640
|
+
return [reference.quarter_turns] if reference.quarter_turns is not None else [0, 1, 2, 3]
|
|
641
|
+
|
|
642
|
+
|
|
643
|
+
def camera_direction(yaw_degrees: float, pitch_degrees: float) -> np.ndarray:
|
|
644
|
+
"""
|
|
645
|
+
Unit vector from the model toward a camera, in the oriented model frame.
|
|
646
|
+
|
|
647
|
+
:param yaw_degrees: 0 = in front, 90 = on the model's left, 180 = behind, -90 = on its right.
|
|
648
|
+
:param pitch_degrees: Height above the horizon; 90 = straight above.
|
|
649
|
+
:returns: float64 3-vector.
|
|
650
|
+
"""
|
|
651
|
+
yaw, pitch = math.radians(yaw_degrees), math.radians(pitch_degrees)
|
|
652
|
+
return np.array((math.sin(yaw) * math.cos(pitch), -math.cos(yaw) * math.cos(pitch), math.sin(pitch)))
|
|
653
|
+
|
|
654
|
+
|
|
655
|
+
def tilt_direction(direction: np.ndarray, across_degrees: float, up_degrees: float) -> np.ndarray:
|
|
656
|
+
"""
|
|
657
|
+
Moves a camera direction by small angles along its own image axes: `across` toward the image's right,
|
|
658
|
+
`up` toward the image's top. Used to search around a named or coarse camera direction.
|
|
659
|
+
|
|
660
|
+
:returns: Unit float64 3-vector.
|
|
661
|
+
"""
|
|
662
|
+
right, up = uv_layout.view_axes(np.asarray(direction, dtype=np.float64))
|
|
663
|
+
tilted = direction + right * math.tan(math.radians(across_degrees)) + up * math.tan(math.radians(up_degrees))
|
|
664
|
+
return tilted / np.linalg.norm(tilted)
|
|
665
|
+
|
|
666
|
+
|
|
667
|
+
def _angle_between(first: np.ndarray, second: np.ndarray) -> float:
|
|
668
|
+
"""Angle between two unit vectors, in degrees."""
|
|
669
|
+
return math.degrees(math.acos(float(np.clip(np.dot(first, second), -1.0, 1.0))))
|
|
670
|
+
|
|
671
|
+
|
|
672
|
+
def _pattern_search(scorer: _PoseScorer, start: _Pose, tilt_limit: float, steps: tuple) -> _Pose:
|
|
673
|
+
"""
|
|
674
|
+
Refines a camera candidate by compass search over its two tilt angles and its perspective strength:
|
|
675
|
+
tries a step either way along each, moves as soon as one helps, and halves the step when none does.
|
|
676
|
+
|
|
677
|
+
:param scorer: Scores poses for the reference.
|
|
678
|
+
:param start: Starting pose (scored here); tilts are measured from its direction.
|
|
679
|
+
:param tilt_limit: Largest total tilt from the start, degrees (0 searches perspective only).
|
|
680
|
+
:param steps: (first, last) step in degrees.
|
|
681
|
+
:returns: The best pose found.
|
|
682
|
+
"""
|
|
683
|
+
best = scorer.evaluate(_Pose(start.direction, start.quarter_turns, start.perspective))
|
|
684
|
+
across = up = 0.0
|
|
685
|
+
step, last_step = steps
|
|
686
|
+
while step >= last_step - 1e-9:
|
|
687
|
+
improved = False
|
|
688
|
+
perspective_step = step * PERSPECTIVE_PER_DEGREE
|
|
689
|
+
for across_change, up_change, perspective_change in ((step, 0.0, 0.0), (-step, 0.0, 0.0), (0.0, step, 0.0),
|
|
690
|
+
(0.0, -step, 0.0), (0.0, 0.0, perspective_step),
|
|
691
|
+
(0.0, 0.0, -perspective_step)):
|
|
692
|
+
candidate_across, candidate_up = across + across_change, up + up_change
|
|
693
|
+
perspective = best.perspective + perspective_change
|
|
694
|
+
if math.hypot(candidate_across, candidate_up) > tilt_limit + 1e-9:
|
|
695
|
+
continue
|
|
696
|
+
if not 0.0 <= perspective <= PERSPECTIVE_LIMIT:
|
|
697
|
+
continue
|
|
698
|
+
candidate = scorer.evaluate(_Pose(tilt_direction(start.direction, candidate_across, candidate_up),
|
|
699
|
+
best.quarter_turns, perspective))
|
|
700
|
+
if candidate.score > best.score + 1e-6:
|
|
701
|
+
best, across, up, improved = candidate, candidate_across, candidate_up, True
|
|
702
|
+
break
|
|
703
|
+
if not improved:
|
|
704
|
+
step /= 2.0
|
|
705
|
+
return best
|
|
706
|
+
|
|
707
|
+
|
|
708
|
+
def _refine_pose(reference: ReferenceImage, proxies: "SilhouetteProxies", start: _Pose, tilt_limit: float) -> _Pose:
|
|
709
|
+
"""Compass-searches a pose on the small canvas, then finishes on the full canvas."""
|
|
710
|
+
coarse = _pattern_search(_PoseScorer(reference, proxies.coarse, COARSE_CANVAS_SIZE), start, tilt_limit,
|
|
711
|
+
COARSE_PATTERN_STEPS)
|
|
712
|
+
# The full-canvas pass only polishes: it may move a little around the small-canvas result.
|
|
713
|
+
fine_limit = 0.0 if tilt_limit == 0.0 else FINE_PATTERN_STEPS[0] * 2.0
|
|
714
|
+
return _pattern_search(_PoseScorer(reference, proxies.fine, SCORE_CANVAS_SIZE), coarse, fine_limit,
|
|
715
|
+
FINE_PATTERN_STEPS)
|
|
716
|
+
|
|
717
|
+
|
|
718
|
+
def _solve_straight_camera(reference: ReferenceImage, proxies: "SilhouetteProxies") -> _Pose:
|
|
719
|
+
"""
|
|
720
|
+
Fits a straight view's camera: the in-plane rotation (top / bottom views), the perspective strength,
|
|
721
|
+
and a small tilt off the named axis, kept only when it clearly matches the silhouette better.
|
|
722
|
+
"""
|
|
723
|
+
named = np.asarray(reference.direction, dtype=np.float64)
|
|
724
|
+
turn_scorer = _PoseScorer(reference, proxies.coarse, COARSE_CANVAS_SIZE)
|
|
725
|
+
starts = [turn_scorer.evaluate(_Pose(named, turns, PERSPECTIVE_START)) for turns in _quarter_turn_candidates(reference)]
|
|
726
|
+
tilted = _refine_pose(reference, proxies, max(starts, key=lambda pose: pose.score), STRAIGHT_TILT_LIMIT)
|
|
727
|
+
# The named axis with the tilted fit's perspective, polished: the yardstick the tilt must clearly beat.
|
|
728
|
+
upright = _pattern_search(_PoseScorer(reference, proxies.fine, SCORE_CANVAS_SIZE),
|
|
729
|
+
_Pose(named, tilted.quarter_turns, tilted.perspective), 0.0, FINE_PATTERN_STEPS)
|
|
730
|
+
return tilted if tilted.score >= upright.score + STRAIGHT_TILT_MINIMUM_GAIN else upright
|
|
731
|
+
|
|
732
|
+
|
|
733
|
+
def _solve_oblique_camera(reference: ReferenceImage, proxies: "SilhouetteProxies") -> _Pose:
|
|
734
|
+
"""
|
|
735
|
+
Finds an angled view's camera: a coarse yaw / pitch grid on a small canvas (yaw kept to the front or
|
|
736
|
+
rear half when the file name says which; left and right are always searched, because names often give
|
|
737
|
+
them from the viewer's side), then the best few starts refined.
|
|
738
|
+
"""
|
|
739
|
+
coarse = _PoseScorer(reference, proxies.coarse, COARSE_CANVAS_SIZE)
|
|
740
|
+
candidates = [coarse.evaluate(_Pose(camera_direction(yaw, pitch), 0, PERSPECTIVE_START))
|
|
741
|
+
for yaw in _oblique_yaw_candidates(reference.named_views)
|
|
742
|
+
for pitch in _oblique_pitch_candidates(reference.named_views)]
|
|
743
|
+
candidates.sort(key=lambda pose: pose.score, reverse=True)
|
|
744
|
+
starts = []
|
|
745
|
+
for candidate in candidates:
|
|
746
|
+
if all(_angle_between(candidate.direction, chosen.direction) >= OBLIQUE_DISTINCT_DEGREES for chosen in starts):
|
|
747
|
+
starts.append(candidate)
|
|
748
|
+
if len(starts) == OBLIQUE_STARTS:
|
|
749
|
+
break
|
|
750
|
+
refined = [_refine_pose(reference, proxies, start, OBLIQUE_TILT_LIMIT) for start in starts]
|
|
751
|
+
return max(refined, key=lambda pose: pose.score)
|
|
752
|
+
|
|
753
|
+
|
|
754
|
+
def _oblique_yaw_candidates(named_views: tuple) -> np.ndarray:
|
|
755
|
+
"""Coarse camera yaws for an angled view: the named front or rear half, or all the way round."""
|
|
756
|
+
if "front" in named_views or "rear" in named_views:
|
|
757
|
+
center = 0.0 if "front" in named_views else 180.0
|
|
758
|
+
steps = int(OBLIQUE_FRONT_REAR_WINDOW // OBLIQUE_YAW_STEP)
|
|
759
|
+
return center + OBLIQUE_YAW_STEP * np.arange(-steps, steps + 1)
|
|
760
|
+
return np.arange(-180.0, 180.0, OBLIQUE_YAW_STEP)
|
|
761
|
+
|
|
762
|
+
|
|
763
|
+
def _oblique_pitch_candidates(named_views: tuple) -> tuple:
|
|
764
|
+
"""Coarse camera pitches for an angled view: from above when named 'top', from below when 'bottom'."""
|
|
765
|
+
if "top" in named_views:
|
|
766
|
+
return OBLIQUE_PITCH_STEPS["top"]
|
|
767
|
+
if "bottom" in named_views:
|
|
768
|
+
return OBLIQUE_PITCH_STEPS["bottom"]
|
|
769
|
+
return OBLIQUE_PITCH_STEPS["level"]
|
|
770
|
+
|
|
771
|
+
|
|
772
|
+
def compass_name(direction: np.ndarray) -> str:
|
|
773
|
+
"""Name of the side a camera looks from: front, front_left, left ... (top_ / bottom_ prefix when steep)."""
|
|
774
|
+
yaw, pitch = direction_angles(direction)
|
|
775
|
+
nearest = min(COMPASS_NAMES, key=lambda entry: abs((yaw - entry[0] + 180.0) % 360.0 - 180.0))[1]
|
|
776
|
+
if pitch >= 50.0:
|
|
777
|
+
return f"top_{nearest}"
|
|
778
|
+
if pitch <= -50.0:
|
|
779
|
+
return f"bottom_{nearest}"
|
|
780
|
+
return nearest
|
|
781
|
+
|
|
782
|
+
|
|
783
|
+
@dataclass
|
|
784
|
+
class SilhouetteProxies:
|
|
785
|
+
"""Stand-in meshes for scoring silhouettes: one for the small search canvas, one for the full canvas."""
|
|
786
|
+
|
|
787
|
+
coarse: np.ndarray # float array (count, 3, 3)
|
|
788
|
+
fine: np.ndarray
|
|
789
|
+
|
|
790
|
+
|
|
791
|
+
def build_silhouette_proxies(triangle_positions: np.ndarray) -> SilhouetteProxies:
|
|
792
|
+
"""
|
|
793
|
+
Builds the stand-ins used to score silhouettes quickly at any mesh size.
|
|
794
|
+
|
|
795
|
+
:param triangle_positions: float array (count, 3, 3) of the model.
|
|
796
|
+
:returns: Coarse and fine stand-ins (the model itself when it is already small).
|
|
797
|
+
"""
|
|
798
|
+
return SilhouetteProxies(coarse=_cluster_vertices(triangle_positions, COARSE_PROXY_CELLS),
|
|
799
|
+
fine=_cluster_vertices(triangle_positions, FINE_PROXY_CELLS))
|
|
800
|
+
|
|
801
|
+
|
|
802
|
+
def _cluster_vertices(triangle_positions: np.ndarray, cells_across: int) -> np.ndarray:
|
|
803
|
+
"""
|
|
804
|
+
Snaps every vertex to a grid of `cells_across` cells along the model's diagonal (averaging the corners in
|
|
805
|
+
a cell) and drops the triangles that collapse: a hole-free silhouette stand-in of bounded size.
|
|
806
|
+
Meshes under PROXY_MINIMUM_TRIANGLES are returned unchanged.
|
|
807
|
+
|
|
808
|
+
:param triangle_positions: float array (count, 3, 3).
|
|
809
|
+
:param cells_across: Grid cells across the diagonal.
|
|
810
|
+
:returns: float array (proxy_count, 3, 3).
|
|
811
|
+
"""
|
|
812
|
+
if triangle_positions.shape[0] <= PROXY_MINIMUM_TRIANGLES:
|
|
813
|
+
return triangle_positions
|
|
814
|
+
corners = triangle_positions.reshape(-1, 3)
|
|
815
|
+
minimum = corners.min(axis=0)
|
|
816
|
+
cell = float(np.linalg.norm(corners.max(axis=0) - minimum)) / cells_across
|
|
817
|
+
grid = np.floor((corners - minimum) / max(cell, 1e-12)).astype(np.int64)
|
|
818
|
+
span = grid.max(axis=0) + 1
|
|
819
|
+
cell_keys = (grid[:, 0] * span[1] + grid[:, 1]) * span[2] + grid[:, 2]
|
|
820
|
+
unique_cells, corner_cluster = np.unique(cell_keys, return_inverse=True)
|
|
821
|
+
members = np.bincount(corner_cluster)
|
|
822
|
+
representative = np.stack([np.bincount(corner_cluster, weights=corners[:, axis]) for axis in range(3)],
|
|
823
|
+
axis=1) / members[:, None]
|
|
824
|
+
clusters = corner_cluster.reshape(-1, 3)
|
|
825
|
+
whole = (clusters[:, 0] != clusters[:, 1]) & (clusters[:, 1] != clusters[:, 2]) & (clusters[:, 0] != clusters[:, 2])
|
|
826
|
+
clusters = np.sort(clusters[whole], axis=1)
|
|
827
|
+
cluster_count = unique_cells.size
|
|
828
|
+
triangle_keys = (clusters[:, 0] * cluster_count + clusters[:, 1]) * cluster_count + clusters[:, 2]
|
|
829
|
+
_, first = np.unique(triangle_keys, return_index=True)
|
|
830
|
+
return representative[clusters[first]]
|
|
831
|
+
|
|
832
|
+
|
|
833
|
+
def detect_forward(references: list, triangle_positions: np.ndarray) -> tuple:
|
|
834
|
+
"""
|
|
835
|
+
Works out which horizontal axis the model's front faces by fitting its silhouette into every straight
|
|
836
|
+
reference under each of the four possible headings. The side views settle front versus back; the front /
|
|
837
|
+
rear views versus the sides settle which axis is the long one. Angled views are not used: their camera
|
|
838
|
+
direction is itself solved against the heading.
|
|
839
|
+
|
|
840
|
+
:param references: Loaded references.
|
|
841
|
+
:param triangle_positions: float array (count, 3, 3) of the model as imported.
|
|
842
|
+
:returns: (forward axis name '+x' / '-x' / '+y' / '-y', dict of score per axis); ('keep', {}) when
|
|
843
|
+
there is no straight reference.
|
|
844
|
+
"""
|
|
845
|
+
straight = [reference for reference in references if not reference.oblique]
|
|
846
|
+
if not straight:
|
|
847
|
+
return "keep", {}
|
|
848
|
+
proxy = _cluster_vertices(triangle_positions, COARSE_PROXY_CELLS)
|
|
849
|
+
scorers = [_PoseScorer(reference, proxy, COARSE_CANVAS_SIZE) for reference in straight]
|
|
850
|
+
scores = {}
|
|
851
|
+
for axis, rotation_degrees in mesh_tools.FORWARD_ROTATION_DEGREES.items():
|
|
852
|
+
per_reference = []
|
|
853
|
+
for scorer in scorers:
|
|
854
|
+
reference = scorer.reference
|
|
855
|
+
per_reference.append(max(scorer.score(reference.direction, turns, perspective, rotation_degrees)
|
|
856
|
+
for turns in _quarter_turn_candidates(reference) for perspective in (0.0, 0.3)))
|
|
857
|
+
scores[axis] = float(np.mean(per_reference))
|
|
858
|
+
forward = max(scores, key=scores.get)
|
|
859
|
+
return forward, {axis: round(score, 3) for axis, score in scores.items()}
|
|
860
|
+
|
|
861
|
+
|
|
862
|
+
def align_reference(reference: ReferenceImage, triangle_positions: np.ndarray, refine: bool, minimum_iou: float,
|
|
863
|
+
proxies: Optional[SilhouetteProxies] = None) -> None:
|
|
864
|
+
"""
|
|
865
|
+
Fits a reference's camera to the oriented model: its direction (a small tilt for a straight view, a full
|
|
866
|
+
search for an angled one), in-plane rotation (top / bottom), perspective strength, and optionally small
|
|
867
|
+
scale and offset corrections; then decides whether the image is trustworthy enough to paint with.
|
|
868
|
+
|
|
869
|
+
:param reference: A loaded reference; updated in place (direction, frame, refine, iou, used, note).
|
|
870
|
+
:param triangle_positions: float array (count, 3, 3) of the oriented model.
|
|
871
|
+
:param refine: Search scale / offset corrections as well (absorbs AI-drawn proportions).
|
|
872
|
+
:param minimum_iou: References matching worse than this are not used.
|
|
873
|
+
:param proxies: Silhouette stand-ins of the same model (build_silhouette_proxies); built when omitted.
|
|
874
|
+
"""
|
|
875
|
+
proxies = proxies if proxies is not None else build_silhouette_proxies(triangle_positions)
|
|
876
|
+
if reference.oblique:
|
|
877
|
+
pose = _solve_oblique_camera(reference, proxies)
|
|
878
|
+
else:
|
|
879
|
+
named = np.asarray(reference.direction, dtype=np.float64)
|
|
880
|
+
pose = _solve_straight_camera(reference, proxies)
|
|
881
|
+
reference.camera_tilt = _angle_between(named, pose.direction)
|
|
882
|
+
reference.direction = pose.direction
|
|
883
|
+
reference.frame = build_view_frame(triangle_positions, pose.direction, pose.quarter_turns, pose.perspective)
|
|
884
|
+
|
|
885
|
+
canvas = _ScoreCanvas(reference)
|
|
886
|
+
projected = project_with_frame(triangle_positions, pose.direction, reference.frame)
|
|
887
|
+
mesh_mask = canvas.mesh_mask(_nominal_mapping(projected, reference.frame.extents, reference.bbox))
|
|
888
|
+
iou, refine_values = canvas.overlap(mesh_mask, IDENTITY_REFINE), IDENTITY_REFINE
|
|
889
|
+
if refine:
|
|
890
|
+
iou, refine_values = _search_refine(canvas, mesh_mask)
|
|
891
|
+
reference.iou = iou
|
|
892
|
+
reference.refine = tuple(float(value) for value in refine_values)
|
|
893
|
+
reference.used = reference.iou >= minimum_iou
|
|
894
|
+
if not reference.used:
|
|
895
|
+
reference.note = (f"silhouette match {reference.iou:.2f} is below --ref-min-iou {minimum_iou:.2f}; "
|
|
896
|
+
"the image does not line up with the model")
|
|
897
|
+
|
|
898
|
+
|
|
899
|
+
def settle_oblique_views(references: list) -> list:
|
|
900
|
+
"""
|
|
901
|
+
Gives every aligned angled view a name from where its camera really is (front_left, rear_right ...),
|
|
902
|
+
noting when that disagrees with its file name, and drops an angled view whose camera nearly repeats a
|
|
903
|
+
better-matching view's.
|
|
904
|
+
|
|
905
|
+
:param references: Aligned references; updated in place.
|
|
906
|
+
:returns: Notes for the report.
|
|
907
|
+
"""
|
|
908
|
+
notes = []
|
|
909
|
+
taken = {reference.view for reference in references if not reference.oblique}
|
|
910
|
+
for reference in sorted([reference for reference in references if reference.oblique], key=lambda item: -item.iou):
|
|
911
|
+
yaw, pitch = direction_angles(reference.direction)
|
|
912
|
+
name = compass_name(reference.direction)
|
|
913
|
+
if reference.named_views and not set(reference.named_views) <= set(name.split("_")):
|
|
914
|
+
notes.append(f"{os.path.basename(reference.path)}: named {'_'.join(reference.named_views)}, but its "
|
|
915
|
+
f"camera is at the model's {name} (yaw {yaw:.0f}, pitch {pitch:.0f}); file names often "
|
|
916
|
+
f"give left / right from the viewer's side")
|
|
917
|
+
unique_name, number = name, 2
|
|
918
|
+
while unique_name in taken:
|
|
919
|
+
unique_name, number = f"{name}_{number}", number + 1
|
|
920
|
+
reference.view = unique_name
|
|
921
|
+
taken.add(unique_name)
|
|
922
|
+
if not reference.used:
|
|
923
|
+
continue
|
|
924
|
+
for other in references:
|
|
925
|
+
if other is reference or not other.used or other.iou < reference.iou:
|
|
926
|
+
continue
|
|
927
|
+
if _angle_between(other.direction, reference.direction) < OBLIQUE_DUPLICATE_DEGREES:
|
|
928
|
+
reference.used = False
|
|
929
|
+
reference.note = f"its camera nearly repeats the {other.view} view, which matches better"
|
|
930
|
+
break
|
|
931
|
+
return notes
|
|
932
|
+
|
|
933
|
+
|
|
934
|
+
def build_depth_buffer(reference: ReferenceImage, triangle_positions: np.ndarray) -> None:
|
|
935
|
+
"""
|
|
936
|
+
Renders the oriented model's nearest-surface depth into the reference's pixel grid, so texels hidden
|
|
937
|
+
behind other parts in that view are not painted from it.
|
|
938
|
+
|
|
939
|
+
:param reference: An aligned reference; its depth buffer is stored on it.
|
|
940
|
+
:param triangle_positions: float array (count, 3, 3) of the oriented model.
|
|
941
|
+
"""
|
|
942
|
+
height, width = reference.mask.shape
|
|
943
|
+
pixel_points = map_to_reference(reference, triangle_positions)
|
|
944
|
+
triangle_depth = depth_along(triangle_positions, reference.direction)
|
|
945
|
+
reference.depth = rasterizer.rasterize_depth(pixel_points, triangle_depth, width, height)
|