# つけっぱなしで動く仕組み: 増え続けるものを持たない # 作業場(VRAM): 今のコマ・直前のコマ・直近の基準のコマ(最大 WIN 枚)だけ。照らし合わせ・当て直し・仕上げ・全体の直しは tracker.py と同じ計算 # 地図(SSD、合計 MAP_MB まで): # 形の地図 … 2cm のます目に色つきの点を 1 つ。同じ場所は書き換え(歩いた広さで決まり、時間では増えない) # 場所の札 … 1m の箱 × 向き(60° より違う向きだけ別)ごとに基準のコマ 1 枚を縮めて残す(名札は 8 ビット、奥行きは四角の真ん中だけ) # 戻った場所に気づく・見失った時に今どこかを当てる、のに使う。予算を超えたら一番長く来ていない札から消す # カメラの道 … 1 コマごとにファイルへ書き出す(メモリには持たない) import os, time, json, numpy as np, cv2, torch, torch.nn as nn, torch.nn.functional as F from scipy.spatial.transform import Rotation as Rot import frontend as TE, rigid3d as RG from tracker import ba_refine from finenet import FineNet, refine_q, sample def _q8(hs): """奥行きの AI の前のコマの記憶(テンソルの並び)を 8 ビットにしまう(最後の次元ごとに倍率を持つ)""" out = [] for h in hs: sc = h.float().abs().amax(-1, keepdim=True).clamp(min=1e-6) / 127; out.append(((h.float() / sc).round().to(torch.int8), sc.half())) return out def _dq(hs): return [q.half() * sc for q, sc in hs] def vda_infer(dm, frame, size, q8): """公式の infer_video_depth_one と同じ計算。q8 のとき、前のコマの記憶を 8 ビットでしまい、使う時に 16 ビットへ戻す""" import video_depth_anything.video_depth_stream as V if not q8 or dm.transform is None: d = dm.infer_video_depth_one(frame, input_size=size, device=TE.dev.type, fp32=False) if q8: z = _q8(dm.frame_cache_list[-1]); dm.frame_cache_list = [z] * len(dm.frame_cache_list) return d dm.id += 1; fh, fw = frame.shape[:2] x = torch.from_numpy(dm.transform({"image": frame.astype(np.float32) / 255.0})["image"]).unsqueeze(0).unsqueeze(0).to(TE.dev) with torch.no_grad(), torch.autocast(device_type=TE.dev.type): feat = dm.forward_features(x) cur = dm.frame_cache_list[0:2] + dm.frame_cache_list[-V.INFER_LEN + 3:] dq = [_dq(h) for h in cur]; cache = [torch.cat([h[i] for h in dq], dim=1) for i in range(len(cur[0]))]; del dq depth, new = dm.forward_depth(feat, x.shape, cached_hidden_state_list=cache) depth = F.interpolate(depth.to(x.dtype).flatten(0, 1).unsqueeze(1), size=(fh, fw), mode="bilinear", align_corners=True) dm.frame_cache_list.append(_q8(new)); dm.frame_id_list.append(dm.id) if dm.id + V.INFER_LEN > dm.gap + 1: del dm.frame_id_list[1]; del dm.frame_cache_list[1] return depth[-1][0].cpu().numpy() def _to_weight_dtype(mod, inp): return tuple(t.to(mod.weight.dtype) if torch.is_tensor(t) and t.is_floating_point() and t.dtype != mod.weight.dtype else t for t in inp) class Store(dict): """frontend.matches が s.feats[i]・s.deps[i] で読むための入れ物(中身は作業場にあるものだけ)""" pass class Toru3D: def __init__(s, K, da3, posenet, finenet, vda, out, WIN=12, MAP_MB=100.0, shape_vox=0.02, place_box=1.0, depth_res=518, half=False, q8=False): TE.init(da3, posenet); TE.DIRN = "rev"; TE.ITERS = 300 from video_depth_anything.video_depth_stream import VideoDepthAnything s.dm = VideoDepthAnything(encoder="vits", features=64, out_channels=[48, 96, 192, 384]) s.dm.load_state_dict(torch.load(vda, map_location="cpu"), strict=True); s.dm = s.dm.to(TE.dev).eval(); s.depth_res = depth_res; s.half = half; s.q8 = q8 if half: # 重みを 16 ビットで持つ(計算はもともと 16 ビット)。各層に入る直前で型をそろえる for net_ in (TE.enc, s.dm): net_.to(torch.bfloat16 if net_ is TE.enc else torch.float16) # 入口はもともと bfloat16 で計算している for m_ in net_.modules(): if isinstance(m_, (nn.Conv2d, nn.ConvTranspose2d, nn.Linear, nn.LayerNorm, nn.GroupNorm, nn.BatchNorm2d)) and getattr(m_, "weight", None) is not None: m_.register_forward_pre_hook(_to_weight_dtype) s.fn = FineNet().to(TE.dev).eval(); s.fn.load_state_dict(torch.load(finenet, map_location="cpu")) s.cent = torch.stack([TE.UU, TE.VV], -1)[None] s.S = Store(); s.S.feats = Store(); s.S.deps = Store(); s.S.K = torch.tensor(K, device=TE.dev, dtype=torch.float32); s.S.zmax = 20.0 s.K = np.asarray(K, np.float64); s.WIN, s.MAP_B, s.vox, s.box = WIN, MAP_MB * 1e6, shape_vox, place_box s.cm = {}; s.kq = {}; s.pose = {}; s.n0 = {}; s.g = {} # 作業場: 細かい名札の地図(今と直前)、基準のコマの当て直し用の名札・位置・最初の合った数・全体の名札 s.win = []; s.edges = [] # 作業場の基準のコマと、その間の組(i, j, 合った点) s.places = {}; s.place_ids = 0 # 場所の札: id → dict(SSD に書く中身と同じ。CPU のメモリ) s.shape_k = np.zeros(0, np.int64); s.shape_c = np.zeros((0, 3), np.uint8); s.shape_t = np.zeros(0, np.float32) # 形の地図: ます目の番号・色・最後に見た時刻 s.BOX_VOX = 6000; s.anchored = set() # 1m の箱あたりのます目の上限(2cm で約 2.4m² の面)、戻った場所が見つかった基準のコマ s.chunk = 2.0; s.max_vols = 16; s.keep_tri = 0.1; s.vols = {}; s.vol_seen = {}; s.meshes = {}; s.use_mesh = True # 形の地図をポリゴンで持つ(区画 2m・作りかけ 16 区画まで・三角形を 1 割に減らす) s.prev = None; s.prev2 = None; s.kf = None; s.fail = 0; s.t = 0; s.prev_lost = False os.makedirs(out, exist_ok=True); s.out = out; s.traj = open(os.path.join(out, "trajectory.txt"), "w") s.stat = dict(frames=0, kfs=0, loops=0, relocs=0, places_made=0, places_dropped=0) def reset(s, out): """AI は読み込んだまま、地図・作業場・道・奥行きの AI の前のコマの記憶を空にして、新しい動画を始める""" try: s.traj.close() except Exception: pass dm = s.dm; dm.transform = None; dm.frame_id_list = []; dm.frame_cache_list = []; dm.id = -1 for d in (s.S.feats, s.S.deps): d.clear() s.cm, s.kq, s.pose, s.n0, s.g, s.rgb_small = {}, {}, {}, {}, {}, {} s.win, s.edges, s.places = [], [], {} s.shape_k = np.zeros(0, np.int64); s.shape_c = np.zeros((0, 3), np.uint8); s.shape_t = np.zeros(0, np.float32); s.anchored = set() s.vols, s.vol_seen, s.meshes = {}, {}, {} s.prev = None; s.prev2 = None; s.kf = None; s.fail = 0; s.t = 0; s.prev_lost = False os.makedirs(out, exist_ok=True); s.out = out; s.traj = open(os.path.join(out, "trajectory.txt"), "w") s.stat = dict(frames=0, kfs=0, loops=0, relocs=0, places_made=0, places_dropped=0) torch.cuda.reset_peak_memory_stats() # ---------------------------------------------------------------- 1 コマぶんの下ごしらえ @torch.no_grad() def prep(s, i, bgr): rgb_full = cv2.cvtColor(bgr, cv2.COLOR_BGR2RGB); im = cv2.resize(rgb_full, (TE.W, TE.H), interpolation=cv2.INTER_AREA) d = vda_infer(s.dm, rgb_full, s.depth_res, s.q8) s.S.deps[i] = torch.from_numpy(cv2.resize(np.asarray(d, np.float32), (TE.W, TE.H), interpolation=cv2.INTER_NEAREST)).to(TE.dev) s.S.feats[i] = TE.encode(im) s.cm[i] = s.fn(torch.from_numpy(im).permute(2, 0, 1)[None].float().to(TE.dev) / 255).half() s.rgb_small = getattr(s, "rgb_small", {}); s.rgb_small[i] = im # ---------------------------------------------------------------- 2 コマの動き(tracker.est_min と同じ計算。3D のずれの重みは 0) def est(s, a, b, init, thr=4.0, ba_pts=80): X, uv = TE.matches(s.S, a, b, 0.5) if len(X) < 6: return None, 0, None K = s.K; uv0 = X[:, :2] / X[:, 2:3] * np.array([K[0, 0], K[1, 1]]) + K[:2, 2] ix = np.clip(np.round((uv0[:, 1] - 7) / 14).astype(int), 0, TE.GH - 1) * TE.GW + np.clip(np.round((uv0[:, 0] - 7) / 14).astype(int), 0, TE.GW - 1) with torch.no_grad(): u1, sc = refine_q(s.fn, s.kq[a][torch.tensor(ix, device=TE.dev)][None].float(), s.cm[b].float(), torch.tensor(uv, device=TE.dev, dtype=torch.float32)[None], 6) U = u1[0].cpu().numpy().astype(np.float64); w = (sc[0] > 0.3).cpu().numpy() db = s.S.deps[b].cpu().numpy(); zz = db[np.clip(U[:, 1].round().astype(int), 0, TE.H - 1), np.clip(U[:, 0].round().astype(int), 0, TE.W - 1)] Xb = np.stack([(U[:, 0] - K[0, 2]) / K[0, 0] * zz, (U[:, 1] - K[1, 2]) / K[1, 1] * zz, zz], 1); ok = w & (zz > 0.1) & (zz < 20.0) if ok.sum() < 6: return None, int(ok.sum()), None WZ = 1.0 / np.clip(X[:, 2], 1.0, None) T = RG.hybrid(X[ok], Xb[ok], U[ok], K, init, np.ones(int(ok.sum()), bool), w3=0.0, wz=WZ[ok]) q = (X[ok] - T[:3, 3]) @ T[:3, :3]; pr = q[:, :2] / np.clip(q[:, 2:3], 1e-3, None) * np.array([K[0, 0], K[1, 1]]) + K[:2, 2] good = np.linalg.norm(pr - U[ok], axis=1) < thr; n = int(good.sum()); sel = np.nonzero(ok)[0][good] if len(sel) > ba_pts: sel = np.random.default_rng(len(sel)).choice(sel, ba_pts, replace=False) S_ = np.ones((len(X), 5)); S_[:, 2:] *= WZ[:, None] return T, n, ((X[sel], U[sel], Xb[sel], S_[sel]) if len(sel) >= 6 else None) # ---------------------------------------------------------------- 作業場の出し入れ def to_window(s, i): """直前のコマ i を基準のコマにする(当て直し用の名札・全体の名札を作る)""" with torch.no_grad(): s.kq[i] = sample(s.cm[i].float(), s.cent)[0].half() f = s.S.feats[i].float(); g = f.mean(1)[0]; s.g[i] = (g / g.norm()).cpu().numpy() s.win.append(i); s.stat["kfs"] += 1 def drop_frame(s, i): """作業場にも場所の札にもいらなくなったコマを捨てる""" if i in s.win or i == s.prev or i == s.prev2: return for d in (s.S.feats, s.S.deps, s.cm, s.kq, s.rgb_small): d.pop(i, None) for d in (s.n0, s.g): d.pop(i, None) s.anchored.discard(i) if i not in s.places: s.pose.pop(i, None) def leave_window(s, a): """作業場からあふれた基準のコマ: 形の地図に足し、その場所にまだ札がなければ縮めて札にする""" s.win.remove(a); s.edges = [e for e in s.edges if a not in (e[0], e[1]) or (e[0] in s.places or e[1] in s.places)] (s.add_mesh(a) if s.use_mesh else s.add_shape(a)); s.make_place(a) s.edges = [e for e in s.edges if a not in (e[0], e[1])] s.cm.pop(a, None); s.drop_frame(a) # ---------------------------------------------------------------- 形の地図(ポリゴン): 4m の区画ごとに TSDF(2cm)へ重ね、離れたら三角形にして減らして保存 def add_mesh(s, a): # この環境の Open3D では、広げられる TSDF(Scalable・VoxelBlockGrid)が何も入らないので、大きさを決めた TSDF(Uniform)を 2m の区画ごとに持つ import open3d as o3d T = s.pose[a]; dz = s.S.deps[a].float().cpu().numpy(); K = s.K v, u = np.mgrid[0:TE.H:8, 0:TE.W:8]; z = dz[::8, ::8].reshape(-1); ok = (z > 0.1) & (z < 4.0) ray = np.stack([(u - K[0, 2]) / K[0, 0], (v - K[1, 2]) / K[1, 1], np.ones_like(u, float)], -1).reshape(-1, 3) Pw = (ray[ok] * z[ok, None]) @ T[:3, :3].T + T[:3, 3] cks = {tuple(c) for c in np.floor(Pw / s.chunk).astype(int)} # 奥行きが写っている区画の全部に重ねる(区画のふちで切れない) col = o3d.geometry.Image(np.ascontiguousarray(s.rgb_small[a])); dep = o3d.geometry.Image(np.ascontiguousarray(dz)) rgbd = o3d.geometry.RGBDImage.create_from_color_and_depth(col, dep, depth_scale=1.0, depth_trunc=4.0, convert_rgb_to_intensity=False) intr = o3d.camera.PinholeCameraIntrinsic(int(TE.W), int(TE.H), float(K[0, 0]), float(K[1, 1]), float(K[0, 2]), float(K[1, 2])); ext = np.linalg.inv(T) res = int(round(s.chunk / s.vox)) for ck in cks: if ck not in s.vols: s.vols[ck] = o3d.pipelines.integration.UniformTSDFVolume(length=s.chunk, resolution=res, sdf_trunc=4 * s.vox, color_type=o3d.pipelines.integration.TSDFVolumeColorType.RGB8, origin=(np.array(ck, np.float64) * s.chunk)[:, None]) s.vols[ck].integrate(rgbd, intr, ext); s.vol_seen[ck] = s.t while len(s.vols) > s.max_vols: s.finish_chunk(min(s.vols, key=lambda c: s.vol_seen[c])) # 作りかけの区画は max_vols 個まで(メモリを増やさない) def finish_chunk(s, ck): """区画の TSDF から表面の三角形を作り、平らな所をまとめて三角形を減らし、地図に書き込む(同じ区画は書き換え)""" import open3d as o3d m = s.vols.pop(ck).extract_triangle_mesh(); s.vol_seen.pop(ck, None) if len(m.triangles) == 0: return m = m.simplify_quadric_decimation(target_number_of_triangles=max(100, int(len(m.triangles) * s.keep_tri))) m.remove_degenerate_triangles(); m.remove_unreferenced_vertices() s.meshes[ck] = dict(v=np.asarray(m.vertices, np.float32), f=np.asarray(m.triangles, np.int32), c=(np.asarray(m.vertex_colors) * 255).astype(np.uint8), seen=s.t) s.keep_budget() def mesh_bytes(s): return sum(x["v"].nbytes + x["f"].nbytes + x["c"].nbytes for x in s.meshes.values()) # ---------------------------------------------------------------- (前の作り)2cm のます目の点 def add_shape(s, a, stride=4, zmax=4.0): K = s.K; v, u = np.mgrid[0:TE.H:stride, 0:TE.W:stride] z = s.S.deps[a].cpu().numpy()[::stride, ::stride].reshape(-1).astype(np.float64); ok = (z > 0.1) & (z < zmax) ray = np.stack([(u - K[0, 2]) / K[0, 0], (v - K[1, 2]) / K[1, 1], np.ones_like(u, float)], -1).reshape(-1, 3) P = (ray[ok] * z[ok, None]) @ s.pose[a][:3, :3].T + s.pose[a][:3, 3]; C = s.rgb_small[a][::stride, ::stride].reshape(-1, 3)[ok] q = np.floor(P / s.vox).astype(np.int64) + (1 << 20); key = (q[:, 0] << 42) | (q[:, 1] << 21) | q[:, 2] k_all = np.concatenate([key, s.shape_k]); c_all = np.concatenate([C, s.shape_c]); t_all = np.concatenate([np.full(len(key), s.t, np.float32), s.shape_t]) # 新しい方を先に置く → 同じます目は新しい色で書き換え k_u, first = np.unique(k_all, return_index=True); k_u, c_u, t_u = k_u, c_all[first], t_all[first] # 1m の箱ごとに、ます目は BOX_VOX 個まで(超えたら古いものから消す)→ 同じ場所を何度通っても、形の地図は増えない q = np.stack([(k_u >> 42) & ((1 << 21) - 1), (k_u >> 21) & ((1 << 21) - 1), k_u & ((1 << 21) - 1)], 1) - (1 << 20) bq = np.floor((q + 0.5) * s.vox / s.box).astype(np.int64) + (1 << 20); bk = (bq[:, 0] << 42) | (bq[:, 1] << 21) | bq[:, 2] o = np.lexsort((-t_u, bk)); bk_o = bk[o]; start = np.r_[0, np.nonzero(np.diff(bk_o))[0] + 1] rank = np.arange(len(o)) - np.repeat(start, np.diff(np.r_[start, len(o)])); keep = np.sort(o[rank < s.BOX_VOX]) s.shape_k, s.shape_c, s.shape_t = k_u[keep], c_u[keep], t_u[keep] # ---------------------------------------------------------------- 場所の札 def place_key(s, T): b = tuple(np.floor(T[:3, 3] / s.box).astype(int)); return b def make_place(s, a): T = s.pose[a]; b = s.place_key(T); fwd = T[:3, 2] if a in s.anchored: s.anchored.discard(a); return # 戻った場所だとわかったコマ → 同じ場所なので札を足さない for pid, p in s.places.items(): # 0.75m 以内・似た向きの札がある → 足さない(来た時刻だけ更新) if np.linalg.norm(p["pose"][:3, 3] - T[:3, 3]) < 0.75 * s.box and float(p["pose"][:3, 2] @ fwd) > 0.5: p["seen"] = s.t; return f = s.S.feats[a].float(); fs = f.abs().amax(-1, keepdim=True).clamp(min=1e-6) / 127 kq = s.kq[a].float(); ks = kq.abs().amax(-1, keepdim=True).clamp(min=1e-6) / 127 dz = s.S.deps[a][TE.VV.long().clamp(0, TE.H - 1), TE.UU.long().clamp(0, TE.W - 1)] s.places[a] = dict(box=b, pose=T.copy(), seen=s.t, g=s.g[a].astype(np.float16), n0=int(s.n0.get(a, 30)), f8=(f / fs).round().to(torch.int8).cpu().numpy(), fs=fs.half().cpu().numpy(), k8=(kq / ks).round().to(torch.int8).cpu().numpy(), ks=ks.half().cpu().numpy(), dz=dz.half().cpu().numpy()) s.stat["places_made"] += 1; s.keep_budget() def place_bytes(s, p): return sum(v.nbytes for k, v in p.items() if isinstance(v, np.ndarray)) + 64 def map_bytes(s): return sum(s.place_bytes(p) for p in s.places.values()) + s.shape_k.nbytes + s.shape_c.nbytes + s.shape_t.nbytes + s.mesh_bytes() def keep_budget(s): while s.map_bytes() > s.MAP_B and s.places: old = min(s.places, key=lambda q: s.places[q]["seen"]); s.places.pop(old); s.stat["places_dropped"] += 1 while s.map_bytes() > s.MAP_B and s.meshes: # 札を全部消しても超える時は、一番長く来ていない区画の面を消す s.meshes.pop(min(s.meshes, key=lambda c: s.meshes[c]["seen"])) while s.map_bytes() > s.MAP_B and len(s.shape_k) > 0: s.shape_k, s.shape_c, s.shape_t = s.shape_k[::2], s.shape_c[::2], s.shape_t[::2] def load_place(s, pid): """札を作業場の形に戻す(照らし合わせに使う間だけ)""" p = s.places[pid] s.S.feats[pid] = torch.from_numpy(p["f8"]).to(TE.dev).float().mul_(torch.from_numpy(p["fs"]).to(TE.dev).float()).half() s.kq[pid] = torch.from_numpy(p["k8"]).to(TE.dev).float().mul_(torch.from_numpy(p["ks"]).to(TE.dev).float()).half() d = torch.zeros(TE.H, TE.W, device=TE.dev); d[TE.VV.long().clamp(0, TE.H - 1), TE.UU.long().clamp(0, TE.W - 1)] = torch.from_numpy(p["dz"]).to(TE.dev).float() s.S.deps[pid] = d; s.pose[pid] = p["pose"] def unload_place(s, pid): if pid in s.win: return for d in (s.S.feats, s.S.deps, s.kq): d.pop(pid, None) # ---------------------------------------------------------------- 新しい基準のコマを足す def add_kf(s, new): old_kf = s.win[-1] if s.win else None s.to_window(new) # 1. 直前の 3 枚の基準のコマとの組 for o in s.win[-4:-1]: T, n, c = s.est(o, new, np.linalg.inv(s.pose[o]) @ s.pose[new]) if T is not None and n >= 20 and c is not None: s.edges.append((o, new, c)) # 2. 似た基準のコマを間引く(2 つ前から十分見えていたら間を消す) if len(s.win) >= 4: a3, mid = s.win[-3], s.win[-2] T3, n3, c3 = s.est(a3, new, np.linalg.inv(s.pose[a3]) @ s.pose[new]) if T3 is not None and n3 >= max(30, 0.7 * s.n0.get(a3, 0)): s.win.remove(mid); s.edges = [e for e in s.edges if mid not in (e[0], e[1])] if c3 is not None and not any(e[0] == a3 and e[1] == new for e in s.edges): s.edges.append((a3, new, c3)) s.cm.pop(mid, None); s.drop_frame(mid) # 3. 戻った場所: 場所の札から、近い札 8 枚+全体の名札が似た札 3 枚 anchors = [] if s.places: ids = [p for p in s.places if p not in s.win] if ids: cn = s.pose[new][:3, 3]; d = np.array([np.linalg.norm(s.places[p]["pose"][:3, 3] - cn) for p in ids]) sim = np.array([float(s.places[p]["g"].astype(np.float32) @ s.g[new]) for p in ids]) cand = list(dict.fromkeys([ids[q] for q in np.argsort(d)[:8]] + [ids[q] for q in np.argsort(-sim)[:3]])) for pid in cand: s.load_place(pid); T, n, c = s.est(pid, new, np.linalg.inv(s.pose[pid]) @ s.pose[new]) ok = T is not None and n >= max(40, 0.5 * s.n0.get(old_kf, 0) if old_kf is not None else 40) and c is not None if ok: D = np.linalg.inv(T) @ (np.linalg.inv(s.pose[pid]) @ s.pose[new]) ok = np.linalg.norm(D[:3, 3]) <= 1.0 and np.degrees(Rot.from_matrix(D[:3, :3]).magnitude()) <= 30.0 if ok: s.edges.append((pid, new, c)); anchors.append(pid); s.places[pid]["seen"] = s.t; s.stat["loops"] += 1; s.anchored.add(new) else: s.unload_place(pid) # 4. 作業場の基準のコマ(+見つかった札は動かさない)で全体の直し nodes = {a: s.pose[a] for a in s.win + anchors} new_p = ba_refine(nodes, [(e[0], e[1], None, None) for e in s.edges if e[0] in nodes and e[1] in nodes], [e[2] for e in s.edges if e[0] in nodes and e[1] in nodes], s.K, iters=5, w3=0.0, fixed=(anchors if anchors else [s.win[0]])) for a in s.win: s.pose[a] = new_p[a] for pid in anchors: s.edges = [e for e in s.edges if e[0] != pid]; s.unload_place(pid) # 札との組は、この直しの間だけ使う # 5. あふれたら古い基準のコマを作業場から出す while len(s.win) > s.WIN: s.leave_window(s.win[0]) s.cm.pop(new, None) # 細かい名札の地図は、当て直し用の名札を作ったらいらない # ---------------------------------------------------------------- 見失った時: 場所の札から今どこかを当てる def relocalize(s, i): if not s.places: return None f = s.S.feats[i].float(); g = f.mean(1)[0]; g = (g / g.norm()).cpu().numpy() ids = sorted(s.places, key=lambda p: -float(s.places[p]["g"].astype(np.float32) @ g))[:5] best = None tries = [] for pid in ids: s.load_place(pid); T, n, c = s.est(pid, i, np.eye(4)); tries.append(n) if T is not None and n >= 40 and (best is None or n > best[1]): best = (s.places[pid]["pose"] @ T, n) s.unload_place(pid) if os.environ.get("TORU_DEBUG"): print(f" 当て直しの試し: コマ {i}・札 {len(s.places)} 枚・合った数 {tries}", flush=True) return best # ---------------------------------------------------------------- 1 コマ進める def step(s, i, ts, bgr): s.t = ts; s.prep(i, bgr); s.stat["frames"] += 1 if s.kf is None: s.pose[i] = np.eye(4); s.n0[i] = 0; s.to_window(i); s.kf = i; s.write(ts, s.pose[i]); s.prev = i; return pred = s.pose[s.prev] if s.prev2 is None else s.pose[s.prev] @ (np.linalg.inv(s.pose[s.prev2]) @ s.pose[s.prev]) T, n, _ = s.est(s.kf, i, np.linalg.inv(s.pose[s.kf]) @ pred) need = max(30, 0.7 * s.n0.get(s.kf, 0)) if (T is None or n < need) and s.prev != s.kf and not s.prev_lost: # 見失ったコマ(位置が当てにならない)は基準のコマにしない s.add_kf(s.prev); s.kf = s.prev T, n, _ = s.est(s.kf, i, np.linalg.inv(s.pose[s.kf]) @ pred) if s.n0.get(s.kf, 0) == 0: s.n0[s.kf] = n if T is not None: # 1 コマで 30cm または 20° より大きく動いた答えは、見失ったと扱う D = np.linalg.inv(pred) @ (s.pose[s.kf] @ T) if np.linalg.norm(D[:3, 3]) > 0.3 or np.degrees(Rot.from_matrix(D[:3, :3]).magnitude()) > 20.0: T, n = None, 0 lost = False if T is None or n < 10: s.fail += 1; lost = True; c2w = s.pose[s.prev] if s.fail >= 3 and (s.fail - 3) % 5 == 0: # 3 コマ続けて見失ったら、5 コマごとに場所の札で今どこかを当て直す r = s.relocalize(i) if r is not None: for a in list(s.win): s.leave_window(a) # 今までの作業場は地図に移して捨てる s.edges.clear(); c2w = r[0]; s.pose[i] = c2w; s.n0[i] = 0; s.to_window(i); s.kf = i; s.fail = 0; lost = False; s.stat["relocs"] += 1 if lost and s.fail >= 60: # 2 秒たっても当て直せない → 今のコマからやり直す(新しい場所として地図を作る) for a in list(s.win): s.leave_window(a) s.edges.clear(); s.pose[i] = c2w; s.n0[i] = 0; s.to_window(i); s.kf = i; s.fail = 0; lost = False; s.stat["restarts"] = s.stat.get("restarts", 0) + 1 else: s.fail = 0; c2w = s.pose[s.kf] @ T s.pose[i] = c2w; s.write(ts, c2w); s.prev_lost = lost old2 = s.prev2; s.prev2, s.prev = s.prev, i if old2 is not None: s.cm.pop(old2, None) if old2 not in s.win else None; s.drop_frame(old2) if old2 is not None else None def write(s, ts, T): q = Rot.from_matrix(T[:3, :3]).as_quat(); t = T[:3, 3] s.traj.write(f"{ts:.6f} {t[0]:.6f} {t[1]:.6f} {t[2]:.6f} {q[0]:.6f} {q[1]:.6f} {q[2]:.6f} {q[3]:.6f}\n") # ---------------------------------------------------------------- 地図を SSD に書く def save_map(s): for a in list(s.win): (s.add_mesh(a) if s.use_mesh else s.add_shape(a)) for ck in list(s.vols): s.finish_chunk(ck) M = {} for ck, x in s.meshes.items(): nm = "_".join(map(str, ck)); M[nm + "_v"], M[nm + "_f"], M[nm + "_c"] = x["v"], x["f"], x["c"] np.savez_compressed(os.path.join(s.out, "shape_map.npz"), **M) if s.use_mesh else np.savez_compressed(os.path.join(s.out, "shape_map.npz"), key=s.shape_k, color=s.shape_c, vox=np.array([s.vox])) P = {} for pid, p in s.places.items(): for k, v in p.items(): P[f"{pid}_{k}"] = np.asarray(v) np.savez(os.path.join(s.out, "place_map.npz"), **P) s.traj.flush() return {f: os.path.getsize(os.path.join(s.out, f)) for f in ("shape_map.npz", "place_map.npz")} def write_mesh_ply(s, path): """全部の区画の面を 1 つの .ply(三角形と色)に書き出す""" V, Fc, C, off = [], [], [], 0 for x in s.meshes.values(): V.append(x["v"]); Fc.append(x["f"] + off); C.append(x["c"]); off += len(x["v"]) if not V: return 0, 0 V = np.concatenate(V); Fc = np.concatenate(Fc); C = np.concatenate(C) with open(path, "wb") as f: f.write(f"ply\nformat binary_little_endian 1.0\nelement vertex {len(V)}\nproperty float x\nproperty float y\nproperty float z\nproperty uchar red\nproperty uchar green\nproperty uchar blue\nelement face {len(Fc)}\nproperty list uchar int vertex_indices\nend_header\n".encode()) rv = np.zeros(len(V), dtype=[("x", "> 42) & ((1 << 21) - 1), (s.shape_k >> 21) & ((1 << 21) - 1), s.shape_k & ((1 << 21) - 1)], 1) - (1 << 20) return (q + 0.5) * s.vox, s.shape_c[:, ::-1]