# 前の段: 入口(DA3-Small)で名札を作り、位置の AI(posenet)で 2 コマの四角を照らし合わせる。tracker.py はここを TE として使う import os, numpy as np, cv2, torch, torch.nn.functional as F from encoder import DA3Encoder from posenet import PoseNet dev = torch.device("cuda" if torch.cuda.is_available() else "cpu") H, W, GH, GW = 294, 392, 21, 28; N = GH * GW enc = None; net = None; LAST_C2W = {} UU = ((torch.arange(N, device=dev) % GW).float() + 0.5) * 14; VV = ((torch.arange(N, device=dev) // GW).float() + 0.5) * 14 def init(da3_path, posenet_path): """入口(DA3-SMALL の model.safetensors)と位置の AI(weights/posenet.pt)を読む""" global enc, net enc = DA3Encoder(da3_path).to(dev).eval() net = PoseNet().to(dev).eval(); net.load_state_dict(torch.load(posenet_path, map_location="cpu")) @torch.no_grad() def encode(im_rgb_uint8): """392×294 の RGB → 588 個の四角の名札(1536 個の数)""" x = torch.from_numpy(im_rgb_uint8).permute(2, 0, 1)[None].float().to(dev) / 255 with torch.autocast("cuda", dtype=torch.bfloat16, enabled=dev.type == "cuda"): o = enc(x) return F.normalize(torch.cat([o[0], o[3]], -1).float(), dim=-1).half() class Seq: """K(3×3)、feats[i](名札)、deps[i](奥行き m、H×W)、rgb[i](画像のファイル)、zmax""" pass _G = {} @torch.no_grad() def net_g(fa, fb): if dev.type != "cuda" or fa.shape != (1, N, 1536) or fb.shape != (1, N, 1536): return net(fa, fb) if "g" not in _G: # 同じ形で何度も呼ぶので CUDA graph にする sa, sb = fa.clone(), fb.clone(); st = torch.cuda.Stream(); st.wait_stream(torch.cuda.current_stream()) with torch.cuda.stream(st): for _ in range(3): net(sa, sb) torch.cuda.current_stream().wait_stream(st) g = torch.cuda.CUDAGraph() with torch.cuda.graph(g): out = net(sa, sb) _G.update(g=g, sa=sa, sb=sb, out=out) _G["sa"].copy_(fa); _G["sb"].copy_(fb); _G["g"].replay(); return _G["out"] DIRN = "rev" def matches(s, i0, i1, cth=0.5): """コマ i0(奥行きのある側)と i1 の組 → i0 のカメラ座標の 3D 点、i1 の画素""" if DIRN == "fwd": return matches_fwd(s, i0, i1, cth) return matches_rev(s, i0, i1, cth) @torch.no_grad() def matches_rev(s, i0, i1, cth=0.5): f0, f1 = s.feats[i0].float(), s.feats[i1].float() S, P, conf, a, b = net_g(f1, f0) nn10 = P[0].argmax(-1); mutual = P[0].argmax(0)[nn10] == torch.arange(N, device=dev) m = mutual & (torch.sigmoid(conf[0]) > cth) if m.sum() < 6: m = mutual jj = nn10[m]; o2 = net.offset(a[0, m], b[0, jj]) u1 = ((jj % GW).float() + 0.5 + o2[:, 0]) * 14; v1 = ((jj // GW).float() + 0.5 + o2[:, 1]) * 14 u0, v0 = UU[m], VV[m] z0 = s.deps[i0][v0.long().clamp(0, H - 1), u0.long().clamp(0, W - 1)] X0 = (torch.linalg.inv(s.K) @ torch.stack([u0, v0, torch.ones_like(u0)], -1).T).T * z0[:, None]; keep = (z0 > 0.1) & (z0 < s.zmax) return X0[keep].cpu().numpy().astype(np.float64), torch.stack([u1, v1], -1)[keep].cpu().numpy().astype(np.float64) @torch.no_grad() def matches_fwd(s, i0, i1, cth=0.5): f0, f1 = s.feats[i0].float(), s.feats[i1].float() S, P, conf, a, b = net_g(f0, f1) nn10 = P[0].argmax(-1); mutual = P[0].argmax(0)[nn10] == torch.arange(N, device=dev) m = mutual & (torch.sigmoid(conf[0]) > cth) if m.sum() < 6: m = mutual jj = nn10[m]; o2 = net.offset(a[0, m], b[0, jj]) u0 = ((jj % GW).float() + 0.5 + o2[:, 0]) * 14; v0 = ((jj // GW).float() + 0.5 + o2[:, 1]) * 14 z0 = s.deps[i0][v0.long().clamp(0, H - 1), u0.long().clamp(0, W - 1)] X0 = (torch.linalg.inv(s.K) @ torch.stack([u0, v0, torch.ones_like(u0)], -1).T).T * z0[:, None]; keep = (z0 > 0.1) & (z0 < s.zmax) return X0[keep].cpu().numpy().astype(np.float64), torch.stack([UU[m], VV[m]], -1)[keep].cpu().numpy().astype(np.float64) ITERS = 300 def pnp(X, uv, K, thr, refine): """X(どこかの座標)と画素 → その座標での今のカメラの位置(4×4、カメラ→その座標)と合格数""" if len(X) < 6: return None, 0 ok, rv, tv, inl = cv2.solvePnPRansac(X, uv, K, None, reprojectionError=thr, iterationsCount=ITERS) if not ok or inl is None or len(inl) < 6: return None, 0 if refine: rv, tv = cv2.solvePnPRefineLM(X[inl[:, 0]], uv[inl[:, 0]], K, None, rv, tv) Rc = cv2.Rodrigues(rv)[0]; Tm = np.eye(4); Tm[:3, :3] = Rc.T; Tm[:3, 3] = -(Rc.T @ tv[:, 0]); return Tm, len(inl) def to_world(c2w, X): return (c2w[:3, :3] @ X.T).T + c2w[:3, 3]