#!/usr/bin/env python """Build per-view GT (instance mask + object meshes) for the Fire3D single_image scenes by aligning the source 3D-FRONT room to each annotation and ray-casting it into the annotation camera. Pipeline per scene (see the discussion in the task): 1. shortlist candidate 3D-FRONT rooms whose furniture-model UUID set covers the annotation's objects (index built from the ``*_full.glb`` scene graphs); 2. estimate the glb->annotation-world similarity transform with a RANSAC over per-model candidate matches (robust to duplicate models / extra room objects); 3. for the top-K candidates, ray-cast the placed room objects through the annotation intrinsics and keep the room whose rendered depth best agrees with the dataset metric depth; 4. write outputs: uint16 instance mask (full-res, aligned to rgb), id->object json, per-object meshes (PLY, OpenCV camera frame = the sceneobjgt frame), merged scene-objects mesh, and an rgb overlay for eyeballing the match. Objects only: walls / floor / ceiling are intentionally skipped. """ from __future__ import annotations import argparse import glob import json import os import re import warnings from itertools import combinations, product from typing import Any import numpy as np import trimesh from PIL import Image warnings.filterwarnings("ignore") 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})") SCENE_ROOT = "/mnt/task_runtime/3d-front/3D-FRONT-SCENE" SI_ROOT = "/mnt/task_runtime/data/single_image" CV2GL = np.diag([1.0, -1.0, -1.0]) # OpenCV cam <-> OpenGL cam CANONICAL_R = np.array([[1.0, 0, 0], [0, 0, -1.0], [0, 1.0, 0]]) # glb y-up -> world z-up PALETTE = np.array([ [230, 25, 75], [60, 180, 75], [255, 225, 25], [0, 130, 200], [245, 130, 48], [145, 30, 180], [70, 240, 240], [240, 50, 230], [210, 245, 60], [250, 190, 212], [0, 128, 128], [220, 190, 255], [170, 110, 40], [255, 250, 200], [128, 0, 0], [170, 255, 195], [128, 128, 0], [255, 215, 180], [0, 0, 128], [128, 128, 128], ], dtype=np.uint8) def umeyama(src: np.ndarray, dst: np.ndarray, fixed_r: np.ndarray | None = None ) -> tuple[float, np.ndarray, np.ndarray]: """Fit a similarity transform ``dst ~= s * R @ src + t`` (Umeyama, 1991). If ``fixed_r`` is given the rotation is held fixed and only scale/translation are estimated (used when only two correspondences are available). """ mu_s, mu_d = src.mean(0), dst.mean(0) s_c, d_c = src - mu_s, dst - mu_d if fixed_r is None: cov = d_c.T @ s_c / len(src) u, d, vt = np.linalg.svd(cov) rot = u @ vt if np.linalg.det(rot) < 0: u[:, -1] *= -1 rot = u @ vt scale = float(np.trace(np.diag(d)) / ((s_c ** 2).sum() / len(src))) else: rot = fixed_r scale = float((d_c * (s_c @ rot.T)).sum() / (s_c ** 2).sum()) trans = mu_d - scale * rot @ mu_s return scale, rot, trans def load_room_objects(scene_uuid: str, room: str) -> dict[str, tuple[trimesh.Trimesh, str]]: """Load furniture nodes of ``_full.glb`` as ``node_name -> (mesh, model_uuid)``. Architecture / unnamed geometry (walls, floor, ceiling) carry no model UUID in the node name and are skipped, so only objects are returned. """ full = os.path.join(SCENE_ROOT, scene_uuid, f"{room}_full.glb") if not os.path.exists(full): return {} scene = trimesh.load(full) nodes: dict[str, tuple[trimesh.Trimesh, str]] = {} for name in scene.graph.nodes_geometry: m = UUID_RE.search(name) if not m: continue transform, geom_name = scene.graph[name] geom = scene.geometry[geom_name].copy() geom.apply_transform(transform) nodes[name] = (geom, m.group(1)) return nodes def fit_similarity(ann: dict[str, Any], nodes: dict[str, tuple[trimesh.Trimesh, str]], thresh: float = 0.15) -> dict[str, Any] | None: """RANSAC estimate of the glb->annotation-world similarity transform. Each annotation object may match several same-model room nodes; we sample triples of (object, candidate-node) hypotheses, fit a similarity, and score it by the number of annotation objects whose nearest same-model node lands within ``thresh`` metres. Returns the transform plus the inlier node->object assignment. """ ann_obj = [(o["model_file_name"][0], np.array(o["bbox3d_world_center"], float), oid) for oid, o in enumerate(ann["obj_dict"].values())] node_by_uuid: dict[str, list[tuple[str, np.ndarray]]] = {} for name, (geom, mid) in nodes.items(): node_by_uuid.setdefault(mid, []).append((name, geom.bounds.mean(0))) cand = [[(nm, c) for nm, c in node_by_uuid.get(mid, [])] for mid, _, _ in ann_obj] have = [i for i, c in enumerate(cand) if c] if len(have) < 2: return None def score(scale: float, rot: np.ndarray, trans: np.ndarray ) -> tuple[list[float], dict[str, int]]: res: list[float] = [] assign: dict[str, int] = {} for i in have: dst = ann_obj[i][1] nm, c = min(cand[i], key=lambda nc: np.linalg.norm(scale * (rot @ nc[1]) + trans - dst)) d = float(np.linalg.norm(scale * (rot @ c) + trans - dst)) if d < thresh: res.append(d) assign[nm] = ann_obj[i][2] return res, assign best: tuple[tuple[int, float], float, np.ndarray, np.ndarray, list[float], dict[str, int]] | None = None if len(have) >= 3: trip = sorted(have, key=lambda i: len(cand[i]))[:min(len(have), 6)] for combo in combinations(trip, 3): for picks in product(*[cand[i] for i in combo]): src = np.array([p[1] for p in picks]) dst = np.array([ann_obj[i][1] for i in combo]) if not (np.isfinite(src).all() and np.isfinite(dst).all()): continue try: scale, rot, trans = umeyama(src, dst) except np.linalg.LinAlgError: continue res, assign = score(scale, rot, trans) key = (len(res), -float(np.sum(res)) if res else 0.0) if best is None or key > best[0]: best = (key, scale, rot, trans, res, assign) if best is None: # two-object scene: fix the canonical rotation src = np.array([cand[i][0][1] for i in have]) dst = np.array([ann_obj[i][1] for i in have]) gm = np.isfinite(src).all(1) & np.isfinite(dst).all(1) if gm.sum() < 2: return None try: scale, rot, trans = umeyama(src[gm], dst[gm], CANONICAL_R) except np.linalg.LinAlgError: return None res, assign = score(scale, rot, trans) best = ((len(res), 0.0), scale, rot, trans, res, assign) _, scale, rot, trans, res, assign = best if not res: return None return dict(scale=scale, rot=rot, trans=trans, n_inliers=len(res), max_res=float(np.max(res)), med_res=float(np.median(res)), assign=assign) def camera_from_annotation(ann: dict[str, Any]) -> tuple[np.ndarray, np.ndarray]: """Return ``(K, T_cv_from_world)``: intrinsics and world->OpenCV-camera 4x4.""" k = np.asarray(ann["camera_intrinsics"], float) w2c = np.eye(4) w2c[:3] = np.asarray(ann["camera_extrinsics"], float) # world -> OpenGL cam rot, trans = w2c[:3, :3], w2c[:3, 3] t_world_from_cv = np.eye(4) t_world_from_cv[:3, :3] = rot.T @ CV2GL t_world_from_cv[:3, 3] = -rot.T @ trans return k, np.linalg.inv(t_world_from_cv) def place_objects(nodes: dict[str, tuple[trimesh.Trimesh, str]], fit: dict[str, Any], t_cv_from_world: np.ndarray ) -> list[tuple[str, str, trimesh.Trimesh]]: """Transform each room object node glb->world (similarity)->OpenCV camera frame. Returns a deterministic list of ``(node_name, model_uuid, mesh_in_camera_frame)``. """ scale, rot, trans = fit["scale"], fit["rot"], fit["trans"] placed: list[tuple[str, str, trimesh.Trimesh]] = [] for name in sorted(nodes): geom, mid = nodes[name] mesh = geom.copy() mesh.vertices = scale * (rot @ mesh.vertices.T).T + trans # -> world mesh.apply_transform(t_cv_from_world) # -> camera (cv) placed.append((name, mid, mesh)) return placed def raycast_instance_mask(placed: list[tuple[str, str, trimesh.Trimesh]], k: np.ndarray, hw: tuple[int, int], stride: int = 1 ) -> tuple[np.ndarray, np.ndarray]: """Ray-cast placed objects through ``K``; return ``(instance_id_map, z_depth)``. Instance ids are ``1..len(placed)`` (0 = background); the nearest surface wins per pixel. ``z_depth`` is the camera-frame z of the hit (inf where no hit). """ height, width = hw faces_obj = np.concatenate([np.full(len(m.faces), i + 1, np.int32) for i, (_, _, m) in enumerate(placed)]) combined = trimesh.util.concatenate([m for _, _, m in placed]) fx, fy, cx, cy = k[0, 0], k[1, 1], k[0, 2], k[1, 2] us, vs = np.meshgrid(np.arange(0, width, stride), np.arange(0, height, stride)) flat_u, flat_v = us.ravel(), vs.ravel() dirs = np.stack([(flat_u - cx) / fx, (flat_v - cy) / fy, np.ones_like(flat_u, float)], -1) dirs /= np.linalg.norm(dirs, axis=1, keepdims=True) origins = np.zeros_like(dirs) loc, ray_idx, tri_idx = combined.ray.intersects_location(origins, dirs, multiple_hits=False) id_flat = np.zeros(flat_u.shape, np.int32) z_flat = np.full(flat_u.shape, np.inf) for r, tri, xyz in zip(ray_idx, tri_idx, loc): if xyz[2] < z_flat[r]: z_flat[r] = xyz[2] id_flat[r] = faces_obj[tri] out_h, out_w = us.shape return id_flat.reshape(out_h, out_w), z_flat.reshape(out_h, out_w) def depth_agreement(z_render: np.ndarray, depth: np.ndarray) -> dict[str, float]: """Agreement between rendered object z and dataset metric depth on covered pixels.""" valid = np.isfinite(z_render) & np.isfinite(depth) & (depth > 0) & (depth < 100) if valid.sum() == 0: return dict(coverage=0.0, med_mm=float("inf"), within5mm=0.0, n=0) err = np.abs(z_render[valid] - depth[valid]) return dict(coverage=float(np.isfinite(z_render).mean()), med_mm=float(np.median(err) * 1000), within5mm=float((err < 0.005).mean()), n=int(valid.sum())) def shortlist_rooms(ann: dict[str, Any], u2rooms: dict[str, set[str]]) -> list[str]: """Rooms whose model set covers all annotation models (else the best-covering ones).""" uuids = set(o["model_file_name"][0] for o in ann["obj_dict"].values()) sets = [u2rooms.get(u, set()) for u in uuids] if sets and all(sets): common = set.intersection(*sets) if common: return sorted(common) from collections import Counter counter: Counter[str] = Counter() for s in sets: counter.update(s) if not counter: return [] top = max(counter.values()) return sorted(r for r, n in counter.items() if n == top) def process_scene(scene_id: str, u2rooms: dict[str, set[str]], out_root: str, top_k: int, sel_stride: int, min_conf: float = 0.5) -> dict[str, Any]: """Match one scene to its 3D-FRONT room and, if confident, write GT into the scene folder next to the original files, using the ``_`` naming. Low-confidence matches (rendered depth disagrees with the metric depth) are not written; the scene is reported as ``low-confidence`` instead. """ scene_dir = os.path.join(out_root, scene_id) idx6 = f"{int(scene_id):06d}" ann = json.load(open(glob.glob(f"{scene_dir}/annotation_*.json")[0])) k, t_cv_from_world = camera_from_annotation(ann) depth = np.load(glob.glob(f"{scene_dir}/depth_*.npy")[0]).astype(np.float64) height, width = depth.shape candidates = shortlist_rooms(ann, u2rooms) scored: list[tuple[tuple[int, float], str, str, dict[str, Any]]] = [] for room_key in candidates: scene_uuid, room = room_key.split("|") nodes = load_room_objects(scene_uuid, room) if not nodes: continue fit = fit_similarity(ann, nodes) if fit is None: continue scored.append(((-fit["n_inliers"], fit["max_res"]), scene_uuid, room, fit)) if not scored: return dict(scene=scene_id, status="no-match", n_candidates=len(candidates)) scored.sort(key=lambda x: x[0]) # verify the top-K by rendered-depth agreement (decisive for ambiguous scenes) best = None for _, scene_uuid, room, fit in scored[:top_k]: nodes = load_room_objects(scene_uuid, room) placed = place_objects(nodes, fit, t_cv_from_world) _, z_low = raycast_instance_mask(placed, k, (height, width), stride=sel_stride) agree = depth_agreement(z_low, depth[::sel_stride, ::sel_stride]) key = (agree["within5mm"], -agree["med_mm"]) if best is None or key > best[0]: best = (key, scene_uuid, room, fit, agree) _, scene_uuid, room, fit, _ = best # full-res render for the winner nodes = load_room_objects(scene_uuid, room) placed = place_objects(nodes, fit, t_cv_from_world) id_map, z_render = raycast_instance_mask(placed, k, (height, width), stride=1) agree = depth_agreement(z_render, depth) # id -> object metadata (computed before writing so we can gate on confidence) ann_by_oid = list(ann["obj_dict"].values()) id_records: list[dict[str, Any]] = [] for i, (name, mid, _) in enumerate(placed): inst = i + 1 category = UUID_RE.split(name)[0].strip("_") oid = fit["assign"].get(name) label = ann_by_oid[oid]["label"][0] if oid is not None else category n_pix = int((id_map == inst).sum()) id_records.append(dict(instance_id=inst, node_name=name, model_uuid=mid, category=category, label=label, annotated=oid is not None, obj_id=int(ann_by_oid[oid]["obj_id"][0]) if oid is not None else None, n_pixels=n_pix, visible=n_pix > 0)) confident = agree["within5mm"] >= min_conf result = dict(scene=scene_id, status="ok" if confident else "low-confidence", scene_uuid=scene_uuid, room=room, confident=confident, n_candidates=len(candidates), n_objects=len(placed), n_annotated=sum(r["annotated"] for r in id_records), fit=dict(scale=fit["scale"], n_inliers=fit["n_inliers"], max_res=fit["max_res"], med_res=fit["med_res"]), depth=agree, instances=id_records) if not confident: return result # do not write GT for an unreliable match # write GT into the scene folder, matching the dataset's _ convention obj_dir = os.path.join(scene_dir, f"objects_{idx6}") os.makedirs(obj_dir, exist_ok=True) Image.fromarray(id_map.astype(np.uint16)).save(os.path.join(scene_dir, f"instance_{idx6}.png")) merged: list[trimesh.Trimesh] = [] for (name, _, mesh), rec in zip(placed, id_records): safe = re.sub(r"[^0-9a-zA-Z]+", "_", rec["label"]).strip("_")[:32] mesh.export(os.path.join(obj_dir, f"{rec['instance_id']:03d}_{safe}.ply")) merged.append(mesh) trimesh.util.concatenate(merged).export(os.path.join(scene_dir, f"sceneobjfull_{idx6}.ply")) save_overlay(scene_dir, id_map, os.path.join(scene_dir, f"instance_overlay_{idx6}.png")) json.dump({k2: v for k2, v in result.items() if k2 != "instances"} | { "similarity": dict(scale=fit["scale"], rot=fit["rot"].tolist(), trans=fit["trans"].tolist()), "instances": id_records}, open(os.path.join(scene_dir, f"instance_{idx6}.json"), "w"), indent=2) return result def save_overlay(scene_dir: str, id_map: np.ndarray, path: str) -> None: """Blend the coloured instance mask over the rgb image for visual inspection.""" rgb_path = (glob.glob(f"{scene_dir}/rgb_*.jpeg") + glob.glob(f"{scene_dir}/rgb_*.png"))[0] rgb = np.asarray(Image.open(rgb_path).convert("RGB")) if rgb.shape[:2] != id_map.shape: rgb = np.asarray(Image.fromarray(rgb).resize((id_map.shape[1], id_map.shape[0]))) color = np.zeros_like(rgb) for inst in np.unique(id_map): if inst == 0: continue color[id_map == inst] = PALETTE[(inst - 1) % len(PALETTE)] fg = id_map > 0 out = rgb.copy() out[fg] = (0.5 * rgb[fg] + 0.5 * color[fg]).astype(np.uint8) Image.fromarray(out).save(path) def main() -> None: """CLI entry point: match and export GT for one or all single_image scenes.""" ap = argparse.ArgumentParser(description=__doc__) ap.add_argument("--scenes", nargs="*", default=None, help="scene ids (default: all)") ap.add_argument("--index", default="/tmp/uuid_index.json", help="model-uuid -> [[scene,room],...] index json") ap.add_argument("--out", default=SI_ROOT, help="dataset root; GT is written into each // folder") ap.add_argument("--top-k", type=int, default=8, help="candidates to depth-verify") ap.add_argument("--sel-stride", type=int, default=4, help="pixel stride for verification") args = ap.parse_args() idx = json.load(open(args.index)) u2rooms = {u: set(f"{a}|{b}" for a, b in v) for u, v in idx.items()} scenes = args.scenes or [os.path.basename(p) for p in sorted(glob.glob(f"{args.out}/[0-9]*"))] summary = [] for sid in scenes: try: res = process_scene(sid, u2rooms, args.out, args.top_k, args.sel_stride) except Exception as exc: # noqa: BLE001 - keep the batch going res = dict(scene=sid, status=f"error:{type(exc).__name__}:{exc}") summary.append(res) if res["status"] in ("ok", "low-confidence"): d = res["depth"] flag = "" if res["confident"] else " <-- LOW CONFIDENCE (skipped, likely wrong room)" print(f"{sid}: {res['scene_uuid'][:8]}/{res['room']:26} " f"obj={res['n_objects']:2d} ann={res['n_annotated']} " f"cover={d['coverage']*100:4.1f}% med={d['med_mm']:5.1f}mm " f"<5mm={d['within5mm']*100:4.1f}%{flag}") else: print(f"{sid}: {res['status']}") json.dump(summary, open(os.path.join(args.out, "gt_3dfront_summary.json"), "w"), indent=2) if __name__ == "__main__": main()