Download utils/camera.py from WANG-XIXI/ViDiHand2: direct link, hf CLI and curl.
- Browser
- Download file 2.49 kB
-
https://huggingface.co/spaces/WANG-XIXI/ViDiHand2/resolve/main/utils/camera.py
- Command line
-
hf download hf://spaces/WANG-XIXI/ViDiHand2/utils/camera.py
-
curl -L -o camera.py https://huggingface.co/spaces/WANG-XIXI/ViDiHand2/resolve/main/utils/camera.py
2.49 kB
| """Camera estimation with Depth Anything 3 for videos without a camera JSON.""" | |
| import contextlib | |
| import io | |
| import os | |
| from functools import lru_cache | |
| os.environ.setdefault("DA3_LOG_LEVEL", "ERROR") # Depth Anything 3 logs every step at INFO; read when it is imported | |
| import numpy as np # noqa: E402 | |
| import torch # noqa: E402 | |
| from depth_anything_3.api import DepthAnything3 # noqa: E402 | |
| from huggingface_hub import snapshot_download # noqa: E402 | |
| from utils.io import CHECKPOINTS # noqa: E402 | |
| REPO = "depth-anything/DA3-GIANT-1.1" | |
| FRAMES = 32 # frames spread across the video that the estimate uses | |
| PROCESS_RES = 504 # Depth Anything 3 processing resolution | |
| def load_estimator(): | |
| """Depth Anything 3 on CUDA, downloaded into checkpoints/da3/ on first use (cached; `load_estimator.cache_clear()` frees it).""" | |
| path = CHECKPOINTS / "da3" / REPO.split("/")[1] | |
| if not (path / "model.safetensors").is_file(): | |
| snapshot_download(REPO, local_dir=path) | |
| with contextlib.redirect_stdout(io.StringIO()): # it prints where it loads the weights from | |
| model = DepthAnything3.from_pretrained(str(path)) | |
| return model.to("cuda").eval() | |
| def estimate_camera(video, fps): | |
| """Per-frame pinhole intrinsics K [T, 3, 3] of a video [T, H, W, 3] (estimated on FRAMES frames spread across it, mapped to the video | |
| size and interpolated linearly in time to every frame) and those frames' world-to-camera extrinsics (translation up to scale; NaN on | |
| the other frames), as a camera dict for utils.io.save_camera.""" | |
| n, height, width = video.shape[:3] | |
| model = load_estimator() | |
| index = np.unique(np.linspace(0, n - 1, min(FRAMES, n)).round().astype(int)) | |
| with torch.inference_mode(): | |
| pred = model.inference(list(video[index]), process_res=PROCESS_RES) | |
| torch.cuda.empty_cache() | |
| h, w = pred.depth.shape[1:] | |
| k = np.asarray(pred.intrinsics, np.float64) | |
| sx, sy = width / w, height / h | |
| sampled = (k[:, 0, 0] * sx, k[:, 1, 1] * sy, (k[:, 0, 2] + 0.5) * sx - 0.5, (k[:, 1, 2] + 0.5) * sy - 0.5) | |
| fx, fy, cx, cy = (np.interp(np.arange(n), index, v) for v in sampled) | |
| K = np.zeros((n, 3, 3)) | |
| K[:, 0, 0], K[:, 1, 1], K[:, 0, 2], K[:, 1, 2], K[:, 2, 2] = fx, fy, cx, cy, 1.0 | |
| E = np.full((n, 4, 4), np.nan) | |
| E[index] = np.eye(4) | |
| E[index, :3] = np.asarray(pred.extrinsics, np.float64)[:, :3] | |
| return dict(K=K, E=E, source_frame_ids=np.arange(n), fps=float(fps), size=(width, height)) | |