TianhangCheng7 commited on
Commit
46f479f
·
verified ·
1 Parent(s): d7a11dc

gather gt from full dataset (part 3)

Browse files
Files changed (3) hide show
  1. README.md +51 -8
  2. build_gt_from_3dfront.py +396 -0
  3. gt_3dfront_summary.json +0 -0
README.md CHANGED
@@ -15,16 +15,27 @@ tags:
15
  20 indoor scenes rendered from [3D-FRONT](https://tianchi.aliyun.com/specials/promotion/alibaba-3d-scene-dataset).
16
  Each scene is one RGB view with metric depth, an empty-room depth map, ground-truth object
17
  meshes, and per-object 3D boxes — for single-image 3D scene reconstruction and evaluation.
18
- ~305 MiB.
 
 
19
 
20
  ```
21
- <index>/ # e.g. 3025, index06 = 003025
22
- ├── rgb_<index06>.jpeg # 1296x968 RGB
23
- ├── depth_<index06>.npy # (968, 1296) float64, metric z-depth
24
- ├── bgdepth_<index06>.npy # (484, 648) float64, depth of the empty room (half res)
25
- ├── annotation_<index06>.json # intrinsics, extrinsics, per-object boxes + labels
26
- ── sceneobjgt_<index06>.ply # GT object meshes, OpenCV camera frame
27
- lift_3d_pcd.py # reference loader: depth -> point cloud, + viewer
 
 
 
 
 
 
 
 
 
28
  ```
29
 
30
  Scenes: `3025 3084 3126 3200 3266 3277 3376 3392 3401 3431 3454 3477 3844 3847 3966 4033 4087 4091 4124 4135`
@@ -62,6 +73,38 @@ Each `obj_dict` entry has `label` / `cls_id`, `obj_id` / `model_file_name`,
62
  `obj_tran` / `obj_rot` (local→world) / `obj_scale`, `bbox3d_world` (3, 8) corners,
63
  `bbox3d_world_center` + `half_length`, `bbox3d_camera`, the 2D boxes, and `occ_iou`.
64
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
65
  ## Point clouds and visualization
66
 
67
  `lift_3d_pcd.py` sits in the dataset root and finds the scenes next to itself, so it runs
 
15
  20 indoor scenes rendered from [3D-FRONT](https://tianchi.aliyun.com/specials/promotion/alibaba-3d-scene-dataset).
16
  Each scene is one RGB view with metric depth, an empty-room depth map, ground-truth object
17
  meshes, and per-object 3D boxes — for single-image 3D scene reconstruction and evaluation.
18
+ 19 of the 20 scenes additionally ship a **full-resolution instance mask** and **complete
19
+ per-object / whole-scene meshes** recovered from the source 3D-FRONT room (see
20
+ [Instance-level GT](#instance-level-gt-from-3d-front)). ~305 MiB.
21
 
22
  ```
23
+ <index>/ # e.g. 3025, index06 = 003025
24
+ ├── rgb_<index06>.jpeg # 1296x968 RGB
25
+ ├── depth_<index06>.npy # (968, 1296) float64, metric z-depth
26
+ ├── bgdepth_<index06>.npy # (484, 648) float64, depth of the empty room (half res)
27
+ ├── annotation_<index06>.json # intrinsics, extrinsics, per-object boxes + labels
28
+ ── sceneobjgt_<index06>.ply # partial GT object meshes (as shipped), OpenCV camera frame
29
+
30
+ │ # instance-level GT aligned from 3D-FRONT (19/20 scenes; absent for 3966):
31
+ ├── instance_<index06>.png # (968, 1296) uint16 instance-id mask (0 = background)
32
+ ├── instance_<index06>.json # id -> {label, obj_id, model_uuid, n_pixels, ...} + match/similarity
33
+ ├── instance_overlay_<index06>.png # RGB with the coloured mask blended in, for eyeballing
34
+ ├── sceneobjfull_<index06>.ply # all objects merged, OpenCV camera frame
35
+ └── objects_<index06>/ # per-object meshes: <instid:03d>_<label>.ply
36
+ lift_3d_pcd.py # reference loader: depth -> point cloud, + viewer
37
+ build_gt_from_3dfront.py # regenerates the instance-level GT from 3D-FRONT
38
+ gt_3dfront_summary.json # per-scene match report (room, depth-agreement stats)
39
  ```
40
 
41
  Scenes: `3025 3084 3126 3200 3266 3277 3376 3392 3401 3431 3454 3477 3844 3847 3966 4033 4087 4091 4124 4135`
 
73
  `obj_tran` / `obj_rot` (local→world) / `obj_scale`, `bbox3d_world` (3, 8) corners,
74
  `bbox3d_world_center` + `half_length`, `bbox3d_camera`, the 2D boxes, and `occ_iou`.
75
 
76
+ ## Instance-level GT (from 3D-FRONT)
77
+
78
+ Because `single_image` is a subset of 3D-FRONT, each view is re-aligned to its source
79
+ 3D-FRONT room to recover a **complete** instance mask and object meshes (the shipped
80
+ `sceneobjgt_*.ply` is only a partial merge). `build_gt_from_3dfront.py` does this:
81
+
82
+ 1. index each furniture model UUID → the 3D-FRONT rooms containing it (from the
83
+ `*_full.glb` scene graphs);
84
+ 2. shortlist rooms whose models cover the annotation and RANSAC-fit the glb→world
85
+ similarity transform from object-centroid correspondences;
86
+ 3. disambiguate the room by ray-casting the placed objects through the annotation
87
+ intrinsics and comparing the rendered z-depth against the metric `depth`;
88
+ 4. write the outputs above into the scene folder.
89
+
90
+ Objects only — walls / floor / ceiling are excluded. The meshes are in the **OpenCV**
91
+ camera frame (same as `sceneobjgt_*` / the lifted cloud), so `sceneobjfull_*.ply` overlays
92
+ `depth` directly. `instance_*.png` is full resolution and aligned to `rgb_*`; ids `1..N`
93
+ index the `objects_<index06>/` meshes and the `instances` list in `instance_*.json`.
94
+
95
+ Coverage: **19/20 scenes** align to < 1.5 mm median depth error (> 87 % of object pixels
96
+ within 5 mm; see `gt_3dfront_summary.json`). **3966 is intentionally omitted** — its
97
+ objects are near-coplanar (six identical chairs) so the room could not be recovered
98
+ reliably; it keeps only the originally shipped files.
99
+
100
+ Regenerate (needs `pip install trimesh embreex pillow`; uses a model-UUID index built from
101
+ the local 3D-FRONT copy):
102
+
103
+ ```bash
104
+ python build_gt_from_3dfront.py # all scenes
105
+ python build_gt_from_3dfront.py --scenes 3025 # one scene
106
+ ```
107
+
108
  ## Point clouds and visualization
109
 
110
  `lift_3d_pcd.py` sits in the dataset root and finds the scenes next to itself, so it runs
build_gt_from_3dfront.py ADDED
@@ -0,0 +1,396 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python
2
+ """Build per-view GT (instance mask + object meshes) for the Fire3D single_image
3
+ scenes by aligning the source 3D-FRONT room to each annotation and ray-casting it
4
+ into the annotation camera.
5
+
6
+ Pipeline per scene (see the discussion in the task):
7
+ 1. shortlist candidate 3D-FRONT rooms whose furniture-model UUID set covers the
8
+ annotation's objects (index built from the ``*_full.glb`` scene graphs);
9
+ 2. estimate the glb->annotation-world similarity transform with a RANSAC over
10
+ per-model candidate matches (robust to duplicate models / extra room objects);
11
+ 3. for the top-K candidates, ray-cast the placed room objects through the
12
+ annotation intrinsics and keep the room whose rendered depth best agrees with
13
+ the dataset metric depth;
14
+ 4. write outputs: uint16 instance mask (full-res, aligned to rgb), id->object
15
+ json, per-object meshes (PLY, OpenCV camera frame = the sceneobjgt frame),
16
+ merged scene-objects mesh, and an rgb overlay for eyeballing the match.
17
+
18
+ Objects only: walls / floor / ceiling are intentionally skipped.
19
+ """
20
+ from __future__ import annotations
21
+
22
+ import argparse
23
+ import glob
24
+ import json
25
+ import os
26
+ import re
27
+ import warnings
28
+ from itertools import combinations, product
29
+ from typing import Any
30
+
31
+ import numpy as np
32
+ import trimesh
33
+ from PIL import Image
34
+
35
+ warnings.filterwarnings("ignore")
36
+
37
+ UUID_RE = re.compile(r"([0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12})")
38
+ SCENE_ROOT = "/mnt/task_runtime/3d-front/3D-FRONT-SCENE"
39
+ SI_ROOT = "/mnt/task_runtime/data/single_image"
40
+ CV2GL = np.diag([1.0, -1.0, -1.0]) # OpenCV cam <-> OpenGL cam
41
+ CANONICAL_R = np.array([[1.0, 0, 0], [0, 0, -1.0], [0, 1.0, 0]]) # glb y-up -> world z-up
42
+ PALETTE = np.array([
43
+ [230, 25, 75], [60, 180, 75], [255, 225, 25], [0, 130, 200], [245, 130, 48],
44
+ [145, 30, 180], [70, 240, 240], [240, 50, 230], [210, 245, 60], [250, 190, 212],
45
+ [0, 128, 128], [220, 190, 255], [170, 110, 40], [255, 250, 200], [128, 0, 0],
46
+ [170, 255, 195], [128, 128, 0], [255, 215, 180], [0, 0, 128], [128, 128, 128],
47
+ ], dtype=np.uint8)
48
+
49
+
50
+ def umeyama(src: np.ndarray, dst: np.ndarray, fixed_r: np.ndarray | None = None
51
+ ) -> tuple[float, np.ndarray, np.ndarray]:
52
+ """Fit a similarity transform ``dst ~= s * R @ src + t`` (Umeyama, 1991).
53
+
54
+ If ``fixed_r`` is given the rotation is held fixed and only scale/translation
55
+ are estimated (used when only two correspondences are available).
56
+ """
57
+ mu_s, mu_d = src.mean(0), dst.mean(0)
58
+ s_c, d_c = src - mu_s, dst - mu_d
59
+ if fixed_r is None:
60
+ cov = d_c.T @ s_c / len(src)
61
+ u, d, vt = np.linalg.svd(cov)
62
+ rot = u @ vt
63
+ if np.linalg.det(rot) < 0:
64
+ u[:, -1] *= -1
65
+ rot = u @ vt
66
+ scale = float(np.trace(np.diag(d)) / ((s_c ** 2).sum() / len(src)))
67
+ else:
68
+ rot = fixed_r
69
+ scale = float((d_c * (s_c @ rot.T)).sum() / (s_c ** 2).sum())
70
+ trans = mu_d - scale * rot @ mu_s
71
+ return scale, rot, trans
72
+
73
+
74
+ def load_room_objects(scene_uuid: str, room: str) -> dict[str, tuple[trimesh.Trimesh, str]]:
75
+ """Load furniture nodes of ``<room>_full.glb`` as ``node_name -> (mesh, model_uuid)``.
76
+
77
+ Architecture / unnamed geometry (walls, floor, ceiling) carry no model UUID in
78
+ the node name and are skipped, so only objects are returned.
79
+ """
80
+ full = os.path.join(SCENE_ROOT, scene_uuid, f"{room}_full.glb")
81
+ if not os.path.exists(full):
82
+ return {}
83
+ scene = trimesh.load(full)
84
+ nodes: dict[str, tuple[trimesh.Trimesh, str]] = {}
85
+ for name in scene.graph.nodes_geometry:
86
+ m = UUID_RE.search(name)
87
+ if not m:
88
+ continue
89
+ transform, geom_name = scene.graph[name]
90
+ geom = scene.geometry[geom_name].copy()
91
+ geom.apply_transform(transform)
92
+ nodes[name] = (geom, m.group(1))
93
+ return nodes
94
+
95
+
96
+ def fit_similarity(ann: dict[str, Any],
97
+ nodes: dict[str, tuple[trimesh.Trimesh, str]],
98
+ thresh: float = 0.15) -> dict[str, Any] | None:
99
+ """RANSAC estimate of the glb->annotation-world similarity transform.
100
+
101
+ Each annotation object may match several same-model room nodes; we sample
102
+ triples of (object, candidate-node) hypotheses, fit a similarity, and score it
103
+ by the number of annotation objects whose nearest same-model node lands within
104
+ ``thresh`` metres. Returns the transform plus the inlier node->object assignment.
105
+ """
106
+ ann_obj = [(o["model_file_name"][0], np.array(o["bbox3d_world_center"], float), oid)
107
+ for oid, o in enumerate(ann["obj_dict"].values())]
108
+ node_by_uuid: dict[str, list[tuple[str, np.ndarray]]] = {}
109
+ for name, (geom, mid) in nodes.items():
110
+ node_by_uuid.setdefault(mid, []).append((name, geom.bounds.mean(0)))
111
+ cand = [[(nm, c) for nm, c in node_by_uuid.get(mid, [])] for mid, _, _ in ann_obj]
112
+ have = [i for i, c in enumerate(cand) if c]
113
+ if len(have) < 2:
114
+ return None
115
+
116
+ def score(scale: float, rot: np.ndarray, trans: np.ndarray
117
+ ) -> tuple[list[float], dict[str, int]]:
118
+ res: list[float] = []
119
+ assign: dict[str, int] = {}
120
+ for i in have:
121
+ dst = ann_obj[i][1]
122
+ nm, c = min(cand[i], key=lambda nc: np.linalg.norm(scale * (rot @ nc[1]) + trans - dst))
123
+ d = float(np.linalg.norm(scale * (rot @ c) + trans - dst))
124
+ if d < thresh:
125
+ res.append(d)
126
+ assign[nm] = ann_obj[i][2]
127
+ return res, assign
128
+
129
+ best: tuple[tuple[int, float], float, np.ndarray, np.ndarray, list[float], dict[str, int]] | None = None
130
+ if len(have) >= 3:
131
+ trip = sorted(have, key=lambda i: len(cand[i]))[:min(len(have), 6)]
132
+ for combo in combinations(trip, 3):
133
+ for picks in product(*[cand[i] for i in combo]):
134
+ src = np.array([p[1] for p in picks])
135
+ dst = np.array([ann_obj[i][1] for i in combo])
136
+ if not (np.isfinite(src).all() and np.isfinite(dst).all()):
137
+ continue
138
+ try:
139
+ scale, rot, trans = umeyama(src, dst)
140
+ except np.linalg.LinAlgError:
141
+ continue
142
+ res, assign = score(scale, rot, trans)
143
+ key = (len(res), -float(np.sum(res)) if res else 0.0)
144
+ if best is None or key > best[0]:
145
+ best = (key, scale, rot, trans, res, assign)
146
+ if best is None: # two-object scene: fix the canonical rotation
147
+ src = np.array([cand[i][0][1] for i in have])
148
+ dst = np.array([ann_obj[i][1] for i in have])
149
+ gm = np.isfinite(src).all(1) & np.isfinite(dst).all(1)
150
+ if gm.sum() < 2:
151
+ return None
152
+ try:
153
+ scale, rot, trans = umeyama(src[gm], dst[gm], CANONICAL_R)
154
+ except np.linalg.LinAlgError:
155
+ return None
156
+ res, assign = score(scale, rot, trans)
157
+ best = ((len(res), 0.0), scale, rot, trans, res, assign)
158
+ _, scale, rot, trans, res, assign = best
159
+ if not res:
160
+ return None
161
+ return dict(scale=scale, rot=rot, trans=trans, n_inliers=len(res),
162
+ max_res=float(np.max(res)), med_res=float(np.median(res)), assign=assign)
163
+
164
+
165
+ def camera_from_annotation(ann: dict[str, Any]) -> tuple[np.ndarray, np.ndarray]:
166
+ """Return ``(K, T_cv_from_world)``: intrinsics and world->OpenCV-camera 4x4."""
167
+ k = np.asarray(ann["camera_intrinsics"], float)
168
+ w2c = np.eye(4)
169
+ w2c[:3] = np.asarray(ann["camera_extrinsics"], float) # world -> OpenGL cam
170
+ rot, trans = w2c[:3, :3], w2c[:3, 3]
171
+ t_world_from_cv = np.eye(4)
172
+ t_world_from_cv[:3, :3] = rot.T @ CV2GL
173
+ t_world_from_cv[:3, 3] = -rot.T @ trans
174
+ return k, np.linalg.inv(t_world_from_cv)
175
+
176
+
177
+ def place_objects(nodes: dict[str, tuple[trimesh.Trimesh, str]], fit: dict[str, Any],
178
+ t_cv_from_world: np.ndarray
179
+ ) -> list[tuple[str, str, trimesh.Trimesh]]:
180
+ """Transform each room object node glb->world (similarity)->OpenCV camera frame.
181
+
182
+ Returns a deterministic list of ``(node_name, model_uuid, mesh_in_camera_frame)``.
183
+ """
184
+ scale, rot, trans = fit["scale"], fit["rot"], fit["trans"]
185
+ placed: list[tuple[str, str, trimesh.Trimesh]] = []
186
+ for name in sorted(nodes):
187
+ geom, mid = nodes[name]
188
+ mesh = geom.copy()
189
+ mesh.vertices = scale * (rot @ mesh.vertices.T).T + trans # -> world
190
+ mesh.apply_transform(t_cv_from_world) # -> camera (cv)
191
+ placed.append((name, mid, mesh))
192
+ return placed
193
+
194
+
195
+ def raycast_instance_mask(placed: list[tuple[str, str, trimesh.Trimesh]],
196
+ k: np.ndarray, hw: tuple[int, int], stride: int = 1
197
+ ) -> tuple[np.ndarray, np.ndarray]:
198
+ """Ray-cast placed objects through ``K``; return ``(instance_id_map, z_depth)``.
199
+
200
+ Instance ids are ``1..len(placed)`` (0 = background); the nearest surface wins
201
+ per pixel. ``z_depth`` is the camera-frame z of the hit (inf where no hit).
202
+ """
203
+ height, width = hw
204
+ faces_obj = np.concatenate([np.full(len(m.faces), i + 1, np.int32)
205
+ for i, (_, _, m) in enumerate(placed)])
206
+ combined = trimesh.util.concatenate([m for _, _, m in placed])
207
+ fx, fy, cx, cy = k[0, 0], k[1, 1], k[0, 2], k[1, 2]
208
+ us, vs = np.meshgrid(np.arange(0, width, stride), np.arange(0, height, stride))
209
+ flat_u, flat_v = us.ravel(), vs.ravel()
210
+ dirs = np.stack([(flat_u - cx) / fx, (flat_v - cy) / fy, np.ones_like(flat_u, float)], -1)
211
+ dirs /= np.linalg.norm(dirs, axis=1, keepdims=True)
212
+ origins = np.zeros_like(dirs)
213
+ loc, ray_idx, tri_idx = combined.ray.intersects_location(origins, dirs, multiple_hits=False)
214
+ id_flat = np.zeros(flat_u.shape, np.int32)
215
+ z_flat = np.full(flat_u.shape, np.inf)
216
+ for r, tri, xyz in zip(ray_idx, tri_idx, loc):
217
+ if xyz[2] < z_flat[r]:
218
+ z_flat[r] = xyz[2]
219
+ id_flat[r] = faces_obj[tri]
220
+ out_h, out_w = us.shape
221
+ return id_flat.reshape(out_h, out_w), z_flat.reshape(out_h, out_w)
222
+
223
+
224
+ def depth_agreement(z_render: np.ndarray, depth: np.ndarray) -> dict[str, float]:
225
+ """Agreement between rendered object z and dataset metric depth on covered pixels."""
226
+ valid = np.isfinite(z_render) & np.isfinite(depth) & (depth > 0) & (depth < 100)
227
+ if valid.sum() == 0:
228
+ return dict(coverage=0.0, med_mm=float("inf"), within5mm=0.0, n=0)
229
+ err = np.abs(z_render[valid] - depth[valid])
230
+ return dict(coverage=float(np.isfinite(z_render).mean()),
231
+ med_mm=float(np.median(err) * 1000), within5mm=float((err < 0.005).mean()),
232
+ n=int(valid.sum()))
233
+
234
+
235
+ def shortlist_rooms(ann: dict[str, Any], u2rooms: dict[str, set[str]]) -> list[str]:
236
+ """Rooms whose model set covers all annotation models (else the best-covering ones)."""
237
+ uuids = set(o["model_file_name"][0] for o in ann["obj_dict"].values())
238
+ sets = [u2rooms.get(u, set()) for u in uuids]
239
+ if sets and all(sets):
240
+ common = set.intersection(*sets)
241
+ if common:
242
+ return sorted(common)
243
+ from collections import Counter
244
+ counter: Counter[str] = Counter()
245
+ for s in sets:
246
+ counter.update(s)
247
+ if not counter:
248
+ return []
249
+ top = max(counter.values())
250
+ return sorted(r for r, n in counter.items() if n == top)
251
+
252
+
253
+ def process_scene(scene_id: str, u2rooms: dict[str, set[str]], out_root: str,
254
+ top_k: int, sel_stride: int, min_conf: float = 0.5) -> dict[str, Any]:
255
+ """Match one scene to its 3D-FRONT room and, if confident, write GT into the
256
+ scene folder next to the original files, using the ``_<index06>`` naming.
257
+
258
+ Low-confidence matches (rendered depth disagrees with the metric depth) are
259
+ not written; the scene is reported as ``low-confidence`` instead.
260
+ """
261
+ scene_dir = os.path.join(out_root, scene_id)
262
+ idx6 = f"{int(scene_id):06d}"
263
+ ann = json.load(open(glob.glob(f"{scene_dir}/annotation_*.json")[0]))
264
+ k, t_cv_from_world = camera_from_annotation(ann)
265
+ depth = np.load(glob.glob(f"{scene_dir}/depth_*.npy")[0]).astype(np.float64)
266
+ height, width = depth.shape
267
+
268
+ candidates = shortlist_rooms(ann, u2rooms)
269
+ scored: list[tuple[tuple[int, float], str, str, dict[str, Any]]] = []
270
+ for room_key in candidates:
271
+ scene_uuid, room = room_key.split("|")
272
+ nodes = load_room_objects(scene_uuid, room)
273
+ if not nodes:
274
+ continue
275
+ fit = fit_similarity(ann, nodes)
276
+ if fit is None:
277
+ continue
278
+ scored.append(((-fit["n_inliers"], fit["max_res"]), scene_uuid, room, fit))
279
+ if not scored:
280
+ return dict(scene=scene_id, status="no-match", n_candidates=len(candidates))
281
+ scored.sort(key=lambda x: x[0])
282
+
283
+ # verify the top-K by rendered-depth agreement (decisive for ambiguous scenes)
284
+ best = None
285
+ for _, scene_uuid, room, fit in scored[:top_k]:
286
+ nodes = load_room_objects(scene_uuid, room)
287
+ placed = place_objects(nodes, fit, t_cv_from_world)
288
+ _, z_low = raycast_instance_mask(placed, k, (height, width), stride=sel_stride)
289
+ agree = depth_agreement(z_low, depth[::sel_stride, ::sel_stride])
290
+ key = (agree["within5mm"], -agree["med_mm"])
291
+ if best is None or key > best[0]:
292
+ best = (key, scene_uuid, room, fit, agree)
293
+ _, scene_uuid, room, fit, _ = best
294
+
295
+ # full-res render for the winner
296
+ nodes = load_room_objects(scene_uuid, room)
297
+ placed = place_objects(nodes, fit, t_cv_from_world)
298
+ id_map, z_render = raycast_instance_mask(placed, k, (height, width), stride=1)
299
+ agree = depth_agreement(z_render, depth)
300
+
301
+ # id -> object metadata (computed before writing so we can gate on confidence)
302
+ ann_by_oid = list(ann["obj_dict"].values())
303
+ id_records: list[dict[str, Any]] = []
304
+ for i, (name, mid, _) in enumerate(placed):
305
+ inst = i + 1
306
+ category = UUID_RE.split(name)[0].strip("_")
307
+ oid = fit["assign"].get(name)
308
+ label = ann_by_oid[oid]["label"][0] if oid is not None else category
309
+ n_pix = int((id_map == inst).sum())
310
+ id_records.append(dict(instance_id=inst, node_name=name, model_uuid=mid,
311
+ category=category, label=label, annotated=oid is not None,
312
+ obj_id=int(ann_by_oid[oid]["obj_id"][0]) if oid is not None else None,
313
+ n_pixels=n_pix, visible=n_pix > 0))
314
+
315
+ confident = agree["within5mm"] >= min_conf
316
+ result = dict(scene=scene_id, status="ok" if confident else "low-confidence",
317
+ scene_uuid=scene_uuid, room=room, confident=confident,
318
+ n_candidates=len(candidates), n_objects=len(placed),
319
+ n_annotated=sum(r["annotated"] for r in id_records),
320
+ fit=dict(scale=fit["scale"], n_inliers=fit["n_inliers"],
321
+ max_res=fit["max_res"], med_res=fit["med_res"]),
322
+ depth=agree, instances=id_records)
323
+ if not confident:
324
+ return result # do not write GT for an unreliable match
325
+
326
+ # write GT into the scene folder, matching the dataset's _<index06> convention
327
+ obj_dir = os.path.join(scene_dir, f"objects_{idx6}")
328
+ os.makedirs(obj_dir, exist_ok=True)
329
+ Image.fromarray(id_map.astype(np.uint16)).save(os.path.join(scene_dir, f"instance_{idx6}.png"))
330
+ merged: list[trimesh.Trimesh] = []
331
+ for (name, _, mesh), rec in zip(placed, id_records):
332
+ safe = re.sub(r"[^0-9a-zA-Z]+", "_", rec["label"]).strip("_")[:32]
333
+ mesh.export(os.path.join(obj_dir, f"{rec['instance_id']:03d}_{safe}.ply"))
334
+ merged.append(mesh)
335
+ trimesh.util.concatenate(merged).export(os.path.join(scene_dir, f"sceneobjfull_{idx6}.ply"))
336
+ save_overlay(scene_dir, id_map, os.path.join(scene_dir, f"instance_overlay_{idx6}.png"))
337
+ json.dump({k2: v for k2, v in result.items() if k2 != "instances"} | {
338
+ "similarity": dict(scale=fit["scale"], rot=fit["rot"].tolist(), trans=fit["trans"].tolist()),
339
+ "instances": id_records}, open(os.path.join(scene_dir, f"instance_{idx6}.json"), "w"), indent=2)
340
+ return result
341
+
342
+
343
+ def save_overlay(scene_dir: str, id_map: np.ndarray, path: str) -> None:
344
+ """Blend the coloured instance mask over the rgb image for visual inspection."""
345
+ rgb_path = (glob.glob(f"{scene_dir}/rgb_*.jpeg") + glob.glob(f"{scene_dir}/rgb_*.png"))[0]
346
+ rgb = np.asarray(Image.open(rgb_path).convert("RGB"))
347
+ if rgb.shape[:2] != id_map.shape:
348
+ rgb = np.asarray(Image.fromarray(rgb).resize((id_map.shape[1], id_map.shape[0])))
349
+ color = np.zeros_like(rgb)
350
+ for inst in np.unique(id_map):
351
+ if inst == 0:
352
+ continue
353
+ color[id_map == inst] = PALETTE[(inst - 1) % len(PALETTE)]
354
+ fg = id_map > 0
355
+ out = rgb.copy()
356
+ out[fg] = (0.5 * rgb[fg] + 0.5 * color[fg]).astype(np.uint8)
357
+ Image.fromarray(out).save(path)
358
+
359
+
360
+ def main() -> None:
361
+ """CLI entry point: match and export GT for one or all single_image scenes."""
362
+ ap = argparse.ArgumentParser(description=__doc__)
363
+ ap.add_argument("--scenes", nargs="*", default=None, help="scene ids (default: all)")
364
+ ap.add_argument("--index", default="/tmp/uuid_index.json",
365
+ help="model-uuid -> [[scene,room],...] index json")
366
+ ap.add_argument("--out", default=SI_ROOT,
367
+ help="dataset root; GT is written into each <out>/<scene>/ folder")
368
+ ap.add_argument("--top-k", type=int, default=8, help="candidates to depth-verify")
369
+ ap.add_argument("--sel-stride", type=int, default=4, help="pixel stride for verification")
370
+ args = ap.parse_args()
371
+
372
+ idx = json.load(open(args.index))
373
+ u2rooms = {u: set(f"{a}|{b}" for a, b in v) for u, v in idx.items()}
374
+ scenes = args.scenes or [os.path.basename(p) for p in sorted(glob.glob(f"{args.out}/[0-9]*"))]
375
+
376
+ summary = []
377
+ for sid in scenes:
378
+ try:
379
+ res = process_scene(sid, u2rooms, args.out, args.top_k, args.sel_stride)
380
+ except Exception as exc: # noqa: BLE001 - keep the batch going
381
+ res = dict(scene=sid, status=f"error:{type(exc).__name__}:{exc}")
382
+ summary.append(res)
383
+ if res["status"] in ("ok", "low-confidence"):
384
+ d = res["depth"]
385
+ flag = "" if res["confident"] else " <-- LOW CONFIDENCE (skipped, likely wrong room)"
386
+ print(f"{sid}: {res['scene_uuid'][:8]}/{res['room']:26} "
387
+ f"obj={res['n_objects']:2d} ann={res['n_annotated']} "
388
+ f"cover={d['coverage']*100:4.1f}% med={d['med_mm']:5.1f}mm "
389
+ f"<5mm={d['within5mm']*100:4.1f}%{flag}")
390
+ else:
391
+ print(f"{sid}: {res['status']}")
392
+ json.dump(summary, open(os.path.join(args.out, "gt_3dfront_summary.json"), "w"), indent=2)
393
+
394
+
395
+ if __name__ == "__main__":
396
+ main()
gt_3dfront_summary.json ADDED
The diff for this file is too large to render. See raw diff