Download run.py from Yakimask/Toru3D: direct link, hf CLI and curl.
- Browser
- Download file 6.7 kB
-
https://huggingface.co/Yakimask/Toru3D/resolve/main/run.py
- Command line
-
hf download hf://Yakimask/Toru3D/run.py
-
curl -L -o run.py https://huggingface.co/Yakimask/Toru3D/resolve/main/run.py
6.7 kB
| # 撮った映像(または写真の並び)から、カメラの道と色つきの 3D の点の集まりを作る | |
| # 使い方: | |
| # python run.py --images path/to/frames --fx 517.3 --fy 516.5 --cx 318.6 --cy 255.3 --out out_dir | |
| # python run.py --video clip.mp4 --fx ... --out out_dir | |
| # 出力: out_dir/trajectory.txt(TUM 形式: 時刻 tx ty tz qx qy qz qw)、out_dir/points.ply(色つきの点) | |
| # 部品: 入口 DA3-Small(固定)→ 位置の AI(posenet)→ 細かく当て直す AI(finenet)→ 全体の直し | |
| # 奥行きは Video Depth Anything の m を出す版(Small、1 コマずつ流す使い方) | |
| import os, sys, glob, time, argparse, numpy as np, cv2, torch | |
| HERE = os.path.dirname(os.path.abspath(__file__)) | |
| sys.path.insert(0, HERE); sys.path.insert(0, os.path.join(HERE, "third_party")) | |
| import frontend as TE, tracker as PG | |
| from scipy.spatial.transform import Rotation as Rot | |
| CFG = dict(front=dict(mode="kf", ratio=0.7, thr=4.0, dirn="rev"), loop=True, near_n=8, loop_min=40, cons=True, both_depth=True, | |
| ba=True, ba_loop=True, ba_pts=80, w_depth=True, kf_cull=True, w3=0.0) | |
| def frames_from(args): | |
| if args.images: | |
| fs = sorted(sum([glob.glob(os.path.join(args.images, e)) for e in ("*.png", "*.jpg", "*.jpeg")], [])) | |
| return fs, [float(os.path.splitext(os.path.basename(f))[0]) if os.path.splitext(os.path.basename(f))[0].replace(".", "").isdigit() else float(k) for k, f in enumerate(fs)] | |
| d = os.path.join(args.out, "frames"); os.makedirs(d, exist_ok=True); cap = cv2.VideoCapture(args.video); fps = cap.get(cv2.CAP_PROP_FPS) or 30.0; fs = [] | |
| while True: | |
| ok, im = cap.read() | |
| if not ok: break | |
| f = os.path.join(d, f"{len(fs):06d}.jpg"); cv2.imwrite(f, im); fs.append(f) | |
| return fs, [k / fps for k in range(len(fs))] | |
| def depth_model(path): | |
| from video_depth_anything.video_depth_stream import VideoDepthAnything | |
| m = VideoDepthAnything(encoder="vits", features=64, out_channels=[48, 96, 192, 384]) | |
| m.load_state_dict(torch.load(path, map_location="cpu"), strict=True); return m.to(TE.dev).eval() | |
| def write_ply(path, P, C): | |
| rec = np.zeros(len(P), dtype=[("x", "<f4"), ("y", "<f4"), ("z", "<f4"), ("r", "u1"), ("g", "u1"), ("b", "u1")]) | |
| rec["x"], rec["y"], rec["z"] = P.T; rec["r"], rec["g"], rec["b"] = np.clip(C, 0, 255).astype(np.uint8).T | |
| with open(path, "wb") as f: | |
| f.write(f"ply\nformat binary_little_endian 1.0\nelement vertex {len(P)}\nproperty float x\nproperty float y\nproperty float z\nproperty uchar red\nproperty uchar green\nproperty uchar blue\nend_header\n".encode()); f.write(rec.tobytes()) | |
| def fuse(s, c2w, step=10, stride=4, zmax=4.0, vox=0.02): | |
| """10 コマおきに、奥行き 0.1〜4m の画素を 4 画素おきに世界の座標へ。2cm のます目で 1 点にまとめる""" | |
| K = s.K.cpu().numpy(); v, u = np.mgrid[0:TE.H:stride, 0:TE.W:stride] | |
| 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, C = [], [] | |
| for i in range(0, len(s.rgb), step): | |
| if i not in c2w: continue | |
| z = s.deps[i].cpu().numpy()[::stride, ::stride].reshape(-1).astype(np.float64); ok = (z > 0.1) & (z < zmax) | |
| im = cv2.resize(cv2.imread(s.rgb[i]), (TE.W, TE.H), interpolation=cv2.INTER_AREA)[::stride, ::stride].reshape(-1, 3) | |
| P.append((ray[ok] * z[ok, None]) @ c2w[i][:3, :3].T + c2w[i][:3, 3]); C.append(im[ok][:, ::-1]) | |
| P = np.concatenate(P); C = np.concatenate(C).astype(np.float64) | |
| key = np.floor(P / vox).astype(np.int64); _, inv, cnt = np.unique(key, axis=0, return_inverse=True, return_counts=True); inv = inv.reshape(-1) | |
| Pm = np.zeros((len(cnt), 3)); Cm = np.zeros((len(cnt), 3)); np.add.at(Pm, inv, P); np.add.at(Cm, inv, C) | |
| return Pm / cnt[:, None], Cm / cnt[:, None] | |
| def build(fs, K0, wh, da3, posenet, vda, log=print): | |
| """写真の並び → Seq(名札・奥行き)。K0 は元の大きさのカメラの値、wh は元の (幅, 高さ)""" | |
| TE.init(da3, posenet); dm = depth_model(vda); s = TE.Seq(); sx, sy = TE.W / wh[0], TE.H / wh[1] | |
| s.K = torch.tensor([[K0[0] * sx, 0, K0[2] * sx], [0, K0[1] * sy, K0[3] * sy], [0, 0, 1]], device=TE.dev, dtype=torch.float32) | |
| s.feats, s.deps, s.rgb, s.zmax = [], [], fs, 20.0; t0 = time.time() | |
| for k, f in enumerate(fs): | |
| bgr = cv2.imread(f) | |
| with torch.no_grad(): d = dm.infer_video_depth_one(cv2.cvtColor(bgr, cv2.COLOR_BGR2RGB), input_size=518, device=TE.dev.type, fp32=False) | |
| s.deps.append(torch.from_numpy(cv2.resize(np.asarray(d, np.float32), (TE.W, TE.H), interpolation=cv2.INTER_NEAREST)).to(TE.dev)) | |
| s.feats.append(TE.encode(cv2.resize(cv2.cvtColor(bgr, cv2.COLOR_BGR2RGB), (TE.W, TE.H), interpolation=cv2.INTER_AREA))) | |
| if k % 100 == 0: log(f" 奥行きと名札 {k}/{len(fs)} コマ({time.time()-t0:.0f} 秒)") | |
| del dm; torch.cuda.empty_cache(); return s | |
| def main(): | |
| ap = argparse.ArgumentParser() | |
| ap.add_argument("--images"); ap.add_argument("--video"); ap.add_argument("--out", required=True) | |
| ap.add_argument("--fx", type=float, required=True); ap.add_argument("--fy", type=float, required=True); ap.add_argument("--cx", type=float, required=True); ap.add_argument("--cy", type=float, required=True) | |
| ap.add_argument("--da3", default=os.path.join(HERE, "weights", "da3-small", "model.safetensors")) | |
| ap.add_argument("--vda", default=os.path.join(HERE, "weights", "metric_video_depth_anything_vits.pth")) | |
| ap.add_argument("--posenet", default=os.path.join(HERE, "weights", "posenet.pt")); ap.add_argument("--finenet", default=os.path.join(HERE, "weights", "finenet.pt")) | |
| a = ap.parse_args(); os.makedirs(a.out, exist_ok=True) | |
| fs, ts = frames_from(a); h, w = cv2.imread(fs[0]).shape[:2]; print(f"{len(fs)} コマ({w}×{h})", flush=True) | |
| t0 = time.time(); s = build(fs, (a.fx, a.fy, a.cx, a.cy), (w, h), a.da3, a.posenet, a.vda, log=lambda m: print(m, flush=True)); t1 = time.time() | |
| info = PG.track_pgo(s, ai4min=a.finenet, **CFG); c2w = TE.LAST_C2W; t2 = time.time() | |
| with open(os.path.join(a.out, "trajectory.txt"), "w") as f: | |
| for i in sorted(c2w): | |
| q = Rot.from_matrix(c2w[i][:3, :3]).as_quat(); t = c2w[i][:3, 3]; f.write(f"{ts[i]:.6f} {t[0]:.6f} {t[1]:.6f} {t[2]:.6f} {q[0]:.6f} {q[1]:.6f} {q[2]:.6f} {q[3]:.6f}\n") | |
| P, C = fuse(s, c2w); write_ply(os.path.join(a.out, "points.ply"), P, C) | |
| print(f"できた: 道 {len(c2w)} コマ・基準のコマ {info['nkf']} 枚・点 {len(P)} 個 時間: 奥行きと名札 {t1-t0:.0f} 秒・追いかける {t2-t1:.0f} 秒 → {a.out}", flush=True) | |
| if __name__ == "__main__": | |
| main() | |