Upload third-party source (skip LFS pointer assets) (part 10)
Browse filesThis view is limited to 50 files because it contains too many changes. See raw diff
Files changed (50)
- third-party/video_to_data/reconstruction/modules/v2d_detectron2/docker/__init__.pyAdded+2
- third-party/video_to_data/reconstruction/modules/v2d_detectron2/docker/_config.pyAdded+6
- third-party/video_to_data/reconstruction/modules/v2d_detectron2/docker/build.pyAdded+19
- third-party/video_to_data/reconstruction/modules/v2d_detectron2/docker/pyproject.tomlAdded+18
- third-party/video_to_data/reconstruction/modules/v2d_detectron2/docker/run_download_weights.pyAdded+41
- third-party/video_to_data/reconstruction/modules/v2d_detectron2/docker/run_mv_track_bboxes.pyAdded+70
- third-party/video_to_data/reconstruction/modules/v2d_detectron2/docker/run_shell.pyAdded+26
- third-party/video_to_data/reconstruction/modules/v2d_detectron2/docker/run_track_bboxes.pyAdded+78
- third-party/video_to_data/reconstruction/modules/v2d_detectron2/lib/__init__.pyAdded+2
- third-party/video_to_data/reconstruction/modules/v2d_detectron2/lib/build_detector.pyAdded+188
- third-party/video_to_data/reconstruction/modules/v2d_detectron2/lib/bytetracker.pyAdded+286
- third-party/video_to_data/reconstruction/modules/v2d_detectron2/lib/cascade_mask_rcnn_vitdet_b_100ep.pyAdded+101
- third-party/video_to_data/reconstruction/modules/v2d_detectron2/lib/cascade_mask_rcnn_vitdet_h_75ep.pyAdded+131
- third-party/video_to_data/reconstruction/modules/v2d_detectron2/lib/cascade_mask_rcnn_vitdet_l_100ep.pyAdded+112
- third-party/video_to_data/reconstruction/modules/v2d_detectron2/lib/download_weights.pyAdded+53
- third-party/video_to_data/reconstruction/modules/v2d_detectron2/lib/mv_track_bboxes.pyAdded+111
- third-party/video_to_data/reconstruction/modules/v2d_detectron2/lib/mv_track_bboxes.yamlAdded+41
- third-party/video_to_data/reconstruction/modules/v2d_detectron2/lib/pyproject.tomlAdded+31
- third-party/video_to_data/reconstruction/modules/v2d_detectron2/lib/track_bboxes.pyAdded+245
- third-party/video_to_data/reconstruction/modules/v2d_detectron2/lib/tracker.pyAdded+503
- third-party/video_to_data/reconstruction/modules/v2d_docker/LICENSEAdded+15
- third-party/video_to_data/reconstruction/modules/v2d_docker/__init__.pyAdded+5
- third-party/video_to_data/reconstruction/modules/v2d_docker/container.pyAdded+103
- third-party/video_to_data/reconstruction/modules/v2d_docker/pyproject.tomlAdded+18
- third-party/video_to_data/reconstruction/modules/v2d_droid_slam/LICENSEAdded+15
- third-party/video_to_data/reconstruction/modules/v2d_droid_slam/docker/DockerfileAdded+43
- third-party/video_to_data/reconstruction/modules/v2d_droid_slam/docker/__init__.pyAdded+2
- third-party/video_to_data/reconstruction/modules/v2d_droid_slam/docker/_config.pyAdded+6
- third-party/video_to_data/reconstruction/modules/v2d_droid_slam/docker/build.pyAdded+19
- third-party/video_to_data/reconstruction/modules/v2d_droid_slam/docker/pyproject.tomlAdded+18
- third-party/video_to_data/reconstruction/modules/v2d_droid_slam/docker/run_download_weights.pyAdded+36
- third-party/video_to_data/reconstruction/modules/v2d_droid_slam/docker/run_image_list_to_slam.pyAdded+152
- third-party/video_to_data/reconstruction/modules/v2d_droid_slam/docker/run_video_to_slam.pyAdded+152
- third-party/video_to_data/reconstruction/modules/v2d_droid_slam/lib/__init__.pyAdded+2
- third-party/video_to_data/reconstruction/modules/v2d_droid_slam/lib/_slam.pyAdded+350
- third-party/video_to_data/reconstruction/modules/v2d_droid_slam/lib/download_weights.pyAdded+32
- third-party/video_to_data/reconstruction/modules/v2d_droid_slam/lib/image_list_to_slam.pyAdded+223
- third-party/video_to_data/reconstruction/modules/v2d_droid_slam/lib/pyproject.tomlAdded+25
- third-party/video_to_data/reconstruction/modules/v2d_droid_slam/lib/video_to_slam.pyAdded+217
- third-party/video_to_data/reconstruction/modules/v2d_droid_slam/tools/poses_to_frustums.pyAdded+125
- third-party/video_to_data/reconstruction/modules/v2d_ego_hand_reconstruction/.gitignoreAdded+4
- third-party/video_to_data/reconstruction/modules/v2d_ego_hand_reconstruction/LICENSEAdded+15
- third-party/video_to_data/reconstruction/modules/v2d_ego_hand_reconstruction/README.mdAdded+115
- third-party/video_to_data/reconstruction/modules/v2d_ego_hand_reconstruction/__init__.pyAdded+2
- third-party/video_to_data/reconstruction/modules/v2d_ego_hand_reconstruction/diff.shAdded+44
- third-party/video_to_data/reconstruction/modules/v2d_ego_hand_reconstruction/docker/__init__.pyAdded+2
- third-party/video_to_data/reconstruction/modules/v2d_ego_hand_reconstruction/docker/_config.pyAdded+6
- third-party/video_to_data/reconstruction/modules/v2d_ego_hand_reconstruction/docker/build.pyAdded+48
- third-party/video_to_data/reconstruction/modules/v2d_ego_hand_reconstruction/docker/pyproject.tomlAdded+19
- third-party/video_to_data/reconstruction/modules/v2d_ego_hand_reconstruction/docker/run_mesh_generation.pyAdded+72
12# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.# SPDX-License-Identifier: Apache-2.0123456# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.# SPDX-License-Identifier: Apache-2.0import os
IMAGE_NAME = "v2d_detectron2"MODULES_DIR = os.path.abspath(os.path.join(os.path.dirname(os.path.abspath(__file__)), "..", ".."))12345678910111213141516171819# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.# SPDX-License-Identifier: Apache-2.0import subprocessimport os
IMAGE_NAME = "v2d_detectron2"
current_dir = os.path.dirname(os.path.abspath(__file__))module_dir = os.path.join(current_dir, "..")root_dir = os.path.join(module_dir, "..")dockerfile_path = os.path.join(current_dir, "Dockerfile")
def build_docker_image() -> None: subprocess.run(["docker", "build", "-t", IMAGE_NAME, "-f", dockerfile_path, root_dir], check=True)
if __name__ == "__main__": build_docker_image()123456789101112131415161718# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.# SPDX-License-Identifier: Apache-2.0[build-system]requires = ["setuptools>=68.0", "wheel"]build-backend = "setuptools.build_meta"
[project]name = "v2d-detectron2-docker"version = "0.1.0"description = "Docker orchestration scripts for Detectron2 tracking"requires-python = ">=3.10"dependencies = ["v2d-docker", "omegaconf"]
[tool.setuptools]packages = ["v2d.detectron2.docker"]
[tool.setuptools.package-dir]"v2d.detectron2.docker" = "."1234567891011121314151617181920212223242526272829303132333435363738394041# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.# SPDX-License-Identifier: Apache-2.0import osimport subprocessfrom v2d.detectron2.docker._config import IMAGE_NAME, MODULES_DIR
def run_download_weights( output_dir: str, model_sizes: list[str] | None = None, dev: bool = False,) -> None: if not os.path.exists(output_dir): os.makedirs(output_dir) output_dir = os.path.abspath(output_dir)
cmd = [ "docker", "run", "--rm", "--user", f"{os.getuid()}:{os.getgid()}", "-v", f"{output_dir}:/data/weights", ] if dev: cmd += ["-v", f"{MODULES_DIR}:/workspace"] cmd += [IMAGE_NAME, "python", "-m", "v2d.detectron2.lib.download_weights", "--output_dir", "/data/weights"] if model_sizes: cmd += ["--model_sizes"] + model_sizes
subprocess.run(cmd, check=True)
if __name__ == "__main__": import argparse
parser = argparse.ArgumentParser(description="Download ViTDet checkpoints") parser.add_argument("--output_dir", type=str, required=True) parser.add_argument("--model_sizes", type=str, nargs="+", default=["b"], choices=["b", "l", "h"]) parser.add_argument("--dev", action="store_true") args = parser.parse_args()
run_download_weights(args.output_dir, args.model_sizes, dev=args.dev)12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.# SPDX-License-Identifier: Apache-2.0from pathlib import Path
from v2d.docker.container import run_in_containerfrom v2d.detectron2.docker._config import IMAGE_NAME, MODULES_DIR
_LIB_CONFIG = Path(__file__).parent.parent / "lib" / "mv_track_bboxes.yaml"
def run_mv_track_bboxes( rgb_dir: str, weights_dir: str, output_dir: str, labeled_bbox_dir: str | None = None, config_path: str = str(_LIB_CONFIG), debug: int = -1, dev: bool = False,) -> None: inputs = { "rgb_dir": rgb_dir, "weights_dir": weights_dir, "config_path": config_path, } if labeled_bbox_dir: inputs["labeled_bbox_dir"] = labeled_bbox_dir
outputs = {"output_dir": output_dir}
run_in_container( image=IMAGE_NAME, module="v2d.detectron2.lib.mv_track_bboxes", inputs=inputs, outputs=outputs, extra_args={"debug": debug if debug >= 0 else None}, dev=dev, modules_dir=MODULES_DIR, gpus=True, env={ "PYTHONUNBUFFERED": "1", }, )
if __name__ == "__main__": import argparse
parser = argparse.ArgumentParser(description="Run multi-view bbox tracking") parser.add_argument("--rgb_dir", type=str, required=True, help="Directory containing input frames") parser.add_argument("--weights_dir", type=str, required=True, help="Directory containing model weights") parser.add_argument("--output_dir", type=str, required=True, help="Directory for outputs") parser.add_argument( "--labeled_bbox_dir", type=str, default=None, help="Optional directory with per-camera labeled object bbox JSONs " "(anchors primary person selection to the object bbox).", ) parser.add_argument("--config_path", type=str, default=str(_LIB_CONFIG), help="Path to mv_track_bboxes.yaml") parser.add_argument("--debug", type=int, default=-1, help="Debug level") parser.add_argument("--dev", action="store_true") args = parser.parse_args()
run_mv_track_bboxes( rgb_dir=args.rgb_dir, weights_dir=args.weights_dir, output_dir=args.output_dir, labeled_bbox_dir=args.labeled_bbox_dir, config_path=args.config_path, debug=args.debug, dev=args.dev, )1234567891011121314151617181920212223242526# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.# SPDX-License-Identifier: Apache-2.0import subprocessimport osfrom v2d.detectron2.docker._config import IMAGE_NAME, MODULES_DIR
def run_shell(dev: bool = False) -> None: cmd = [ "docker", "run", "-it", "--rm", "--gpus", "all", "--user", f"{os.getuid()}:{os.getgid()}", ] if dev: cmd += ["-v", f"{MODULES_DIR}:/workspace"] cmd += [IMAGE_NAME, "bash"] subprocess.run(cmd, check=True)
if __name__ == "__main__": import argparse
parser = argparse.ArgumentParser(description="Run shell in v2d_detectron2 container") parser.add_argument("--dev", action="store_true", help="Mount local modules for development") args = parser.parse_args() run_shell(dev=args.dev)123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.# SPDX-License-Identifier: Apache-2.0from v2d.docker.container import run_in_containerfrom v2d.detectron2.docker._config import IMAGE_NAME, MODULES_DIR
def run_track_bboxes( rgb_path: str, weights_dir: str, output_path: str, model_size: str = "b", bbox_thr: float = 0.5, iou_threshold: float = 0.3, max_lost: int = 30, min_hits: int = 3, batch_size: int = 1, debug: int = 0, dev: bool = False,) -> None: inputs = { "rgb_path": rgb_path, "weights_dir": weights_dir, }
run_in_container( image=IMAGE_NAME, module="v2d.detectron2.lib.track_bboxes", inputs=inputs, outputs={"output_path": output_path}, extra_args={ "model_size": model_size, "bbox_thr": bbox_thr, "iou_threshold": iou_threshold, "max_lost": max_lost, "min_hits": min_hits, "batch_size": batch_size, "debug": debug if debug > 0 else None, }, dev=dev, modules_dir=MODULES_DIR, gpus=True, env={ "PYTHONUNBUFFERED": "1", }, )
if __name__ == "__main__": import argparse
parser = argparse.ArgumentParser(description="Run bbox tracking (single camera)") parser.add_argument("--rgb_path", type=str, required=True, help="Path to input frames (image dir, .h5, or video file)") parser.add_argument("--weights_dir", type=str, required=True) parser.add_argument("--output_path", type=str, required=True, help="Output .pt file path") parser.add_argument("--model_size", type=str, default="b", choices=["b", "l", "h"]) parser.add_argument("--bbox_thr", type=float, default=0.5) parser.add_argument("--iou_threshold", type=float, default=0.3) parser.add_argument("--max_lost", type=int, default=30) parser.add_argument("--min_hits", type=int, default=3) parser.add_argument("--batch_size", type=int, default=1) parser.add_argument("--debug", type=int, default=0) parser.add_argument("--dev", action="store_true") args = parser.parse_args()
run_track_bboxes( rgb_path=args.rgb_path, weights_dir=args.weights_dir, output_path=args.output_path, model_size=args.model_size, bbox_thr=args.bbox_thr, iou_threshold=args.iou_threshold, max_lost=args.max_lost, min_hits=args.min_hits, batch_size=args.batch_size, debug=args.debug, dev=args.dev, )12# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.# SPDX-License-Identifier: Apache-2.0123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188# Copyright (c) Meta Platforms, Inc. and affiliates.
import osfrom pathlib import Path
import numpy as npimport torch
class Detector: def __init__( self, name="vitdet", device="cuda", model_size="b", test_score_thresh: float = 0.25, **kwargs, ): self.device = device
if name == "vitdet": print(f"Loading ViTDet-{model_size.upper()} detector...") self.detector = load_detectron2_vitdet( model_size=model_size, test_score_thresh=test_score_thresh, **kwargs, ) self.detector_func = run_detectron2_vitdet self.batch_func = run_detectron2_vitdet_batch
self.detector = self.detector.to(self.device) self.detector.eval() else: raise NotImplementedError
def run_detection(self, img, **kwargs): return self.detector_func(self.detector, img, **kwargs)
def run_detection_batch(self, images: list[np.ndarray], **kwargs) -> list[tuple[np.ndarray, np.ndarray]]: return self.batch_func(self.detector, images, **kwargs)
VITDET_VARIANTS = { "b": { "config": "cascade_mask_rcnn_vitdet_b_100ep.py", "checkpoint_url": "https://dl.fbaipublicfiles.com/detectron2/ViTDet/COCO/cascade_mask_rcnn_vitdet_b/f325358525/model_final_435fa9.pkl", "checkpoint_file": "model_final_435fa9.pkl", }, "l": { "config": "cascade_mask_rcnn_vitdet_l_100ep.py", "checkpoint_url": "https://dl.fbaipublicfiles.com/detectron2/ViTDet/COCO/cascade_mask_rcnn_vitdet_l/f328021305/model_final_1a9f28.pkl", "checkpoint_file": "model_final_1a9f28.pkl", }, "h": { "config": "cascade_mask_rcnn_vitdet_h_75ep.py", "checkpoint_url": "https://dl.fbaipublicfiles.com/detectron2/ViTDet/COCO/cascade_mask_rcnn_vitdet_h/f328730692/model_final_f05665.pkl", "checkpoint_file": "model_final_f05665.pkl", },}
def load_detectron2_vitdet( path: str = "", model_size: str = "b", test_score_thresh: float = 0.25,): """Load a ViTDet Cascade Mask R-CNN detector.
Args: path: Directory containing the checkpoint file. If empty, downloads from the detectron2 model zoo. model_size: One of "b" (ViT-Base, fastest), "l" (ViT-Large), "h" (ViT-Huge, most accurate). test_score_thresh: Internal NMS score threshold. Detections below this are discarded before they leave the model. Lower for ByteTrack (e.g. 0.1) to retain partial-occlusion detections. """ from detectron2.checkpoint import DetectionCheckpointer from detectron2.config import instantiate, LazyConfig
if model_size not in VITDET_VARIANTS: raise ValueError(f"Unknown model_size '{model_size}', expected one of {list(VITDET_VARIANTS)}") variant = VITDET_VARIANTS[model_size]
cfg_path = Path(__file__).parent / variant["config"] if not cfg_path.exists(): raise FileNotFoundError(f"Config file not found at {cfg_path}")
detectron2_cfg = LazyConfig.load(str(cfg_path)) detectron2_cfg.train.init_checkpoint = ( variant["checkpoint_url"] if path == "" else os.path.join(path, variant["checkpoint_file"]) ) for i in range(3): detectron2_cfg.model.roi_heads.box_predictors[i].test_score_thresh = test_score_thresh detector = instantiate(detectron2_cfg.model) checkpointer = DetectionCheckpointer(detector) checkpointer.load(detectron2_cfg.train.init_checkpoint)
detector.eval() return detector
def run_detectron2_vitdet( detector, img, det_cat_id: int = 0, # 0: person bbox_thr: float = 0.5, default_to_full_image: bool = True,): import detectron2.data.transforms as T
height, width = img.shape[:2]
IMAGE_SIZE = 1024 transforms = T.ResizeShortestEdge(short_edge_length=IMAGE_SIZE, max_size=IMAGE_SIZE) img_transformed = transforms(T.AugInput(img)).apply_image(img) img_transformed = torch.as_tensor( img_transformed.astype("float32").transpose(2, 0, 1) ) inputs = {"image": img_transformed, "height": height, "width": width}
with torch.no_grad(): det_out = detector([inputs])
det_instances = det_out[0]["instances"] valid_idx = (det_instances.pred_classes == det_cat_id) & ( det_instances.scores > bbox_thr ) if valid_idx.sum() == 0 and default_to_full_image: boxes = np.array([0, 0, width, height]).reshape(1, 4) scores = np.array([1.0]) else: boxes = det_instances.pred_boxes.tensor[valid_idx].cpu().numpy() scores = det_instances.scores[valid_idx].cpu().numpy()
sorted_indices = np.argsort(scores)[::-1] return boxes[sorted_indices].reshape(-1, 4), scores[sorted_indices]
def run_detectron2_vitdet_batch( detector, images: list[np.ndarray], det_cat_id: int = 0, bbox_thr: float = 0.5, default_to_full_image: bool = True,) -> list[tuple[np.ndarray, np.ndarray]]: """Run ViTDet detection on a batch of images in a single forward pass.
Memory scales linearly with batch size (~2-3 GB per image for ViTDet-B at 1024px). Batch sizes of 4-8 are practical on a 24 GB GPU. """ import detectron2.data.transforms as T
IMAGE_SIZE = 768 transforms = T.ResizeShortestEdge(short_edge_length=IMAGE_SIZE, max_size=IMAGE_SIZE)
inputs = [] for img in images: height, width = img.shape[:2] img_transformed = transforms(T.AugInput(img)).apply_image(img) img_transformed = torch.as_tensor( img_transformed.astype("float32").transpose(2, 0, 1) ) inputs.append({"image": img_transformed, "height": height, "width": width})
with torch.no_grad(): det_outputs = detector(inputs)
results = [] for img, det_out in zip(images, det_outputs): height, width = img.shape[:2] det_instances = det_out["instances"] valid_idx = (det_instances.pred_classes == det_cat_id) & ( det_instances.scores > bbox_thr ) if valid_idx.sum() == 0 and default_to_full_image: boxes = np.array([0, 0, width, height]).reshape(1, 4) scores = np.array([1.0]) else: boxes = det_instances.pred_boxes.tensor[valid_idx].cpu().numpy() scores = det_instances.scores[valid_idx].cpu().numpy()
sorted_indices = np.argsort(scores)[::-1] results.append((boxes[sorted_indices].reshape(-1, 4), scores[sorted_indices]))
return results123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.# SPDX-License-Identifier: Apache-2.0"""ByteTrack multi-object tracker.
Implements the two-stage association strategy from: Zhang et al., "ByteTrack: Multi-Object Tracking by Associating Every Detection Box", ECCV 2022.
Key idea: low-confidence detections (from partial occlusion) are used in a secondassociation pass to maintain tracks that would otherwise be lost.
Uses a Kalman filter with constant-velocity model for bbox state prediction."""
from __future__ import annotations
import numpy as np
from .tracker import Track, TrackState, bbox_iou_matrix, hungarian_assign
def _bbox_to_z(bbox: np.ndarray) -> np.ndarray: """Convert [x1, y1, x2, y2] to Kalman measurement [cx, cy, a, h].""" w = bbox[2] - bbox[0] h = bbox[3] - bbox[1] cx = bbox[0] + w / 2 cy = bbox[1] + h / 2 a = w / (h + 1e-6) return np.array([cx, cy, a, h])
def _z_to_bbox(z: np.ndarray) -> np.ndarray: """Convert Kalman measurement [cx, cy, a, h] to [x1, y1, x2, y2].""" w = z[2] * z[3] h = z[3] return np.array([ z[0] - w / 2, z[1] - h / 2, z[0] + w / 2, z[1] + h / 2, ])
class KalmanBoxTracker: """Per-track Kalman filter over [cx, cy, aspect_ratio, h, vcx, vcy, va, vh]."""
_DIM_Z = 4 _DIM_X = 8
def __init__(self, bbox: np.ndarray): self.x = np.zeros(self._DIM_X) self.x[:self._DIM_Z] = _bbox_to_z(bbox)
# State transition (constant velocity) self.F = np.eye(self._DIM_X) for i in range(self._DIM_Z): self.F[i, self._DIM_Z + i] = 1.0
# Measurement matrix self.H = np.zeros((self._DIM_Z, self._DIM_X)) self.H[:self._DIM_Z, :self._DIM_Z] = np.eye(self._DIM_Z)
# Covariance self.P = np.eye(self._DIM_X) * 10.0 self.P[self._DIM_Z:, self._DIM_Z:] *= 1000.0
# Process noise self.Q = np.eye(self._DIM_X) self.Q[self._DIM_Z:, self._DIM_Z:] *= 0.01
# Measurement noise self.R = np.eye(self._DIM_Z) self.R[2, 2] *= 10.0 # aspect ratio is less certain
def predict(self) -> np.ndarray: """Advance state and return predicted bbox [x1, y1, x2, y2].""" # Prevent negative height if self.x[3] + self.x[7] <= 0: self.x[7] = 0.0
self.x = self.F @ self.x self.P = self.F @ self.P @ self.F.T + self.Q return self.get_bbox()
def update(self, bbox: np.ndarray) -> None: """Correct state with observed bbox.""" z = _bbox_to_z(bbox) y = z - self.H @ self.x S = self.H @ self.P @ self.H.T + self.R K = self.P @ self.H.T @ np.linalg.inv(S) self.x = self.x + K @ y I_KH = np.eye(self._DIM_X) - K @ self.H self.P = I_KH @ self.P
def get_bbox(self) -> np.ndarray: """Current state as [x1, y1, x2, y2].""" return _z_to_bbox(self.x[:self._DIM_Z])
class _STrack: """Internal tracked object pairing a Track with its Kalman state."""
def __init__(self, track: Track, kalman: KalmanBoxTracker): self.track = track self.kalman = kalman
class ByteTracker: """ByteTrack multi-object tracker with two-stage association.
Args: track_thresh: Confidence split between high and low detections. match_thresh: IoU threshold for first (high-confidence) association. second_match_thresh: IoU threshold for second (low-confidence) association. max_lost: Frames a track survives without a match before removal. min_hits: Minimum detections before a tentative track is confirmed. """
def __init__( self, track_thresh: float = 0.6, match_thresh: float = 0.8, second_match_thresh: float = 0.5, max_lost: int = 30, min_hits: int = 3, ): self.track_thresh = track_thresh self.match_thresh = match_thresh self.second_match_thresh = second_match_thresh self.max_lost = max_lost self.min_hits = min_hits
self._next_id = 0 self._active: list[_STrack] = [] self._lost: list[_STrack] = [] self._tentative: list[_STrack] = [] self._finished: list[_STrack] = []
def _new_strack(self, frame_idx: int, bbox: np.ndarray, score: float) -> _STrack: track = Track(track_id=self._next_id, state=TrackState.TENTATIVE) track.append(frame_idx, bbox, score) kalman = KalmanBoxTracker(bbox) self._next_id += 1 return _STrack(track, kalman)
def _predicted_bboxes(self, stracks: list[_STrack]) -> np.ndarray: if not stracks: return np.empty((0, 4)) return np.array([st.kalman.predict() for st in stracks])
def update(self, frame_idx: int, bboxes: np.ndarray, scores: np.ndarray): """Process one frame of detections (all above det_thresh).
The caller should pass ALL detections above det_thresh; this method splits them into high/low confidence internally. """ # Split detections by confidence high_mask = scores >= self.track_thresh low_mask = ~high_mask
high_bboxes = bboxes[high_mask] if high_mask.any() else np.empty((0, 4)) high_scores = scores[high_mask] if high_mask.any() else np.empty(0) low_bboxes = bboxes[low_mask] if low_mask.any() else np.empty((0, 4)) low_scores = scores[low_mask] if low_mask.any() else np.empty(0)
# Predict positions for all tracked objects established = self._active + self._lost pred_bboxes = self._predicted_bboxes(established)
# --- First association: high-confidence detections vs all tracks --- if len(established) > 0 and len(high_bboxes) > 0: iou = bbox_iou_matrix(pred_bboxes, high_bboxes) matches_1, unmatched_t_1, unmatched_d_1 = hungarian_assign( iou, self.match_thresh ) elif len(established) > 0: matches_1 = [] unmatched_t_1 = list(range(len(established))) unmatched_d_1 = [] else: matches_1 = [] unmatched_t_1 = [] unmatched_d_1 = list(range(len(high_bboxes)))
new_active: list[_STrack] = []
for t_idx, d_idx in matches_1: st = established[t_idx] st.kalman.update(high_bboxes[d_idx]) st.track.append(frame_idx, high_bboxes[d_idx], float(high_scores[d_idx])) new_active.append(st)
# --- Second association: low-confidence detections vs unmatched tracks --- remaining_stracks = [established[i] for i in unmatched_t_1]
if len(remaining_stracks) > 0 and len(low_bboxes) > 0: remaining_pred = np.array([st.kalman.get_bbox() for st in remaining_stracks]) iou_2 = bbox_iou_matrix(remaining_pred, low_bboxes) matches_2, unmatched_t_2, _ = hungarian_assign( iou_2, self.second_match_thresh ) elif len(remaining_stracks) > 0: matches_2 = [] unmatched_t_2 = list(range(len(remaining_stracks))) else: matches_2 = [] unmatched_t_2 = []
for t_idx, d_idx in matches_2: st = remaining_stracks[t_idx] st.kalman.update(low_bboxes[d_idx]) st.track.append(frame_idx, low_bboxes[d_idx], float(low_scores[d_idx])) new_active.append(st)
# Handle tracks that matched neither stage new_lost: list[_STrack] = [] for t_idx in unmatched_t_2: st = remaining_stracks[t_idx] st.track.frames_since_match += 1 if st.track.frames_since_match > self.max_lost: st.track.state = TrackState.FINISHED self._finished.append(st) else: st.track.state = TrackState.LOST new_lost.append(st)
# --- Tentative track association with unmatched high-conf detections --- unmatched_high_bboxes = high_bboxes[unmatched_d_1] if unmatched_d_1 else np.empty((0, 4)) unmatched_high_scores = high_scores[unmatched_d_1] if unmatched_d_1 else np.empty(0)
new_tentative: list[_STrack] = []
if len(self._tentative) > 0 and len(unmatched_high_bboxes) > 0: tent_pred = self._predicted_bboxes(self._tentative) iou_3 = bbox_iou_matrix(tent_pred, unmatched_high_bboxes) matches_3, unmatched_tent, unmatched_d_3 = hungarian_assign( iou_3, self.match_thresh ) elif len(self._tentative) > 0: matches_3 = [] unmatched_tent = list(range(len(self._tentative))) unmatched_d_3 = [] else: matches_3 = [] unmatched_tent = [] unmatched_d_3 = list(range(len(unmatched_high_bboxes)))
for t_idx, d_idx in matches_3: st = self._tentative[t_idx] st.kalman.update(unmatched_high_bboxes[d_idx]) st.track.append( frame_idx, unmatched_high_bboxes[d_idx], float(unmatched_high_scores[d_idx]), ) if st.track.length >= self.min_hits: st.track.state = TrackState.ACTIVE new_active.append(st) else: new_tentative.append(st)
for t_idx in unmatched_tent: st = self._tentative[t_idx] st.track.state = TrackState.FINISHED self._finished.append(st)
# Only high-confidence unmatched detections start new tracks for d_idx in unmatched_d_3: new_tentative.append( self._new_strack( frame_idx, unmatched_high_bboxes[d_idx], float(unmatched_high_scores[d_idx]), ) )
self._active = new_active self._lost = new_lost self._tentative = new_tentative
def finalize(self) -> list[Track]: """Return all tracks sorted by track_id.""" all_stracks = ( self._finished + self._active + self._lost + self._tentative ) tracks = [st.track for st in all_stracks] tracks.sort(key=lambda t: t.track_id) return tracks123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101# Copyright (c) Meta Platforms, Inc. and affiliates.# Cascade Mask R-CNN with ViT-B backbone (100 epochs).# Adapted from detectron2 model zoo: projects/ViTDet/configs/COCO/
## coco_loader_lsj.py
import detectron2.data.transforms as Tfrom detectron2 import model_zoofrom detectron2.config import LazyCall as L
# Data using LSJimage_size = 1024dataloader = model_zoo.get_config("common/data/coco.py").dataloaderdataloader.train.mapper.augmentations = [ L(T.RandomFlip)(horizontal=True), # flip first L(T.ResizeScale)( min_scale=0.1, max_scale=2.0, target_height=image_size, target_width=image_size ), L(T.FixedSizeCrop)(crop_size=(image_size, image_size), pad=False),]dataloader.train.mapper.image_format = "RGB"dataloader.train.total_batch_size = 64dataloader.train.mapper.recompute_boxes = True
dataloader.test.mapper.augmentations = [ L(T.ResizeShortestEdge)(short_edge_length=image_size, max_size=image_size),]
from functools import partialfrom fvcore.common.param_scheduler import MultiStepParamScheduler
from detectron2 import model_zoofrom detectron2.config import LazyCall as Lfrom detectron2.solver import WarmupParamSchedulerfrom detectron2.modeling.backbone.vit import get_vit_lr_decay_rate
## mask_rcnn_vitdet_b_100ep.py
model = model_zoo.get_config("common/models/mask_rcnn_vitdet.py").model
train = model_zoo.get_config("common/train.py").traintrain.amp.enabled = Truetrain.ddp.fp16_compression = Truetrain.init_checkpoint = "detectron2://ImageNetPretrained/MAE/mae_pretrain_vit_base.pth"
train.max_iter = 184375
lr_multiplier = L(WarmupParamScheduler)( scheduler=L(MultiStepParamScheduler)( values=[1.0, 0.1, 0.01], milestones=[163889, 177546], num_updates=train.max_iter, ), warmup_length=250 / train.max_iter, warmup_factor=0.001,)
optimizer = model_zoo.get_config("common/optim.py").AdamWoptimizer.params.lr_factor_func = partial(get_vit_lr_decay_rate, num_layers=12, lr_decay_rate=0.7)optimizer.params.overrides = {"pos_embed": {"weight_decay": 0.0}}
## cascade_mask_rcnn_vitdet_b_100ep.py
from detectron2.config import LazyCall as Lfrom detectron2.layers import ShapeSpecfrom detectron2.modeling.box_regression import Box2BoxTransformfrom detectron2.modeling.matcher import Matcherfrom detectron2.modeling.roi_heads import ( FastRCNNOutputLayers, FastRCNNConvFCHead, CascadeROIHeads,)
[model.roi_heads.pop(k) for k in ["box_head", "box_predictor", "proposal_matcher"]]
model.roi_heads.update( _target_=CascadeROIHeads, box_heads=[ L(FastRCNNConvFCHead)( input_shape=ShapeSpec(channels=256, height=7, width=7), conv_dims=[256, 256, 256, 256], fc_dims=[1024], conv_norm="LN", ) for _ in range(3) ], box_predictors=[ L(FastRCNNOutputLayers)( input_shape=ShapeSpec(channels=1024), test_score_thresh=0.05, box2box_transform=L(Box2BoxTransform)(weights=(w1, w1, w2, w2)), cls_agnostic_bbox_reg=True, num_classes="${...num_classes}", ) for (w1, w2) in [(10, 5), (20, 10), (30, 15)] ], proposal_matchers=[ L(Matcher)(thresholds=[th], labels=[0, 1], allow_low_quality_matches=False) for th in [0.5, 0.6, 0.7] ],)123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131# Copyright (c) Meta Platforms, Inc. and affiliates.
## coco_loader_lsj.py
import detectron2.data.transforms as Tfrom detectron2 import model_zoofrom detectron2.config import LazyCall as L
# Data using LSJimage_size = 1024dataloader = model_zoo.get_config("common/data/coco.py").dataloaderdataloader.train.mapper.augmentations = [ L(T.RandomFlip)(horizontal=True), # flip first L(T.ResizeScale)( min_scale=0.1, max_scale=2.0, target_height=image_size, target_width=image_size ), L(T.FixedSizeCrop)(crop_size=(image_size, image_size), pad=False),]dataloader.train.mapper.image_format = "RGB"dataloader.train.total_batch_size = 64# recompute boxes due to croppingdataloader.train.mapper.recompute_boxes = True
dataloader.test.mapper.augmentations = [ L(T.ResizeShortestEdge)(short_edge_length=image_size, max_size=image_size),]
from functools import partialfrom fvcore.common.param_scheduler import MultiStepParamScheduler
from detectron2 import model_zoofrom detectron2.config import LazyCall as Lfrom detectron2.solver import WarmupParamSchedulerfrom detectron2.modeling.backbone.vit import get_vit_lr_decay_rate
# mask_rcnn_vitdet_b_100ep.py
model = model_zoo.get_config("common/models/mask_rcnn_vitdet.py").model
# Initialization and trainer settingstrain = model_zoo.get_config("common/train.py").traintrain.amp.enabled = Truetrain.ddp.fp16_compression = Truetrain.init_checkpoint = "detectron2://ImageNetPretrained/MAE/mae_pretrain_vit_base.pth"
# Schedule# 100 ep = 184375 iters * 64 images/iter / 118000 images/eptrain.max_iter = 184375
lr_multiplier = L(WarmupParamScheduler)( scheduler=L(MultiStepParamScheduler)( values=[1.0, 0.1, 0.01], milestones=[163889, 177546], num_updates=train.max_iter, ), warmup_length=250 / train.max_iter, warmup_factor=0.001,)
# Optimizeroptimizer = model_zoo.get_config("common/optim.py").AdamWoptimizer.params.lr_factor_func = partial(get_vit_lr_decay_rate, num_layers=12, lr_decay_rate=0.7)optimizer.params.overrides = {"pos_embed": {"weight_decay": 0.0}}
# cascade_mask_rcnn_vitdet_b_100ep.py
from detectron2.config import LazyCall as Lfrom detectron2.layers import ShapeSpecfrom detectron2.modeling.box_regression import Box2BoxTransformfrom detectron2.modeling.matcher import Matcherfrom detectron2.modeling.roi_heads import ( FastRCNNOutputLayers, FastRCNNConvFCHead, CascadeROIHeads,)
# arguments that don't exist for Cascade R-CNN[model.roi_heads.pop(k) for k in ["box_head", "box_predictor", "proposal_matcher"]]
model.roi_heads.update( _target_=CascadeROIHeads, box_heads=[ L(FastRCNNConvFCHead)( input_shape=ShapeSpec(channels=256, height=7, width=7), conv_dims=[256, 256, 256, 256], fc_dims=[1024], conv_norm="LN", ) for _ in range(3) ], box_predictors=[ L(FastRCNNOutputLayers)( input_shape=ShapeSpec(channels=1024), test_score_thresh=0.05, box2box_transform=L(Box2BoxTransform)(weights=(w1, w1, w2, w2)), cls_agnostic_bbox_reg=True, num_classes="${...num_classes}", ) for (w1, w2) in [(10, 5), (20, 10), (30, 15)] ], proposal_matchers=[ L(Matcher)(thresholds=[th], labels=[0, 1], allow_low_quality_matches=False) for th in [0.5, 0.6, 0.7] ],)
# cascade_mask_rcnn_vitdet_h_75ep.py
from functools import partial
train.init_checkpoint = "detectron2://ImageNetPretrained/MAE/mae_pretrain_vit_huge_p14to16.pth"
model.backbone.net.embed_dim = 1280model.backbone.net.depth = 32model.backbone.net.num_heads = 16model.backbone.net.drop_path_rate = 0.5# 7, 15, 23, 31 for global attentionmodel.backbone.net.window_block_indexes = ( list(range(0, 7)) + list(range(8, 15)) + list(range(16, 23)) + list(range(24, 31)))
optimizer.params.lr_factor_func = partial(get_vit_lr_decay_rate, lr_decay_rate=0.9, num_layers=32)optimizer.params.overrides = {}optimizer.params.weight_decay_norm = None
train.max_iter = train.max_iter * 3 // 4 # 100ep -> 75eplr_multiplier.scheduler.milestones = [ milestone * 3 // 4 for milestone in lr_multiplier.scheduler.milestones]lr_multiplier.scheduler.num_updates = train.max_iter123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112# Copyright (c) Meta Platforms, Inc. and affiliates.# Cascade Mask R-CNN with ViT-L backbone (100 epochs).# Adapted from detectron2 model zoo: projects/ViTDet/configs/COCO/
## coco_loader_lsj.py
import detectron2.data.transforms as Tfrom detectron2 import model_zoofrom detectron2.config import LazyCall as L
# Data using LSJimage_size = 1024dataloader = model_zoo.get_config("common/data/coco.py").dataloaderdataloader.train.mapper.augmentations = [ L(T.RandomFlip)(horizontal=True), # flip first L(T.ResizeScale)( min_scale=0.1, max_scale=2.0, target_height=image_size, target_width=image_size ), L(T.FixedSizeCrop)(crop_size=(image_size, image_size), pad=False),]dataloader.train.mapper.image_format = "RGB"dataloader.train.total_batch_size = 64dataloader.train.mapper.recompute_boxes = True
dataloader.test.mapper.augmentations = [ L(T.ResizeShortestEdge)(short_edge_length=image_size, max_size=image_size),]
from functools import partialfrom fvcore.common.param_scheduler import MultiStepParamScheduler
from detectron2 import model_zoofrom detectron2.config import LazyCall as Lfrom detectron2.solver import WarmupParamSchedulerfrom detectron2.modeling.backbone.vit import get_vit_lr_decay_rate
## mask_rcnn_vitdet_b_100ep.py (base)
model = model_zoo.get_config("common/models/mask_rcnn_vitdet.py").model
train = model_zoo.get_config("common/train.py").traintrain.amp.enabled = Truetrain.ddp.fp16_compression = Truetrain.init_checkpoint = "detectron2://ImageNetPretrained/MAE/mae_pretrain_vit_large.pth?matching_heuristics=True"
train.max_iter = 184375
lr_multiplier = L(WarmupParamScheduler)( scheduler=L(MultiStepParamScheduler)( values=[1.0, 0.1, 0.01], milestones=[163889, 177546], num_updates=train.max_iter, ), warmup_length=250 / train.max_iter, warmup_factor=0.001,)
optimizer = model_zoo.get_config("common/optim.py").AdamWoptimizer.params.lr_factor_func = partial(get_vit_lr_decay_rate, lr_decay_rate=0.8, num_layers=24)optimizer.params.overrides = {"pos_embed": {"weight_decay": 0.0}}
## cascade_mask_rcnn_vitdet_b_100ep.py (cascade heads)
from detectron2.config import LazyCall as Lfrom detectron2.layers import ShapeSpecfrom detectron2.modeling.box_regression import Box2BoxTransformfrom detectron2.modeling.matcher import Matcherfrom detectron2.modeling.roi_heads import ( FastRCNNOutputLayers, FastRCNNConvFCHead, CascadeROIHeads,)
[model.roi_heads.pop(k) for k in ["box_head", "box_predictor", "proposal_matcher"]]
model.roi_heads.update( _target_=CascadeROIHeads, box_heads=[ L(FastRCNNConvFCHead)( input_shape=ShapeSpec(channels=256, height=7, width=7), conv_dims=[256, 256, 256, 256], fc_dims=[1024], conv_norm="LN", ) for _ in range(3) ], box_predictors=[ L(FastRCNNOutputLayers)( input_shape=ShapeSpec(channels=1024), test_score_thresh=0.05, box2box_transform=L(Box2BoxTransform)(weights=(w1, w1, w2, w2)), cls_agnostic_bbox_reg=True, num_classes="${...num_classes}", ) for (w1, w2) in [(10, 5), (20, 10), (30, 15)] ], proposal_matchers=[ L(Matcher)(thresholds=[th], labels=[0, 1], allow_low_quality_matches=False) for th in [0.5, 0.6, 0.7] ],)
## cascade_mask_rcnn_vitdet_l_100ep.py (ViT-L backbone overrides)
model.backbone.net.embed_dim = 1024model.backbone.net.depth = 24model.backbone.net.num_heads = 16model.backbone.net.drop_path_rate = 0.4# 5, 11, 17, 23 for global attentionmodel.backbone.net.window_block_indexes = ( list(range(0, 5)) + list(range(6, 11)) + list(range(12, 17)) + list(range(18, 23)))1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.# SPDX-License-Identifier: Apache-2.0import argparseimport urllib.requestfrom pathlib import Path
VITDET_VARIANTS = { "b": { "url": "https://dl.fbaipublicfiles.com/detectron2/ViTDet/COCO/cascade_mask_rcnn_vitdet_b/f325358525/model_final_435fa9.pkl", "file": "model_final_435fa9.pkl", }, "l": { "url": "https://dl.fbaipublicfiles.com/detectron2/ViTDet/COCO/cascade_mask_rcnn_vitdet_l/f328021305/model_final_1a9f28.pkl", "file": "model_final_1a9f28.pkl", }, "h": { "url": "https://dl.fbaipublicfiles.com/detectron2/ViTDet/COCO/cascade_mask_rcnn_vitdet_h/f328730692/model_final_f05665.pkl", "file": "model_final_f05665.pkl", },}
def download_weights(output_dir: str, model_sizes: list[str] | None = None): if model_sizes is None: model_sizes = ["b"]
for size in model_sizes: if size not in VITDET_VARIANTS: raise ValueError(f"Unknown model size '{size}', expected one of {list(VITDET_VARIANTS)}")
variant = VITDET_VARIANTS[size] dest_dir = Path(output_dir) / f"cascade_mask_rcnn_vitdet_{size}" dest_dir.mkdir(parents=True, exist_ok=True) dest_file = dest_dir / variant["file"]
if dest_file.exists(): print(f"ViTDet-{size.upper()} checkpoint already exists at {dest_file}") continue
print(f"Downloading ViTDet-{size.upper()} checkpoint to {dest_file}...") urllib.request.urlretrieve(variant["url"], dest_file) print("Done.")
if __name__ == "__main__": parser = argparse.ArgumentParser(description="Download ViTDet checkpoints") parser.add_argument("--output_dir", type=str, required=True, help="Directory to save checkpoints") parser.add_argument( "--model_sizes", type=str, nargs="+", default=["b"], choices=["b", "l", "h"], help="Which model sizes to download (default: b)", ) args = parser.parse_args() download_weights(args.output_dir, args.model_sizes)123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.# SPDX-License-Identifier: Apache-2.0from pathlib import Path
import torch
from v2d.mv.rig import RigConfig
from .build_detector import Detectorfrom .track_bboxes import ( ByteTrackerConfig, DetectorConfig, IoUTrackerConfig, track_bboxes,)
DEVICE = torch.device("cuda" if torch.cuda.is_available() else "cpu")
def mv_track_bboxes_from_config(cfg): """Run detection + tracking across multiple cameras defined by a rig config.""" rig = RigConfig(cfg.rig_config)
detector_cfg = DetectorConfig( model_size=cfg.detector.model_size, weights_dir=cfg.detector.weights_dir, det_cat_id=cfg.detector.det_cat_id, bbox_thr=cfg.detector.bbox_thr, default_to_full_image=cfg.detector.default_to_full_image, test_score_thresh=cfg.detector.get("test_score_thresh", 0.25), ) tracker_type = cfg.get("tracker_type", "iou") if tracker_type == "byte": bt = cfg.byte_tracker tracker_cfg = ByteTrackerConfig( track_thresh=bt.get("track_thresh", 0.6), det_thresh=bt.get("det_thresh", 0.1), match_thresh=bt.get("match_thresh", 0.8), second_match_thresh=bt.get("second_match_thresh", 0.5), max_lost=bt.get("max_lost", 30), min_hits=bt.get("min_hits", 3), merge_max_gap=bt.get("merge_max_gap", 60), merge_iou_threshold=bt.get("merge_iou_threshold", 0.3), ) else: it = cfg.iou_tracker tracker_cfg = IoUTrackerConfig( iou_threshold=it.get("iou_threshold", 0.3), max_lost=it.get("max_lost", 30), min_hits=it.get("min_hits", 3), merge_max_gap=it.get("merge_max_gap", 10), merge_iou_threshold=it.get("merge_iou_threshold", 0.5), )
weights_path = f"{detector_cfg.weights_dir}/cascade_mask_rcnn_vitdet_{detector_cfg.model_size}" detector = Detector( name="vitdet", device=DEVICE, model_size=detector_cfg.model_size, path=weights_path, test_score_thresh=detector_cfg.test_score_thresh, )
batch_size = cfg.get("batch_size", 1)
for cam_id in cfg.cameras: cam = rig.get_camera(cam_id) print(f"Running Detectron2 bbox tracking for camera: {cam.name}")
rgb_path = Path(cfg.rgb_path_template.format(cam_name=cam.name)) output_path = Path(cfg.output_path_template.format(cam_name=cam.name))
track_bboxes( rgb_path=rgb_path, output_path=output_path, detector_cfg=detector_cfg, tracker_cfg=tracker_cfg, batch_size=batch_size, detector=detector, debug=cfg.debug, )
if __name__ == "__main__": import argparse
from omegaconf import OmegaConf
parser = argparse.ArgumentParser(description="Run multi-view detection + tracking") parser.add_argument("--rgb_dir", type=str, required=True, help="Directory containing input frames") parser.add_argument("--weights_dir", type=str, required=True, help="Directory containing model weights") parser.add_argument("--output_dir", type=str, required=True, help="Directory for outputs") parser.add_argument("--config_path", type=str, default=None, help="Optional override config (merged on top of defaults)") parser.add_argument("--debug", type=int, default=None, help="Debug level override") args = parser.parse_args()
cfg = OmegaConf.load(Path(__file__).parent / "mv_track_bboxes.yaml") if args.config_path: cfg = OmegaConf.merge(cfg, OmegaConf.load(args.config_path)) overrides: dict = { "rgb_dir": args.rgb_dir, "detector": {"weights_dir": args.weights_dir}, "output_dir": args.output_dir, } if args.debug is not None: overrides["debug"] = args.debug
cfg = OmegaConf.merge(cfg, overrides) mv_track_bboxes_from_config(cfg)1234567891011121314151617181920212223242526272829303132333435363738394041# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.# SPDX-License-Identifier: Apache-2.0rgb_dir: ???output_dir: ???
rig_config: stereo-4cameras: [0, 2, 4, 6]
rgb_path_template: "${rgb_dir}/{cam_name}"output_path_template: "${output_dir}/{cam_name}_bbox_track.pt"
batch_size: 2
detector: weights_dir: ??? model_size: b # "b" (ViT-Base, fastest), "l" (ViT-Large), "h" (ViT-Huge, most accurate) det_cat_id: 0 # 0: person bbox_thr: 0.5 # minimum confidence score for a detection to be considered valid default_to_full_image: True # if no valid detections, return the full image as a detection test_score_thresh: 0.1 # model-internal NMS threshold; lower for ByteTrack (0.1), default IoU (0.25)
tracker_type: byte # "iou" or "byte"
iou_tracker: iou_threshold: 0.3 max_lost: 30 min_hits: 3 merge_max_gap: 10 merge_iou_threshold: 0.5
byte_tracker: track_thresh: 0.6 # high confidence threshold (first association) det_thresh: 0.1 # low confidence threshold (second association) match_thresh: 0.8 # IoU threshold for first association second_match_thresh: 0.5 # IoU threshold for second association max_lost: 30 min_hits: 3 merge_max_gap: 60 # frames gap tolerance for merging fragmented tracks merge_iou_threshold: 0.3 # IoU threshold for merging (lower = more aggressive)
debug: 212345678910111213141516171819202122232425262728293031# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.# SPDX-License-Identifier: Apache-2.0[build-system]requires = ["setuptools>=68.0", "wheel"]build-backend = "setuptools.build_meta"
[project]name = "v2d-detectron2-lib"version = "0.1.0"description = "Detectron2-based human detection and tracking"requires-python = ">=3.10"dependencies = [ "numpy", "scipy", "opencv-python", "imageio[pyav]", "av", "tqdm", "torch", "omegaconf", "v2d-mv[io,math]",]
[tool.setuptools]packages = ["v2d.detectron2.lib"]
[tool.setuptools.package-data]"v2d.detectron2.lib" = ["*.yaml"]
[tool.setuptools.package-dir]"v2d.detectron2.lib" = "."123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.# SPDX-License-Identifier: Apache-2.0from __future__ import annotations
import argparsefrom dataclasses import dataclassfrom pathlib import Pathimport time
import cv2import imageio.v3 as iioimport torchfrom tqdm import tqdm
from v2d.common.video import FrameSource, get_video_writer
from .build_detector import Detectorfrom .bytetracker import ByteTrackerfrom .tracker import IoUTracker
DEVICE = torch.device("cuda" if torch.cuda.is_available() else "cpu")
@dataclassclass DetectorConfig: model_size: str = "b" weights_dir: str = "" det_cat_id: int = 0 bbox_thr: float = 0.5 default_to_full_image: bool = True test_score_thresh: float = 0.25
@dataclassclass IoUTrackerConfig: iou_threshold: float = 0.3 max_lost: int = 30 min_hits: int = 3 merge_max_gap: int = 10 merge_iou_threshold: float = 0.5
@dataclassclass ByteTrackerConfig: track_thresh: float = 0.6 det_thresh: float = 0.1 match_thresh: float = 0.8 second_match_thresh: float = 0.5 max_lost: int = 30 min_hits: int = 3 merge_max_gap: int = 60 merge_iou_threshold: float = 0.3
TrackerConfig = IoUTrackerConfig | ByteTrackerConfig
def track_bboxes( rgb_path: Path, output_path: str | Path, detector_cfg: DetectorConfig | None = None, tracker_cfg: TrackerConfig | None = None, batch_size: int = 1, debug: int = 0, detector: Detector | None = None,) -> dict: """Run detection + tracking on a single camera's frames.
Saves a .pt dict to *output_path* and returns it.
Debug levels: 0 — no debug output 1 — print track info, save per-frame detection images (every 30th frame) 2 — also render bbox_track overlay video """ if detector_cfg is None: detector_cfg = DetectorConfig() if tracker_cfg is None: tracker_cfg = IoUTrackerConfig()
use_byte = isinstance(tracker_cfg, ByteTrackerConfig)
output_path = Path(output_path).resolve() output_path.parent.mkdir(parents=True, exist_ok=True)
frame_source = FrameSource.from_path(rgb_path) n_frames = frame_source.n_frames image_size = frame_source.image_size
effective_bbox_thr = tracker_cfg.det_thresh if use_byte else detector_cfg.bbox_thr
if detector is None: weights_path = f"{detector_cfg.weights_dir}/cascade_mask_rcnn_vitdet_{detector_cfg.model_size}" detector = Detector( name="vitdet", device=DEVICE, model_size=detector_cfg.model_size, path=weights_path, test_score_thresh=detector_cfg.test_score_thresh, )
if debug > 0: debug_det_dir = output_path.parent / f"{output_path.stem}_detections" debug_det_dir.mkdir(parents=True, exist_ok=True)
det_kwargs = dict( det_cat_id=detector_cfg.det_cat_id, bbox_thr=effective_bbox_thr, default_to_full_image=detector_cfg.default_to_full_image, )
if use_byte: tracker: IoUTracker | ByteTracker = ByteTracker( track_thresh=tracker_cfg.track_thresh, match_thresh=tracker_cfg.match_thresh, second_match_thresh=tracker_cfg.second_match_thresh, max_lost=tracker_cfg.max_lost, min_hits=tracker_cfg.min_hits, ) print(f"Using ByteTracker (track_thresh={tracker_cfg.track_thresh}, " f"det_thresh={tracker_cfg.det_thresh})") else: tracker = IoUTracker( iou_threshold=tracker_cfg.iou_threshold, max_lost=tracker_cfg.max_lost, min_hits=tracker_cfg.min_hits, ) print(f"Using IoUTracker (iou_threshold={tracker_cfg.iou_threshold})")
n_batches = (n_frames + batch_size - 1) // batch_size for batch_start, batch_frames in tqdm(frame_source.iter_batches(batch_size), total=n_batches, desc="Running detection"): start_time = time.time() if len(batch_frames) == 1: batch_results = [detector.run_detection(batch_frames[0], **det_kwargs)] else: batch_results = detector.run_detection_batch(batch_frames, **det_kwargs)
for offset, (bboxes, scores) in enumerate(batch_results): frame_idx = batch_start + offset tracker.update(frame_idx, bboxes, scores)
if debug > 0 and frame_idx % 30 == 0: elapsed = time.time() - start_time tqdm.write(f"Frame {frame_idx} detection time: {elapsed:.3f}s") image = batch_frames[offset].copy() H_img, W_img = image.shape[:2] label = f"Frame {frame_idx}" (tw, th), _ = cv2.getTextSize(label, cv2.FONT_HERSHEY_SIMPLEX, 1.0, 2) cv2.putText(image, label, (W_img - tw - 10, th + 10), cv2.FONT_HERSHEY_SIMPLEX, 1.0, (0, 255, 0), 2) bboxes_int = bboxes.astype(int) for j, bbox in enumerate(bboxes_int): cv2.rectangle(image, (bbox[0], bbox[1]), (bbox[2], bbox[3]), (0, 255, 255), 2) cv2.putText(image, f"Score: {scores[j]:.2f}", (bbox[0], bbox[1] - 10), cv2.FONT_HERSHEY_SIMPLEX, 0.5, (0, 255, 255), 2) iio.imwrite(debug_det_dir / f"bbox_{frame_idx:06d}.png", image)
tracks = tracker.finalize() tracks = IoUTracker.merge_fragmented_tracks( tracks, max_gap=tracker_cfg.merge_max_gap, iou_threshold=tracker_cfg.merge_iou_threshold, ) if debug > 0: print("=== Tracking Results ===") for track in tracks: print(track)
primary_track = IoUTracker.select_primary_track(tracks, image_size) primary_track.interpolate(n_frames) bbox_track = primary_track.get_bboxes() scores = primary_track.get_scores() print(f"Primary bbox track: {primary_track}")
result = { "det_cat_id": detector_cfg.det_cat_id, "scores": scores, "bbox_track": bbox_track, } torch.save(result, output_path) print(f"Saved bbox track ({n_frames} frames) to {output_path}")
if debug > 1: debug_video_path = output_path.with_suffix(".mp4") writer = get_video_writer(debug_video_path, fps=30, crf=23) for i, image in tqdm(enumerate(frame_source.iter_frames()), total=n_frames, desc="Rendering debug video"): H_img, W_img = image.shape[:2] label = f"Frame {i}" (tw, th), _ = cv2.getTextSize(label, cv2.FONT_HERSHEY_SIMPLEX, 1.0, 2) cv2.putText(image, label, (W_img - tw - 10, th + 10), cv2.FONT_HERSHEY_SIMPLEX, 1.0, (0, 255, 0), 2) bbox = bbox_track[i].astype(int) cv2.rectangle(image, (bbox[0], bbox[1]), (bbox[2], bbox[3]), (0, 255, 255), 2) cv2.putText(image, f"Score: {scores[i]:.2f}", (bbox[0], bbox[1] - 10), cv2.FONT_HERSHEY_SIMPLEX, 0.5, (0, 255, 255), 2) writer.write_frame(image) writer.close() print(f"Saved debug video to {debug_video_path}")
return result
if __name__ == "__main__": parser = argparse.ArgumentParser(description="Run person detection + tracking on a single camera") parser.add_argument("--rgb_path", type=str, required=True, help="Path to input frames (image dir, .h5, or video file)") parser.add_argument("--output_path", type=str, required=True, help="Output .pt file path")
det = parser.add_argument_group("detector") det.add_argument("--model_size", type=str, default="b", choices=["b", "l", "h"]) det.add_argument("--weights_dir", type=str, default="") det.add_argument("--det_cat_id", type=int, default=0, help="COCO category id (0=person)") det.add_argument("--bbox_thr", type=float, default=0.5) det.add_argument("--no_default_to_full_image", action="store_true")
trk = parser.add_argument_group("tracker") trk.add_argument("--iou_threshold", type=float, default=0.3) trk.add_argument("--max_lost", type=int, default=30) trk.add_argument("--min_hits", type=int, default=3)
parser.add_argument("--batch_size", type=int, default=1) parser.add_argument("--debug", type=int, default=0)
args = parser.parse_args()
track_bboxes( rgb_path=args.rgb_path, output_path=args.output_path, detector_cfg=DetectorConfig( model_size=args.model_size, weights_dir=args.weights_dir, det_cat_id=args.det_cat_id, bbox_thr=args.bbox_thr, default_to_full_image=not args.no_default_to_full_image, ), tracker_cfg=IoUTrackerConfig( iou_threshold=args.iou_threshold, max_lost=args.max_lost, min_hits=args.min_hits, ), batch_size=args.batch_size, debug=args.debug, )123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.# SPDX-License-Identifier: Apache-2.0from __future__ import annotations
from dataclasses import dataclass, fieldfrom enum import Enum, auto
import numpy as npfrom scipy.optimize import linear_sum_assignment
from v2d.mv.math.numpy_fn import linear_one_euro_filter
class TrackState(Enum): TENTATIVE = auto() ACTIVE = auto() LOST = auto() FINISHED = auto()
@dataclassclass Track: track_id: int state: TrackState = TrackState.ACTIVE frames_since_match: int = 0 history: list[tuple[int, np.ndarray, float]] = field(default_factory=list)
@property def first_bbox(self) -> np.ndarray: return self.history[0][1]
@property def last_bbox(self) -> np.ndarray: return self.history[-1][1]
@property def last_score(self) -> float: return self.history[-1][2]
@property def start_frame(self) -> int: return self.history[0][0]
@property def end_frame(self) -> int: return self.history[-1][0]
@property def length(self) -> int: return len(self.history)
def __repr__(self) -> str: motion = self.total_motion() return ( f"Track(id={self.track_id}, frames={self.length}, " f"span={self.start_frame}-{self.end_frame}, " f"motion={motion:.0f}px, state={self.state.name})" )
def append(self, frame_idx: int, bbox: np.ndarray, score: float): self.history.append((frame_idx, bbox, score)) self.state = TrackState.ACTIVE self.frames_since_match = 0
def get_bboxes(self) -> np.ndarray: """Return (N, 4) array of all bboxes in this track.""" return np.array([h[1] for h in self.history])
def get_scores(self) -> np.ndarray: return np.array([h[2] for h in self.history])
def get_frame_indices(self) -> np.ndarray: return np.array([h[0] for h in self.history])
def interpolate(self, total_frames: int): """Fill gaps in-place with linearly interpolated bboxes (score=-1).
After calling, self.history has exactly total_frames entries covering frames 0..total_frames-1. Interpolated entries use score=-1 to distinguish them from real detections. Frames before the first or after the last observation are held (nearest bbox, score=-1). """ frame_indices = self.get_frame_indices() bboxes = self.get_bboxes() scores = self.get_scores()
observed = {int(f): (b, s) for f, b, s in zip(frame_indices, bboxes, scores)} first, last = int(frame_indices[0]), int(frame_indices[-1])
new_history: list[tuple[int, np.ndarray, float]] = []
for f in range(total_frames): if f in observed: new_history.append((f, observed[f][0], float(observed[f][1]))) elif f < first: new_history.append((f, bboxes[0].copy(), -1.0)) elif f > last: new_history.append((f, bboxes[-1].copy(), -1.0)) else: # Find surrounding observations lo = max(fi for fi in frame_indices if fi < f) hi = min(fi for fi in frame_indices if fi > f) t = (f - lo) / (hi - lo) bbox = observed[lo][0] * (1 - t) + observed[hi][0] * t new_history.append((f, bbox, -1.0))
self.history = new_history
def _smoothed_centers(self, f_cutoff: float = 5.0, f_sample: float = 30.0) -> np.ndarray: """Bbox centers low-passed by a One Euro filter with beta=0 (plain low-pass).
f_cutoff defaults high (5 Hz at 30 fps) so only very-high-frequency noise — e.g. bbox flicker from intermittent occlusion — is removed; real person motion (sub-Hz) passes through. """ bboxes = self.get_bboxes() centers = np.column_stack([ (bboxes[:, 0] + bboxes[:, 2]) / 2, (bboxes[:, 1] + bboxes[:, 3]) / 2, ]) if centers.shape[0] < 2: return centers # linear_one_euro_filter expects time on the last axis -> (2, T) smoothed = linear_one_euro_filter( centers.T, min_f_cutoff=f_cutoff, beta=0.0, f_sample=f_sample, ).T return smoothed
def total_motion(self) -> float: """Sum of frame-to-frame bbox center displacements (in pixels), after smoothing.
Centers are low-passed first so occlusion-induced bbox flicker doesn't inflate the score. A truly stationary (but jittery) track yields ~0. """ if self.length < 2: return 0.0 centers = self._smoothed_centers() deltas = np.diff(centers, axis=0) return float(np.sum(np.linalg.norm(deltas, axis=1)))
def trajectory_span(self) -> float: """Diagonal of the axis-aligned bbox enclosing (smoothed) bbox centers.
Unlike total_motion, this is immune to back-and-forth flicker: a track that jitters in one spot has near-zero span regardless of cumulative motion. """ if self.length < 1: return 0.0 centers = self._smoothed_centers() return float(np.hypot(np.ptp(centers[:, 0]), np.ptp(centers[:, 1])))
def bbox_iou_matrix(boxes_a: np.ndarray, boxes_b: np.ndarray) -> np.ndarray: """Compute pairwise IoU between two sets of [x1, y1, x2, y2] boxes.
Returns shape (len(boxes_a), len(boxes_b)). """ x1 = np.maximum(boxes_a[:, None, 0], boxes_b[None, :, 0]) y1 = np.maximum(boxes_a[:, None, 1], boxes_b[None, :, 1]) x2 = np.minimum(boxes_a[:, None, 2], boxes_b[None, :, 2]) y2 = np.minimum(boxes_a[:, None, 3], boxes_b[None, :, 3])
inter = np.maximum(0, x2 - x1) * np.maximum(0, y2 - y1) area_a = (boxes_a[:, 2] - boxes_a[:, 0]) * (boxes_a[:, 3] - boxes_a[:, 1]) area_b = (boxes_b[:, 2] - boxes_b[:, 0]) * (boxes_b[:, 3] - boxes_b[:, 1]) union = area_a[:, None] + area_b[None, :] - inter
return inter / (union + 1e-6)
def greedy_assign( iou_matrix: np.ndarray, threshold: float) -> tuple[list[tuple[int, int]], list[int], list[int]]: """Greedy matching by descending IoU.
Returns (matches, unmatched_track_indices, unmatched_det_indices). """ if iou_matrix.size == 0: return ( [], list(range(iou_matrix.shape[0])), list(range(iou_matrix.shape[1])), )
matches = [] matched_tracks = set() matched_dets = set()
flat_order = np.argsort(iou_matrix.ravel())[::-1] n_cols = iou_matrix.shape[1]
for idx in flat_order: t = int(idx // n_cols) d = int(idx % n_cols) if iou_matrix[t, d] < threshold: break if t in matched_tracks or d in matched_dets: continue matches.append((t, d)) matched_tracks.add(t) matched_dets.add(d)
unmatched_tracks = [i for i in range(iou_matrix.shape[0]) if i not in matched_tracks] unmatched_dets = [i for i in range(iou_matrix.shape[1]) if i not in matched_dets] return matches, unmatched_tracks, unmatched_dets
def hungarian_assign( iou_matrix: np.ndarray, threshold: float) -> tuple[list[tuple[int, int]], list[int], list[int]]: """Optimal matching via the Hungarian algorithm on an IoU cost matrix.
Returns (matches, unmatched_track_indices, unmatched_det_indices). """ if iou_matrix.size == 0: return ( [], list(range(iou_matrix.shape[0])), list(range(iou_matrix.shape[1])), )
cost = 1.0 - iou_matrix row_indices, col_indices = linear_sum_assignment(cost)
matches = [] matched_tracks = set() matched_dets = set() for r, c in zip(row_indices, col_indices): if iou_matrix[r, c] >= threshold: matches.append((int(r), int(c))) matched_tracks.add(int(r)) matched_dets.add(int(c))
unmatched_tracks = [i for i in range(iou_matrix.shape[0]) if i not in matched_tracks] unmatched_dets = [i for i in range(iou_matrix.shape[1]) if i not in matched_dets] return matches, unmatched_tracks, unmatched_dets
class IoUTracker: """Simple IoU-based multi-object tracker with lost-track buffer.
Args: iou_threshold: Minimum IoU to match a detection to a track. max_lost: Frames a track survives without a match before removal. """
def __init__( self, iou_threshold: float = 0.3, max_lost: int = 30, min_hits: int = 3, ): self.iou_threshold = iou_threshold self.max_lost = max_lost self.min_hits = min_hits self._next_id = 0 self.active_tracks: list[Track] = [] self.lost_tracks: list[Track] = [] self.tentative_tracks: list[Track] = [] self.finished_tracks: list[Track] = []
def _new_track(self, frame_idx: int, bbox: np.ndarray, score: float) -> Track: track = Track(track_id=self._next_id, state=TrackState.TENTATIVE) track.append(frame_idx, bbox, score) self._next_id += 1 return track
def update(self, frame_idx: int, bboxes: np.ndarray, scores: np.ndarray): """Process one frame of detections.
Two-stage matching: 1. Match detections against active + lost tracks (established tracks get priority). 2. Match remaining detections against tentative tracks. Unmatched detections from stage 2 create new tentative tracks. Tentative tracks that reach *min_hits* consecutive matches are promoted to active.
Args: frame_idx: Current frame number. bboxes: (M, 4) array of [x1, y1, x2, y2] detections. scores: (M,) confidence scores. """ # Stage 1: match against established (active + lost) tracks established = self.active_tracks + self.lost_tracks
if len(established) > 0 and len(bboxes) > 0: track_boxes = np.array([t.last_bbox for t in established]) iou = bbox_iou_matrix(track_boxes, bboxes) matches_1, unmatched_t_1, unmatched_d_1 = greedy_assign(iou, self.iou_threshold) elif len(established) > 0: matches_1, unmatched_t_1, unmatched_d_1 = [], list(range(len(established))), [] else: matches_1, unmatched_t_1, unmatched_d_1 = [], [], list(range(len(bboxes)))
new_active = [] new_lost = []
for t_idx, d_idx in matches_1: track = established[t_idx] track.append(frame_idx, bboxes[d_idx], scores[d_idx]) new_active.append(track)
for t_idx in unmatched_t_1: track = established[t_idx] track.frames_since_match += 1 if track.frames_since_match > self.max_lost: track.state = TrackState.FINISHED self.finished_tracks.append(track) else: track.state = TrackState.LOST new_lost.append(track)
# Stage 2: match remaining detections against tentative tracks remaining_bboxes = bboxes[unmatched_d_1] if len(unmatched_d_1) > 0 else np.empty((0, 4)) remaining_scores = scores[unmatched_d_1] if len(unmatched_d_1) > 0 else np.empty(0)
new_tentative = []
if len(self.tentative_tracks) > 0 and len(remaining_bboxes) > 0: tent_boxes = np.array([t.last_bbox for t in self.tentative_tracks]) iou_2 = bbox_iou_matrix(tent_boxes, remaining_bboxes) matches_2, unmatched_t_2, unmatched_d_2 = greedy_assign(iou_2, self.iou_threshold) elif len(self.tentative_tracks) > 0: matches_2, unmatched_t_2, unmatched_d_2 = [], list(range(len(self.tentative_tracks))), [] else: matches_2, unmatched_t_2, unmatched_d_2 = [], [], list(range(len(remaining_bboxes)))
for t_idx, d_idx in matches_2: track = self.tentative_tracks[t_idx] track.append(frame_idx, remaining_bboxes[d_idx], float(remaining_scores[d_idx])) if track.length >= self.min_hits: track.state = TrackState.ACTIVE new_active.append(track) else: new_tentative.append(track)
# Unmatched tentative tracks are dropped immediately for t_idx in unmatched_t_2: track = self.tentative_tracks[t_idx] track.state = TrackState.FINISHED self.finished_tracks.append(track)
# Unmatched detections start new tentative tracks for d_idx in unmatched_d_2: new_tentative.append( self._new_track(frame_idx, remaining_bboxes[d_idx], float(remaining_scores[d_idx])) )
self.active_tracks = new_active self.lost_tracks = new_lost self.tentative_tracks = new_tentative
def finalize(self) -> list[Track]: """Return all tracks (active + lost + tentative + finished), sorted by track_id.""" all_tracks = ( self.finished_tracks + self.active_tracks + self.lost_tracks + self.tentative_tracks ) all_tracks.sort(key=lambda t: t.track_id) return all_tracks
@staticmethod def _track_merge_score(a: Track, b: Track) -> float: """Compute merge affinity between two tracks.
For overlapping tracks: mean IoU across shared frames. For non-overlapping tracks: IoU between A's last bbox and B's first bbox. Returns -1 if tracks have no overlapping frames and no observations to compare. """ a_by_frame = {int(h[0]): h[1] for h in a.history} b_by_frame = {int(h[0]): h[1] for h in b.history} shared_frames = sorted(set(a_by_frame) & set(b_by_frame))
if shared_frames: a_boxes = np.array([a_by_frame[f] for f in shared_frames]) b_boxes = np.array([b_by_frame[f] for f in shared_frames]) ious = bbox_iou_matrix(a_boxes, b_boxes) return float(np.mean(np.diag(ious)))
return float(bbox_iou_matrix( a.last_bbox.reshape(1, 4), b.first_bbox.reshape(1, 4), )[0, 0])
@staticmethod def merge_fragmented_tracks( tracks: list[Track], max_gap: int = 10, iou_threshold: float = 0.5, ) -> list[Track]: """Merge tracks that likely represent the same object across ID switches.
Two tracks are merged when: - Track A ends within *max_gap* frames of track B starting (or they overlap) - Their merge score (mean IoU over shared frames, or boundary IoU if no overlap) >= *iou_threshold*
Merging is greedy: the best pair (highest score) is merged first, then the search repeats until no more pairs qualify.
Returns a new list of tracks (merged tracks get the earlier track's ID). """ tracks = list(tracks) changed = True while changed: changed = False tracks.sort(key=lambda t: t.start_frame) best_score = -1.0 best_pair = None for i in range(len(tracks)): for j in range(i + 1, len(tracks)): a, b = tracks[i], tracks[j] gap = b.start_frame - a.end_frame if gap > max_gap: continue score = IoUTracker._track_merge_score(a, b) if score >= iou_threshold and score > best_score: best_score = score best_pair = (i, j)
if best_pair is not None: i, j = best_pair a, b = tracks[i], tracks[j] # For overlapping frames, keep A's observation (earlier track) b_frames = {int(h[0]) for h in b.history} a_frames = {int(h[0]) for h in a.history} a.history.extend(h for h in b.history if int(h[0]) not in a_frames) a.history.sort(key=lambda h: h[0]) tracks.pop(j) changed = True
return tracks
@staticmethod def select_primary_track( tracks: list[Track], image_size: tuple[int, int] | None = None, method: str = "combined", weights: dict[str, float] | None = None, ) -> Track: """Select the primary subject from a set of tracks.
Args: tracks: List of completed tracks. image_size: (height, width) of the frames, needed for center-based methods. method: "longest" — track with the most frames. "center" — track whose avg bbox center is closest to image center. "motion" — track with the most total bbox-center displacement. "combined" — weighted sum of normalized length, center proximity, motion, and trajectory span. Tune via *weights* dict. weights: Weights for "combined" mode. Keys: "length", "center", "motion", "span". Defaults to {"length": 0.2, "center": 0.2, "motion": 0.3, "span": 0.3}. """ if not tracks: raise ValueError("No tracks to select from")
if method == "longest": return max(tracks, key=lambda t: t.length)
if method == "motion": return max(tracks, key=lambda t: t.total_motion())
if method in ("center", "combined"): if image_size is None: raise ValueError("image_size required for center-based selection")
h, w = image_size img_cx, img_cy = w / 2, h / 2
def center_dist(t: Track) -> float: bboxes = t.get_bboxes() cx = (bboxes[:, 0] + bboxes[:, 2]) / 2 cy = (bboxes[:, 1] + bboxes[:, 3]) / 2 return float(np.mean(np.sqrt((cx - img_cx) ** 2 + (cy - img_cy) ** 2)))
if method == "center": return min(tracks, key=center_dist)
if method == "combined": w_cfg = weights or {"length": 0.2, "center": 0.2, "motion": 0.3, "span": 0.3}
lengths = np.array([t.length for t in tracks], dtype=float) dists = np.array([center_dist(t) for t in tracks], dtype=float) motions = np.array([t.total_motion() for t in tracks], dtype=float) spans = np.array([t.trajectory_span() for t in tracks], dtype=float)
def normalize(a: np.ndarray) -> np.ndarray: r = a.max() - a.min() return (a - a.min()) / r if r > 0 else np.zeros_like(a)
scores = ( w_cfg.get("length", 0) * normalize(lengths) + w_cfg.get("center", 0) * (1.0 - normalize(dists)) + w_cfg.get("motion", 0) * normalize(motions) + w_cfg.get("span", 0) * normalize(spans) ) return tracks[int(np.argmax(scores))]
raise ValueError(f"Unknown selection method: {method}")123456789101112131415# Apache License 2.0
Copyright 2025 NVIDIA CORPORATION
Licensed under the Apache License, Version 2.0 (the "License");you may not use this file except in compliance with the License.You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, softwaredistributed under the License is distributed on an "AS IS" BASIS,WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.See the License for the specific language governing permissions andlimitations under the License.12345# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.# SPDX-License-Identifier: Apache-2.0from v2d.docker.container import run_in_container
__all__ = ["run_in_container"]123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.# SPDX-License-Identifier: Apache-2.0import osimport subprocessfrom pathlib import Path
def _base_dir(path: str) -> str: """ Return the deepest directory component of path that contains no glob characters. For plain paths this equals dirname(path). For paths like /out/*/*.glb it returns /out, so the container mount covers the full glob subtree. """ parts = Path(path).parts clean = [] for part in parts[:-1]: # skip the filename/last component if '*' in part or '?' in part: break clean.append(part) return str(Path(*clean)) if clean else str(Path(path).parent)
def run_in_container( image: str, module: str, inputs: dict[str, str], outputs: dict[str, str], extra_args: dict[str, object] | None = None, dev: bool = False, modules_dir: str | None = None, gpus: bool = False, env: dict[str, str] | None = None, extra_volumes: list[str] | None = None,) -> None: """ Run a Python module inside a Docker container with file arguments.
inputs: arg_name → host_path (read file mounts; None values are skipped) outputs: arg_name → host_path (write file mounts; parent dirs created; None skipped) extra_args: arg_name → value (non-path CLI args) None or False → omit entirely True → add as a bare flag (--arg_name, no value) other → add as --arg_name str(value) env: extra environment variables passed via -e extra_volumes: raw -v arguments appended after all other mounts (e.g. anonymous volumes to preserve image-built artifacts under a dev mount)
Each unique host directory gets one volume mount at /data/<arg_name>, where the arg_name is taken from the first argument that references that directory. Subsequent arguments in the same directory reuse the same mount. """ inputs = {k: os.path.abspath(v) for k, v in inputs.items() if v is not None} outputs = {k: os.path.abspath(v) for k, v in outputs.items() if v is not None}
for path in outputs.values(): os.makedirs(_base_dir(path), exist_ok=True)
# Map each unique host directory to a container mount point. # First arg to reference a directory claims the mount name. dir_to_mount: dict[str, str] = {} for arg_name, path in {**inputs, **outputs}.items(): host_dir = _base_dir(path) if host_dir not in dir_to_mount: dir_to_mount[host_dir] = f"/data/{arg_name}"
cmd = ["docker", "run", "--rm"] if gpus: cmd += ["--runtime=nvidia", "--gpus", "all"] cmd += [ "--user", f"{os.getuid()}:{os.getgid()}", "-e", "HOME=/tmp", ] if env: for key, value in env.items(): cmd += ["-e", f"{key}={value}"] for host_dir, container_dir in dir_to_mount.items(): cmd += ["-v", f"{host_dir}:{container_dir}"] if dev: if modules_dir is None: raise ValueError("modules_dir must be provided when dev=True") cmd += ["-v", f"{modules_dir}:/workspace"] if extra_volumes: for vol in extra_volumes: cmd += ["-v", vol]
cmd += [image, "python", "-m", module]
for arg_name, path in {**inputs, **outputs}.items(): host_dir = _base_dir(path) rel = os.path.relpath(path, host_dir) container_path = f"{dir_to_mount[host_dir]}/{rel}" cmd += [f"--{arg_name}", container_path]
if extra_args: for arg_name, value in extra_args.items(): if value is None or value is False: pass elif value is True: cmd += [f"--{arg_name}"] else: cmd += [f"--{arg_name}", str(value)]
subprocess.run(cmd, check=True)123456789101112131415161718# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.# SPDX-License-Identifier: Apache-2.0[build-system]requires = ["setuptools>=68.0", "wheel"]build-backend = "setuptools.build_meta"
[project]name = "v2d-docker"version = "0.1.0"description = "Shared Docker container orchestration utilities for v2d modules"requires-python = ">=3.10"dependencies = []
[tool.setuptools]packages = ["v2d.docker"]
[tool.setuptools.package-dir]"v2d.docker" = "."123456789101112131415# Apache License 2.0
Copyright 2025 NVIDIA CORPORATION
Licensed under the Apache License, Version 2.0 (the "License");you may not use this file except in compliance with the License.You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, softwaredistributed under the License is distributed on an "AS IS" BASIS,WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.See the License for the specific language governing permissions andlimitations under the License.12345678910111213141516171819202122232425262728293031323334353637383940414243FROM pytorch/pytorch:2.5.1-cuda12.4-cudnn9-develENV DEBIAN_FRONTEND=noninteractiveWORKDIR /app
RUN apt-get update && apt-get install -y \ git \ wget \ libgl1 \ libglib2.0-0 \ build-essential \ cmake \ ninja-build \ libeigen3-dev \ && rm -rf /var/lib/apt/lists/*
RUN pip install --no-cache-dir \ numpy \ scipy \ opencv-python \ Pillow \ pyyaml \ tqdm \ matplotlib \ einops \ evo \ gdown \ open3d
RUN pip install --no-cache-dir torch-scatter -f https://data.pyg.org/whl/torch-2.5.1+cu124.html
RUN git clone --recursive https://github.com/princeton-vl/DROID-SLAM.git /opt/droid-slam
RUN cd /opt/droid-slam/thirdparty/lietorch && \ TORCH_CUDA_ARCH_LIST="8.0 8.6 8.9 9.0" pip install --no-build-isolation -e .
RUN cd /opt/droid-slam && \ TORCH_CUDA_ARCH_LIST="8.0 8.6 8.9 9.0" pip install --no-build-isolation -e .
ENV PYTHONPATH=/opt/droid-slam:/opt/droid-slam/droid_slam:${PYTHONPATH}
COPY . /workspace
RUN pip install -e /workspace/v2d_common -e /workspace/v2d_droid_slam/lib12# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.# SPDX-License-Identifier: Apache-2.0123456# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.# SPDX-License-Identifier: Apache-2.0import os
IMAGE_NAME = "v2d_droid_slam"MODULES_DIR = os.path.abspath(os.path.join(os.path.dirname(os.path.abspath(__file__)), "..", ".."))12345678910111213141516171819# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.# SPDX-License-Identifier: Apache-2.0import osimport subprocess
IMAGE_NAME = "v2d_droid_slam"
current_dir = os.path.dirname(os.path.abspath(__file__))module_dir = os.path.join(current_dir, "..")root_dir = os.path.join(module_dir, "..")dockerfile_path = os.path.join(current_dir, "Dockerfile")
def build_docker_image() -> None: subprocess.run(["docker", "build", "-t", IMAGE_NAME, "-f", dockerfile_path, root_dir], check=True)
if __name__ == "__main__": build_docker_image()123456789101112131415161718# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.# SPDX-License-Identifier: Apache-2.0[build-system]requires = ["setuptools>=68.0", "wheel"]build-backend = "setuptools.build_meta"
[project]name = "v2d-droid-slam-docker"version = "0.1.0"description = "Docker orchestration scripts for DROID-SLAM"requires-python = ">=3.10"dependencies = ["v2d-docker"]
[tool.setuptools]packages = ["v2d.droid_slam.docker"]
[tool.setuptools.package-dir]"v2d.droid_slam.docker" = "."123456789101112131415161718192021222324252627282930313233343536# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.# SPDX-License-Identifier: Apache-2.0import osimport subprocess
from v2d.droid_slam.docker._config import IMAGE_NAME, MODULES_DIR
def run_download(output_dir: str, dev: bool = False) -> None: os.makedirs(output_dir, exist_ok=True) output_dir = os.path.abspath(output_dir)
cmd = [ "docker", "run", "--rm", "--user", f"{os.getuid()}:{os.getgid()}", "-e", "HOME=/tmp", "-v", f"{output_dir}:/data/weights", ] if dev: cmd += ["-v", f"{MODULES_DIR}:/workspace"] cmd += [ IMAGE_NAME, "python", "-m", "v2d.droid_slam.lib.download_weights", "--output_dir", "/data/weights", ] subprocess.run(cmd, check=True)
if __name__ == "__main__": import argparse
parser = argparse.ArgumentParser(description="Download DROID-SLAM checkpoint") parser.add_argument("--output_dir", type=str, required=True) parser.add_argument("--dev", action="store_true") args = parser.parse_args() run_download(output_dir=args.output_dir, dev=args.dev)123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.# SPDX-License-Identifier: Apache-2.0from v2d.docker.container import run_in_containerfrom v2d.droid_slam.docker._config import IMAGE_NAME, MODULES_DIR
def run_image_list_to_slam( image_folder: str, poses_folder: str, weights_path: str, input_intrinsics_path: str = None, input_intrinsics_folder: str = None, input_depth_folder: str = None, align_to_depth_folder: str = None, depth_folder: str = None, pointcloud_path: str = None, trajectory_path: str = None, stride: int = 1, image_height: int = 384, image_width: int = 512, buffer_size: int = 512, beta: float = 0.3, filter_thresh: float = 2.4, warmup: int = 8, keyframe_thresh: float = 4.0, frontend_thresh: float = 16.0, frontend_window: int = 25, frontend_radius: int = 2, frontend_nms: int = 1, backend_thresh: float = 22.0, backend_radius: int = 2, backend_nms: int = 3, upsample: bool = False, pointcloud_min_views: int = 2, dev: bool = False,) -> None: inputs = {"image_folder": image_folder, "weights_path": weights_path} if input_intrinsics_path is not None: inputs["input_intrinsics_path"] = input_intrinsics_path if input_intrinsics_folder is not None: inputs["input_intrinsics_folder"] = input_intrinsics_folder if input_depth_folder is not None: inputs["input_depth_folder"] = input_depth_folder if align_to_depth_folder is not None: inputs["align_to_depth_folder"] = align_to_depth_folder
outputs = {"poses_folder": poses_folder} if depth_folder is not None: outputs["depth_folder"] = depth_folder if pointcloud_path is not None: outputs["pointcloud_path"] = pointcloud_path if trajectory_path is not None: outputs["trajectory_path"] = trajectory_path
extra_args = { "stride": stride, "image_height": image_height, "image_width": image_width, "buffer_size": buffer_size, "beta": beta, "filter_thresh": filter_thresh, "warmup": warmup, "keyframe_thresh": keyframe_thresh, "frontend_thresh": frontend_thresh, "frontend_window": frontend_window, "frontend_radius": frontend_radius, "frontend_nms": frontend_nms, "backend_thresh": backend_thresh, "backend_radius": backend_radius, "backend_nms": backend_nms, "upsample": upsample, "pointcloud_min_views": pointcloud_min_views, }
run_in_container( image=IMAGE_NAME, module="v2d.droid_slam.lib.image_list_to_slam", inputs=inputs, outputs=outputs, extra_args=extra_args, dev=dev, modules_dir=MODULES_DIR, gpus=True, )
if __name__ == "__main__": import argparse
parser = argparse.ArgumentParser(description="Run DROID-SLAM on a folder of frames") parser.add_argument("--image_folder", required=True) parser.add_argument("--poses_folder", required=True) parser.add_argument("--weights_path", required=True) parser.add_argument("--input_intrinsics_path", default=None) parser.add_argument("--input_intrinsics_folder", default=None) parser.add_argument("--input_depth_folder", default=None, help="Per-frame metric depth fed into BA as a sensor prior.") parser.add_argument("--align_to_depth_folder", default=None, help="Per-frame metric depth used post-hoc for scale alignment only.") parser.add_argument("--depth_folder", default=None) parser.add_argument("--pointcloud_path", default=None) parser.add_argument("--trajectory_path", default=None) parser.add_argument("--stride", type=int, default=1) parser.add_argument("--image_height", type=int, default=384) parser.add_argument("--image_width", type=int, default=512) parser.add_argument("--buffer_size", type=int, default=512) parser.add_argument("--beta", type=float, default=0.3) parser.add_argument("--filter_thresh", type=float, default=2.4) parser.add_argument("--warmup", type=int, default=8) parser.add_argument("--keyframe_thresh", type=float, default=4.0) parser.add_argument("--frontend_thresh", type=float, default=16.0) parser.add_argument("--frontend_window", type=int, default=25) parser.add_argument("--frontend_radius", type=int, default=2) parser.add_argument("--frontend_nms", type=int, default=1) parser.add_argument("--backend_thresh", type=float, default=22.0) parser.add_argument("--backend_radius", type=int, default=2) parser.add_argument("--backend_nms", type=int, default=3) parser.add_argument("--upsample", action="store_true") parser.add_argument("--pointcloud_min_views", type=int, default=2) parser.add_argument("--dev", action="store_true") args = parser.parse_args()
run_image_list_to_slam( image_folder=args.image_folder, poses_folder=args.poses_folder, weights_path=args.weights_path, input_intrinsics_path=args.input_intrinsics_path, input_intrinsics_folder=args.input_intrinsics_folder, input_depth_folder=args.input_depth_folder, align_to_depth_folder=args.align_to_depth_folder, depth_folder=args.depth_folder, pointcloud_path=args.pointcloud_path, trajectory_path=args.trajectory_path, stride=args.stride, image_height=args.image_height, image_width=args.image_width, buffer_size=args.buffer_size, beta=args.beta, filter_thresh=args.filter_thresh, warmup=args.warmup, keyframe_thresh=args.keyframe_thresh, frontend_thresh=args.frontend_thresh, frontend_window=args.frontend_window, frontend_radius=args.frontend_radius, frontend_nms=args.frontend_nms, backend_thresh=args.backend_thresh, backend_radius=args.backend_radius, backend_nms=args.backend_nms, upsample=args.upsample, pointcloud_min_views=args.pointcloud_min_views, dev=args.dev, )123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.# SPDX-License-Identifier: Apache-2.0from v2d.docker.container import run_in_containerfrom v2d.droid_slam.docker._config import IMAGE_NAME, MODULES_DIR
def run_video_to_slam( video_path: str, poses_folder: str, weights_path: str, input_intrinsics_path: str = None, input_intrinsics_folder: str = None, input_depth_folder: str = None, align_to_depth_folder: str = None, depth_folder: str = None, pointcloud_path: str = None, trajectory_path: str = None, stride: int = 1, image_height: int = 384, image_width: int = 512, buffer_size: int = 512, beta: float = 0.3, filter_thresh: float = 2.4, warmup: int = 8, keyframe_thresh: float = 4.0, frontend_thresh: float = 16.0, frontend_window: int = 25, frontend_radius: int = 2, frontend_nms: int = 1, backend_thresh: float = 22.0, backend_radius: int = 2, backend_nms: int = 3, upsample: bool = False, pointcloud_min_views: int = 2, dev: bool = False,) -> None: inputs = {"video_path": video_path, "weights_path": weights_path} if input_intrinsics_path is not None: inputs["input_intrinsics_path"] = input_intrinsics_path if input_intrinsics_folder is not None: inputs["input_intrinsics_folder"] = input_intrinsics_folder if input_depth_folder is not None: inputs["input_depth_folder"] = input_depth_folder if align_to_depth_folder is not None: inputs["align_to_depth_folder"] = align_to_depth_folder
outputs = {"poses_folder": poses_folder} if depth_folder is not None: outputs["depth_folder"] = depth_folder if pointcloud_path is not None: outputs["pointcloud_path"] = pointcloud_path if trajectory_path is not None: outputs["trajectory_path"] = trajectory_path
extra_args = { "stride": stride, "image_height": image_height, "image_width": image_width, "buffer_size": buffer_size, "beta": beta, "filter_thresh": filter_thresh, "warmup": warmup, "keyframe_thresh": keyframe_thresh, "frontend_thresh": frontend_thresh, "frontend_window": frontend_window, "frontend_radius": frontend_radius, "frontend_nms": frontend_nms, "backend_thresh": backend_thresh, "backend_radius": backend_radius, "backend_nms": backend_nms, "upsample": upsample, "pointcloud_min_views": pointcloud_min_views, }
run_in_container( image=IMAGE_NAME, module="v2d.droid_slam.lib.video_to_slam", inputs=inputs, outputs=outputs, extra_args=extra_args, dev=dev, modules_dir=MODULES_DIR, gpus=True, )
if __name__ == "__main__": import argparse
parser = argparse.ArgumentParser(description="Run DROID-SLAM on a video") parser.add_argument("--video_path", required=True) parser.add_argument("--poses_folder", required=True) parser.add_argument("--weights_path", required=True) parser.add_argument("--input_intrinsics_path", default=None) parser.add_argument("--input_intrinsics_folder", default=None) parser.add_argument("--input_depth_folder", default=None, help="Per-frame metric depth fed into BA as a sensor prior.") parser.add_argument("--align_to_depth_folder", default=None, help="Per-frame metric depth used post-hoc for scale alignment only.") parser.add_argument("--depth_folder", default=None) parser.add_argument("--pointcloud_path", default=None) parser.add_argument("--trajectory_path", default=None) parser.add_argument("--stride", type=int, default=1) parser.add_argument("--image_height", type=int, default=384) parser.add_argument("--image_width", type=int, default=512) parser.add_argument("--buffer_size", type=int, default=512) parser.add_argument("--beta", type=float, default=0.3) parser.add_argument("--filter_thresh", type=float, default=2.4) parser.add_argument("--warmup", type=int, default=8) parser.add_argument("--keyframe_thresh", type=float, default=4.0) parser.add_argument("--frontend_thresh", type=float, default=16.0) parser.add_argument("--frontend_window", type=int, default=25) parser.add_argument("--frontend_radius", type=int, default=2) parser.add_argument("--frontend_nms", type=int, default=1) parser.add_argument("--backend_thresh", type=float, default=22.0) parser.add_argument("--backend_radius", type=int, default=2) parser.add_argument("--backend_nms", type=int, default=3) parser.add_argument("--upsample", action="store_true") parser.add_argument("--pointcloud_min_views", type=int, default=2) parser.add_argument("--dev", action="store_true") args = parser.parse_args()
run_video_to_slam( video_path=args.video_path, poses_folder=args.poses_folder, weights_path=args.weights_path, input_intrinsics_path=args.input_intrinsics_path, input_intrinsics_folder=args.input_intrinsics_folder, input_depth_folder=args.input_depth_folder, align_to_depth_folder=args.align_to_depth_folder, depth_folder=args.depth_folder, pointcloud_path=args.pointcloud_path, trajectory_path=args.trajectory_path, stride=args.stride, image_height=args.image_height, image_width=args.image_width, buffer_size=args.buffer_size, beta=args.beta, filter_thresh=args.filter_thresh, warmup=args.warmup, keyframe_thresh=args.keyframe_thresh, frontend_thresh=args.frontend_thresh, frontend_window=args.frontend_window, frontend_radius=args.frontend_radius, frontend_nms=args.frontend_nms, backend_thresh=args.backend_thresh, backend_radius=args.backend_radius, backend_nms=args.backend_nms, upsample=args.upsample, pointcloud_min_views=args.pointcloud_min_views, dev=args.dev, )12# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.# SPDX-License-Identifier: Apache-2.0123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.# SPDX-License-Identifier: Apache-2.0"""Internal DROID-SLAM driver shared by video_to_slam and image_list_to_slam.
Loads the upstream Droid runner, drives tracking over a frame iterator,optionally scale-aligns the result to a reference metric-depth source,and writes outputs in the v2d common formats."""from __future__ import annotations
import osfrom dataclasses import dataclassfrom types import SimpleNamespacefrom typing import Callable, Iterator
import cv2import numpy as npimport torch
from v2d.common.datatypes import CameraIntrinsics, DepthImage, Transform3d
@dataclassclass Frame: frame_idx: int # source frame index (zero-padded filename stem) image_bgr: np.ndarray # (H, W, 3) uint8 intrinsics: CameraIntrinsics # intrinsics at the source resolution prior_depth: np.ndarray | None = None # (H, W) float32 metres — fed into BA as sensor prior align_to_depth: np.ndarray | None = None # (H, W) float32 metres — used post-hoc for scale alignment
def _resize_for_droid( image_bgr: np.ndarray, fxfycxcy: np.ndarray, image_size: tuple[int, int], prior_depth: np.ndarray | None = None,) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor | None]: """Resize a frame to DROID's network input and rescale intrinsics to match.
Returns image as (1, 3, H, W) uint8 BGR (upstream motion_filter adds its own [None]+[2,1,0] reorder to get RGB internally), scaled intrinsics, and optional depth resized to the network input resolution. Invalid (non-positive or non-finite) depth pixels are zeroed; depth_video.append() interprets zero as "no prior at this pixel". """ target_h, target_w = image_size src_h, src_w = image_bgr.shape[:2] image_bgr = cv2.resize(image_bgr, (target_w, target_h), interpolation=cv2.INTER_AREA) image = torch.from_numpy(image_bgr).permute(2, 0, 1)[None] # (1, 3, H, W) uint8
sx = target_w / src_w sy = target_h / src_h fx, fy, cx, cy = fxfycxcy scaled = torch.tensor([fx * sx, fy * sy, cx * sx, cy * sy], dtype=torch.float32)
depth_t: torch.Tensor | None = None if prior_depth is not None: d = prior_depth.astype(np.float32) invalid = ~np.isfinite(d) | (d <= 0) d[invalid] = 0.0 if d.shape != (target_h, target_w): d = cv2.resize(d, (target_w, target_h), interpolation=cv2.INTER_NEAREST) depth_t = torch.from_numpy(d)
return image, scaled, depth_t
def _load_droid_class(): """Import the upstream Droid class lazily so module import stays cheap.""" from droid import Droid # provided by the DROID-SLAM repo on PYTHONPATH return Droid
def _get_keyframe_disps(droid, upsample: bool) -> np.ndarray: """Return per-keyframe disparity. Upsampled to source resolution if available.""" video = droid.video if upsample and hasattr(video, "disps_up"): return video.disps_up.detach().cpu().numpy() return video.disps.detach().cpu().numpy()
def _solve_global_scale(droid, frames_by_idx: dict[int, Frame], upsample: bool) -> float: """Compute a robust scale factor that maps DROID depth → reference depth.
Sampled at every keyframe where reference depth is available. Per-keyframe median ratios are aggregated into a final global median. """ video = droid.video n_kf = int(video.counter.value) disps = _get_keyframe_disps(droid, upsample) tstamps = video.tstamp.detach().cpu().numpy().astype(np.int64)
per_kf_scales: list[float] = [] for kf in range(n_kf): frame_idx = int(tstamps[kf]) if frame_idx not in frames_by_idx: continue ref = frames_by_idx[frame_idx].align_to_depth if ref is None: continue disp = disps[kf] # DROID disparity is in network-resolution pixels; resize to source. ref_h, ref_w = ref.shape[:2] if disp.shape != (ref_h, ref_w): disp = cv2.resize(disp, (ref_w, ref_h), interpolation=cv2.INTER_LINEAR) valid = (disp > 1e-3) & (ref > 1e-3) & np.isfinite(ref) if valid.sum() < 64: continue droid_depth = 1.0 / disp[valid] ratios = ref[valid] / droid_depth per_kf_scales.append(float(np.median(ratios)))
if not per_kf_scales: return 1.0 return float(np.median(per_kf_scales))
def _write_pointcloud_ply(droid, scale: float, path: str, min_views: int = 2, filter_thresh: float = 0.005) -> None: """Dump the post-BA keyframe point cloud as a binary-little-endian PLY.
Uses upstream's depth_filter for multi-view consistency: a pixel is kept only if its depth is consistent with at least ``min_views`` other keyframes. This is what produces clean (non-fuzzy) clouds. """ import torch import droid_backends from lietorch import SE3
video = droid.video n_kf = int(video.counter.value) if n_kf == 0: print("[droid-slam] no keyframes; skipping PLY") return
# depth_filter inspects the FULL buffer using dirty_index to know which # slots are valid, so we hand it the unsliced tensors as upstream does. dirty_index = torch.arange(n_kf, device=video.poses.device) thresh = filter_thresh * torch.ones(n_kf, device=video.poses.device) count = droid_backends.depth_filter( video.poses, video.disps, video.intrinsics[0], dirty_index, thresh ) # (N, h, w) per-pixel consistent-view count
poses = video.poses[:n_kf].detach() disps = video.disps[:n_kf].detach() images = video.images[:n_kf].detach() intrinsics = video.intrinsics[0].detach()
cam_to_world = SE3(poses).inv() points_world = droid_backends.iproj(cam_to_world.data, disps, intrinsics) points_world = (points_world * scale).cpu().numpy() # (N, h, w, 3)
colors_rgb = images[:, [2, 1, 0], 3::8, 3::8] colors_rgb = colors_rgb.permute(0, 2, 3, 1).cpu().numpy() # (N, h, w, 3) RGB
disp_np = disps.cpu().numpy() disp_mean = disp_np.reshape(n_kf, -1).mean(axis=1).reshape(n_kf, 1, 1) consistency_mask = count.cpu().numpy() >= min_views mask = consistency_mask & (disp_np > 0.5 * disp_mean) & (disp_np > 1e-3)
points_arr = points_world[mask].astype(np.float32) colors_arr = colors_rgb[mask].astype(np.uint8) if points_arr.size == 0: print("[droid-slam] no points passed consistency filter; skipping PLY") return
t_arr = cam_to_world.data[:, :3].cpu().numpy() n_total = int(mask.size) print(f"[droid-slam] PLY: {n_kf} keyframes, {points_arr.shape[0]} / {n_total} points " f"kept (min_views={min_views}); " f"cam x∈[{t_arr[:,0].min():.3f},{t_arr[:,0].max():.3f}] " f"y∈[{t_arr[:,1].min():.3f},{t_arr[:,1].max():.3f}] " f"z∈[{t_arr[:,2].min():.3f},{t_arr[:,2].max():.3f}]")
os.makedirs(os.path.dirname(os.path.abspath(path)) or ".", exist_ok=True) with open(path, "wb") as f: header = ( "ply\n" "format binary_little_endian 1.0\n" f"element vertex {points_arr.shape[0]}\n" "property float x\nproperty float y\nproperty float z\n" "property uchar red\nproperty uchar green\nproperty uchar blue\n" "end_header\n" ) f.write(header.encode("ascii")) interleaved = np.empty(points_arr.shape[0], dtype=[("xyz", np.float32, 3), ("rgb", np.uint8, 3)]) interleaved["xyz"] = points_arr interleaved["rgb"] = colors_arr interleaved.tofile(f)
def _se3_quat_to_matrix(pose: np.ndarray) -> np.ndarray: """Convert DROID's [tx,ty,tz,qx,qy,qz,qw] world-to-camera into a 4×4 matrix.""" from scipy.spatial.transform import Rotation tx, ty, tz, qx, qy, qz, qw = pose.tolist() R = Rotation.from_quat([qx, qy, qz, qw]).as_matrix() M = np.eye(4) M[:3, :3] = R M[:3, 3] = [tx, ty, tz] return M
def run_droid_slam( frame_iter: Callable[[], Iterator[Frame]], weights_path: str, poses_folder: str, depth_folder: str | None = None, pointcloud_path: str | None = None, trajectory_path: str | None = None, image_size: tuple[int, int] = (384, 512), buffer_size: int = 512, beta: float = 0.3, filter_thresh: float = 2.4, warmup: int = 8, keyframe_thresh: float = 4.0, frontend_thresh: float = 16.0, frontend_window: int = 25, frontend_radius: int = 2, frontend_nms: int = 1, backend_thresh: float = 22.0, backend_radius: int = 2, backend_nms: int = 3, upsample: bool = False, pointcloud_min_views: int = 2,) -> None: """Run DROID-SLAM over a frame iterator and write outputs.
The frame iterator is invoked twice: once for tracking, then again for scale alignment so we can correlate keyframes with their reference depth without holding all frames in memory. """ os.makedirs(poses_folder, exist_ok=True) if depth_folder is not None: os.makedirs(depth_folder, exist_ok=True)
weights_file = os.path.join(weights_path, "droid.pth") \ if os.path.isdir(weights_path) else weights_path if not os.path.exists(weights_file): raise FileNotFoundError(f"droid.pth not found at {weights_file}")
args = SimpleNamespace( weights=weights_file, image_size=list(image_size), buffer=buffer_size, beta=beta, filter_thresh=filter_thresh, warmup=warmup, keyframe_thresh=keyframe_thresh, frontend_thresh=frontend_thresh, frontend_window=frontend_window, frontend_radius=frontend_radius, frontend_nms=frontend_nms, backend_thresh=backend_thresh, backend_radius=backend_radius, backend_nms=backend_nms, upsample=upsample, disable_vis=True, stereo=False, )
Droid = _load_droid_class() droid: object | None = None
frames_by_idx: dict[int, Frame] = {} ordered_indices: list[int] = []
for frame in frame_iter(): if droid is None: droid = Droid(args) fxfycxcy = np.array([frame.intrinsics.fx, frame.intrinsics.fy, frame.intrinsics.cx, frame.intrinsics.cy], dtype=np.float32) image_t, intr_t, depth_t = _resize_for_droid( frame.image_bgr, fxfycxcy, image_size, prior_depth=frame.prior_depth, ) droid.track(frame.frame_idx, image_t, depth=depth_t, intrinsics=intr_t) frames_by_idx[frame.frame_idx] = frame ordered_indices.append(frame.frame_idx)
if droid is None: raise RuntimeError("frame_iter produced no frames")
# Reconstruct the stream for terminate() — used internally by DROID # for the final global BA pass. def replay(): for f in frame_iter(): fxfycxcy = np.array([f.intrinsics.fx, f.intrinsics.fy, f.intrinsics.cx, f.intrinsics.cy], dtype=np.float32) image_t, intr_t, _ = _resize_for_droid( f.image_bgr, fxfycxcy, image_size, prior_depth=None, ) yield (f.frame_idx, image_t, intr_t)
traj_est = droid.terminate(replay()) # (N_frames, 7) camera-to-world [tx,ty,tz,qx,qy,qz,qw]
scale = _solve_global_scale(droid, frames_by_idx, upsample) if scale != 1.0: print(f"[droid-slam] applying global scale {scale:.6f} from reference depth")
# Write per-frame poses. from scipy.spatial.transform import Rotation for row_i, frame_idx in enumerate(ordered_indices): tx, ty, tz, qx, qy, qz, qw = traj_est[row_i].tolist() M = np.eye(4) M[:3, :3] = Rotation.from_quat([qx, qy, qz, qw]).as_matrix() M[:3, 3] = [tx * scale, ty * scale, tz * scale] Transform3d.from_matrix(M).save( os.path.join(poses_folder, f"{frame_idx:06d}.json") )
# Optional TUM trajectory. if trajectory_path is not None: os.makedirs(os.path.dirname(os.path.abspath(trajectory_path)) or ".", exist_ok=True) with open(trajectory_path, "w") as f: for row_i, frame_idx in enumerate(ordered_indices): tx, ty, tz, qx, qy, qz, qw = traj_est[row_i].tolist() f.write(f"{frame_idx} {tx*scale} {ty*scale} {tz*scale} " f"{qx} {qy} {qz} {qw}\n")
# Optional per-keyframe depth output (scaled, upsampled to source resolution). if depth_folder is not None: video = droid.video n_kf = int(video.counter.value) disps = _get_keyframe_disps(droid, upsample) tstamps = video.tstamp.detach().cpu().numpy().astype(np.int64)
for kf in range(n_kf): disp = disps[kf] frame_idx = int(tstamps[kf]) frame = frames_by_idx.get(frame_idx) if frame is None: continue tgt_h, tgt_w = frame.intrinsics.height, frame.intrinsics.width if disp.shape != (tgt_h, tgt_w): disp = cv2.resize(disp, (tgt_w, tgt_h), interpolation=cv2.INTER_LINEAR) # Dense depth output: every pixel gets a value. Tiny-disparity pixels # (effectively "no information") map to large depth and therefore # near-black in the inverse-depth PNG encoding — distinguishable # from depth≈0, which would have been white and visually misleading. safe_disp = np.maximum(disp, 1e-6) depth = (1.0 / safe_disp) * scale DepthImage(depth=depth.astype(np.float32)).to_pil_image().save( os.path.join(depth_folder, f"{frame_idx:06d}.png") )
if pointcloud_path is not None: _write_pointcloud_ply(droid, scale, pointcloud_path, min_views=pointcloud_min_views)1234567891011121314151617181920212223242526272829303132# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.# SPDX-License-Identifier: Apache-2.0"""Download the DROID-SLAM checkpoint (droid.pth) into a local weights folder.
Upstream hosts the file on Google Drive — we use gdown to fetch it."""import argparseimport os
import gdown
DROID_GDRIVE_FILE_ID = "1PpqVt1H4maBa_GbPJp4NwxRsd9jk-elh"
def download_droid(output_dir: str) -> None: os.makedirs(output_dir, exist_ok=True) out_path = os.path.join(output_dir, "droid.pth") if os.path.exists(out_path): print(f"droid.pth already present at {out_path} — skipping download") return url = f"https://drive.google.com/uc?id={DROID_GDRIVE_FILE_ID}" gdown.download(url, out_path, quiet=False) print(f"DROID-SLAM checkpoint downloaded to {out_path}")
if __name__ == "__main__": parser = argparse.ArgumentParser(description="Download DROID-SLAM checkpoint") parser.add_argument("--output_dir", type=str, required=True, help="Output directory for droid.pth") args = parser.parse_args() download_droid(args.output_dir)123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.# SPDX-License-Identifier: Apache-2.0"""Run DROID-SLAM on a folder of frame images → per-frame camera poses(+ optional depth, PLY). Sibling of video_to_slam with the same options.
Image folder may contain .png, .jpg, or .jpeg files. Frame index is parsedfrom the filename stem as an integer (zero-padded names like 000123.png)."""from __future__ import annotations
import argparseimport osfrom typing import Iterator
import cv2import numpy as np
from v2d.common.datatypes import CameraIntrinsics, DepthImagefrom v2d.droid_slam.lib._slam import Frame, run_droid_slam
_IMAGE_EXTS = (".png", ".jpg", ".jpeg")
def _list_image_files(image_folder: str) -> list[str]: files = [ os.path.join(image_folder, f) for f in os.listdir(image_folder) if f.lower().endswith(_IMAGE_EXTS) ] files.sort() return files
def _frame_idx_from_path(path: str) -> int: stem = os.path.splitext(os.path.basename(path))[0] return int(stem)
def _load_intrinsics_for_frame( input_intrinsics_path: str | None, input_intrinsics_folder: str | None, frame_idx: int, fallback: CameraIntrinsics | None,) -> CameraIntrinsics: if input_intrinsics_folder is not None: path = os.path.join(input_intrinsics_folder, f"{frame_idx:06d}.json") if os.path.exists(path): return CameraIntrinsics.load(path) if fallback is None: raise FileNotFoundError( f"No intrinsics file for frame {frame_idx} at {path} and no fallback") return fallback assert fallback is not None return fallback
def _depth_for_frame(folder: str | None, frame_idx: int) -> np.ndarray | None: if folder is None: return None path = os.path.join(folder, f"{frame_idx:06d}.png") if not os.path.exists(path): return None return DepthImage.load(path).depth.astype(np.float32)
def image_list_to_slam( image_folder: str, poses_folder: str, weights_path: str, input_intrinsics_path: str | None = None, input_intrinsics_folder: str | None = None, input_depth_folder: str | None = None, align_to_depth_folder: str | None = None, depth_folder: str | None = None, pointcloud_path: str | None = None, trajectory_path: str | None = None, stride: int = 1, image_size: tuple[int, int] = (384, 512), buffer_size: int = 512, beta: float = 0.3, filter_thresh: float = 2.4, warmup: int = 8, keyframe_thresh: float = 4.0, frontend_thresh: float = 16.0, frontend_window: int = 25, frontend_radius: int = 2, frontend_nms: int = 1, backend_thresh: float = 22.0, backend_radius: int = 2, backend_nms: int = 3, upsample: bool = False, pointcloud_min_views: int = 2,) -> None: if input_intrinsics_path is None and input_intrinsics_folder is None: raise ValueError("Provide either --input_intrinsics_path or --input_intrinsics_folder")
fallback_intrinsics = None if input_intrinsics_path is not None: fallback_intrinsics = CameraIntrinsics.load(input_intrinsics_path) elif input_intrinsics_folder is not None: # Use the first available file as a fallback for any frame missing its own. files = sorted( os.path.join(input_intrinsics_folder, f) for f in os.listdir(input_intrinsics_folder) if f.endswith(".json") ) if not files: raise FileNotFoundError(f"No intrinsics JSONs in {input_intrinsics_folder}") fallback_intrinsics = CameraIntrinsics.load(files[0])
image_paths = _list_image_files(image_folder) if not image_paths: raise FileNotFoundError(f"No images in {image_folder}")
def frame_iter() -> Iterator[Frame]: for i, path in enumerate(image_paths): if i % stride != 0: continue frame_idx = _frame_idx_from_path(path) image_bgr = cv2.imread(path, cv2.IMREAD_COLOR) if image_bgr is None: raise IOError(f"Failed to read image {path}") intr = _load_intrinsics_for_frame( input_intrinsics_path, input_intrinsics_folder, frame_idx, fallback_intrinsics, ) yield Frame( frame_idx=frame_idx, image_bgr=image_bgr, intrinsics=intr, prior_depth=_depth_for_frame(input_depth_folder, frame_idx), align_to_depth=_depth_for_frame(align_to_depth_folder, frame_idx), )
run_droid_slam( frame_iter=frame_iter, weights_path=weights_path, poses_folder=poses_folder, depth_folder=depth_folder, pointcloud_path=pointcloud_path, trajectory_path=trajectory_path, image_size=image_size, buffer_size=buffer_size, beta=beta, filter_thresh=filter_thresh, warmup=warmup, keyframe_thresh=keyframe_thresh, frontend_thresh=frontend_thresh, frontend_window=frontend_window, frontend_radius=frontend_radius, frontend_nms=frontend_nms, backend_thresh=backend_thresh, backend_radius=backend_radius, backend_nms=backend_nms, upsample=upsample, pointcloud_min_views=pointcloud_min_views, )
if __name__ == "__main__": parser = argparse.ArgumentParser(description="Run DROID-SLAM on a folder of frames") parser.add_argument("--image_folder", required=True) parser.add_argument("--poses_folder", required=True) parser.add_argument("--weights_path", required=True) parser.add_argument("--input_intrinsics_path", default=None) parser.add_argument("--input_intrinsics_folder", default=None) parser.add_argument("--input_depth_folder", default=None, help="Per-frame metric depth fed into BA as a sensor prior.") parser.add_argument("--align_to_depth_folder", default=None, help="Per-frame metric depth used post-hoc for scale alignment only.") parser.add_argument("--depth_folder", default=None) parser.add_argument("--pointcloud_path", default=None) parser.add_argument("--trajectory_path", default=None) parser.add_argument("--stride", type=int, default=1) parser.add_argument("--image_height", type=int, default=384) parser.add_argument("--image_width", type=int, default=512) parser.add_argument("--buffer_size", type=int, default=512) parser.add_argument("--beta", type=float, default=0.3) parser.add_argument("--filter_thresh", type=float, default=2.4) parser.add_argument("--warmup", type=int, default=8) parser.add_argument("--keyframe_thresh", type=float, default=4.0) parser.add_argument("--frontend_thresh", type=float, default=16.0) parser.add_argument("--frontend_window", type=int, default=25) parser.add_argument("--frontend_radius", type=int, default=2) parser.add_argument("--frontend_nms", type=int, default=1) parser.add_argument("--backend_thresh", type=float, default=22.0) parser.add_argument("--backend_radius", type=int, default=2) parser.add_argument("--backend_nms", type=int, default=3) parser.add_argument("--upsample", action="store_true") parser.add_argument("--pointcloud_min_views", type=int, default=2, help="Multi-view consistency threshold for PLY output.") args = parser.parse_args()
image_list_to_slam( image_folder=args.image_folder, poses_folder=args.poses_folder, weights_path=args.weights_path, input_intrinsics_path=args.input_intrinsics_path, input_intrinsics_folder=args.input_intrinsics_folder, input_depth_folder=args.input_depth_folder, align_to_depth_folder=args.align_to_depth_folder, depth_folder=args.depth_folder, pointcloud_path=args.pointcloud_path, trajectory_path=args.trajectory_path, stride=args.stride, image_size=(args.image_height, args.image_width), buffer_size=args.buffer_size, beta=args.beta, filter_thresh=args.filter_thresh, warmup=args.warmup, keyframe_thresh=args.keyframe_thresh, frontend_thresh=args.frontend_thresh, frontend_window=args.frontend_window, frontend_radius=args.frontend_radius, frontend_nms=args.frontend_nms, backend_thresh=args.backend_thresh, backend_radius=args.backend_radius, backend_nms=args.backend_nms, upsample=args.upsample, pointcloud_min_views=args.pointcloud_min_views, )12345678910111213141516171819202122232425# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.# SPDX-License-Identifier: Apache-2.0[build-system]requires = ["setuptools>=68.0", "wheel"]build-backend = "setuptools.build_meta"
[project]name = "v2d-droid-slam-lib"version = "0.1.0"description = "DROID-SLAM monocular SLAM library"requires-python = ">=3.10"dependencies = [ "numpy", "scipy", "opencv-python", "Pillow", "gdown", "v2d-common",]
[tool.setuptools]packages = ["v2d.droid_slam.lib"]
[tool.setuptools.package-dir]"v2d.droid_slam.lib" = "."123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.# SPDX-License-Identifier: Apache-2.0"""Run DROID-SLAM on a video file → per-frame camera poses (+ optional depth, PLY).
Intrinsics can be supplied either as a single CameraIntrinsics JSON(--input_intrinsics_path; reused for every frame) or as a folder ofper-frame intrinsics JSON files (--input_intrinsics_folder; values aremedian-pooled into a single set, since DROID-SLAM uses a fixed intrinsicfor the whole sequence).
If --input_depth_folder is provided, per-frame depth (e.g. from MoGe) isfed into DROID-SLAM's bundle adjustment as a metric prior — this directlyshapes the reconstructed geometry rather than rescaling it after the fact.
If --align_to_depth_folder is provided, the reconstructed poses and depthsare scale-aligned to that metric reference via a robust per-keyframe ratiofit. Pure post-processing — does not affect SLAM behaviour.
The two flags are independent and may be combined: --input_depth_foldershapes BA, --align_to_depth_folder rescales output. With a metric priorprovided, post-hoc rescaling is usually unnecessary."""from __future__ import annotations
import argparseimport osfrom typing import Iterator
import cv2import numpy as np
from v2d.common.datatypes import CameraIntrinsics, DepthImagefrom v2d.droid_slam.lib._slam import Frame, run_droid_slam
def _load_intrinsics( input_intrinsics_path: str | None, input_intrinsics_folder: str | None,) -> CameraIntrinsics: if input_intrinsics_path is None and input_intrinsics_folder is None: raise ValueError("Provide either --input_intrinsics_path or --input_intrinsics_folder") if input_intrinsics_path is not None: return CameraIntrinsics.load(input_intrinsics_path) # Per-frame intrinsics → median pool into one shared intrinsic for DROID. files = sorted( os.path.join(input_intrinsics_folder, f) for f in os.listdir(input_intrinsics_folder) if f.endswith(".json") ) if not files: raise FileNotFoundError(f"No intrinsics JSONs in {input_intrinsics_folder}") fx, fy, cx, cy, w, h = [], [], [], [], [], [] for fp in files: ci = CameraIntrinsics.load(fp) fx.append(ci.fx); fy.append(ci.fy); cx.append(ci.cx); cy.append(ci.cy) w.append(ci.width); h.append(ci.height) return CameraIntrinsics( fx=float(np.median(fx)), fy=float(np.median(fy)), cx=float(np.median(cx)), cy=float(np.median(cy)), width=int(np.median(w)), height=int(np.median(h)), )
def _depth_for_frame(folder: str | None, frame_idx: int) -> np.ndarray | None: if folder is None: return None path = os.path.join(folder, f"{frame_idx:06d}.png") if not os.path.exists(path): return None return DepthImage.load(path).depth.astype(np.float32)
def video_to_slam( video_path: str, poses_folder: str, weights_path: str, input_intrinsics_path: str | None = None, input_intrinsics_folder: str | None = None, input_depth_folder: str | None = None, align_to_depth_folder: str | None = None, depth_folder: str | None = None, pointcloud_path: str | None = None, trajectory_path: str | None = None, stride: int = 1, image_size: tuple[int, int] = (384, 512), buffer_size: int = 512, beta: float = 0.3, filter_thresh: float = 2.4, warmup: int = 8, keyframe_thresh: float = 4.0, frontend_thresh: float = 16.0, frontend_window: int = 25, frontend_radius: int = 2, frontend_nms: int = 1, backend_thresh: float = 22.0, backend_radius: int = 2, backend_nms: int = 3, upsample: bool = False, pointcloud_min_views: int = 2,) -> None: intrinsics = _load_intrinsics(input_intrinsics_path, input_intrinsics_folder)
def frame_iter() -> Iterator[Frame]: cap = cv2.VideoCapture(video_path) try: i = 0 while True: ret, frame_bgr = cap.read() if not ret: break if i % stride == 0: yield Frame( frame_idx=i, image_bgr=frame_bgr, intrinsics=intrinsics, prior_depth=_depth_for_frame(input_depth_folder, i), align_to_depth=_depth_for_frame(align_to_depth_folder, i), ) i += 1 finally: cap.release()
run_droid_slam( frame_iter=frame_iter, weights_path=weights_path, poses_folder=poses_folder, depth_folder=depth_folder, pointcloud_path=pointcloud_path, trajectory_path=trajectory_path, image_size=image_size, buffer_size=buffer_size, beta=beta, filter_thresh=filter_thresh, warmup=warmup, keyframe_thresh=keyframe_thresh, frontend_thresh=frontend_thresh, frontend_window=frontend_window, frontend_radius=frontend_radius, frontend_nms=frontend_nms, backend_thresh=backend_thresh, backend_radius=backend_radius, backend_nms=backend_nms, upsample=upsample, pointcloud_min_views=pointcloud_min_views, )
if __name__ == "__main__": parser = argparse.ArgumentParser(description="Run DROID-SLAM on a video") parser.add_argument("--video_path", required=True) parser.add_argument("--poses_folder", required=True) parser.add_argument("--weights_path", required=True) parser.add_argument("--input_intrinsics_path", default=None) parser.add_argument("--input_intrinsics_folder", default=None) parser.add_argument("--input_depth_folder", default=None, help="Per-frame metric depth fed into BA as a sensor prior " "(e.g. MoGe output). Shapes the reconstruction.") parser.add_argument("--align_to_depth_folder", default=None, help="Per-frame metric depth used post-hoc for scale " "alignment only. Does not influence BA.") parser.add_argument("--depth_folder", default=None, help="Optional output: per-keyframe DROID depth (scale-aligned)") parser.add_argument("--pointcloud_path", default=None, help="Optional output: fused .ply of keyframe points") parser.add_argument("--trajectory_path", default=None, help="Optional output: TUM-format trajectory .txt") parser.add_argument("--stride", type=int, default=1) parser.add_argument("--image_height", type=int, default=384) parser.add_argument("--image_width", type=int, default=512) parser.add_argument("--buffer_size", type=int, default=512) parser.add_argument("--beta", type=float, default=0.3) parser.add_argument("--filter_thresh", type=float, default=2.4) parser.add_argument("--warmup", type=int, default=8) parser.add_argument("--keyframe_thresh", type=float, default=4.0) parser.add_argument("--frontend_thresh", type=float, default=16.0) parser.add_argument("--frontend_window", type=int, default=25) parser.add_argument("--frontend_radius", type=int, default=2) parser.add_argument("--frontend_nms", type=int, default=1) parser.add_argument("--backend_thresh", type=float, default=22.0) parser.add_argument("--backend_radius", type=int, default=2) parser.add_argument("--backend_nms", type=int, default=3) parser.add_argument("--upsample", action="store_true") parser.add_argument("--pointcloud_min_views", type=int, default=2, help="Multi-view consistency threshold for PLY output. " "1 = keep all pixels above the disparity threshold " "(dense, noisier); 2 = upstream default (clean, sparse).") args = parser.parse_args()
video_to_slam( video_path=args.video_path, poses_folder=args.poses_folder, weights_path=args.weights_path, input_intrinsics_path=args.input_intrinsics_path, input_intrinsics_folder=args.input_intrinsics_folder, input_depth_folder=args.input_depth_folder, align_to_depth_folder=args.align_to_depth_folder, depth_folder=args.depth_folder, pointcloud_path=args.pointcloud_path, trajectory_path=args.trajectory_path, stride=args.stride, image_size=(args.image_height, args.image_width), buffer_size=args.buffer_size, beta=args.beta, filter_thresh=args.filter_thresh, warmup=args.warmup, keyframe_thresh=args.keyframe_thresh, frontend_thresh=args.frontend_thresh, frontend_window=args.frontend_window, frontend_radius=args.frontend_radius, frontend_nms=args.frontend_nms, backend_thresh=args.backend_thresh, backend_radius=args.backend_radius, backend_nms=args.backend_nms, upsample=args.upsample, pointcloud_min_views=args.pointcloud_min_views, )123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.# SPDX-License-Identifier: Apache-2.0"""Convert a folder of Transform3d (camera-to-world) JSONs into a PLY of camerafrustum wireframes. Open this PLY alongside the point cloud in MeshLab (orany PLY viewer) to see where each camera is pointing.
Usage: python modules/v2d_droid_slam/tools/poses_to_frustums.py \ --poses_folder data/clean/agent_90_undist/output/droid_slam/poses \ --intrinsics_path data/clean/agent_90_undist/undistorted_intrinsics.json \ --output_path data/clean/agent_90_undist/output/droid_slam/cameras.ply \ [--frustum_size 0.05] # near-plane distance in scene units [--stride 1] # skip frames
Open in MeshLab (drag both files into the same window): meshlab data/clean/agent_90_undist/output/droid_slam/pointcloud.ply \ data/clean/agent_90_undist/output/droid_slam/cameras.ply"""import argparseimport jsonimport osimport sys
import numpy as np
# Make `v2d.common.datatypes` importable without installing anything._REPO_MODULES = os.path.abspath(os.path.join(os.path.dirname(__file__), "..", ".."))sys.path.insert(0, os.path.join(_REPO_MODULES, "v2d_common"))from datatypes import CameraIntrinsics, Transform3d # noqa: E402
def _frustum_vertices(K: np.ndarray, T_cw: np.ndarray, near: float, width: int, height: int) -> np.ndarray: """Return 5 vertices (world frame): camera centre + 4 near-plane corners.""" fx, fy = K[0, 0], K[1, 1] cx, cy = K[0, 2], K[1, 2] corners_pix = np.array([ [0, 0], [width, 0], [width, height], [0, height], ], dtype=np.float64) rays_cam = np.stack([ (corners_pix[:, 0] - cx) / fx, (corners_pix[:, 1] - cy) / fy, np.ones(4), ], axis=1) * near pts_cam = np.concatenate([np.zeros((1, 3)), rays_cam], axis=0) # (5, 3) pts_world = (T_cw[:3, :3] @ pts_cam.T + T_cw[:3, 3:4]).T return pts_world
_FRUSTUM_EDGES = [ (0, 1), (0, 2), (0, 3), (0, 4), # apex → corners (1, 2), (2, 3), (3, 4), (4, 1), # near-plane rectangle]
def _rgb_for_index(i: int, n: int) -> tuple[int, int, int]: """Linearly interpolate red → green → blue across the trajectory.""" t = i / max(n - 1, 1) if t < 0.5: r = int(255 * (1 - 2 * t)) g = int(255 * (2 * t)) b = 0 else: r = 0 g = int(255 * (2 * (1 - t))) b = int(255 * (2 * t - 1)) return r, g, b
def main(): parser = argparse.ArgumentParser() parser.add_argument("--poses_folder", required=True) parser.add_argument("--intrinsics_path", required=True) parser.add_argument("--output_path", required=True) parser.add_argument("--frustum_size", type=float, default=0.05, help="Near-plane distance in scene units") parser.add_argument("--stride", type=int, default=1) args = parser.parse_args()
intr = CameraIntrinsics.load(args.intrinsics_path) K = intr.to_matrix() pose_files = sorted(f for f in os.listdir(args.poses_folder) if f.endswith(".json")) pose_files = pose_files[::args.stride] if not pose_files: raise FileNotFoundError(f"No pose JSONs in {args.poses_folder}")
verts, edges, edge_colors = [], [], [] n = len(pose_files) for i, fn in enumerate(pose_files): T_cw = Transform3d.load(os.path.join(args.poses_folder, fn)).to_matrix() v = _frustum_vertices(K, T_cw, args.frustum_size, intr.width, intr.height) base = i * 5 verts.append(v) rgb = _rgb_for_index(i, n) for a, b in _FRUSTUM_EDGES: edges.append((base + a, base + b)) edge_colors.append(rgb)
verts_arr = np.concatenate(verts, axis=0).astype(np.float32) n_v = verts_arr.shape[0] n_e = len(edges)
os.makedirs(os.path.dirname(os.path.abspath(args.output_path)) or ".", exist_ok=True) with open(args.output_path, "w") as f: f.write( f"ply\nformat ascii 1.0\n" f"element vertex {n_v}\n" "property float x\nproperty float y\nproperty float z\n" f"element edge {n_e}\n" "property int vertex1\nproperty int vertex2\n" "property uchar red\nproperty uchar green\nproperty uchar blue\n" "end_header\n" ) for x, y, z in verts_arr: f.write(f"{x} {y} {z}\n") for (a, b), (r, g, bl) in zip(edges, edge_colors): f.write(f"{a} {b} {r} {g} {bl}\n")
print(f"wrote {args.output_path}: {n} frustums, {n_v} vertices, {n_e} edges") print(f"View with: meshlab <pointcloud.ply> {args.output_path}")
if __name__ == "__main__": main()1234vendor/__pycache__/*.egg-info/
123456789101112131415# Apache License 2.0
Copyright 2025 NVIDIA CORPORATION
Licensed under the Apache License, Version 2.0 (the "License");you may not use this file except in compliance with the License.You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, softwaredistributed under the License is distributed on an "AS IS" BASIS,WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.See the License for the specific language governing permissions andlimitations under the License.123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115<!--SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.SPDX-License-Identifier: Apache-2.0-->
# Egocentric Hand Reconstruction
Automated pipeline for 4D hand and camera pose reconstruction from egocentric videos. Integrates ViPE and Dyn-HaMR in containerized environments.
## Setup
Fetch vendored sources from [IsaacTeleop](https://github.com/NVIDIA/IsaacTeleop):
```bash./sync.sh```
Install the host-side orchestration package:
```bashpip install -e docker/```
Build both Docker images (ViPE + Dyn-HaMR):
```bashpython -m v2d_ego_hand_reconstruction.docker.build```
Place required data in your weights directory before running (see [Isaac Teleop Documentation](https://nvidia.github.io/IsaacTeleop/main/references/egocentric_hand_reconstruction.html)).The layout follows the manotorch convention so the same directory is shared with `v2d_hamer`:
```<weights_dir>/├── models/│ └── MANO_RIGHT.pkl # from https://mano.is.tue.mpg.de/└── BMC/ └── *.npy # from the Hand-BMC-pytorch repo```
## Usage
**Python (programmatic):**
```pythonfrom v2d_ego_hand_reconstruction.docker.run_reconstruction import run_reconstruction
run_reconstruction( video_input="path/to/video.mp4", output_dir="data/outputs/ego_hand",)```
**CLI:**
```bashpython -m v2d_ego_hand_reconstruction.docker.run_reconstruction \ --video_input path/to/video.mp4 \ --output_dir data/outputs/ego_hand```
Remote videos (S3/Swift) are also supported:
Set environment variables ACCESS_KEY_ID and SECRET_ACCESS_KEY for S3/Swift permission.
```bashexport ACCESS_KEY_ID=XXX SECRET_ACCESS_KEY=XXX```
Please check [Isaac Teleop Documentation](https://nvidia.github.io/IsaacTeleop/main/references/egocentric_hand_reconstruction.html) for detail.
```bashpython -m v2d_ego_hand_reconstruction.docker.run_reconstruction \ --video_input s3://bucket/video.mp4 \ --output_dir data/outputs/ego_hand```
Results are saved to `<output_dir>/logs/`.
### Hand mesh generation
After running reconstruction, export per-track MANO hand mesh trajectories from every run under `<output_dir>/logs/`:
```pythonfrom v2d_ego_hand_reconstruction.docker.run_mesh_generation import run_mesh_generation
run_mesh_generation(output_dir="data/outputs/ego_hand")```
CLI:
```bashpython -m v2d_ego_hand_reconstruction.docker.run_mesh_generation \ --output_dir data/outputs/ego_hand```
Results land at `<output_dir>/logs/.../smooth_fit/<seq>_hand_mesh_traj_<iter>.npz`.
## Upstream Diff
To see local modifications vs upstream IsaacTeleop:
```bash./diff.sh # summary./diff.sh --full # full unified diff```
## Structure
```docker/ Native Python orchestration (tracked in git)vendor/ Upstream content from IsaacTeleop (gitignored, populated by sync.sh)sync.sh Fetch/update vendored sourcesdiff.sh Compare vendor/ against upstream```12# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.# SPDX-License-Identifier: Apache-2.01234567891011121314151617181920212223242526272829303132333435363738394041424344#!/bin/bash# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.# SPDX-License-Identifier: Apache-2.0# Show local modifications to vendored content vs upstream IsaacTeleop.# Usage: ./diff.sh (summary of changed files)# ./diff.sh --full (full unified diff)# ./diff.sh --patch (git-format patch, apply with: git apply <patch>)set -euo pipefail
SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)"VENDOR_DIR="$SCRIPT_DIR/vendor"REPO="https://github.com/NVIDIA/IsaacTeleop.git"BRANCH="main"DIR="src/postprocessing/egocentric_hand_reconstruction"
if [ ! -d "$VENDOR_DIR" ]; then echo "vendor/ not found. Run ./sync.sh first." >&2 exit 1fi
tmp=$(mktemp -d)trap 'rm -rf "$tmp"' EXIT
echo "Fetching upstream ($BRANCH)..." >&2git clone --filter=blob:none --sparse --branch "$BRANCH" --depth 1 "$REPO" "$tmp/repo" 2>/dev/nullcd "$tmp/repo" && git sparse-checkout set "$DIR" 2>/dev/null && cd - > /dev/null
upstream="$tmp/repo/$DIR"
case "${1:-}" in --patch) # Produce a git-format patch with paths relative to the IsaacTeleop repo root. # Apply in an IsaacTeleop clone with: git apply <patch> cp -r "$VENDOR_DIR/." "$tmp/repo/$DIR/" cd "$tmp/repo" git diff || true ;; --full) diff -ru "$upstream/" "$VENDOR_DIR/" || true ;; *) diff -rq "$upstream/" "$VENDOR_DIR/" && echo "(no differences)" || true ;;esac12# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.# SPDX-License-Identifier: Apache-2.0123456# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.# SPDX-License-Identifier: Apache-2.0import os
MODULE_DIR = os.path.abspath(os.path.join(os.path.dirname(__file__), ".."))VENDOR_DIR = os.path.join(MODULE_DIR, "vendor")123456789101112131415161718192021222324252627282930313233343536373839404142434445464748# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.# SPDX-License-Identifier: Apache-2.0"""Build Docker images for ego hand reconstruction (ViPE + Dyn-HaMR).
Delegates to the vendored shell scripts so build flags stay in sync withupstream IsaacTeleop."""
import subprocessfrom pathlib import Path
from v2d_ego_hand_reconstruction.docker._config import MODULE_DIR, VENDOR_DIR
def _sync_vendor() -> None: """Fetch vendored sources from IsaacTeleop if not already present.""" subprocess.run([str(Path(MODULE_DIR) / "sync.sh")], check=True)
def _run_vendor_script(script: str, *args: str) -> None: vendor = Path(VENDOR_DIR) if not vendor.is_dir(): print(f"{vendor} not found. Running sync.sh to fetch vendored sources...") _sync_vendor() subprocess.run( [str(vendor / "docker" / script), *args], check=True, )
def build_vipe() -> None: """Build the ViPE camera estimation image.""" _run_vendor_script("vipe.sh", "build")
def build_dynhamr() -> None: """Build the Dyn-HaMR hand reconstruction image.""" _run_vendor_script("dynhamr.sh", "build")
def build_all() -> None: """Build both ViPE and Dyn-HaMR images.""" build_vipe() build_dynhamr()
if __name__ == "__main__": build_all()12345678910111213141516171819# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.# SPDX-License-Identifier: Apache-2.0[build-system]requires = ["setuptools>=68.0", "wheel"]build-backend = "setuptools.build_meta"
[project]name = "v2d-ego-hand-reconstruction-docker"version = "0.1.0"description = "Docker orchestration for ego hand reconstruction (ViPE + Dyn-HaMR)"requires-python = ">=3.10"dependencies = ["boto3"]
[tool.setuptools]packages = ["v2d_ego_hand_reconstruction", "v2d_ego_hand_reconstruction.docker"]
[tool.setuptools.package-dir]"v2d_ego_hand_reconstruction" = "..""v2d_ego_hand_reconstruction.docker" = "."123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.# SPDX-License-Identifier: Apache-2.0"""Export per-track MANO hand meshes and joint trajectories from Dyn-HaMR results.
Delegates to the vendored ``run_mesh_generation.sh`` so mesh export logic staysin sync with upstream IsaacTeleop.
Prerequisites: - Dyn-HaMR Docker image must be built (``python -m v2d_ego_hand_reconstruction.docker.build``). - MANO_RIGHT.pkl must be placed in *output_dir*."""
import osimport subprocess
from v2d_ego_hand_reconstruction.docker._config import VENDOR_DIR
def run_mesh_generation( output_dir: str, *, phase: str = "smooth_fit", gpu: int = 0, no_temporal_smooth: bool = False, no_smooth_trans: bool = False,) -> None: """Run hand mesh export over every Dyn-HaMR run under *output_dir*.
Args: output_dir: Directory containing Dyn-HaMR ``logs/.../smooth_fit/*_world_results.npz``. phase: Phase subdir under each run dir (default: ``smooth_fit``). gpu: GPU index inside the container. no_temporal_smooth: Disable OneEuro smoothing on poses. no_smooth_trans: Smooth pose only, not translation. """ output_dir = os.path.abspath(output_dir) os.makedirs(output_dir, exist_ok=True)
env = { **os.environ, "OUTPUTS_DIR": output_dir, "PHASE": phase, "GPU": str(gpu), "NO_TEMPORAL_SMOOTH": "1" if no_temporal_smooth else "0", "NO_SMOOTH_TRANS": "1" if no_smooth_trans else "0", }
subprocess.run( [os.path.join(VENDOR_DIR, "scripts", "run_mesh_generation.sh")], env=env, check=True, )
if __name__ == "__main__": import argparse
parser = argparse.ArgumentParser(description=__doc__) parser.add_argument("--output_dir", required=True, help="Output directory (contains logs/)") parser.add_argument("--phase", default="smooth_fit") parser.add_argument("--gpu", type=int, default=0) parser.add_argument("--no_temporal_smooth", action="store_true") parser.add_argument("--no_smooth_trans", action="store_true") args = parser.parse_args() run_mesh_generation( args.output_dir, phase=args.phase, gpu=args.gpu, no_temporal_smooth=args.no_temporal_smooth, no_smooth_trans=args.no_smooth_trans, )third-party/video_to_data/reconstruction/modules/v2d_detectron2/docker/__init__.pyAdded+2
third-party/video_to_data/reconstruction/modules/v2d_detectron2/docker/_config.pyAdded+6
third-party/video_to_data/reconstruction/modules/v2d_detectron2/docker/build.pyAdded+19
third-party/video_to_data/reconstruction/modules/v2d_detectron2/docker/pyproject.tomlAdded+18
third-party/video_to_data/reconstruction/modules/v2d_detectron2/docker/run_download_weights.pyAdded+41
third-party/video_to_data/reconstruction/modules/v2d_detectron2/docker/run_mv_track_bboxes.pyAdded+70
third-party/video_to_data/reconstruction/modules/v2d_detectron2/docker/run_shell.pyAdded+26
third-party/video_to_data/reconstruction/modules/v2d_detectron2/docker/run_track_bboxes.pyAdded+78
third-party/video_to_data/reconstruction/modules/v2d_detectron2/lib/__init__.pyAdded+2
third-party/video_to_data/reconstruction/modules/v2d_detectron2/lib/build_detector.pyAdded+188
third-party/video_to_data/reconstruction/modules/v2d_detectron2/lib/bytetracker.pyAdded+286
third-party/video_to_data/reconstruction/modules/v2d_detectron2/lib/cascade_mask_rcnn_vitdet_b_100ep.pyAdded+101
third-party/video_to_data/reconstruction/modules/v2d_detectron2/lib/cascade_mask_rcnn_vitdet_h_75ep.pyAdded+131
third-party/video_to_data/reconstruction/modules/v2d_detectron2/lib/cascade_mask_rcnn_vitdet_l_100ep.pyAdded+112
third-party/video_to_data/reconstruction/modules/v2d_detectron2/lib/download_weights.pyAdded+53
third-party/video_to_data/reconstruction/modules/v2d_detectron2/lib/mv_track_bboxes.pyAdded+111
third-party/video_to_data/reconstruction/modules/v2d_detectron2/lib/mv_track_bboxes.yamlAdded+41
third-party/video_to_data/reconstruction/modules/v2d_detectron2/lib/pyproject.tomlAdded+31
third-party/video_to_data/reconstruction/modules/v2d_detectron2/lib/track_bboxes.pyAdded+245
third-party/video_to_data/reconstruction/modules/v2d_detectron2/lib/tracker.pyAdded+503
third-party/video_to_data/reconstruction/modules/v2d_docker/LICENSEAdded+15
third-party/video_to_data/reconstruction/modules/v2d_docker/__init__.pyAdded+5
third-party/video_to_data/reconstruction/modules/v2d_docker/container.pyAdded+103
third-party/video_to_data/reconstruction/modules/v2d_docker/pyproject.tomlAdded+18
third-party/video_to_data/reconstruction/modules/v2d_droid_slam/LICENSEAdded+15
third-party/video_to_data/reconstruction/modules/v2d_droid_slam/docker/DockerfileAdded+43
third-party/video_to_data/reconstruction/modules/v2d_droid_slam/docker/__init__.pyAdded+2
third-party/video_to_data/reconstruction/modules/v2d_droid_slam/docker/_config.pyAdded+6
third-party/video_to_data/reconstruction/modules/v2d_droid_slam/docker/build.pyAdded+19
third-party/video_to_data/reconstruction/modules/v2d_droid_slam/docker/pyproject.tomlAdded+18
third-party/video_to_data/reconstruction/modules/v2d_droid_slam/docker/run_download_weights.pyAdded+36
third-party/video_to_data/reconstruction/modules/v2d_droid_slam/docker/run_image_list_to_slam.pyAdded+152
third-party/video_to_data/reconstruction/modules/v2d_droid_slam/docker/run_video_to_slam.pyAdded+152
third-party/video_to_data/reconstruction/modules/v2d_droid_slam/lib/__init__.pyAdded+2
third-party/video_to_data/reconstruction/modules/v2d_droid_slam/lib/_slam.pyAdded+350
third-party/video_to_data/reconstruction/modules/v2d_droid_slam/lib/download_weights.pyAdded+32
third-party/video_to_data/reconstruction/modules/v2d_droid_slam/lib/image_list_to_slam.pyAdded+223
third-party/video_to_data/reconstruction/modules/v2d_droid_slam/lib/pyproject.tomlAdded+25
third-party/video_to_data/reconstruction/modules/v2d_droid_slam/lib/video_to_slam.pyAdded+217
third-party/video_to_data/reconstruction/modules/v2d_droid_slam/tools/poses_to_frustums.pyAdded+125
third-party/video_to_data/reconstruction/modules/v2d_ego_hand_reconstruction/.gitignoreAdded+4
third-party/video_to_data/reconstruction/modules/v2d_ego_hand_reconstruction/LICENSEAdded+15
third-party/video_to_data/reconstruction/modules/v2d_ego_hand_reconstruction/README.mdAdded+115
third-party/video_to_data/reconstruction/modules/v2d_ego_hand_reconstruction/__init__.pyAdded+2
third-party/video_to_data/reconstruction/modules/v2d_ego_hand_reconstruction/diff.shAdded+44
third-party/video_to_data/reconstruction/modules/v2d_ego_hand_reconstruction/docker/__init__.pyAdded+2
third-party/video_to_data/reconstruction/modules/v2d_ego_hand_reconstruction/docker/_config.pyAdded+6
third-party/video_to_data/reconstruction/modules/v2d_ego_hand_reconstruction/docker/build.pyAdded+48
third-party/video_to_data/reconstruction/modules/v2d_ego_hand_reconstruction/docker/pyproject.tomlAdded+19
third-party/video_to_data/reconstruction/modules/v2d_ego_hand_reconstruction/docker/run_mesh_generation.pyAdded+72