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
- third-party/video_to_data/reconstruction/modules/v2d_detectron2/docker/__init__.py +2 -0
- third-party/video_to_data/reconstruction/modules/v2d_detectron2/docker/_config.py +6 -0
- third-party/video_to_data/reconstruction/modules/v2d_detectron2/docker/build.py +19 -0
- third-party/video_to_data/reconstruction/modules/v2d_detectron2/docker/pyproject.toml +18 -0
- third-party/video_to_data/reconstruction/modules/v2d_detectron2/docker/run_download_weights.py +41 -0
- third-party/video_to_data/reconstruction/modules/v2d_detectron2/docker/run_mv_track_bboxes.py +70 -0
- third-party/video_to_data/reconstruction/modules/v2d_detectron2/docker/run_shell.py +26 -0
- third-party/video_to_data/reconstruction/modules/v2d_detectron2/docker/run_track_bboxes.py +78 -0
- third-party/video_to_data/reconstruction/modules/v2d_detectron2/lib/__init__.py +2 -0
- third-party/video_to_data/reconstruction/modules/v2d_detectron2/lib/build_detector.py +188 -0
- third-party/video_to_data/reconstruction/modules/v2d_detectron2/lib/bytetracker.py +286 -0
- third-party/video_to_data/reconstruction/modules/v2d_detectron2/lib/cascade_mask_rcnn_vitdet_b_100ep.py +101 -0
- third-party/video_to_data/reconstruction/modules/v2d_detectron2/lib/cascade_mask_rcnn_vitdet_h_75ep.py +131 -0
- third-party/video_to_data/reconstruction/modules/v2d_detectron2/lib/cascade_mask_rcnn_vitdet_l_100ep.py +112 -0
- third-party/video_to_data/reconstruction/modules/v2d_detectron2/lib/download_weights.py +53 -0
- third-party/video_to_data/reconstruction/modules/v2d_detectron2/lib/mv_track_bboxes.py +111 -0
- third-party/video_to_data/reconstruction/modules/v2d_detectron2/lib/mv_track_bboxes.yaml +41 -0
- third-party/video_to_data/reconstruction/modules/v2d_detectron2/lib/pyproject.toml +31 -0
- third-party/video_to_data/reconstruction/modules/v2d_detectron2/lib/track_bboxes.py +245 -0
- third-party/video_to_data/reconstruction/modules/v2d_detectron2/lib/tracker.py +503 -0
- third-party/video_to_data/reconstruction/modules/v2d_docker/LICENSE +15 -0
- third-party/video_to_data/reconstruction/modules/v2d_docker/__init__.py +5 -0
- third-party/video_to_data/reconstruction/modules/v2d_docker/container.py +103 -0
- third-party/video_to_data/reconstruction/modules/v2d_docker/pyproject.toml +18 -0
- third-party/video_to_data/reconstruction/modules/v2d_droid_slam/LICENSE +15 -0
- third-party/video_to_data/reconstruction/modules/v2d_droid_slam/docker/Dockerfile +43 -0
- third-party/video_to_data/reconstruction/modules/v2d_droid_slam/docker/__init__.py +2 -0
- third-party/video_to_data/reconstruction/modules/v2d_droid_slam/docker/_config.py +6 -0
- third-party/video_to_data/reconstruction/modules/v2d_droid_slam/docker/build.py +19 -0
- third-party/video_to_data/reconstruction/modules/v2d_droid_slam/docker/pyproject.toml +18 -0
- third-party/video_to_data/reconstruction/modules/v2d_droid_slam/docker/run_download_weights.py +36 -0
- third-party/video_to_data/reconstruction/modules/v2d_droid_slam/docker/run_image_list_to_slam.py +152 -0
- third-party/video_to_data/reconstruction/modules/v2d_droid_slam/docker/run_video_to_slam.py +152 -0
- third-party/video_to_data/reconstruction/modules/v2d_droid_slam/lib/__init__.py +2 -0
- third-party/video_to_data/reconstruction/modules/v2d_droid_slam/lib/_slam.py +350 -0
- third-party/video_to_data/reconstruction/modules/v2d_droid_slam/lib/download_weights.py +32 -0
- third-party/video_to_data/reconstruction/modules/v2d_droid_slam/lib/image_list_to_slam.py +223 -0
- third-party/video_to_data/reconstruction/modules/v2d_droid_slam/lib/pyproject.toml +25 -0
- third-party/video_to_data/reconstruction/modules/v2d_droid_slam/lib/video_to_slam.py +217 -0
- third-party/video_to_data/reconstruction/modules/v2d_droid_slam/tools/poses_to_frustums.py +125 -0
- third-party/video_to_data/reconstruction/modules/v2d_ego_hand_reconstruction/.gitignore +4 -0
- third-party/video_to_data/reconstruction/modules/v2d_ego_hand_reconstruction/LICENSE +15 -0
- third-party/video_to_data/reconstruction/modules/v2d_ego_hand_reconstruction/README.md +115 -0
- third-party/video_to_data/reconstruction/modules/v2d_ego_hand_reconstruction/__init__.py +2 -0
- third-party/video_to_data/reconstruction/modules/v2d_ego_hand_reconstruction/diff.sh +44 -0
- third-party/video_to_data/reconstruction/modules/v2d_ego_hand_reconstruction/docker/__init__.py +2 -0
- third-party/video_to_data/reconstruction/modules/v2d_ego_hand_reconstruction/docker/_config.py +6 -0
- third-party/video_to_data/reconstruction/modules/v2d_ego_hand_reconstruction/docker/build.py +48 -0
- third-party/video_to_data/reconstruction/modules/v2d_ego_hand_reconstruction/docker/pyproject.toml +19 -0
- third-party/video_to_data/reconstruction/modules/v2d_ego_hand_reconstruction/docker/run_mesh_generation.py +72 -0
third-party/video_to_data/reconstruction/modules/v2d_detectron2/docker/__init__.py
ADDED
|
@@ -0,0 +1,2 @@
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
|
| 2 |
+
# SPDX-License-Identifier: Apache-2.0
|
third-party/video_to_data/reconstruction/modules/v2d_detectron2/docker/_config.py
ADDED
|
@@ -0,0 +1,6 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
|
| 2 |
+
# SPDX-License-Identifier: Apache-2.0
|
| 3 |
+
import os
|
| 4 |
+
|
| 5 |
+
IMAGE_NAME = "v2d_detectron2"
|
| 6 |
+
MODULES_DIR = os.path.abspath(os.path.join(os.path.dirname(os.path.abspath(__file__)), "..", ".."))
|
third-party/video_to_data/reconstruction/modules/v2d_detectron2/docker/build.py
ADDED
|
@@ -0,0 +1,19 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
|
| 2 |
+
# SPDX-License-Identifier: Apache-2.0
|
| 3 |
+
import subprocess
|
| 4 |
+
import os
|
| 5 |
+
|
| 6 |
+
IMAGE_NAME = "v2d_detectron2"
|
| 7 |
+
|
| 8 |
+
current_dir = os.path.dirname(os.path.abspath(__file__))
|
| 9 |
+
module_dir = os.path.join(current_dir, "..")
|
| 10 |
+
root_dir = os.path.join(module_dir, "..")
|
| 11 |
+
dockerfile_path = os.path.join(current_dir, "Dockerfile")
|
| 12 |
+
|
| 13 |
+
|
| 14 |
+
def build_docker_image() -> None:
|
| 15 |
+
subprocess.run(["docker", "build", "-t", IMAGE_NAME, "-f", dockerfile_path, root_dir], check=True)
|
| 16 |
+
|
| 17 |
+
|
| 18 |
+
if __name__ == "__main__":
|
| 19 |
+
build_docker_image()
|
third-party/video_to_data/reconstruction/modules/v2d_detectron2/docker/pyproject.toml
ADDED
|
@@ -0,0 +1,18 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
|
| 2 |
+
# SPDX-License-Identifier: Apache-2.0
|
| 3 |
+
[build-system]
|
| 4 |
+
requires = ["setuptools>=68.0", "wheel"]
|
| 5 |
+
build-backend = "setuptools.build_meta"
|
| 6 |
+
|
| 7 |
+
[project]
|
| 8 |
+
name = "v2d-detectron2-docker"
|
| 9 |
+
version = "0.1.0"
|
| 10 |
+
description = "Docker orchestration scripts for Detectron2 tracking"
|
| 11 |
+
requires-python = ">=3.10"
|
| 12 |
+
dependencies = ["v2d-docker", "omegaconf"]
|
| 13 |
+
|
| 14 |
+
[tool.setuptools]
|
| 15 |
+
packages = ["v2d.detectron2.docker"]
|
| 16 |
+
|
| 17 |
+
[tool.setuptools.package-dir]
|
| 18 |
+
"v2d.detectron2.docker" = "."
|
third-party/video_to_data/reconstruction/modules/v2d_detectron2/docker/run_download_weights.py
ADDED
|
@@ -0,0 +1,41 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
|
| 2 |
+
# SPDX-License-Identifier: Apache-2.0
|
| 3 |
+
import os
|
| 4 |
+
import subprocess
|
| 5 |
+
from v2d.detectron2.docker._config import IMAGE_NAME, MODULES_DIR
|
| 6 |
+
|
| 7 |
+
|
| 8 |
+
def run_download_weights(
|
| 9 |
+
output_dir: str,
|
| 10 |
+
model_sizes: list[str] | None = None,
|
| 11 |
+
dev: bool = False,
|
| 12 |
+
) -> None:
|
| 13 |
+
if not os.path.exists(output_dir):
|
| 14 |
+
os.makedirs(output_dir)
|
| 15 |
+
output_dir = os.path.abspath(output_dir)
|
| 16 |
+
|
| 17 |
+
cmd = [
|
| 18 |
+
"docker", "run", "--rm",
|
| 19 |
+
"--user", f"{os.getuid()}:{os.getgid()}",
|
| 20 |
+
"-v", f"{output_dir}:/data/weights",
|
| 21 |
+
]
|
| 22 |
+
if dev:
|
| 23 |
+
cmd += ["-v", f"{MODULES_DIR}:/workspace"]
|
| 24 |
+
cmd += [IMAGE_NAME, "python", "-m", "v2d.detectron2.lib.download_weights",
|
| 25 |
+
"--output_dir", "/data/weights"]
|
| 26 |
+
if model_sizes:
|
| 27 |
+
cmd += ["--model_sizes"] + model_sizes
|
| 28 |
+
|
| 29 |
+
subprocess.run(cmd, check=True)
|
| 30 |
+
|
| 31 |
+
|
| 32 |
+
if __name__ == "__main__":
|
| 33 |
+
import argparse
|
| 34 |
+
|
| 35 |
+
parser = argparse.ArgumentParser(description="Download ViTDet checkpoints")
|
| 36 |
+
parser.add_argument("--output_dir", type=str, required=True)
|
| 37 |
+
parser.add_argument("--model_sizes", type=str, nargs="+", default=["b"], choices=["b", "l", "h"])
|
| 38 |
+
parser.add_argument("--dev", action="store_true")
|
| 39 |
+
args = parser.parse_args()
|
| 40 |
+
|
| 41 |
+
run_download_weights(args.output_dir, args.model_sizes, dev=args.dev)
|
third-party/video_to_data/reconstruction/modules/v2d_detectron2/docker/run_mv_track_bboxes.py
ADDED
|
@@ -0,0 +1,70 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
|
| 2 |
+
# SPDX-License-Identifier: Apache-2.0
|
| 3 |
+
from pathlib import Path
|
| 4 |
+
|
| 5 |
+
from v2d.docker.container import run_in_container
|
| 6 |
+
from v2d.detectron2.docker._config import IMAGE_NAME, MODULES_DIR
|
| 7 |
+
|
| 8 |
+
_LIB_CONFIG = Path(__file__).parent.parent / "lib" / "mv_track_bboxes.yaml"
|
| 9 |
+
|
| 10 |
+
|
| 11 |
+
def run_mv_track_bboxes(
|
| 12 |
+
rgb_dir: str,
|
| 13 |
+
weights_dir: str,
|
| 14 |
+
output_dir: str,
|
| 15 |
+
labeled_bbox_dir: str | None = None,
|
| 16 |
+
config_path: str = str(_LIB_CONFIG),
|
| 17 |
+
debug: int = -1,
|
| 18 |
+
dev: bool = False,
|
| 19 |
+
) -> None:
|
| 20 |
+
inputs = {
|
| 21 |
+
"rgb_dir": rgb_dir,
|
| 22 |
+
"weights_dir": weights_dir,
|
| 23 |
+
"config_path": config_path,
|
| 24 |
+
}
|
| 25 |
+
if labeled_bbox_dir:
|
| 26 |
+
inputs["labeled_bbox_dir"] = labeled_bbox_dir
|
| 27 |
+
|
| 28 |
+
outputs = {"output_dir": output_dir}
|
| 29 |
+
|
| 30 |
+
run_in_container(
|
| 31 |
+
image=IMAGE_NAME,
|
| 32 |
+
module="v2d.detectron2.lib.mv_track_bboxes",
|
| 33 |
+
inputs=inputs,
|
| 34 |
+
outputs=outputs,
|
| 35 |
+
extra_args={"debug": debug if debug >= 0 else None},
|
| 36 |
+
dev=dev,
|
| 37 |
+
modules_dir=MODULES_DIR,
|
| 38 |
+
gpus=True,
|
| 39 |
+
env={
|
| 40 |
+
"PYTHONUNBUFFERED": "1",
|
| 41 |
+
},
|
| 42 |
+
)
|
| 43 |
+
|
| 44 |
+
|
| 45 |
+
if __name__ == "__main__":
|
| 46 |
+
import argparse
|
| 47 |
+
|
| 48 |
+
parser = argparse.ArgumentParser(description="Run multi-view bbox tracking")
|
| 49 |
+
parser.add_argument("--rgb_dir", type=str, required=True, help="Directory containing input frames")
|
| 50 |
+
parser.add_argument("--weights_dir", type=str, required=True, help="Directory containing model weights")
|
| 51 |
+
parser.add_argument("--output_dir", type=str, required=True, help="Directory for outputs")
|
| 52 |
+
parser.add_argument(
|
| 53 |
+
"--labeled_bbox_dir", type=str, default=None,
|
| 54 |
+
help="Optional directory with per-camera labeled object bbox JSONs "
|
| 55 |
+
"(anchors primary person selection to the object bbox).",
|
| 56 |
+
)
|
| 57 |
+
parser.add_argument("--config_path", type=str, default=str(_LIB_CONFIG), help="Path to mv_track_bboxes.yaml")
|
| 58 |
+
parser.add_argument("--debug", type=int, default=-1, help="Debug level")
|
| 59 |
+
parser.add_argument("--dev", action="store_true")
|
| 60 |
+
args = parser.parse_args()
|
| 61 |
+
|
| 62 |
+
run_mv_track_bboxes(
|
| 63 |
+
rgb_dir=args.rgb_dir,
|
| 64 |
+
weights_dir=args.weights_dir,
|
| 65 |
+
output_dir=args.output_dir,
|
| 66 |
+
labeled_bbox_dir=args.labeled_bbox_dir,
|
| 67 |
+
config_path=args.config_path,
|
| 68 |
+
debug=args.debug,
|
| 69 |
+
dev=args.dev,
|
| 70 |
+
)
|
third-party/video_to_data/reconstruction/modules/v2d_detectron2/docker/run_shell.py
ADDED
|
@@ -0,0 +1,26 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
|
| 2 |
+
# SPDX-License-Identifier: Apache-2.0
|
| 3 |
+
import subprocess
|
| 4 |
+
import os
|
| 5 |
+
from v2d.detectron2.docker._config import IMAGE_NAME, MODULES_DIR
|
| 6 |
+
|
| 7 |
+
|
| 8 |
+
def run_shell(dev: bool = False) -> None:
|
| 9 |
+
cmd = [
|
| 10 |
+
"docker", "run", "-it", "--rm",
|
| 11 |
+
"--gpus", "all",
|
| 12 |
+
"--user", f"{os.getuid()}:{os.getgid()}",
|
| 13 |
+
]
|
| 14 |
+
if dev:
|
| 15 |
+
cmd += ["-v", f"{MODULES_DIR}:/workspace"]
|
| 16 |
+
cmd += [IMAGE_NAME, "bash"]
|
| 17 |
+
subprocess.run(cmd, check=True)
|
| 18 |
+
|
| 19 |
+
|
| 20 |
+
if __name__ == "__main__":
|
| 21 |
+
import argparse
|
| 22 |
+
|
| 23 |
+
parser = argparse.ArgumentParser(description="Run shell in v2d_detectron2 container")
|
| 24 |
+
parser.add_argument("--dev", action="store_true", help="Mount local modules for development")
|
| 25 |
+
args = parser.parse_args()
|
| 26 |
+
run_shell(dev=args.dev)
|
third-party/video_to_data/reconstruction/modules/v2d_detectron2/docker/run_track_bboxes.py
ADDED
|
@@ -0,0 +1,78 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
|
| 2 |
+
# SPDX-License-Identifier: Apache-2.0
|
| 3 |
+
from v2d.docker.container import run_in_container
|
| 4 |
+
from v2d.detectron2.docker._config import IMAGE_NAME, MODULES_DIR
|
| 5 |
+
|
| 6 |
+
|
| 7 |
+
def run_track_bboxes(
|
| 8 |
+
rgb_path: str,
|
| 9 |
+
weights_dir: str,
|
| 10 |
+
output_path: str,
|
| 11 |
+
model_size: str = "b",
|
| 12 |
+
bbox_thr: float = 0.5,
|
| 13 |
+
iou_threshold: float = 0.3,
|
| 14 |
+
max_lost: int = 30,
|
| 15 |
+
min_hits: int = 3,
|
| 16 |
+
batch_size: int = 1,
|
| 17 |
+
debug: int = 0,
|
| 18 |
+
dev: bool = False,
|
| 19 |
+
) -> None:
|
| 20 |
+
inputs = {
|
| 21 |
+
"rgb_path": rgb_path,
|
| 22 |
+
"weights_dir": weights_dir,
|
| 23 |
+
}
|
| 24 |
+
|
| 25 |
+
run_in_container(
|
| 26 |
+
image=IMAGE_NAME,
|
| 27 |
+
module="v2d.detectron2.lib.track_bboxes",
|
| 28 |
+
inputs=inputs,
|
| 29 |
+
outputs={"output_path": output_path},
|
| 30 |
+
extra_args={
|
| 31 |
+
"model_size": model_size,
|
| 32 |
+
"bbox_thr": bbox_thr,
|
| 33 |
+
"iou_threshold": iou_threshold,
|
| 34 |
+
"max_lost": max_lost,
|
| 35 |
+
"min_hits": min_hits,
|
| 36 |
+
"batch_size": batch_size,
|
| 37 |
+
"debug": debug if debug > 0 else None,
|
| 38 |
+
},
|
| 39 |
+
dev=dev,
|
| 40 |
+
modules_dir=MODULES_DIR,
|
| 41 |
+
gpus=True,
|
| 42 |
+
env={
|
| 43 |
+
"PYTHONUNBUFFERED": "1",
|
| 44 |
+
},
|
| 45 |
+
)
|
| 46 |
+
|
| 47 |
+
|
| 48 |
+
if __name__ == "__main__":
|
| 49 |
+
import argparse
|
| 50 |
+
|
| 51 |
+
parser = argparse.ArgumentParser(description="Run bbox tracking (single camera)")
|
| 52 |
+
parser.add_argument("--rgb_path", type=str, required=True,
|
| 53 |
+
help="Path to input frames (image dir, .h5, or video file)")
|
| 54 |
+
parser.add_argument("--weights_dir", type=str, required=True)
|
| 55 |
+
parser.add_argument("--output_path", type=str, required=True, help="Output .pt file path")
|
| 56 |
+
parser.add_argument("--model_size", type=str, default="b", choices=["b", "l", "h"])
|
| 57 |
+
parser.add_argument("--bbox_thr", type=float, default=0.5)
|
| 58 |
+
parser.add_argument("--iou_threshold", type=float, default=0.3)
|
| 59 |
+
parser.add_argument("--max_lost", type=int, default=30)
|
| 60 |
+
parser.add_argument("--min_hits", type=int, default=3)
|
| 61 |
+
parser.add_argument("--batch_size", type=int, default=1)
|
| 62 |
+
parser.add_argument("--debug", type=int, default=0)
|
| 63 |
+
parser.add_argument("--dev", action="store_true")
|
| 64 |
+
args = parser.parse_args()
|
| 65 |
+
|
| 66 |
+
run_track_bboxes(
|
| 67 |
+
rgb_path=args.rgb_path,
|
| 68 |
+
weights_dir=args.weights_dir,
|
| 69 |
+
output_path=args.output_path,
|
| 70 |
+
model_size=args.model_size,
|
| 71 |
+
bbox_thr=args.bbox_thr,
|
| 72 |
+
iou_threshold=args.iou_threshold,
|
| 73 |
+
max_lost=args.max_lost,
|
| 74 |
+
min_hits=args.min_hits,
|
| 75 |
+
batch_size=args.batch_size,
|
| 76 |
+
debug=args.debug,
|
| 77 |
+
dev=args.dev,
|
| 78 |
+
)
|
third-party/video_to_data/reconstruction/modules/v2d_detectron2/lib/__init__.py
ADDED
|
@@ -0,0 +1,2 @@
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
|
| 2 |
+
# SPDX-License-Identifier: Apache-2.0
|
third-party/video_to_data/reconstruction/modules/v2d_detectron2/lib/build_detector.py
ADDED
|
@@ -0,0 +1,188 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright (c) Meta Platforms, Inc. and affiliates.
|
| 2 |
+
|
| 3 |
+
import os
|
| 4 |
+
from pathlib import Path
|
| 5 |
+
|
| 6 |
+
import numpy as np
|
| 7 |
+
import torch
|
| 8 |
+
|
| 9 |
+
|
| 10 |
+
class Detector:
|
| 11 |
+
def __init__(
|
| 12 |
+
self,
|
| 13 |
+
name="vitdet",
|
| 14 |
+
device="cuda",
|
| 15 |
+
model_size="b",
|
| 16 |
+
test_score_thresh: float = 0.25,
|
| 17 |
+
**kwargs,
|
| 18 |
+
):
|
| 19 |
+
self.device = device
|
| 20 |
+
|
| 21 |
+
if name == "vitdet":
|
| 22 |
+
print(f"Loading ViTDet-{model_size.upper()} detector...")
|
| 23 |
+
self.detector = load_detectron2_vitdet(
|
| 24 |
+
model_size=model_size,
|
| 25 |
+
test_score_thresh=test_score_thresh,
|
| 26 |
+
**kwargs,
|
| 27 |
+
)
|
| 28 |
+
self.detector_func = run_detectron2_vitdet
|
| 29 |
+
self.batch_func = run_detectron2_vitdet_batch
|
| 30 |
+
|
| 31 |
+
self.detector = self.detector.to(self.device)
|
| 32 |
+
self.detector.eval()
|
| 33 |
+
else:
|
| 34 |
+
raise NotImplementedError
|
| 35 |
+
|
| 36 |
+
def run_detection(self, img, **kwargs):
|
| 37 |
+
return self.detector_func(self.detector, img, **kwargs)
|
| 38 |
+
|
| 39 |
+
def run_detection_batch(self, images: list[np.ndarray], **kwargs) -> list[tuple[np.ndarray, np.ndarray]]:
|
| 40 |
+
return self.batch_func(self.detector, images, **kwargs)
|
| 41 |
+
|
| 42 |
+
|
| 43 |
+
VITDET_VARIANTS = {
|
| 44 |
+
"b": {
|
| 45 |
+
"config": "cascade_mask_rcnn_vitdet_b_100ep.py",
|
| 46 |
+
"checkpoint_url": "https://dl.fbaipublicfiles.com/detectron2/ViTDet/COCO/cascade_mask_rcnn_vitdet_b/f325358525/model_final_435fa9.pkl",
|
| 47 |
+
"checkpoint_file": "model_final_435fa9.pkl",
|
| 48 |
+
},
|
| 49 |
+
"l": {
|
| 50 |
+
"config": "cascade_mask_rcnn_vitdet_l_100ep.py",
|
| 51 |
+
"checkpoint_url": "https://dl.fbaipublicfiles.com/detectron2/ViTDet/COCO/cascade_mask_rcnn_vitdet_l/f328021305/model_final_1a9f28.pkl",
|
| 52 |
+
"checkpoint_file": "model_final_1a9f28.pkl",
|
| 53 |
+
},
|
| 54 |
+
"h": {
|
| 55 |
+
"config": "cascade_mask_rcnn_vitdet_h_75ep.py",
|
| 56 |
+
"checkpoint_url": "https://dl.fbaipublicfiles.com/detectron2/ViTDet/COCO/cascade_mask_rcnn_vitdet_h/f328730692/model_final_f05665.pkl",
|
| 57 |
+
"checkpoint_file": "model_final_f05665.pkl",
|
| 58 |
+
},
|
| 59 |
+
}
|
| 60 |
+
|
| 61 |
+
|
| 62 |
+
def load_detectron2_vitdet(
|
| 63 |
+
path: str = "",
|
| 64 |
+
model_size: str = "b",
|
| 65 |
+
test_score_thresh: float = 0.25,
|
| 66 |
+
):
|
| 67 |
+
"""Load a ViTDet Cascade Mask R-CNN detector.
|
| 68 |
+
|
| 69 |
+
Args:
|
| 70 |
+
path: Directory containing the checkpoint file. If empty, downloads
|
| 71 |
+
from the detectron2 model zoo.
|
| 72 |
+
model_size: One of "b" (ViT-Base, fastest), "l" (ViT-Large),
|
| 73 |
+
"h" (ViT-Huge, most accurate).
|
| 74 |
+
test_score_thresh: Internal NMS score threshold. Detections below this
|
| 75 |
+
are discarded before they leave the model. Lower for ByteTrack
|
| 76 |
+
(e.g. 0.1) to retain partial-occlusion detections.
|
| 77 |
+
"""
|
| 78 |
+
from detectron2.checkpoint import DetectionCheckpointer
|
| 79 |
+
from detectron2.config import instantiate, LazyConfig
|
| 80 |
+
|
| 81 |
+
if model_size not in VITDET_VARIANTS:
|
| 82 |
+
raise ValueError(f"Unknown model_size '{model_size}', expected one of {list(VITDET_VARIANTS)}")
|
| 83 |
+
variant = VITDET_VARIANTS[model_size]
|
| 84 |
+
|
| 85 |
+
cfg_path = Path(__file__).parent / variant["config"]
|
| 86 |
+
if not cfg_path.exists():
|
| 87 |
+
raise FileNotFoundError(f"Config file not found at {cfg_path}")
|
| 88 |
+
|
| 89 |
+
detectron2_cfg = LazyConfig.load(str(cfg_path))
|
| 90 |
+
detectron2_cfg.train.init_checkpoint = (
|
| 91 |
+
variant["checkpoint_url"]
|
| 92 |
+
if path == ""
|
| 93 |
+
else os.path.join(path, variant["checkpoint_file"])
|
| 94 |
+
)
|
| 95 |
+
for i in range(3):
|
| 96 |
+
detectron2_cfg.model.roi_heads.box_predictors[i].test_score_thresh = test_score_thresh
|
| 97 |
+
detector = instantiate(detectron2_cfg.model)
|
| 98 |
+
checkpointer = DetectionCheckpointer(detector)
|
| 99 |
+
checkpointer.load(detectron2_cfg.train.init_checkpoint)
|
| 100 |
+
|
| 101 |
+
detector.eval()
|
| 102 |
+
return detector
|
| 103 |
+
|
| 104 |
+
|
| 105 |
+
def run_detectron2_vitdet(
|
| 106 |
+
detector,
|
| 107 |
+
img,
|
| 108 |
+
det_cat_id: int = 0, # 0: person
|
| 109 |
+
bbox_thr: float = 0.5,
|
| 110 |
+
default_to_full_image: bool = True,
|
| 111 |
+
):
|
| 112 |
+
import detectron2.data.transforms as T
|
| 113 |
+
|
| 114 |
+
height, width = img.shape[:2]
|
| 115 |
+
|
| 116 |
+
IMAGE_SIZE = 1024
|
| 117 |
+
transforms = T.ResizeShortestEdge(short_edge_length=IMAGE_SIZE, max_size=IMAGE_SIZE)
|
| 118 |
+
img_transformed = transforms(T.AugInput(img)).apply_image(img)
|
| 119 |
+
img_transformed = torch.as_tensor(
|
| 120 |
+
img_transformed.astype("float32").transpose(2, 0, 1)
|
| 121 |
+
)
|
| 122 |
+
inputs = {"image": img_transformed, "height": height, "width": width}
|
| 123 |
+
|
| 124 |
+
with torch.no_grad():
|
| 125 |
+
det_out = detector([inputs])
|
| 126 |
+
|
| 127 |
+
det_instances = det_out[0]["instances"]
|
| 128 |
+
valid_idx = (det_instances.pred_classes == det_cat_id) & (
|
| 129 |
+
det_instances.scores > bbox_thr
|
| 130 |
+
)
|
| 131 |
+
if valid_idx.sum() == 0 and default_to_full_image:
|
| 132 |
+
boxes = np.array([0, 0, width, height]).reshape(1, 4)
|
| 133 |
+
scores = np.array([1.0])
|
| 134 |
+
else:
|
| 135 |
+
boxes = det_instances.pred_boxes.tensor[valid_idx].cpu().numpy()
|
| 136 |
+
scores = det_instances.scores[valid_idx].cpu().numpy()
|
| 137 |
+
|
| 138 |
+
sorted_indices = np.argsort(scores)[::-1]
|
| 139 |
+
return boxes[sorted_indices].reshape(-1, 4), scores[sorted_indices]
|
| 140 |
+
|
| 141 |
+
|
| 142 |
+
def run_detectron2_vitdet_batch(
|
| 143 |
+
detector,
|
| 144 |
+
images: list[np.ndarray],
|
| 145 |
+
det_cat_id: int = 0,
|
| 146 |
+
bbox_thr: float = 0.5,
|
| 147 |
+
default_to_full_image: bool = True,
|
| 148 |
+
) -> list[tuple[np.ndarray, np.ndarray]]:
|
| 149 |
+
"""Run ViTDet detection on a batch of images in a single forward pass.
|
| 150 |
+
|
| 151 |
+
Memory scales linearly with batch size (~2-3 GB per image for ViTDet-B
|
| 152 |
+
at 1024px). Batch sizes of 4-8 are practical on a 24 GB GPU.
|
| 153 |
+
"""
|
| 154 |
+
import detectron2.data.transforms as T
|
| 155 |
+
|
| 156 |
+
IMAGE_SIZE = 768
|
| 157 |
+
transforms = T.ResizeShortestEdge(short_edge_length=IMAGE_SIZE, max_size=IMAGE_SIZE)
|
| 158 |
+
|
| 159 |
+
inputs = []
|
| 160 |
+
for img in images:
|
| 161 |
+
height, width = img.shape[:2]
|
| 162 |
+
img_transformed = transforms(T.AugInput(img)).apply_image(img)
|
| 163 |
+
img_transformed = torch.as_tensor(
|
| 164 |
+
img_transformed.astype("float32").transpose(2, 0, 1)
|
| 165 |
+
)
|
| 166 |
+
inputs.append({"image": img_transformed, "height": height, "width": width})
|
| 167 |
+
|
| 168 |
+
with torch.no_grad():
|
| 169 |
+
det_outputs = detector(inputs)
|
| 170 |
+
|
| 171 |
+
results = []
|
| 172 |
+
for img, det_out in zip(images, det_outputs):
|
| 173 |
+
height, width = img.shape[:2]
|
| 174 |
+
det_instances = det_out["instances"]
|
| 175 |
+
valid_idx = (det_instances.pred_classes == det_cat_id) & (
|
| 176 |
+
det_instances.scores > bbox_thr
|
| 177 |
+
)
|
| 178 |
+
if valid_idx.sum() == 0 and default_to_full_image:
|
| 179 |
+
boxes = np.array([0, 0, width, height]).reshape(1, 4)
|
| 180 |
+
scores = np.array([1.0])
|
| 181 |
+
else:
|
| 182 |
+
boxes = det_instances.pred_boxes.tensor[valid_idx].cpu().numpy()
|
| 183 |
+
scores = det_instances.scores[valid_idx].cpu().numpy()
|
| 184 |
+
|
| 185 |
+
sorted_indices = np.argsort(scores)[::-1]
|
| 186 |
+
results.append((boxes[sorted_indices].reshape(-1, 4), scores[sorted_indices]))
|
| 187 |
+
|
| 188 |
+
return results
|
third-party/video_to_data/reconstruction/modules/v2d_detectron2/lib/bytetracker.py
ADDED
|
@@ -0,0 +1,286 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
|
| 2 |
+
# SPDX-License-Identifier: Apache-2.0
|
| 3 |
+
"""ByteTrack multi-object tracker.
|
| 4 |
+
|
| 5 |
+
Implements the two-stage association strategy from:
|
| 6 |
+
Zhang et al., "ByteTrack: Multi-Object Tracking by Associating Every Detection Box", ECCV 2022.
|
| 7 |
+
|
| 8 |
+
Key idea: low-confidence detections (from partial occlusion) are used in a second
|
| 9 |
+
association pass to maintain tracks that would otherwise be lost.
|
| 10 |
+
|
| 11 |
+
Uses a Kalman filter with constant-velocity model for bbox state prediction.
|
| 12 |
+
"""
|
| 13 |
+
|
| 14 |
+
from __future__ import annotations
|
| 15 |
+
|
| 16 |
+
import numpy as np
|
| 17 |
+
|
| 18 |
+
from .tracker import Track, TrackState, bbox_iou_matrix, hungarian_assign
|
| 19 |
+
|
| 20 |
+
|
| 21 |
+
def _bbox_to_z(bbox: np.ndarray) -> np.ndarray:
|
| 22 |
+
"""Convert [x1, y1, x2, y2] to Kalman measurement [cx, cy, a, h]."""
|
| 23 |
+
w = bbox[2] - bbox[0]
|
| 24 |
+
h = bbox[3] - bbox[1]
|
| 25 |
+
cx = bbox[0] + w / 2
|
| 26 |
+
cy = bbox[1] + h / 2
|
| 27 |
+
a = w / (h + 1e-6)
|
| 28 |
+
return np.array([cx, cy, a, h])
|
| 29 |
+
|
| 30 |
+
|
| 31 |
+
def _z_to_bbox(z: np.ndarray) -> np.ndarray:
|
| 32 |
+
"""Convert Kalman measurement [cx, cy, a, h] to [x1, y1, x2, y2]."""
|
| 33 |
+
w = z[2] * z[3]
|
| 34 |
+
h = z[3]
|
| 35 |
+
return np.array([
|
| 36 |
+
z[0] - w / 2,
|
| 37 |
+
z[1] - h / 2,
|
| 38 |
+
z[0] + w / 2,
|
| 39 |
+
z[1] + h / 2,
|
| 40 |
+
])
|
| 41 |
+
|
| 42 |
+
|
| 43 |
+
class KalmanBoxTracker:
|
| 44 |
+
"""Per-track Kalman filter over [cx, cy, aspect_ratio, h, vcx, vcy, va, vh]."""
|
| 45 |
+
|
| 46 |
+
_DIM_Z = 4
|
| 47 |
+
_DIM_X = 8
|
| 48 |
+
|
| 49 |
+
def __init__(self, bbox: np.ndarray):
|
| 50 |
+
self.x = np.zeros(self._DIM_X)
|
| 51 |
+
self.x[:self._DIM_Z] = _bbox_to_z(bbox)
|
| 52 |
+
|
| 53 |
+
# State transition (constant velocity)
|
| 54 |
+
self.F = np.eye(self._DIM_X)
|
| 55 |
+
for i in range(self._DIM_Z):
|
| 56 |
+
self.F[i, self._DIM_Z + i] = 1.0
|
| 57 |
+
|
| 58 |
+
# Measurement matrix
|
| 59 |
+
self.H = np.zeros((self._DIM_Z, self._DIM_X))
|
| 60 |
+
self.H[:self._DIM_Z, :self._DIM_Z] = np.eye(self._DIM_Z)
|
| 61 |
+
|
| 62 |
+
# Covariance
|
| 63 |
+
self.P = np.eye(self._DIM_X) * 10.0
|
| 64 |
+
self.P[self._DIM_Z:, self._DIM_Z:] *= 1000.0
|
| 65 |
+
|
| 66 |
+
# Process noise
|
| 67 |
+
self.Q = np.eye(self._DIM_X)
|
| 68 |
+
self.Q[self._DIM_Z:, self._DIM_Z:] *= 0.01
|
| 69 |
+
|
| 70 |
+
# Measurement noise
|
| 71 |
+
self.R = np.eye(self._DIM_Z)
|
| 72 |
+
self.R[2, 2] *= 10.0 # aspect ratio is less certain
|
| 73 |
+
|
| 74 |
+
def predict(self) -> np.ndarray:
|
| 75 |
+
"""Advance state and return predicted bbox [x1, y1, x2, y2]."""
|
| 76 |
+
# Prevent negative height
|
| 77 |
+
if self.x[3] + self.x[7] <= 0:
|
| 78 |
+
self.x[7] = 0.0
|
| 79 |
+
|
| 80 |
+
self.x = self.F @ self.x
|
| 81 |
+
self.P = self.F @ self.P @ self.F.T + self.Q
|
| 82 |
+
return self.get_bbox()
|
| 83 |
+
|
| 84 |
+
def update(self, bbox: np.ndarray) -> None:
|
| 85 |
+
"""Correct state with observed bbox."""
|
| 86 |
+
z = _bbox_to_z(bbox)
|
| 87 |
+
y = z - self.H @ self.x
|
| 88 |
+
S = self.H @ self.P @ self.H.T + self.R
|
| 89 |
+
K = self.P @ self.H.T @ np.linalg.inv(S)
|
| 90 |
+
self.x = self.x + K @ y
|
| 91 |
+
I_KH = np.eye(self._DIM_X) - K @ self.H
|
| 92 |
+
self.P = I_KH @ self.P
|
| 93 |
+
|
| 94 |
+
def get_bbox(self) -> np.ndarray:
|
| 95 |
+
"""Current state as [x1, y1, x2, y2]."""
|
| 96 |
+
return _z_to_bbox(self.x[:self._DIM_Z])
|
| 97 |
+
|
| 98 |
+
|
| 99 |
+
class _STrack:
|
| 100 |
+
"""Internal tracked object pairing a Track with its Kalman state."""
|
| 101 |
+
|
| 102 |
+
def __init__(self, track: Track, kalman: KalmanBoxTracker):
|
| 103 |
+
self.track = track
|
| 104 |
+
self.kalman = kalman
|
| 105 |
+
|
| 106 |
+
|
| 107 |
+
class ByteTracker:
|
| 108 |
+
"""ByteTrack multi-object tracker with two-stage association.
|
| 109 |
+
|
| 110 |
+
Args:
|
| 111 |
+
track_thresh: Confidence split between high and low detections.
|
| 112 |
+
match_thresh: IoU threshold for first (high-confidence) association.
|
| 113 |
+
second_match_thresh: IoU threshold for second (low-confidence) association.
|
| 114 |
+
max_lost: Frames a track survives without a match before removal.
|
| 115 |
+
min_hits: Minimum detections before a tentative track is confirmed.
|
| 116 |
+
"""
|
| 117 |
+
|
| 118 |
+
def __init__(
|
| 119 |
+
self,
|
| 120 |
+
track_thresh: float = 0.6,
|
| 121 |
+
match_thresh: float = 0.8,
|
| 122 |
+
second_match_thresh: float = 0.5,
|
| 123 |
+
max_lost: int = 30,
|
| 124 |
+
min_hits: int = 3,
|
| 125 |
+
):
|
| 126 |
+
self.track_thresh = track_thresh
|
| 127 |
+
self.match_thresh = match_thresh
|
| 128 |
+
self.second_match_thresh = second_match_thresh
|
| 129 |
+
self.max_lost = max_lost
|
| 130 |
+
self.min_hits = min_hits
|
| 131 |
+
|
| 132 |
+
self._next_id = 0
|
| 133 |
+
self._active: list[_STrack] = []
|
| 134 |
+
self._lost: list[_STrack] = []
|
| 135 |
+
self._tentative: list[_STrack] = []
|
| 136 |
+
self._finished: list[_STrack] = []
|
| 137 |
+
|
| 138 |
+
def _new_strack(self, frame_idx: int, bbox: np.ndarray, score: float) -> _STrack:
|
| 139 |
+
track = Track(track_id=self._next_id, state=TrackState.TENTATIVE)
|
| 140 |
+
track.append(frame_idx, bbox, score)
|
| 141 |
+
kalman = KalmanBoxTracker(bbox)
|
| 142 |
+
self._next_id += 1
|
| 143 |
+
return _STrack(track, kalman)
|
| 144 |
+
|
| 145 |
+
def _predicted_bboxes(self, stracks: list[_STrack]) -> np.ndarray:
|
| 146 |
+
if not stracks:
|
| 147 |
+
return np.empty((0, 4))
|
| 148 |
+
return np.array([st.kalman.predict() for st in stracks])
|
| 149 |
+
|
| 150 |
+
def update(self, frame_idx: int, bboxes: np.ndarray, scores: np.ndarray):
|
| 151 |
+
"""Process one frame of detections (all above det_thresh).
|
| 152 |
+
|
| 153 |
+
The caller should pass ALL detections above det_thresh; this method
|
| 154 |
+
splits them into high/low confidence internally.
|
| 155 |
+
"""
|
| 156 |
+
# Split detections by confidence
|
| 157 |
+
high_mask = scores >= self.track_thresh
|
| 158 |
+
low_mask = ~high_mask
|
| 159 |
+
|
| 160 |
+
high_bboxes = bboxes[high_mask] if high_mask.any() else np.empty((0, 4))
|
| 161 |
+
high_scores = scores[high_mask] if high_mask.any() else np.empty(0)
|
| 162 |
+
low_bboxes = bboxes[low_mask] if low_mask.any() else np.empty((0, 4))
|
| 163 |
+
low_scores = scores[low_mask] if low_mask.any() else np.empty(0)
|
| 164 |
+
|
| 165 |
+
# Predict positions for all tracked objects
|
| 166 |
+
established = self._active + self._lost
|
| 167 |
+
pred_bboxes = self._predicted_bboxes(established)
|
| 168 |
+
|
| 169 |
+
# --- First association: high-confidence detections vs all tracks ---
|
| 170 |
+
if len(established) > 0 and len(high_bboxes) > 0:
|
| 171 |
+
iou = bbox_iou_matrix(pred_bboxes, high_bboxes)
|
| 172 |
+
matches_1, unmatched_t_1, unmatched_d_1 = hungarian_assign(
|
| 173 |
+
iou, self.match_thresh
|
| 174 |
+
)
|
| 175 |
+
elif len(established) > 0:
|
| 176 |
+
matches_1 = []
|
| 177 |
+
unmatched_t_1 = list(range(len(established)))
|
| 178 |
+
unmatched_d_1 = []
|
| 179 |
+
else:
|
| 180 |
+
matches_1 = []
|
| 181 |
+
unmatched_t_1 = []
|
| 182 |
+
unmatched_d_1 = list(range(len(high_bboxes)))
|
| 183 |
+
|
| 184 |
+
new_active: list[_STrack] = []
|
| 185 |
+
|
| 186 |
+
for t_idx, d_idx in matches_1:
|
| 187 |
+
st = established[t_idx]
|
| 188 |
+
st.kalman.update(high_bboxes[d_idx])
|
| 189 |
+
st.track.append(frame_idx, high_bboxes[d_idx], float(high_scores[d_idx]))
|
| 190 |
+
new_active.append(st)
|
| 191 |
+
|
| 192 |
+
# --- Second association: low-confidence detections vs unmatched tracks ---
|
| 193 |
+
remaining_stracks = [established[i] for i in unmatched_t_1]
|
| 194 |
+
|
| 195 |
+
if len(remaining_stracks) > 0 and len(low_bboxes) > 0:
|
| 196 |
+
remaining_pred = np.array([st.kalman.get_bbox() for st in remaining_stracks])
|
| 197 |
+
iou_2 = bbox_iou_matrix(remaining_pred, low_bboxes)
|
| 198 |
+
matches_2, unmatched_t_2, _ = hungarian_assign(
|
| 199 |
+
iou_2, self.second_match_thresh
|
| 200 |
+
)
|
| 201 |
+
elif len(remaining_stracks) > 0:
|
| 202 |
+
matches_2 = []
|
| 203 |
+
unmatched_t_2 = list(range(len(remaining_stracks)))
|
| 204 |
+
else:
|
| 205 |
+
matches_2 = []
|
| 206 |
+
unmatched_t_2 = []
|
| 207 |
+
|
| 208 |
+
for t_idx, d_idx in matches_2:
|
| 209 |
+
st = remaining_stracks[t_idx]
|
| 210 |
+
st.kalman.update(low_bboxes[d_idx])
|
| 211 |
+
st.track.append(frame_idx, low_bboxes[d_idx], float(low_scores[d_idx]))
|
| 212 |
+
new_active.append(st)
|
| 213 |
+
|
| 214 |
+
# Handle tracks that matched neither stage
|
| 215 |
+
new_lost: list[_STrack] = []
|
| 216 |
+
for t_idx in unmatched_t_2:
|
| 217 |
+
st = remaining_stracks[t_idx]
|
| 218 |
+
st.track.frames_since_match += 1
|
| 219 |
+
if st.track.frames_since_match > self.max_lost:
|
| 220 |
+
st.track.state = TrackState.FINISHED
|
| 221 |
+
self._finished.append(st)
|
| 222 |
+
else:
|
| 223 |
+
st.track.state = TrackState.LOST
|
| 224 |
+
new_lost.append(st)
|
| 225 |
+
|
| 226 |
+
# --- Tentative track association with unmatched high-conf detections ---
|
| 227 |
+
unmatched_high_bboxes = high_bboxes[unmatched_d_1] if unmatched_d_1 else np.empty((0, 4))
|
| 228 |
+
unmatched_high_scores = high_scores[unmatched_d_1] if unmatched_d_1 else np.empty(0)
|
| 229 |
+
|
| 230 |
+
new_tentative: list[_STrack] = []
|
| 231 |
+
|
| 232 |
+
if len(self._tentative) > 0 and len(unmatched_high_bboxes) > 0:
|
| 233 |
+
tent_pred = self._predicted_bboxes(self._tentative)
|
| 234 |
+
iou_3 = bbox_iou_matrix(tent_pred, unmatched_high_bboxes)
|
| 235 |
+
matches_3, unmatched_tent, unmatched_d_3 = hungarian_assign(
|
| 236 |
+
iou_3, self.match_thresh
|
| 237 |
+
)
|
| 238 |
+
elif len(self._tentative) > 0:
|
| 239 |
+
matches_3 = []
|
| 240 |
+
unmatched_tent = list(range(len(self._tentative)))
|
| 241 |
+
unmatched_d_3 = []
|
| 242 |
+
else:
|
| 243 |
+
matches_3 = []
|
| 244 |
+
unmatched_tent = []
|
| 245 |
+
unmatched_d_3 = list(range(len(unmatched_high_bboxes)))
|
| 246 |
+
|
| 247 |
+
for t_idx, d_idx in matches_3:
|
| 248 |
+
st = self._tentative[t_idx]
|
| 249 |
+
st.kalman.update(unmatched_high_bboxes[d_idx])
|
| 250 |
+
st.track.append(
|
| 251 |
+
frame_idx, unmatched_high_bboxes[d_idx],
|
| 252 |
+
float(unmatched_high_scores[d_idx]),
|
| 253 |
+
)
|
| 254 |
+
if st.track.length >= self.min_hits:
|
| 255 |
+
st.track.state = TrackState.ACTIVE
|
| 256 |
+
new_active.append(st)
|
| 257 |
+
else:
|
| 258 |
+
new_tentative.append(st)
|
| 259 |
+
|
| 260 |
+
for t_idx in unmatched_tent:
|
| 261 |
+
st = self._tentative[t_idx]
|
| 262 |
+
st.track.state = TrackState.FINISHED
|
| 263 |
+
self._finished.append(st)
|
| 264 |
+
|
| 265 |
+
# Only high-confidence unmatched detections start new tracks
|
| 266 |
+
for d_idx in unmatched_d_3:
|
| 267 |
+
new_tentative.append(
|
| 268 |
+
self._new_strack(
|
| 269 |
+
frame_idx,
|
| 270 |
+
unmatched_high_bboxes[d_idx],
|
| 271 |
+
float(unmatched_high_scores[d_idx]),
|
| 272 |
+
)
|
| 273 |
+
)
|
| 274 |
+
|
| 275 |
+
self._active = new_active
|
| 276 |
+
self._lost = new_lost
|
| 277 |
+
self._tentative = new_tentative
|
| 278 |
+
|
| 279 |
+
def finalize(self) -> list[Track]:
|
| 280 |
+
"""Return all tracks sorted by track_id."""
|
| 281 |
+
all_stracks = (
|
| 282 |
+
self._finished + self._active + self._lost + self._tentative
|
| 283 |
+
)
|
| 284 |
+
tracks = [st.track for st in all_stracks]
|
| 285 |
+
tracks.sort(key=lambda t: t.track_id)
|
| 286 |
+
return tracks
|
third-party/video_to_data/reconstruction/modules/v2d_detectron2/lib/cascade_mask_rcnn_vitdet_b_100ep.py
ADDED
|
@@ -0,0 +1,101 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright (c) Meta Platforms, Inc. and affiliates.
|
| 2 |
+
# Cascade Mask R-CNN with ViT-B backbone (100 epochs).
|
| 3 |
+
# Adapted from detectron2 model zoo: projects/ViTDet/configs/COCO/
|
| 4 |
+
|
| 5 |
+
## coco_loader_lsj.py
|
| 6 |
+
|
| 7 |
+
import detectron2.data.transforms as T
|
| 8 |
+
from detectron2 import model_zoo
|
| 9 |
+
from detectron2.config import LazyCall as L
|
| 10 |
+
|
| 11 |
+
# Data using LSJ
|
| 12 |
+
image_size = 1024
|
| 13 |
+
dataloader = model_zoo.get_config("common/data/coco.py").dataloader
|
| 14 |
+
dataloader.train.mapper.augmentations = [
|
| 15 |
+
L(T.RandomFlip)(horizontal=True), # flip first
|
| 16 |
+
L(T.ResizeScale)(
|
| 17 |
+
min_scale=0.1, max_scale=2.0, target_height=image_size, target_width=image_size
|
| 18 |
+
),
|
| 19 |
+
L(T.FixedSizeCrop)(crop_size=(image_size, image_size), pad=False),
|
| 20 |
+
]
|
| 21 |
+
dataloader.train.mapper.image_format = "RGB"
|
| 22 |
+
dataloader.train.total_batch_size = 64
|
| 23 |
+
dataloader.train.mapper.recompute_boxes = True
|
| 24 |
+
|
| 25 |
+
dataloader.test.mapper.augmentations = [
|
| 26 |
+
L(T.ResizeShortestEdge)(short_edge_length=image_size, max_size=image_size),
|
| 27 |
+
]
|
| 28 |
+
|
| 29 |
+
from functools import partial
|
| 30 |
+
from fvcore.common.param_scheduler import MultiStepParamScheduler
|
| 31 |
+
|
| 32 |
+
from detectron2 import model_zoo
|
| 33 |
+
from detectron2.config import LazyCall as L
|
| 34 |
+
from detectron2.solver import WarmupParamScheduler
|
| 35 |
+
from detectron2.modeling.backbone.vit import get_vit_lr_decay_rate
|
| 36 |
+
|
| 37 |
+
## mask_rcnn_vitdet_b_100ep.py
|
| 38 |
+
|
| 39 |
+
model = model_zoo.get_config("common/models/mask_rcnn_vitdet.py").model
|
| 40 |
+
|
| 41 |
+
train = model_zoo.get_config("common/train.py").train
|
| 42 |
+
train.amp.enabled = True
|
| 43 |
+
train.ddp.fp16_compression = True
|
| 44 |
+
train.init_checkpoint = "detectron2://ImageNetPretrained/MAE/mae_pretrain_vit_base.pth"
|
| 45 |
+
|
| 46 |
+
train.max_iter = 184375
|
| 47 |
+
|
| 48 |
+
lr_multiplier = L(WarmupParamScheduler)(
|
| 49 |
+
scheduler=L(MultiStepParamScheduler)(
|
| 50 |
+
values=[1.0, 0.1, 0.01],
|
| 51 |
+
milestones=[163889, 177546],
|
| 52 |
+
num_updates=train.max_iter,
|
| 53 |
+
),
|
| 54 |
+
warmup_length=250 / train.max_iter,
|
| 55 |
+
warmup_factor=0.001,
|
| 56 |
+
)
|
| 57 |
+
|
| 58 |
+
optimizer = model_zoo.get_config("common/optim.py").AdamW
|
| 59 |
+
optimizer.params.lr_factor_func = partial(get_vit_lr_decay_rate, num_layers=12, lr_decay_rate=0.7)
|
| 60 |
+
optimizer.params.overrides = {"pos_embed": {"weight_decay": 0.0}}
|
| 61 |
+
|
| 62 |
+
## cascade_mask_rcnn_vitdet_b_100ep.py
|
| 63 |
+
|
| 64 |
+
from detectron2.config import LazyCall as L
|
| 65 |
+
from detectron2.layers import ShapeSpec
|
| 66 |
+
from detectron2.modeling.box_regression import Box2BoxTransform
|
| 67 |
+
from detectron2.modeling.matcher import Matcher
|
| 68 |
+
from detectron2.modeling.roi_heads import (
|
| 69 |
+
FastRCNNOutputLayers,
|
| 70 |
+
FastRCNNConvFCHead,
|
| 71 |
+
CascadeROIHeads,
|
| 72 |
+
)
|
| 73 |
+
|
| 74 |
+
[model.roi_heads.pop(k) for k in ["box_head", "box_predictor", "proposal_matcher"]]
|
| 75 |
+
|
| 76 |
+
model.roi_heads.update(
|
| 77 |
+
_target_=CascadeROIHeads,
|
| 78 |
+
box_heads=[
|
| 79 |
+
L(FastRCNNConvFCHead)(
|
| 80 |
+
input_shape=ShapeSpec(channels=256, height=7, width=7),
|
| 81 |
+
conv_dims=[256, 256, 256, 256],
|
| 82 |
+
fc_dims=[1024],
|
| 83 |
+
conv_norm="LN",
|
| 84 |
+
)
|
| 85 |
+
for _ in range(3)
|
| 86 |
+
],
|
| 87 |
+
box_predictors=[
|
| 88 |
+
L(FastRCNNOutputLayers)(
|
| 89 |
+
input_shape=ShapeSpec(channels=1024),
|
| 90 |
+
test_score_thresh=0.05,
|
| 91 |
+
box2box_transform=L(Box2BoxTransform)(weights=(w1, w1, w2, w2)),
|
| 92 |
+
cls_agnostic_bbox_reg=True,
|
| 93 |
+
num_classes="${...num_classes}",
|
| 94 |
+
)
|
| 95 |
+
for (w1, w2) in [(10, 5), (20, 10), (30, 15)]
|
| 96 |
+
],
|
| 97 |
+
proposal_matchers=[
|
| 98 |
+
L(Matcher)(thresholds=[th], labels=[0, 1], allow_low_quality_matches=False)
|
| 99 |
+
for th in [0.5, 0.6, 0.7]
|
| 100 |
+
],
|
| 101 |
+
)
|
third-party/video_to_data/reconstruction/modules/v2d_detectron2/lib/cascade_mask_rcnn_vitdet_h_75ep.py
ADDED
|
@@ -0,0 +1,131 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright (c) Meta Platforms, Inc. and affiliates.
|
| 2 |
+
|
| 3 |
+
## coco_loader_lsj.py
|
| 4 |
+
|
| 5 |
+
import detectron2.data.transforms as T
|
| 6 |
+
from detectron2 import model_zoo
|
| 7 |
+
from detectron2.config import LazyCall as L
|
| 8 |
+
|
| 9 |
+
# Data using LSJ
|
| 10 |
+
image_size = 1024
|
| 11 |
+
dataloader = model_zoo.get_config("common/data/coco.py").dataloader
|
| 12 |
+
dataloader.train.mapper.augmentations = [
|
| 13 |
+
L(T.RandomFlip)(horizontal=True), # flip first
|
| 14 |
+
L(T.ResizeScale)(
|
| 15 |
+
min_scale=0.1, max_scale=2.0, target_height=image_size, target_width=image_size
|
| 16 |
+
),
|
| 17 |
+
L(T.FixedSizeCrop)(crop_size=(image_size, image_size), pad=False),
|
| 18 |
+
]
|
| 19 |
+
dataloader.train.mapper.image_format = "RGB"
|
| 20 |
+
dataloader.train.total_batch_size = 64
|
| 21 |
+
# recompute boxes due to cropping
|
| 22 |
+
dataloader.train.mapper.recompute_boxes = True
|
| 23 |
+
|
| 24 |
+
dataloader.test.mapper.augmentations = [
|
| 25 |
+
L(T.ResizeShortestEdge)(short_edge_length=image_size, max_size=image_size),
|
| 26 |
+
]
|
| 27 |
+
|
| 28 |
+
from functools import partial
|
| 29 |
+
from fvcore.common.param_scheduler import MultiStepParamScheduler
|
| 30 |
+
|
| 31 |
+
from detectron2 import model_zoo
|
| 32 |
+
from detectron2.config import LazyCall as L
|
| 33 |
+
from detectron2.solver import WarmupParamScheduler
|
| 34 |
+
from detectron2.modeling.backbone.vit import get_vit_lr_decay_rate
|
| 35 |
+
|
| 36 |
+
# mask_rcnn_vitdet_b_100ep.py
|
| 37 |
+
|
| 38 |
+
model = model_zoo.get_config("common/models/mask_rcnn_vitdet.py").model
|
| 39 |
+
|
| 40 |
+
# Initialization and trainer settings
|
| 41 |
+
train = model_zoo.get_config("common/train.py").train
|
| 42 |
+
train.amp.enabled = True
|
| 43 |
+
train.ddp.fp16_compression = True
|
| 44 |
+
train.init_checkpoint = "detectron2://ImageNetPretrained/MAE/mae_pretrain_vit_base.pth"
|
| 45 |
+
|
| 46 |
+
|
| 47 |
+
# Schedule
|
| 48 |
+
# 100 ep = 184375 iters * 64 images/iter / 118000 images/ep
|
| 49 |
+
train.max_iter = 184375
|
| 50 |
+
|
| 51 |
+
lr_multiplier = L(WarmupParamScheduler)(
|
| 52 |
+
scheduler=L(MultiStepParamScheduler)(
|
| 53 |
+
values=[1.0, 0.1, 0.01],
|
| 54 |
+
milestones=[163889, 177546],
|
| 55 |
+
num_updates=train.max_iter,
|
| 56 |
+
),
|
| 57 |
+
warmup_length=250 / train.max_iter,
|
| 58 |
+
warmup_factor=0.001,
|
| 59 |
+
)
|
| 60 |
+
|
| 61 |
+
# Optimizer
|
| 62 |
+
optimizer = model_zoo.get_config("common/optim.py").AdamW
|
| 63 |
+
optimizer.params.lr_factor_func = partial(get_vit_lr_decay_rate, num_layers=12, lr_decay_rate=0.7)
|
| 64 |
+
optimizer.params.overrides = {"pos_embed": {"weight_decay": 0.0}}
|
| 65 |
+
|
| 66 |
+
# cascade_mask_rcnn_vitdet_b_100ep.py
|
| 67 |
+
|
| 68 |
+
from detectron2.config import LazyCall as L
|
| 69 |
+
from detectron2.layers import ShapeSpec
|
| 70 |
+
from detectron2.modeling.box_regression import Box2BoxTransform
|
| 71 |
+
from detectron2.modeling.matcher import Matcher
|
| 72 |
+
from detectron2.modeling.roi_heads import (
|
| 73 |
+
FastRCNNOutputLayers,
|
| 74 |
+
FastRCNNConvFCHead,
|
| 75 |
+
CascadeROIHeads,
|
| 76 |
+
)
|
| 77 |
+
|
| 78 |
+
# arguments that don't exist for Cascade R-CNN
|
| 79 |
+
[model.roi_heads.pop(k) for k in ["box_head", "box_predictor", "proposal_matcher"]]
|
| 80 |
+
|
| 81 |
+
model.roi_heads.update(
|
| 82 |
+
_target_=CascadeROIHeads,
|
| 83 |
+
box_heads=[
|
| 84 |
+
L(FastRCNNConvFCHead)(
|
| 85 |
+
input_shape=ShapeSpec(channels=256, height=7, width=7),
|
| 86 |
+
conv_dims=[256, 256, 256, 256],
|
| 87 |
+
fc_dims=[1024],
|
| 88 |
+
conv_norm="LN",
|
| 89 |
+
)
|
| 90 |
+
for _ in range(3)
|
| 91 |
+
],
|
| 92 |
+
box_predictors=[
|
| 93 |
+
L(FastRCNNOutputLayers)(
|
| 94 |
+
input_shape=ShapeSpec(channels=1024),
|
| 95 |
+
test_score_thresh=0.05,
|
| 96 |
+
box2box_transform=L(Box2BoxTransform)(weights=(w1, w1, w2, w2)),
|
| 97 |
+
cls_agnostic_bbox_reg=True,
|
| 98 |
+
num_classes="${...num_classes}",
|
| 99 |
+
)
|
| 100 |
+
for (w1, w2) in [(10, 5), (20, 10), (30, 15)]
|
| 101 |
+
],
|
| 102 |
+
proposal_matchers=[
|
| 103 |
+
L(Matcher)(thresholds=[th], labels=[0, 1], allow_low_quality_matches=False)
|
| 104 |
+
for th in [0.5, 0.6, 0.7]
|
| 105 |
+
],
|
| 106 |
+
)
|
| 107 |
+
|
| 108 |
+
# cascade_mask_rcnn_vitdet_h_75ep.py
|
| 109 |
+
|
| 110 |
+
from functools import partial
|
| 111 |
+
|
| 112 |
+
train.init_checkpoint = "detectron2://ImageNetPretrained/MAE/mae_pretrain_vit_huge_p14to16.pth"
|
| 113 |
+
|
| 114 |
+
model.backbone.net.embed_dim = 1280
|
| 115 |
+
model.backbone.net.depth = 32
|
| 116 |
+
model.backbone.net.num_heads = 16
|
| 117 |
+
model.backbone.net.drop_path_rate = 0.5
|
| 118 |
+
# 7, 15, 23, 31 for global attention
|
| 119 |
+
model.backbone.net.window_block_indexes = (
|
| 120 |
+
list(range(0, 7)) + list(range(8, 15)) + list(range(16, 23)) + list(range(24, 31))
|
| 121 |
+
)
|
| 122 |
+
|
| 123 |
+
optimizer.params.lr_factor_func = partial(get_vit_lr_decay_rate, lr_decay_rate=0.9, num_layers=32)
|
| 124 |
+
optimizer.params.overrides = {}
|
| 125 |
+
optimizer.params.weight_decay_norm = None
|
| 126 |
+
|
| 127 |
+
train.max_iter = train.max_iter * 3 // 4 # 100ep -> 75ep
|
| 128 |
+
lr_multiplier.scheduler.milestones = [
|
| 129 |
+
milestone * 3 // 4 for milestone in lr_multiplier.scheduler.milestones
|
| 130 |
+
]
|
| 131 |
+
lr_multiplier.scheduler.num_updates = train.max_iter
|
third-party/video_to_data/reconstruction/modules/v2d_detectron2/lib/cascade_mask_rcnn_vitdet_l_100ep.py
ADDED
|
@@ -0,0 +1,112 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright (c) Meta Platforms, Inc. and affiliates.
|
| 2 |
+
# Cascade Mask R-CNN with ViT-L backbone (100 epochs).
|
| 3 |
+
# Adapted from detectron2 model zoo: projects/ViTDet/configs/COCO/
|
| 4 |
+
|
| 5 |
+
## coco_loader_lsj.py
|
| 6 |
+
|
| 7 |
+
import detectron2.data.transforms as T
|
| 8 |
+
from detectron2 import model_zoo
|
| 9 |
+
from detectron2.config import LazyCall as L
|
| 10 |
+
|
| 11 |
+
# Data using LSJ
|
| 12 |
+
image_size = 1024
|
| 13 |
+
dataloader = model_zoo.get_config("common/data/coco.py").dataloader
|
| 14 |
+
dataloader.train.mapper.augmentations = [
|
| 15 |
+
L(T.RandomFlip)(horizontal=True), # flip first
|
| 16 |
+
L(T.ResizeScale)(
|
| 17 |
+
min_scale=0.1, max_scale=2.0, target_height=image_size, target_width=image_size
|
| 18 |
+
),
|
| 19 |
+
L(T.FixedSizeCrop)(crop_size=(image_size, image_size), pad=False),
|
| 20 |
+
]
|
| 21 |
+
dataloader.train.mapper.image_format = "RGB"
|
| 22 |
+
dataloader.train.total_batch_size = 64
|
| 23 |
+
dataloader.train.mapper.recompute_boxes = True
|
| 24 |
+
|
| 25 |
+
dataloader.test.mapper.augmentations = [
|
| 26 |
+
L(T.ResizeShortestEdge)(short_edge_length=image_size, max_size=image_size),
|
| 27 |
+
]
|
| 28 |
+
|
| 29 |
+
from functools import partial
|
| 30 |
+
from fvcore.common.param_scheduler import MultiStepParamScheduler
|
| 31 |
+
|
| 32 |
+
from detectron2 import model_zoo
|
| 33 |
+
from detectron2.config import LazyCall as L
|
| 34 |
+
from detectron2.solver import WarmupParamScheduler
|
| 35 |
+
from detectron2.modeling.backbone.vit import get_vit_lr_decay_rate
|
| 36 |
+
|
| 37 |
+
## mask_rcnn_vitdet_b_100ep.py (base)
|
| 38 |
+
|
| 39 |
+
model = model_zoo.get_config("common/models/mask_rcnn_vitdet.py").model
|
| 40 |
+
|
| 41 |
+
train = model_zoo.get_config("common/train.py").train
|
| 42 |
+
train.amp.enabled = True
|
| 43 |
+
train.ddp.fp16_compression = True
|
| 44 |
+
train.init_checkpoint = "detectron2://ImageNetPretrained/MAE/mae_pretrain_vit_large.pth?matching_heuristics=True"
|
| 45 |
+
|
| 46 |
+
train.max_iter = 184375
|
| 47 |
+
|
| 48 |
+
lr_multiplier = L(WarmupParamScheduler)(
|
| 49 |
+
scheduler=L(MultiStepParamScheduler)(
|
| 50 |
+
values=[1.0, 0.1, 0.01],
|
| 51 |
+
milestones=[163889, 177546],
|
| 52 |
+
num_updates=train.max_iter,
|
| 53 |
+
),
|
| 54 |
+
warmup_length=250 / train.max_iter,
|
| 55 |
+
warmup_factor=0.001,
|
| 56 |
+
)
|
| 57 |
+
|
| 58 |
+
optimizer = model_zoo.get_config("common/optim.py").AdamW
|
| 59 |
+
optimizer.params.lr_factor_func = partial(get_vit_lr_decay_rate, lr_decay_rate=0.8, num_layers=24)
|
| 60 |
+
optimizer.params.overrides = {"pos_embed": {"weight_decay": 0.0}}
|
| 61 |
+
|
| 62 |
+
## cascade_mask_rcnn_vitdet_b_100ep.py (cascade heads)
|
| 63 |
+
|
| 64 |
+
from detectron2.config import LazyCall as L
|
| 65 |
+
from detectron2.layers import ShapeSpec
|
| 66 |
+
from detectron2.modeling.box_regression import Box2BoxTransform
|
| 67 |
+
from detectron2.modeling.matcher import Matcher
|
| 68 |
+
from detectron2.modeling.roi_heads import (
|
| 69 |
+
FastRCNNOutputLayers,
|
| 70 |
+
FastRCNNConvFCHead,
|
| 71 |
+
CascadeROIHeads,
|
| 72 |
+
)
|
| 73 |
+
|
| 74 |
+
[model.roi_heads.pop(k) for k in ["box_head", "box_predictor", "proposal_matcher"]]
|
| 75 |
+
|
| 76 |
+
model.roi_heads.update(
|
| 77 |
+
_target_=CascadeROIHeads,
|
| 78 |
+
box_heads=[
|
| 79 |
+
L(FastRCNNConvFCHead)(
|
| 80 |
+
input_shape=ShapeSpec(channels=256, height=7, width=7),
|
| 81 |
+
conv_dims=[256, 256, 256, 256],
|
| 82 |
+
fc_dims=[1024],
|
| 83 |
+
conv_norm="LN",
|
| 84 |
+
)
|
| 85 |
+
for _ in range(3)
|
| 86 |
+
],
|
| 87 |
+
box_predictors=[
|
| 88 |
+
L(FastRCNNOutputLayers)(
|
| 89 |
+
input_shape=ShapeSpec(channels=1024),
|
| 90 |
+
test_score_thresh=0.05,
|
| 91 |
+
box2box_transform=L(Box2BoxTransform)(weights=(w1, w1, w2, w2)),
|
| 92 |
+
cls_agnostic_bbox_reg=True,
|
| 93 |
+
num_classes="${...num_classes}",
|
| 94 |
+
)
|
| 95 |
+
for (w1, w2) in [(10, 5), (20, 10), (30, 15)]
|
| 96 |
+
],
|
| 97 |
+
proposal_matchers=[
|
| 98 |
+
L(Matcher)(thresholds=[th], labels=[0, 1], allow_low_quality_matches=False)
|
| 99 |
+
for th in [0.5, 0.6, 0.7]
|
| 100 |
+
],
|
| 101 |
+
)
|
| 102 |
+
|
| 103 |
+
## cascade_mask_rcnn_vitdet_l_100ep.py (ViT-L backbone overrides)
|
| 104 |
+
|
| 105 |
+
model.backbone.net.embed_dim = 1024
|
| 106 |
+
model.backbone.net.depth = 24
|
| 107 |
+
model.backbone.net.num_heads = 16
|
| 108 |
+
model.backbone.net.drop_path_rate = 0.4
|
| 109 |
+
# 5, 11, 17, 23 for global attention
|
| 110 |
+
model.backbone.net.window_block_indexes = (
|
| 111 |
+
list(range(0, 5)) + list(range(6, 11)) + list(range(12, 17)) + list(range(18, 23))
|
| 112 |
+
)
|
third-party/video_to_data/reconstruction/modules/v2d_detectron2/lib/download_weights.py
ADDED
|
@@ -0,0 +1,53 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
|
| 2 |
+
# SPDX-License-Identifier: Apache-2.0
|
| 3 |
+
import argparse
|
| 4 |
+
import urllib.request
|
| 5 |
+
from pathlib import Path
|
| 6 |
+
|
| 7 |
+
VITDET_VARIANTS = {
|
| 8 |
+
"b": {
|
| 9 |
+
"url": "https://dl.fbaipublicfiles.com/detectron2/ViTDet/COCO/cascade_mask_rcnn_vitdet_b/f325358525/model_final_435fa9.pkl",
|
| 10 |
+
"file": "model_final_435fa9.pkl",
|
| 11 |
+
},
|
| 12 |
+
"l": {
|
| 13 |
+
"url": "https://dl.fbaipublicfiles.com/detectron2/ViTDet/COCO/cascade_mask_rcnn_vitdet_l/f328021305/model_final_1a9f28.pkl",
|
| 14 |
+
"file": "model_final_1a9f28.pkl",
|
| 15 |
+
},
|
| 16 |
+
"h": {
|
| 17 |
+
"url": "https://dl.fbaipublicfiles.com/detectron2/ViTDet/COCO/cascade_mask_rcnn_vitdet_h/f328730692/model_final_f05665.pkl",
|
| 18 |
+
"file": "model_final_f05665.pkl",
|
| 19 |
+
},
|
| 20 |
+
}
|
| 21 |
+
|
| 22 |
+
|
| 23 |
+
def download_weights(output_dir: str, model_sizes: list[str] | None = None):
|
| 24 |
+
if model_sizes is None:
|
| 25 |
+
model_sizes = ["b"]
|
| 26 |
+
|
| 27 |
+
for size in model_sizes:
|
| 28 |
+
if size not in VITDET_VARIANTS:
|
| 29 |
+
raise ValueError(f"Unknown model size '{size}', expected one of {list(VITDET_VARIANTS)}")
|
| 30 |
+
|
| 31 |
+
variant = VITDET_VARIANTS[size]
|
| 32 |
+
dest_dir = Path(output_dir) / f"cascade_mask_rcnn_vitdet_{size}"
|
| 33 |
+
dest_dir.mkdir(parents=True, exist_ok=True)
|
| 34 |
+
dest_file = dest_dir / variant["file"]
|
| 35 |
+
|
| 36 |
+
if dest_file.exists():
|
| 37 |
+
print(f"ViTDet-{size.upper()} checkpoint already exists at {dest_file}")
|
| 38 |
+
continue
|
| 39 |
+
|
| 40 |
+
print(f"Downloading ViTDet-{size.upper()} checkpoint to {dest_file}...")
|
| 41 |
+
urllib.request.urlretrieve(variant["url"], dest_file)
|
| 42 |
+
print("Done.")
|
| 43 |
+
|
| 44 |
+
|
| 45 |
+
if __name__ == "__main__":
|
| 46 |
+
parser = argparse.ArgumentParser(description="Download ViTDet checkpoints")
|
| 47 |
+
parser.add_argument("--output_dir", type=str, required=True, help="Directory to save checkpoints")
|
| 48 |
+
parser.add_argument(
|
| 49 |
+
"--model_sizes", type=str, nargs="+", default=["b"], choices=["b", "l", "h"],
|
| 50 |
+
help="Which model sizes to download (default: b)",
|
| 51 |
+
)
|
| 52 |
+
args = parser.parse_args()
|
| 53 |
+
download_weights(args.output_dir, args.model_sizes)
|
third-party/video_to_data/reconstruction/modules/v2d_detectron2/lib/mv_track_bboxes.py
ADDED
|
@@ -0,0 +1,111 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
|
| 2 |
+
# SPDX-License-Identifier: Apache-2.0
|
| 3 |
+
from pathlib import Path
|
| 4 |
+
|
| 5 |
+
import torch
|
| 6 |
+
|
| 7 |
+
from v2d.mv.rig import RigConfig
|
| 8 |
+
|
| 9 |
+
from .build_detector import Detector
|
| 10 |
+
from .track_bboxes import (
|
| 11 |
+
ByteTrackerConfig,
|
| 12 |
+
DetectorConfig,
|
| 13 |
+
IoUTrackerConfig,
|
| 14 |
+
track_bboxes,
|
| 15 |
+
)
|
| 16 |
+
|
| 17 |
+
|
| 18 |
+
DEVICE = torch.device("cuda" if torch.cuda.is_available() else "cpu")
|
| 19 |
+
|
| 20 |
+
|
| 21 |
+
def mv_track_bboxes_from_config(cfg):
|
| 22 |
+
"""Run detection + tracking across multiple cameras defined by a rig config."""
|
| 23 |
+
rig = RigConfig(cfg.rig_config)
|
| 24 |
+
|
| 25 |
+
detector_cfg = DetectorConfig(
|
| 26 |
+
model_size=cfg.detector.model_size,
|
| 27 |
+
weights_dir=cfg.detector.weights_dir,
|
| 28 |
+
det_cat_id=cfg.detector.det_cat_id,
|
| 29 |
+
bbox_thr=cfg.detector.bbox_thr,
|
| 30 |
+
default_to_full_image=cfg.detector.default_to_full_image,
|
| 31 |
+
test_score_thresh=cfg.detector.get("test_score_thresh", 0.25),
|
| 32 |
+
)
|
| 33 |
+
tracker_type = cfg.get("tracker_type", "iou")
|
| 34 |
+
if tracker_type == "byte":
|
| 35 |
+
bt = cfg.byte_tracker
|
| 36 |
+
tracker_cfg = ByteTrackerConfig(
|
| 37 |
+
track_thresh=bt.get("track_thresh", 0.6),
|
| 38 |
+
det_thresh=bt.get("det_thresh", 0.1),
|
| 39 |
+
match_thresh=bt.get("match_thresh", 0.8),
|
| 40 |
+
second_match_thresh=bt.get("second_match_thresh", 0.5),
|
| 41 |
+
max_lost=bt.get("max_lost", 30),
|
| 42 |
+
min_hits=bt.get("min_hits", 3),
|
| 43 |
+
merge_max_gap=bt.get("merge_max_gap", 60),
|
| 44 |
+
merge_iou_threshold=bt.get("merge_iou_threshold", 0.3),
|
| 45 |
+
)
|
| 46 |
+
else:
|
| 47 |
+
it = cfg.iou_tracker
|
| 48 |
+
tracker_cfg = IoUTrackerConfig(
|
| 49 |
+
iou_threshold=it.get("iou_threshold", 0.3),
|
| 50 |
+
max_lost=it.get("max_lost", 30),
|
| 51 |
+
min_hits=it.get("min_hits", 3),
|
| 52 |
+
merge_max_gap=it.get("merge_max_gap", 10),
|
| 53 |
+
merge_iou_threshold=it.get("merge_iou_threshold", 0.5),
|
| 54 |
+
)
|
| 55 |
+
|
| 56 |
+
weights_path = f"{detector_cfg.weights_dir}/cascade_mask_rcnn_vitdet_{detector_cfg.model_size}"
|
| 57 |
+
detector = Detector(
|
| 58 |
+
name="vitdet",
|
| 59 |
+
device=DEVICE,
|
| 60 |
+
model_size=detector_cfg.model_size,
|
| 61 |
+
path=weights_path,
|
| 62 |
+
test_score_thresh=detector_cfg.test_score_thresh,
|
| 63 |
+
)
|
| 64 |
+
|
| 65 |
+
batch_size = cfg.get("batch_size", 1)
|
| 66 |
+
|
| 67 |
+
for cam_id in cfg.cameras:
|
| 68 |
+
cam = rig.get_camera(cam_id)
|
| 69 |
+
print(f"Running Detectron2 bbox tracking for camera: {cam.name}")
|
| 70 |
+
|
| 71 |
+
rgb_path = Path(cfg.rgb_path_template.format(cam_name=cam.name))
|
| 72 |
+
output_path = Path(cfg.output_path_template.format(cam_name=cam.name))
|
| 73 |
+
|
| 74 |
+
track_bboxes(
|
| 75 |
+
rgb_path=rgb_path,
|
| 76 |
+
output_path=output_path,
|
| 77 |
+
detector_cfg=detector_cfg,
|
| 78 |
+
tracker_cfg=tracker_cfg,
|
| 79 |
+
batch_size=batch_size,
|
| 80 |
+
detector=detector,
|
| 81 |
+
debug=cfg.debug,
|
| 82 |
+
)
|
| 83 |
+
|
| 84 |
+
|
| 85 |
+
if __name__ == "__main__":
|
| 86 |
+
import argparse
|
| 87 |
+
|
| 88 |
+
from omegaconf import OmegaConf
|
| 89 |
+
|
| 90 |
+
parser = argparse.ArgumentParser(description="Run multi-view detection + tracking")
|
| 91 |
+
parser.add_argument("--rgb_dir", type=str, required=True, help="Directory containing input frames")
|
| 92 |
+
parser.add_argument("--weights_dir", type=str, required=True, help="Directory containing model weights")
|
| 93 |
+
parser.add_argument("--output_dir", type=str, required=True, help="Directory for outputs")
|
| 94 |
+
parser.add_argument("--config_path", type=str, default=None,
|
| 95 |
+
help="Optional override config (merged on top of defaults)")
|
| 96 |
+
parser.add_argument("--debug", type=int, default=None, help="Debug level override")
|
| 97 |
+
args = parser.parse_args()
|
| 98 |
+
|
| 99 |
+
cfg = OmegaConf.load(Path(__file__).parent / "mv_track_bboxes.yaml")
|
| 100 |
+
if args.config_path:
|
| 101 |
+
cfg = OmegaConf.merge(cfg, OmegaConf.load(args.config_path))
|
| 102 |
+
overrides: dict = {
|
| 103 |
+
"rgb_dir": args.rgb_dir,
|
| 104 |
+
"detector": {"weights_dir": args.weights_dir},
|
| 105 |
+
"output_dir": args.output_dir,
|
| 106 |
+
}
|
| 107 |
+
if args.debug is not None:
|
| 108 |
+
overrides["debug"] = args.debug
|
| 109 |
+
|
| 110 |
+
cfg = OmegaConf.merge(cfg, overrides)
|
| 111 |
+
mv_track_bboxes_from_config(cfg)
|
third-party/video_to_data/reconstruction/modules/v2d_detectron2/lib/mv_track_bboxes.yaml
ADDED
|
@@ -0,0 +1,41 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
|
| 2 |
+
# SPDX-License-Identifier: Apache-2.0
|
| 3 |
+
rgb_dir: ???
|
| 4 |
+
output_dir: ???
|
| 5 |
+
|
| 6 |
+
rig_config: stereo-4
|
| 7 |
+
cameras: [0, 2, 4, 6]
|
| 8 |
+
|
| 9 |
+
rgb_path_template: "${rgb_dir}/{cam_name}"
|
| 10 |
+
output_path_template: "${output_dir}/{cam_name}_bbox_track.pt"
|
| 11 |
+
|
| 12 |
+
batch_size: 2
|
| 13 |
+
|
| 14 |
+
detector:
|
| 15 |
+
weights_dir: ???
|
| 16 |
+
model_size: b # "b" (ViT-Base, fastest), "l" (ViT-Large), "h" (ViT-Huge, most accurate)
|
| 17 |
+
det_cat_id: 0 # 0: person
|
| 18 |
+
bbox_thr: 0.5 # minimum confidence score for a detection to be considered valid
|
| 19 |
+
default_to_full_image: True # if no valid detections, return the full image as a detection
|
| 20 |
+
test_score_thresh: 0.1 # model-internal NMS threshold; lower for ByteTrack (0.1), default IoU (0.25)
|
| 21 |
+
|
| 22 |
+
tracker_type: byte # "iou" or "byte"
|
| 23 |
+
|
| 24 |
+
iou_tracker:
|
| 25 |
+
iou_threshold: 0.3
|
| 26 |
+
max_lost: 30
|
| 27 |
+
min_hits: 3
|
| 28 |
+
merge_max_gap: 10
|
| 29 |
+
merge_iou_threshold: 0.5
|
| 30 |
+
|
| 31 |
+
byte_tracker:
|
| 32 |
+
track_thresh: 0.6 # high confidence threshold (first association)
|
| 33 |
+
det_thresh: 0.1 # low confidence threshold (second association)
|
| 34 |
+
match_thresh: 0.8 # IoU threshold for first association
|
| 35 |
+
second_match_thresh: 0.5 # IoU threshold for second association
|
| 36 |
+
max_lost: 30
|
| 37 |
+
min_hits: 3
|
| 38 |
+
merge_max_gap: 60 # frames gap tolerance for merging fragmented tracks
|
| 39 |
+
merge_iou_threshold: 0.3 # IoU threshold for merging (lower = more aggressive)
|
| 40 |
+
|
| 41 |
+
debug: 2
|
third-party/video_to_data/reconstruction/modules/v2d_detectron2/lib/pyproject.toml
ADDED
|
@@ -0,0 +1,31 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
|
| 2 |
+
# SPDX-License-Identifier: Apache-2.0
|
| 3 |
+
[build-system]
|
| 4 |
+
requires = ["setuptools>=68.0", "wheel"]
|
| 5 |
+
build-backend = "setuptools.build_meta"
|
| 6 |
+
|
| 7 |
+
[project]
|
| 8 |
+
name = "v2d-detectron2-lib"
|
| 9 |
+
version = "0.1.0"
|
| 10 |
+
description = "Detectron2-based human detection and tracking"
|
| 11 |
+
requires-python = ">=3.10"
|
| 12 |
+
dependencies = [
|
| 13 |
+
"numpy",
|
| 14 |
+
"scipy",
|
| 15 |
+
"opencv-python",
|
| 16 |
+
"imageio[pyav]",
|
| 17 |
+
"av",
|
| 18 |
+
"tqdm",
|
| 19 |
+
"torch",
|
| 20 |
+
"omegaconf",
|
| 21 |
+
"v2d-mv[io,math]",
|
| 22 |
+
]
|
| 23 |
+
|
| 24 |
+
[tool.setuptools]
|
| 25 |
+
packages = ["v2d.detectron2.lib"]
|
| 26 |
+
|
| 27 |
+
[tool.setuptools.package-data]
|
| 28 |
+
"v2d.detectron2.lib" = ["*.yaml"]
|
| 29 |
+
|
| 30 |
+
[tool.setuptools.package-dir]
|
| 31 |
+
"v2d.detectron2.lib" = "."
|
third-party/video_to_data/reconstruction/modules/v2d_detectron2/lib/track_bboxes.py
ADDED
|
@@ -0,0 +1,245 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
|
| 2 |
+
# SPDX-License-Identifier: Apache-2.0
|
| 3 |
+
from __future__ import annotations
|
| 4 |
+
|
| 5 |
+
import argparse
|
| 6 |
+
from dataclasses import dataclass
|
| 7 |
+
from pathlib import Path
|
| 8 |
+
import time
|
| 9 |
+
|
| 10 |
+
import cv2
|
| 11 |
+
import imageio.v3 as iio
|
| 12 |
+
import torch
|
| 13 |
+
from tqdm import tqdm
|
| 14 |
+
|
| 15 |
+
from v2d.common.video import FrameSource, get_video_writer
|
| 16 |
+
|
| 17 |
+
from .build_detector import Detector
|
| 18 |
+
from .bytetracker import ByteTracker
|
| 19 |
+
from .tracker import IoUTracker
|
| 20 |
+
|
| 21 |
+
DEVICE = torch.device("cuda" if torch.cuda.is_available() else "cpu")
|
| 22 |
+
|
| 23 |
+
|
| 24 |
+
@dataclass
|
| 25 |
+
class DetectorConfig:
|
| 26 |
+
model_size: str = "b"
|
| 27 |
+
weights_dir: str = ""
|
| 28 |
+
det_cat_id: int = 0
|
| 29 |
+
bbox_thr: float = 0.5
|
| 30 |
+
default_to_full_image: bool = True
|
| 31 |
+
test_score_thresh: float = 0.25
|
| 32 |
+
|
| 33 |
+
|
| 34 |
+
@dataclass
|
| 35 |
+
class IoUTrackerConfig:
|
| 36 |
+
iou_threshold: float = 0.3
|
| 37 |
+
max_lost: int = 30
|
| 38 |
+
min_hits: int = 3
|
| 39 |
+
merge_max_gap: int = 10
|
| 40 |
+
merge_iou_threshold: float = 0.5
|
| 41 |
+
|
| 42 |
+
|
| 43 |
+
@dataclass
|
| 44 |
+
class ByteTrackerConfig:
|
| 45 |
+
track_thresh: float = 0.6
|
| 46 |
+
det_thresh: float = 0.1
|
| 47 |
+
match_thresh: float = 0.8
|
| 48 |
+
second_match_thresh: float = 0.5
|
| 49 |
+
max_lost: int = 30
|
| 50 |
+
min_hits: int = 3
|
| 51 |
+
merge_max_gap: int = 60
|
| 52 |
+
merge_iou_threshold: float = 0.3
|
| 53 |
+
|
| 54 |
+
|
| 55 |
+
TrackerConfig = IoUTrackerConfig | ByteTrackerConfig
|
| 56 |
+
|
| 57 |
+
|
| 58 |
+
def track_bboxes(
|
| 59 |
+
rgb_path: Path,
|
| 60 |
+
output_path: str | Path,
|
| 61 |
+
detector_cfg: DetectorConfig | None = None,
|
| 62 |
+
tracker_cfg: TrackerConfig | None = None,
|
| 63 |
+
batch_size: int = 1,
|
| 64 |
+
debug: int = 0,
|
| 65 |
+
detector: Detector | None = None,
|
| 66 |
+
) -> dict:
|
| 67 |
+
"""Run detection + tracking on a single camera's frames.
|
| 68 |
+
|
| 69 |
+
Saves a .pt dict to *output_path* and returns it.
|
| 70 |
+
|
| 71 |
+
Debug levels:
|
| 72 |
+
0 — no debug output
|
| 73 |
+
1 — print track info, save per-frame detection images (every 30th frame)
|
| 74 |
+
2 — also render bbox_track overlay video
|
| 75 |
+
"""
|
| 76 |
+
if detector_cfg is None:
|
| 77 |
+
detector_cfg = DetectorConfig()
|
| 78 |
+
if tracker_cfg is None:
|
| 79 |
+
tracker_cfg = IoUTrackerConfig()
|
| 80 |
+
|
| 81 |
+
use_byte = isinstance(tracker_cfg, ByteTrackerConfig)
|
| 82 |
+
|
| 83 |
+
output_path = Path(output_path).resolve()
|
| 84 |
+
output_path.parent.mkdir(parents=True, exist_ok=True)
|
| 85 |
+
|
| 86 |
+
frame_source = FrameSource.from_path(rgb_path)
|
| 87 |
+
n_frames = frame_source.n_frames
|
| 88 |
+
image_size = frame_source.image_size
|
| 89 |
+
|
| 90 |
+
effective_bbox_thr = tracker_cfg.det_thresh if use_byte else detector_cfg.bbox_thr
|
| 91 |
+
|
| 92 |
+
if detector is None:
|
| 93 |
+
weights_path = f"{detector_cfg.weights_dir}/cascade_mask_rcnn_vitdet_{detector_cfg.model_size}"
|
| 94 |
+
detector = Detector(
|
| 95 |
+
name="vitdet",
|
| 96 |
+
device=DEVICE,
|
| 97 |
+
model_size=detector_cfg.model_size,
|
| 98 |
+
path=weights_path,
|
| 99 |
+
test_score_thresh=detector_cfg.test_score_thresh,
|
| 100 |
+
)
|
| 101 |
+
|
| 102 |
+
if debug > 0:
|
| 103 |
+
debug_det_dir = output_path.parent / f"{output_path.stem}_detections"
|
| 104 |
+
debug_det_dir.mkdir(parents=True, exist_ok=True)
|
| 105 |
+
|
| 106 |
+
det_kwargs = dict(
|
| 107 |
+
det_cat_id=detector_cfg.det_cat_id,
|
| 108 |
+
bbox_thr=effective_bbox_thr,
|
| 109 |
+
default_to_full_image=detector_cfg.default_to_full_image,
|
| 110 |
+
)
|
| 111 |
+
|
| 112 |
+
if use_byte:
|
| 113 |
+
tracker: IoUTracker | ByteTracker = ByteTracker(
|
| 114 |
+
track_thresh=tracker_cfg.track_thresh,
|
| 115 |
+
match_thresh=tracker_cfg.match_thresh,
|
| 116 |
+
second_match_thresh=tracker_cfg.second_match_thresh,
|
| 117 |
+
max_lost=tracker_cfg.max_lost,
|
| 118 |
+
min_hits=tracker_cfg.min_hits,
|
| 119 |
+
)
|
| 120 |
+
print(f"Using ByteTracker (track_thresh={tracker_cfg.track_thresh}, "
|
| 121 |
+
f"det_thresh={tracker_cfg.det_thresh})")
|
| 122 |
+
else:
|
| 123 |
+
tracker = IoUTracker(
|
| 124 |
+
iou_threshold=tracker_cfg.iou_threshold,
|
| 125 |
+
max_lost=tracker_cfg.max_lost,
|
| 126 |
+
min_hits=tracker_cfg.min_hits,
|
| 127 |
+
)
|
| 128 |
+
print(f"Using IoUTracker (iou_threshold={tracker_cfg.iou_threshold})")
|
| 129 |
+
|
| 130 |
+
n_batches = (n_frames + batch_size - 1) // batch_size
|
| 131 |
+
for batch_start, batch_frames in tqdm(frame_source.iter_batches(batch_size),
|
| 132 |
+
total=n_batches, desc="Running detection"):
|
| 133 |
+
start_time = time.time()
|
| 134 |
+
if len(batch_frames) == 1:
|
| 135 |
+
batch_results = [detector.run_detection(batch_frames[0], **det_kwargs)]
|
| 136 |
+
else:
|
| 137 |
+
batch_results = detector.run_detection_batch(batch_frames, **det_kwargs)
|
| 138 |
+
|
| 139 |
+
for offset, (bboxes, scores) in enumerate(batch_results):
|
| 140 |
+
frame_idx = batch_start + offset
|
| 141 |
+
tracker.update(frame_idx, bboxes, scores)
|
| 142 |
+
|
| 143 |
+
if debug > 0 and frame_idx % 30 == 0:
|
| 144 |
+
elapsed = time.time() - start_time
|
| 145 |
+
tqdm.write(f"Frame {frame_idx} detection time: {elapsed:.3f}s")
|
| 146 |
+
image = batch_frames[offset].copy()
|
| 147 |
+
H_img, W_img = image.shape[:2]
|
| 148 |
+
label = f"Frame {frame_idx}"
|
| 149 |
+
(tw, th), _ = cv2.getTextSize(label, cv2.FONT_HERSHEY_SIMPLEX, 1.0, 2)
|
| 150 |
+
cv2.putText(image, label, (W_img - tw - 10, th + 10),
|
| 151 |
+
cv2.FONT_HERSHEY_SIMPLEX, 1.0, (0, 255, 0), 2)
|
| 152 |
+
bboxes_int = bboxes.astype(int)
|
| 153 |
+
for j, bbox in enumerate(bboxes_int):
|
| 154 |
+
cv2.rectangle(image, (bbox[0], bbox[1]), (bbox[2], bbox[3]), (0, 255, 255), 2)
|
| 155 |
+
cv2.putText(image, f"Score: {scores[j]:.2f}", (bbox[0], bbox[1] - 10),
|
| 156 |
+
cv2.FONT_HERSHEY_SIMPLEX, 0.5, (0, 255, 255), 2)
|
| 157 |
+
iio.imwrite(debug_det_dir / f"bbox_{frame_idx:06d}.png", image)
|
| 158 |
+
|
| 159 |
+
tracks = tracker.finalize()
|
| 160 |
+
tracks = IoUTracker.merge_fragmented_tracks(
|
| 161 |
+
tracks,
|
| 162 |
+
max_gap=tracker_cfg.merge_max_gap,
|
| 163 |
+
iou_threshold=tracker_cfg.merge_iou_threshold,
|
| 164 |
+
)
|
| 165 |
+
if debug > 0:
|
| 166 |
+
print("=== Tracking Results ===")
|
| 167 |
+
for track in tracks:
|
| 168 |
+
print(track)
|
| 169 |
+
|
| 170 |
+
primary_track = IoUTracker.select_primary_track(tracks, image_size)
|
| 171 |
+
primary_track.interpolate(n_frames)
|
| 172 |
+
bbox_track = primary_track.get_bboxes()
|
| 173 |
+
scores = primary_track.get_scores()
|
| 174 |
+
print(f"Primary bbox track: {primary_track}")
|
| 175 |
+
|
| 176 |
+
result = {
|
| 177 |
+
"det_cat_id": detector_cfg.det_cat_id,
|
| 178 |
+
"scores": scores,
|
| 179 |
+
"bbox_track": bbox_track,
|
| 180 |
+
}
|
| 181 |
+
torch.save(result, output_path)
|
| 182 |
+
print(f"Saved bbox track ({n_frames} frames) to {output_path}")
|
| 183 |
+
|
| 184 |
+
if debug > 1:
|
| 185 |
+
debug_video_path = output_path.with_suffix(".mp4")
|
| 186 |
+
writer = get_video_writer(debug_video_path, fps=30, crf=23)
|
| 187 |
+
for i, image in tqdm(enumerate(frame_source.iter_frames()),
|
| 188 |
+
total=n_frames, desc="Rendering debug video"):
|
| 189 |
+
H_img, W_img = image.shape[:2]
|
| 190 |
+
label = f"Frame {i}"
|
| 191 |
+
(tw, th), _ = cv2.getTextSize(label, cv2.FONT_HERSHEY_SIMPLEX, 1.0, 2)
|
| 192 |
+
cv2.putText(image, label, (W_img - tw - 10, th + 10),
|
| 193 |
+
cv2.FONT_HERSHEY_SIMPLEX, 1.0, (0, 255, 0), 2)
|
| 194 |
+
bbox = bbox_track[i].astype(int)
|
| 195 |
+
cv2.rectangle(image, (bbox[0], bbox[1]), (bbox[2], bbox[3]), (0, 255, 255), 2)
|
| 196 |
+
cv2.putText(image, f"Score: {scores[i]:.2f}", (bbox[0], bbox[1] - 10),
|
| 197 |
+
cv2.FONT_HERSHEY_SIMPLEX, 0.5, (0, 255, 255), 2)
|
| 198 |
+
writer.write_frame(image)
|
| 199 |
+
writer.close()
|
| 200 |
+
print(f"Saved debug video to {debug_video_path}")
|
| 201 |
+
|
| 202 |
+
return result
|
| 203 |
+
|
| 204 |
+
|
| 205 |
+
if __name__ == "__main__":
|
| 206 |
+
parser = argparse.ArgumentParser(description="Run person detection + tracking on a single camera")
|
| 207 |
+
parser.add_argument("--rgb_path", type=str, required=True,
|
| 208 |
+
help="Path to input frames (image dir, .h5, or video file)")
|
| 209 |
+
parser.add_argument("--output_path", type=str, required=True, help="Output .pt file path")
|
| 210 |
+
|
| 211 |
+
det = parser.add_argument_group("detector")
|
| 212 |
+
det.add_argument("--model_size", type=str, default="b", choices=["b", "l", "h"])
|
| 213 |
+
det.add_argument("--weights_dir", type=str, default="")
|
| 214 |
+
det.add_argument("--det_cat_id", type=int, default=0, help="COCO category id (0=person)")
|
| 215 |
+
det.add_argument("--bbox_thr", type=float, default=0.5)
|
| 216 |
+
det.add_argument("--no_default_to_full_image", action="store_true")
|
| 217 |
+
|
| 218 |
+
trk = parser.add_argument_group("tracker")
|
| 219 |
+
trk.add_argument("--iou_threshold", type=float, default=0.3)
|
| 220 |
+
trk.add_argument("--max_lost", type=int, default=30)
|
| 221 |
+
trk.add_argument("--min_hits", type=int, default=3)
|
| 222 |
+
|
| 223 |
+
parser.add_argument("--batch_size", type=int, default=1)
|
| 224 |
+
parser.add_argument("--debug", type=int, default=0)
|
| 225 |
+
|
| 226 |
+
args = parser.parse_args()
|
| 227 |
+
|
| 228 |
+
track_bboxes(
|
| 229 |
+
rgb_path=args.rgb_path,
|
| 230 |
+
output_path=args.output_path,
|
| 231 |
+
detector_cfg=DetectorConfig(
|
| 232 |
+
model_size=args.model_size,
|
| 233 |
+
weights_dir=args.weights_dir,
|
| 234 |
+
det_cat_id=args.det_cat_id,
|
| 235 |
+
bbox_thr=args.bbox_thr,
|
| 236 |
+
default_to_full_image=not args.no_default_to_full_image,
|
| 237 |
+
),
|
| 238 |
+
tracker_cfg=IoUTrackerConfig(
|
| 239 |
+
iou_threshold=args.iou_threshold,
|
| 240 |
+
max_lost=args.max_lost,
|
| 241 |
+
min_hits=args.min_hits,
|
| 242 |
+
),
|
| 243 |
+
batch_size=args.batch_size,
|
| 244 |
+
debug=args.debug,
|
| 245 |
+
)
|
third-party/video_to_data/reconstruction/modules/v2d_detectron2/lib/tracker.py
ADDED
|
@@ -0,0 +1,503 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
|
| 2 |
+
# SPDX-License-Identifier: Apache-2.0
|
| 3 |
+
from __future__ import annotations
|
| 4 |
+
|
| 5 |
+
from dataclasses import dataclass, field
|
| 6 |
+
from enum import Enum, auto
|
| 7 |
+
|
| 8 |
+
import numpy as np
|
| 9 |
+
from scipy.optimize import linear_sum_assignment
|
| 10 |
+
|
| 11 |
+
from v2d.mv.math.numpy_fn import linear_one_euro_filter
|
| 12 |
+
|
| 13 |
+
|
| 14 |
+
class TrackState(Enum):
|
| 15 |
+
TENTATIVE = auto()
|
| 16 |
+
ACTIVE = auto()
|
| 17 |
+
LOST = auto()
|
| 18 |
+
FINISHED = auto()
|
| 19 |
+
|
| 20 |
+
|
| 21 |
+
@dataclass
|
| 22 |
+
class Track:
|
| 23 |
+
track_id: int
|
| 24 |
+
state: TrackState = TrackState.ACTIVE
|
| 25 |
+
frames_since_match: int = 0
|
| 26 |
+
history: list[tuple[int, np.ndarray, float]] = field(default_factory=list)
|
| 27 |
+
|
| 28 |
+
@property
|
| 29 |
+
def first_bbox(self) -> np.ndarray:
|
| 30 |
+
return self.history[0][1]
|
| 31 |
+
|
| 32 |
+
@property
|
| 33 |
+
def last_bbox(self) -> np.ndarray:
|
| 34 |
+
return self.history[-1][1]
|
| 35 |
+
|
| 36 |
+
@property
|
| 37 |
+
def last_score(self) -> float:
|
| 38 |
+
return self.history[-1][2]
|
| 39 |
+
|
| 40 |
+
@property
|
| 41 |
+
def start_frame(self) -> int:
|
| 42 |
+
return self.history[0][0]
|
| 43 |
+
|
| 44 |
+
@property
|
| 45 |
+
def end_frame(self) -> int:
|
| 46 |
+
return self.history[-1][0]
|
| 47 |
+
|
| 48 |
+
@property
|
| 49 |
+
def length(self) -> int:
|
| 50 |
+
return len(self.history)
|
| 51 |
+
|
| 52 |
+
def __repr__(self) -> str:
|
| 53 |
+
motion = self.total_motion()
|
| 54 |
+
return (
|
| 55 |
+
f"Track(id={self.track_id}, frames={self.length}, "
|
| 56 |
+
f"span={self.start_frame}-{self.end_frame}, "
|
| 57 |
+
f"motion={motion:.0f}px, state={self.state.name})"
|
| 58 |
+
)
|
| 59 |
+
|
| 60 |
+
def append(self, frame_idx: int, bbox: np.ndarray, score: float):
|
| 61 |
+
self.history.append((frame_idx, bbox, score))
|
| 62 |
+
self.state = TrackState.ACTIVE
|
| 63 |
+
self.frames_since_match = 0
|
| 64 |
+
|
| 65 |
+
def get_bboxes(self) -> np.ndarray:
|
| 66 |
+
"""Return (N, 4) array of all bboxes in this track."""
|
| 67 |
+
return np.array([h[1] for h in self.history])
|
| 68 |
+
|
| 69 |
+
def get_scores(self) -> np.ndarray:
|
| 70 |
+
return np.array([h[2] for h in self.history])
|
| 71 |
+
|
| 72 |
+
def get_frame_indices(self) -> np.ndarray:
|
| 73 |
+
return np.array([h[0] for h in self.history])
|
| 74 |
+
|
| 75 |
+
def interpolate(self, total_frames: int):
|
| 76 |
+
"""Fill gaps in-place with linearly interpolated bboxes (score=-1).
|
| 77 |
+
|
| 78 |
+
After calling, self.history has exactly total_frames entries
|
| 79 |
+
covering frames 0..total_frames-1. Interpolated entries use score=-1
|
| 80 |
+
to distinguish them from real detections. Frames before the first or
|
| 81 |
+
after the last observation are held (nearest bbox, score=-1).
|
| 82 |
+
"""
|
| 83 |
+
frame_indices = self.get_frame_indices()
|
| 84 |
+
bboxes = self.get_bboxes()
|
| 85 |
+
scores = self.get_scores()
|
| 86 |
+
|
| 87 |
+
observed = {int(f): (b, s) for f, b, s in zip(frame_indices, bboxes, scores)}
|
| 88 |
+
first, last = int(frame_indices[0]), int(frame_indices[-1])
|
| 89 |
+
|
| 90 |
+
new_history: list[tuple[int, np.ndarray, float]] = []
|
| 91 |
+
|
| 92 |
+
for f in range(total_frames):
|
| 93 |
+
if f in observed:
|
| 94 |
+
new_history.append((f, observed[f][0], float(observed[f][1])))
|
| 95 |
+
elif f < first:
|
| 96 |
+
new_history.append((f, bboxes[0].copy(), -1.0))
|
| 97 |
+
elif f > last:
|
| 98 |
+
new_history.append((f, bboxes[-1].copy(), -1.0))
|
| 99 |
+
else:
|
| 100 |
+
# Find surrounding observations
|
| 101 |
+
lo = max(fi for fi in frame_indices if fi < f)
|
| 102 |
+
hi = min(fi for fi in frame_indices if fi > f)
|
| 103 |
+
t = (f - lo) / (hi - lo)
|
| 104 |
+
bbox = observed[lo][0] * (1 - t) + observed[hi][0] * t
|
| 105 |
+
new_history.append((f, bbox, -1.0))
|
| 106 |
+
|
| 107 |
+
self.history = new_history
|
| 108 |
+
|
| 109 |
+
def _smoothed_centers(self, f_cutoff: float = 5.0, f_sample: float = 30.0) -> np.ndarray:
|
| 110 |
+
"""Bbox centers low-passed by a One Euro filter with beta=0 (plain low-pass).
|
| 111 |
+
|
| 112 |
+
f_cutoff defaults high (5 Hz at 30 fps) so only very-high-frequency noise —
|
| 113 |
+
e.g. bbox flicker from intermittent occlusion — is removed; real person
|
| 114 |
+
motion (sub-Hz) passes through.
|
| 115 |
+
"""
|
| 116 |
+
bboxes = self.get_bboxes()
|
| 117 |
+
centers = np.column_stack([
|
| 118 |
+
(bboxes[:, 0] + bboxes[:, 2]) / 2,
|
| 119 |
+
(bboxes[:, 1] + bboxes[:, 3]) / 2,
|
| 120 |
+
])
|
| 121 |
+
if centers.shape[0] < 2:
|
| 122 |
+
return centers
|
| 123 |
+
# linear_one_euro_filter expects time on the last axis -> (2, T)
|
| 124 |
+
smoothed = linear_one_euro_filter(
|
| 125 |
+
centers.T, min_f_cutoff=f_cutoff, beta=0.0, f_sample=f_sample,
|
| 126 |
+
).T
|
| 127 |
+
return smoothed
|
| 128 |
+
|
| 129 |
+
def total_motion(self) -> float:
|
| 130 |
+
"""Sum of frame-to-frame bbox center displacements (in pixels), after smoothing.
|
| 131 |
+
|
| 132 |
+
Centers are low-passed first so occlusion-induced bbox flicker doesn't inflate
|
| 133 |
+
the score. A truly stationary (but jittery) track yields ~0.
|
| 134 |
+
"""
|
| 135 |
+
if self.length < 2:
|
| 136 |
+
return 0.0
|
| 137 |
+
centers = self._smoothed_centers()
|
| 138 |
+
deltas = np.diff(centers, axis=0)
|
| 139 |
+
return float(np.sum(np.linalg.norm(deltas, axis=1)))
|
| 140 |
+
|
| 141 |
+
def trajectory_span(self) -> float:
|
| 142 |
+
"""Diagonal of the axis-aligned bbox enclosing (smoothed) bbox centers.
|
| 143 |
+
|
| 144 |
+
Unlike total_motion, this is immune to back-and-forth flicker: a track that
|
| 145 |
+
jitters in one spot has near-zero span regardless of cumulative motion.
|
| 146 |
+
"""
|
| 147 |
+
if self.length < 1:
|
| 148 |
+
return 0.0
|
| 149 |
+
centers = self._smoothed_centers()
|
| 150 |
+
return float(np.hypot(np.ptp(centers[:, 0]), np.ptp(centers[:, 1])))
|
| 151 |
+
|
| 152 |
+
|
| 153 |
+
|
| 154 |
+
def bbox_iou_matrix(boxes_a: np.ndarray, boxes_b: np.ndarray) -> np.ndarray:
|
| 155 |
+
"""Compute pairwise IoU between two sets of [x1, y1, x2, y2] boxes.
|
| 156 |
+
|
| 157 |
+
Returns shape (len(boxes_a), len(boxes_b)).
|
| 158 |
+
"""
|
| 159 |
+
x1 = np.maximum(boxes_a[:, None, 0], boxes_b[None, :, 0])
|
| 160 |
+
y1 = np.maximum(boxes_a[:, None, 1], boxes_b[None, :, 1])
|
| 161 |
+
x2 = np.minimum(boxes_a[:, None, 2], boxes_b[None, :, 2])
|
| 162 |
+
y2 = np.minimum(boxes_a[:, None, 3], boxes_b[None, :, 3])
|
| 163 |
+
|
| 164 |
+
inter = np.maximum(0, x2 - x1) * np.maximum(0, y2 - y1)
|
| 165 |
+
area_a = (boxes_a[:, 2] - boxes_a[:, 0]) * (boxes_a[:, 3] - boxes_a[:, 1])
|
| 166 |
+
area_b = (boxes_b[:, 2] - boxes_b[:, 0]) * (boxes_b[:, 3] - boxes_b[:, 1])
|
| 167 |
+
union = area_a[:, None] + area_b[None, :] - inter
|
| 168 |
+
|
| 169 |
+
return inter / (union + 1e-6)
|
| 170 |
+
|
| 171 |
+
|
| 172 |
+
def greedy_assign(
|
| 173 |
+
iou_matrix: np.ndarray, threshold: float
|
| 174 |
+
) -> tuple[list[tuple[int, int]], list[int], list[int]]:
|
| 175 |
+
"""Greedy matching by descending IoU.
|
| 176 |
+
|
| 177 |
+
Returns (matches, unmatched_track_indices, unmatched_det_indices).
|
| 178 |
+
"""
|
| 179 |
+
if iou_matrix.size == 0:
|
| 180 |
+
return (
|
| 181 |
+
[],
|
| 182 |
+
list(range(iou_matrix.shape[0])),
|
| 183 |
+
list(range(iou_matrix.shape[1])),
|
| 184 |
+
)
|
| 185 |
+
|
| 186 |
+
matches = []
|
| 187 |
+
matched_tracks = set()
|
| 188 |
+
matched_dets = set()
|
| 189 |
+
|
| 190 |
+
flat_order = np.argsort(iou_matrix.ravel())[::-1]
|
| 191 |
+
n_cols = iou_matrix.shape[1]
|
| 192 |
+
|
| 193 |
+
for idx in flat_order:
|
| 194 |
+
t = int(idx // n_cols)
|
| 195 |
+
d = int(idx % n_cols)
|
| 196 |
+
if iou_matrix[t, d] < threshold:
|
| 197 |
+
break
|
| 198 |
+
if t in matched_tracks or d in matched_dets:
|
| 199 |
+
continue
|
| 200 |
+
matches.append((t, d))
|
| 201 |
+
matched_tracks.add(t)
|
| 202 |
+
matched_dets.add(d)
|
| 203 |
+
|
| 204 |
+
unmatched_tracks = [i for i in range(iou_matrix.shape[0]) if i not in matched_tracks]
|
| 205 |
+
unmatched_dets = [i for i in range(iou_matrix.shape[1]) if i not in matched_dets]
|
| 206 |
+
return matches, unmatched_tracks, unmatched_dets
|
| 207 |
+
|
| 208 |
+
|
| 209 |
+
def hungarian_assign(
|
| 210 |
+
iou_matrix: np.ndarray, threshold: float
|
| 211 |
+
) -> tuple[list[tuple[int, int]], list[int], list[int]]:
|
| 212 |
+
"""Optimal matching via the Hungarian algorithm on an IoU cost matrix.
|
| 213 |
+
|
| 214 |
+
Returns (matches, unmatched_track_indices, unmatched_det_indices).
|
| 215 |
+
"""
|
| 216 |
+
if iou_matrix.size == 0:
|
| 217 |
+
return (
|
| 218 |
+
[],
|
| 219 |
+
list(range(iou_matrix.shape[0])),
|
| 220 |
+
list(range(iou_matrix.shape[1])),
|
| 221 |
+
)
|
| 222 |
+
|
| 223 |
+
cost = 1.0 - iou_matrix
|
| 224 |
+
row_indices, col_indices = linear_sum_assignment(cost)
|
| 225 |
+
|
| 226 |
+
matches = []
|
| 227 |
+
matched_tracks = set()
|
| 228 |
+
matched_dets = set()
|
| 229 |
+
for r, c in zip(row_indices, col_indices):
|
| 230 |
+
if iou_matrix[r, c] >= threshold:
|
| 231 |
+
matches.append((int(r), int(c)))
|
| 232 |
+
matched_tracks.add(int(r))
|
| 233 |
+
matched_dets.add(int(c))
|
| 234 |
+
|
| 235 |
+
unmatched_tracks = [i for i in range(iou_matrix.shape[0]) if i not in matched_tracks]
|
| 236 |
+
unmatched_dets = [i for i in range(iou_matrix.shape[1]) if i not in matched_dets]
|
| 237 |
+
return matches, unmatched_tracks, unmatched_dets
|
| 238 |
+
|
| 239 |
+
|
| 240 |
+
class IoUTracker:
|
| 241 |
+
"""Simple IoU-based multi-object tracker with lost-track buffer.
|
| 242 |
+
|
| 243 |
+
Args:
|
| 244 |
+
iou_threshold: Minimum IoU to match a detection to a track.
|
| 245 |
+
max_lost: Frames a track survives without a match before removal.
|
| 246 |
+
"""
|
| 247 |
+
|
| 248 |
+
def __init__(
|
| 249 |
+
self,
|
| 250 |
+
iou_threshold: float = 0.3,
|
| 251 |
+
max_lost: int = 30,
|
| 252 |
+
min_hits: int = 3,
|
| 253 |
+
):
|
| 254 |
+
self.iou_threshold = iou_threshold
|
| 255 |
+
self.max_lost = max_lost
|
| 256 |
+
self.min_hits = min_hits
|
| 257 |
+
self._next_id = 0
|
| 258 |
+
self.active_tracks: list[Track] = []
|
| 259 |
+
self.lost_tracks: list[Track] = []
|
| 260 |
+
self.tentative_tracks: list[Track] = []
|
| 261 |
+
self.finished_tracks: list[Track] = []
|
| 262 |
+
|
| 263 |
+
def _new_track(self, frame_idx: int, bbox: np.ndarray, score: float) -> Track:
|
| 264 |
+
track = Track(track_id=self._next_id, state=TrackState.TENTATIVE)
|
| 265 |
+
track.append(frame_idx, bbox, score)
|
| 266 |
+
self._next_id += 1
|
| 267 |
+
return track
|
| 268 |
+
|
| 269 |
+
def update(self, frame_idx: int, bboxes: np.ndarray, scores: np.ndarray):
|
| 270 |
+
"""Process one frame of detections.
|
| 271 |
+
|
| 272 |
+
Two-stage matching:
|
| 273 |
+
1. Match detections against active + lost tracks (established tracks
|
| 274 |
+
get priority).
|
| 275 |
+
2. Match remaining detections against tentative tracks.
|
| 276 |
+
Unmatched detections from stage 2 create new tentative tracks.
|
| 277 |
+
Tentative tracks that reach *min_hits* consecutive matches are promoted
|
| 278 |
+
to active.
|
| 279 |
+
|
| 280 |
+
Args:
|
| 281 |
+
frame_idx: Current frame number.
|
| 282 |
+
bboxes: (M, 4) array of [x1, y1, x2, y2] detections.
|
| 283 |
+
scores: (M,) confidence scores.
|
| 284 |
+
"""
|
| 285 |
+
# Stage 1: match against established (active + lost) tracks
|
| 286 |
+
established = self.active_tracks + self.lost_tracks
|
| 287 |
+
|
| 288 |
+
if len(established) > 0 and len(bboxes) > 0:
|
| 289 |
+
track_boxes = np.array([t.last_bbox for t in established])
|
| 290 |
+
iou = bbox_iou_matrix(track_boxes, bboxes)
|
| 291 |
+
matches_1, unmatched_t_1, unmatched_d_1 = greedy_assign(iou, self.iou_threshold)
|
| 292 |
+
elif len(established) > 0:
|
| 293 |
+
matches_1, unmatched_t_1, unmatched_d_1 = [], list(range(len(established))), []
|
| 294 |
+
else:
|
| 295 |
+
matches_1, unmatched_t_1, unmatched_d_1 = [], [], list(range(len(bboxes)))
|
| 296 |
+
|
| 297 |
+
new_active = []
|
| 298 |
+
new_lost = []
|
| 299 |
+
|
| 300 |
+
for t_idx, d_idx in matches_1:
|
| 301 |
+
track = established[t_idx]
|
| 302 |
+
track.append(frame_idx, bboxes[d_idx], scores[d_idx])
|
| 303 |
+
new_active.append(track)
|
| 304 |
+
|
| 305 |
+
for t_idx in unmatched_t_1:
|
| 306 |
+
track = established[t_idx]
|
| 307 |
+
track.frames_since_match += 1
|
| 308 |
+
if track.frames_since_match > self.max_lost:
|
| 309 |
+
track.state = TrackState.FINISHED
|
| 310 |
+
self.finished_tracks.append(track)
|
| 311 |
+
else:
|
| 312 |
+
track.state = TrackState.LOST
|
| 313 |
+
new_lost.append(track)
|
| 314 |
+
|
| 315 |
+
# Stage 2: match remaining detections against tentative tracks
|
| 316 |
+
remaining_bboxes = bboxes[unmatched_d_1] if len(unmatched_d_1) > 0 else np.empty((0, 4))
|
| 317 |
+
remaining_scores = scores[unmatched_d_1] if len(unmatched_d_1) > 0 else np.empty(0)
|
| 318 |
+
|
| 319 |
+
new_tentative = []
|
| 320 |
+
|
| 321 |
+
if len(self.tentative_tracks) > 0 and len(remaining_bboxes) > 0:
|
| 322 |
+
tent_boxes = np.array([t.last_bbox for t in self.tentative_tracks])
|
| 323 |
+
iou_2 = bbox_iou_matrix(tent_boxes, remaining_bboxes)
|
| 324 |
+
matches_2, unmatched_t_2, unmatched_d_2 = greedy_assign(iou_2, self.iou_threshold)
|
| 325 |
+
elif len(self.tentative_tracks) > 0:
|
| 326 |
+
matches_2, unmatched_t_2, unmatched_d_2 = [], list(range(len(self.tentative_tracks))), []
|
| 327 |
+
else:
|
| 328 |
+
matches_2, unmatched_t_2, unmatched_d_2 = [], [], list(range(len(remaining_bboxes)))
|
| 329 |
+
|
| 330 |
+
for t_idx, d_idx in matches_2:
|
| 331 |
+
track = self.tentative_tracks[t_idx]
|
| 332 |
+
track.append(frame_idx, remaining_bboxes[d_idx], float(remaining_scores[d_idx]))
|
| 333 |
+
if track.length >= self.min_hits:
|
| 334 |
+
track.state = TrackState.ACTIVE
|
| 335 |
+
new_active.append(track)
|
| 336 |
+
else:
|
| 337 |
+
new_tentative.append(track)
|
| 338 |
+
|
| 339 |
+
# Unmatched tentative tracks are dropped immediately
|
| 340 |
+
for t_idx in unmatched_t_2:
|
| 341 |
+
track = self.tentative_tracks[t_idx]
|
| 342 |
+
track.state = TrackState.FINISHED
|
| 343 |
+
self.finished_tracks.append(track)
|
| 344 |
+
|
| 345 |
+
# Unmatched detections start new tentative tracks
|
| 346 |
+
for d_idx in unmatched_d_2:
|
| 347 |
+
new_tentative.append(
|
| 348 |
+
self._new_track(frame_idx, remaining_bboxes[d_idx], float(remaining_scores[d_idx]))
|
| 349 |
+
)
|
| 350 |
+
|
| 351 |
+
self.active_tracks = new_active
|
| 352 |
+
self.lost_tracks = new_lost
|
| 353 |
+
self.tentative_tracks = new_tentative
|
| 354 |
+
|
| 355 |
+
def finalize(self) -> list[Track]:
|
| 356 |
+
"""Return all tracks (active + lost + tentative + finished), sorted by track_id."""
|
| 357 |
+
all_tracks = (
|
| 358 |
+
self.finished_tracks + self.active_tracks
|
| 359 |
+
+ self.lost_tracks + self.tentative_tracks
|
| 360 |
+
)
|
| 361 |
+
all_tracks.sort(key=lambda t: t.track_id)
|
| 362 |
+
return all_tracks
|
| 363 |
+
|
| 364 |
+
@staticmethod
|
| 365 |
+
def _track_merge_score(a: Track, b: Track) -> float:
|
| 366 |
+
"""Compute merge affinity between two tracks.
|
| 367 |
+
|
| 368 |
+
For overlapping tracks: mean IoU across shared frames.
|
| 369 |
+
For non-overlapping tracks: IoU between A's last bbox and B's first bbox.
|
| 370 |
+
Returns -1 if tracks have no overlapping frames and no observations to compare.
|
| 371 |
+
"""
|
| 372 |
+
a_by_frame = {int(h[0]): h[1] for h in a.history}
|
| 373 |
+
b_by_frame = {int(h[0]): h[1] for h in b.history}
|
| 374 |
+
shared_frames = sorted(set(a_by_frame) & set(b_by_frame))
|
| 375 |
+
|
| 376 |
+
if shared_frames:
|
| 377 |
+
a_boxes = np.array([a_by_frame[f] for f in shared_frames])
|
| 378 |
+
b_boxes = np.array([b_by_frame[f] for f in shared_frames])
|
| 379 |
+
ious = bbox_iou_matrix(a_boxes, b_boxes)
|
| 380 |
+
return float(np.mean(np.diag(ious)))
|
| 381 |
+
|
| 382 |
+
return float(bbox_iou_matrix(
|
| 383 |
+
a.last_bbox.reshape(1, 4),
|
| 384 |
+
b.first_bbox.reshape(1, 4),
|
| 385 |
+
)[0, 0])
|
| 386 |
+
|
| 387 |
+
@staticmethod
|
| 388 |
+
def merge_fragmented_tracks(
|
| 389 |
+
tracks: list[Track],
|
| 390 |
+
max_gap: int = 10,
|
| 391 |
+
iou_threshold: float = 0.5,
|
| 392 |
+
) -> list[Track]:
|
| 393 |
+
"""Merge tracks that likely represent the same object across ID switches.
|
| 394 |
+
|
| 395 |
+
Two tracks are merged when:
|
| 396 |
+
- Track A ends within *max_gap* frames of track B starting (or they overlap)
|
| 397 |
+
- Their merge score (mean IoU over shared frames, or boundary IoU
|
| 398 |
+
if no overlap) >= *iou_threshold*
|
| 399 |
+
|
| 400 |
+
Merging is greedy: the best pair (highest score) is merged first, then
|
| 401 |
+
the search repeats until no more pairs qualify.
|
| 402 |
+
|
| 403 |
+
Returns a new list of tracks (merged tracks get the earlier track's ID).
|
| 404 |
+
"""
|
| 405 |
+
tracks = list(tracks)
|
| 406 |
+
changed = True
|
| 407 |
+
while changed:
|
| 408 |
+
changed = False
|
| 409 |
+
tracks.sort(key=lambda t: t.start_frame)
|
| 410 |
+
best_score = -1.0
|
| 411 |
+
best_pair = None
|
| 412 |
+
for i in range(len(tracks)):
|
| 413 |
+
for j in range(i + 1, len(tracks)):
|
| 414 |
+
a, b = tracks[i], tracks[j]
|
| 415 |
+
gap = b.start_frame - a.end_frame
|
| 416 |
+
if gap > max_gap:
|
| 417 |
+
continue
|
| 418 |
+
score = IoUTracker._track_merge_score(a, b)
|
| 419 |
+
if score >= iou_threshold and score > best_score:
|
| 420 |
+
best_score = score
|
| 421 |
+
best_pair = (i, j)
|
| 422 |
+
|
| 423 |
+
if best_pair is not None:
|
| 424 |
+
i, j = best_pair
|
| 425 |
+
a, b = tracks[i], tracks[j]
|
| 426 |
+
# For overlapping frames, keep A's observation (earlier track)
|
| 427 |
+
b_frames = {int(h[0]) for h in b.history}
|
| 428 |
+
a_frames = {int(h[0]) for h in a.history}
|
| 429 |
+
a.history.extend(h for h in b.history if int(h[0]) not in a_frames)
|
| 430 |
+
a.history.sort(key=lambda h: h[0])
|
| 431 |
+
tracks.pop(j)
|
| 432 |
+
changed = True
|
| 433 |
+
|
| 434 |
+
return tracks
|
| 435 |
+
|
| 436 |
+
@staticmethod
|
| 437 |
+
def select_primary_track(
|
| 438 |
+
tracks: list[Track],
|
| 439 |
+
image_size: tuple[int, int] | None = None,
|
| 440 |
+
method: str = "combined",
|
| 441 |
+
weights: dict[str, float] | None = None,
|
| 442 |
+
) -> Track:
|
| 443 |
+
"""Select the primary subject from a set of tracks.
|
| 444 |
+
|
| 445 |
+
Args:
|
| 446 |
+
tracks: List of completed tracks.
|
| 447 |
+
image_size: (height, width) of the frames, needed for center-based methods.
|
| 448 |
+
method:
|
| 449 |
+
"longest" — track with the most frames.
|
| 450 |
+
"center" — track whose avg bbox center is closest to image center.
|
| 451 |
+
"motion" — track with the most total bbox-center displacement.
|
| 452 |
+
"combined" — weighted sum of normalized length, center proximity,
|
| 453 |
+
motion, and trajectory span. Tune via *weights* dict.
|
| 454 |
+
weights: Weights for "combined" mode.
|
| 455 |
+
Keys: "length", "center", "motion", "span".
|
| 456 |
+
Defaults to {"length": 0.2, "center": 0.2, "motion": 0.3, "span": 0.3}.
|
| 457 |
+
"""
|
| 458 |
+
if not tracks:
|
| 459 |
+
raise ValueError("No tracks to select from")
|
| 460 |
+
|
| 461 |
+
if method == "longest":
|
| 462 |
+
return max(tracks, key=lambda t: t.length)
|
| 463 |
+
|
| 464 |
+
if method == "motion":
|
| 465 |
+
return max(tracks, key=lambda t: t.total_motion())
|
| 466 |
+
|
| 467 |
+
if method in ("center", "combined"):
|
| 468 |
+
if image_size is None:
|
| 469 |
+
raise ValueError("image_size required for center-based selection")
|
| 470 |
+
|
| 471 |
+
h, w = image_size
|
| 472 |
+
img_cx, img_cy = w / 2, h / 2
|
| 473 |
+
|
| 474 |
+
def center_dist(t: Track) -> float:
|
| 475 |
+
bboxes = t.get_bboxes()
|
| 476 |
+
cx = (bboxes[:, 0] + bboxes[:, 2]) / 2
|
| 477 |
+
cy = (bboxes[:, 1] + bboxes[:, 3]) / 2
|
| 478 |
+
return float(np.mean(np.sqrt((cx - img_cx) ** 2 + (cy - img_cy) ** 2)))
|
| 479 |
+
|
| 480 |
+
if method == "center":
|
| 481 |
+
return min(tracks, key=center_dist)
|
| 482 |
+
|
| 483 |
+
if method == "combined":
|
| 484 |
+
w_cfg = weights or {"length": 0.2, "center": 0.2, "motion": 0.3, "span": 0.3}
|
| 485 |
+
|
| 486 |
+
lengths = np.array([t.length for t in tracks], dtype=float)
|
| 487 |
+
dists = np.array([center_dist(t) for t in tracks], dtype=float)
|
| 488 |
+
motions = np.array([t.total_motion() for t in tracks], dtype=float)
|
| 489 |
+
spans = np.array([t.trajectory_span() for t in tracks], dtype=float)
|
| 490 |
+
|
| 491 |
+
def normalize(a: np.ndarray) -> np.ndarray:
|
| 492 |
+
r = a.max() - a.min()
|
| 493 |
+
return (a - a.min()) / r if r > 0 else np.zeros_like(a)
|
| 494 |
+
|
| 495 |
+
scores = (
|
| 496 |
+
w_cfg.get("length", 0) * normalize(lengths)
|
| 497 |
+
+ w_cfg.get("center", 0) * (1.0 - normalize(dists))
|
| 498 |
+
+ w_cfg.get("motion", 0) * normalize(motions)
|
| 499 |
+
+ w_cfg.get("span", 0) * normalize(spans)
|
| 500 |
+
)
|
| 501 |
+
return tracks[int(np.argmax(scores))]
|
| 502 |
+
|
| 503 |
+
raise ValueError(f"Unknown selection method: {method}")
|
third-party/video_to_data/reconstruction/modules/v2d_docker/LICENSE
ADDED
|
@@ -0,0 +1,15 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Apache License 2.0
|
| 2 |
+
|
| 3 |
+
Copyright 2025 NVIDIA CORPORATION
|
| 4 |
+
|
| 5 |
+
Licensed under the Apache License, Version 2.0 (the "License");
|
| 6 |
+
you may not use this file except in compliance with the License.
|
| 7 |
+
You may obtain a copy of the License at
|
| 8 |
+
|
| 9 |
+
http://www.apache.org/licenses/LICENSE-2.0
|
| 10 |
+
|
| 11 |
+
Unless required by applicable law or agreed to in writing, software
|
| 12 |
+
distributed under the License is distributed on an "AS IS" BASIS,
|
| 13 |
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 14 |
+
See the License for the specific language governing permissions and
|
| 15 |
+
limitations under the License.
|
third-party/video_to_data/reconstruction/modules/v2d_docker/__init__.py
ADDED
|
@@ -0,0 +1,5 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
|
| 2 |
+
# SPDX-License-Identifier: Apache-2.0
|
| 3 |
+
from v2d.docker.container import run_in_container
|
| 4 |
+
|
| 5 |
+
__all__ = ["run_in_container"]
|
third-party/video_to_data/reconstruction/modules/v2d_docker/container.py
ADDED
|
@@ -0,0 +1,103 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
|
| 2 |
+
# SPDX-License-Identifier: Apache-2.0
|
| 3 |
+
import os
|
| 4 |
+
import subprocess
|
| 5 |
+
from pathlib import Path
|
| 6 |
+
|
| 7 |
+
|
| 8 |
+
def _base_dir(path: str) -> str:
|
| 9 |
+
"""
|
| 10 |
+
Return the deepest directory component of path that contains no glob characters.
|
| 11 |
+
For plain paths this equals dirname(path). For paths like /out/*/*.glb it
|
| 12 |
+
returns /out, so the container mount covers the full glob subtree.
|
| 13 |
+
"""
|
| 14 |
+
parts = Path(path).parts
|
| 15 |
+
clean = []
|
| 16 |
+
for part in parts[:-1]: # skip the filename/last component
|
| 17 |
+
if '*' in part or '?' in part:
|
| 18 |
+
break
|
| 19 |
+
clean.append(part)
|
| 20 |
+
return str(Path(*clean)) if clean else str(Path(path).parent)
|
| 21 |
+
|
| 22 |
+
|
| 23 |
+
def run_in_container(
|
| 24 |
+
image: str,
|
| 25 |
+
module: str,
|
| 26 |
+
inputs: dict[str, str],
|
| 27 |
+
outputs: dict[str, str],
|
| 28 |
+
extra_args: dict[str, object] | None = None,
|
| 29 |
+
dev: bool = False,
|
| 30 |
+
modules_dir: str | None = None,
|
| 31 |
+
gpus: bool = False,
|
| 32 |
+
env: dict[str, str] | None = None,
|
| 33 |
+
extra_volumes: list[str] | None = None,
|
| 34 |
+
) -> None:
|
| 35 |
+
"""
|
| 36 |
+
Run a Python module inside a Docker container with file arguments.
|
| 37 |
+
|
| 38 |
+
inputs: arg_name → host_path (read file mounts; None values are skipped)
|
| 39 |
+
outputs: arg_name → host_path (write file mounts; parent dirs created; None skipped)
|
| 40 |
+
extra_args: arg_name → value (non-path CLI args)
|
| 41 |
+
None or False → omit entirely
|
| 42 |
+
True → add as a bare flag (--arg_name, no value)
|
| 43 |
+
other → add as --arg_name str(value)
|
| 44 |
+
env: extra environment variables passed via -e
|
| 45 |
+
extra_volumes: raw -v arguments appended after all other mounts (e.g.
|
| 46 |
+
anonymous volumes to preserve image-built artifacts under a dev mount)
|
| 47 |
+
|
| 48 |
+
Each unique host directory gets one volume mount at /data/<arg_name>, where the
|
| 49 |
+
arg_name is taken from the first argument that references that directory. Subsequent
|
| 50 |
+
arguments in the same directory reuse the same mount.
|
| 51 |
+
"""
|
| 52 |
+
inputs = {k: os.path.abspath(v) for k, v in inputs.items() if v is not None}
|
| 53 |
+
outputs = {k: os.path.abspath(v) for k, v in outputs.items() if v is not None}
|
| 54 |
+
|
| 55 |
+
for path in outputs.values():
|
| 56 |
+
os.makedirs(_base_dir(path), exist_ok=True)
|
| 57 |
+
|
| 58 |
+
# Map each unique host directory to a container mount point.
|
| 59 |
+
# First arg to reference a directory claims the mount name.
|
| 60 |
+
dir_to_mount: dict[str, str] = {}
|
| 61 |
+
for arg_name, path in {**inputs, **outputs}.items():
|
| 62 |
+
host_dir = _base_dir(path)
|
| 63 |
+
if host_dir not in dir_to_mount:
|
| 64 |
+
dir_to_mount[host_dir] = f"/data/{arg_name}"
|
| 65 |
+
|
| 66 |
+
cmd = ["docker", "run", "--rm"]
|
| 67 |
+
if gpus:
|
| 68 |
+
cmd += ["--runtime=nvidia", "--gpus", "all"]
|
| 69 |
+
cmd += [
|
| 70 |
+
"--user", f"{os.getuid()}:{os.getgid()}",
|
| 71 |
+
"-e", "HOME=/tmp",
|
| 72 |
+
]
|
| 73 |
+
if env:
|
| 74 |
+
for key, value in env.items():
|
| 75 |
+
cmd += ["-e", f"{key}={value}"]
|
| 76 |
+
for host_dir, container_dir in dir_to_mount.items():
|
| 77 |
+
cmd += ["-v", f"{host_dir}:{container_dir}"]
|
| 78 |
+
if dev:
|
| 79 |
+
if modules_dir is None:
|
| 80 |
+
raise ValueError("modules_dir must be provided when dev=True")
|
| 81 |
+
cmd += ["-v", f"{modules_dir}:/workspace"]
|
| 82 |
+
if extra_volumes:
|
| 83 |
+
for vol in extra_volumes:
|
| 84 |
+
cmd += ["-v", vol]
|
| 85 |
+
|
| 86 |
+
cmd += [image, "python", "-m", module]
|
| 87 |
+
|
| 88 |
+
for arg_name, path in {**inputs, **outputs}.items():
|
| 89 |
+
host_dir = _base_dir(path)
|
| 90 |
+
rel = os.path.relpath(path, host_dir)
|
| 91 |
+
container_path = f"{dir_to_mount[host_dir]}/{rel}"
|
| 92 |
+
cmd += [f"--{arg_name}", container_path]
|
| 93 |
+
|
| 94 |
+
if extra_args:
|
| 95 |
+
for arg_name, value in extra_args.items():
|
| 96 |
+
if value is None or value is False:
|
| 97 |
+
pass
|
| 98 |
+
elif value is True:
|
| 99 |
+
cmd += [f"--{arg_name}"]
|
| 100 |
+
else:
|
| 101 |
+
cmd += [f"--{arg_name}", str(value)]
|
| 102 |
+
|
| 103 |
+
subprocess.run(cmd, check=True)
|
third-party/video_to_data/reconstruction/modules/v2d_docker/pyproject.toml
ADDED
|
@@ -0,0 +1,18 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
|
| 2 |
+
# SPDX-License-Identifier: Apache-2.0
|
| 3 |
+
[build-system]
|
| 4 |
+
requires = ["setuptools>=68.0", "wheel"]
|
| 5 |
+
build-backend = "setuptools.build_meta"
|
| 6 |
+
|
| 7 |
+
[project]
|
| 8 |
+
name = "v2d-docker"
|
| 9 |
+
version = "0.1.0"
|
| 10 |
+
description = "Shared Docker container orchestration utilities for v2d modules"
|
| 11 |
+
requires-python = ">=3.10"
|
| 12 |
+
dependencies = []
|
| 13 |
+
|
| 14 |
+
[tool.setuptools]
|
| 15 |
+
packages = ["v2d.docker"]
|
| 16 |
+
|
| 17 |
+
[tool.setuptools.package-dir]
|
| 18 |
+
"v2d.docker" = "."
|
third-party/video_to_data/reconstruction/modules/v2d_droid_slam/LICENSE
ADDED
|
@@ -0,0 +1,15 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Apache License 2.0
|
| 2 |
+
|
| 3 |
+
Copyright 2025 NVIDIA CORPORATION
|
| 4 |
+
|
| 5 |
+
Licensed under the Apache License, Version 2.0 (the "License");
|
| 6 |
+
you may not use this file except in compliance with the License.
|
| 7 |
+
You may obtain a copy of the License at
|
| 8 |
+
|
| 9 |
+
http://www.apache.org/licenses/LICENSE-2.0
|
| 10 |
+
|
| 11 |
+
Unless required by applicable law or agreed to in writing, software
|
| 12 |
+
distributed under the License is distributed on an "AS IS" BASIS,
|
| 13 |
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 14 |
+
See the License for the specific language governing permissions and
|
| 15 |
+
limitations under the License.
|
third-party/video_to_data/reconstruction/modules/v2d_droid_slam/docker/Dockerfile
ADDED
|
@@ -0,0 +1,43 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
FROM pytorch/pytorch:2.5.1-cuda12.4-cudnn9-devel
|
| 2 |
+
ENV DEBIAN_FRONTEND=noninteractive
|
| 3 |
+
WORKDIR /app
|
| 4 |
+
|
| 5 |
+
RUN apt-get update && apt-get install -y \
|
| 6 |
+
git \
|
| 7 |
+
wget \
|
| 8 |
+
libgl1 \
|
| 9 |
+
libglib2.0-0 \
|
| 10 |
+
build-essential \
|
| 11 |
+
cmake \
|
| 12 |
+
ninja-build \
|
| 13 |
+
libeigen3-dev \
|
| 14 |
+
&& rm -rf /var/lib/apt/lists/*
|
| 15 |
+
|
| 16 |
+
RUN pip install --no-cache-dir \
|
| 17 |
+
numpy \
|
| 18 |
+
scipy \
|
| 19 |
+
opencv-python \
|
| 20 |
+
Pillow \
|
| 21 |
+
pyyaml \
|
| 22 |
+
tqdm \
|
| 23 |
+
matplotlib \
|
| 24 |
+
einops \
|
| 25 |
+
evo \
|
| 26 |
+
gdown \
|
| 27 |
+
open3d
|
| 28 |
+
|
| 29 |
+
RUN pip install --no-cache-dir torch-scatter -f https://data.pyg.org/whl/torch-2.5.1+cu124.html
|
| 30 |
+
|
| 31 |
+
RUN git clone --recursive https://github.com/princeton-vl/DROID-SLAM.git /opt/droid-slam
|
| 32 |
+
|
| 33 |
+
RUN cd /opt/droid-slam/thirdparty/lietorch && \
|
| 34 |
+
TORCH_CUDA_ARCH_LIST="8.0 8.6 8.9 9.0" pip install --no-build-isolation -e .
|
| 35 |
+
|
| 36 |
+
RUN cd /opt/droid-slam && \
|
| 37 |
+
TORCH_CUDA_ARCH_LIST="8.0 8.6 8.9 9.0" pip install --no-build-isolation -e .
|
| 38 |
+
|
| 39 |
+
ENV PYTHONPATH=/opt/droid-slam:/opt/droid-slam/droid_slam:${PYTHONPATH}
|
| 40 |
+
|
| 41 |
+
COPY . /workspace
|
| 42 |
+
|
| 43 |
+
RUN pip install -e /workspace/v2d_common -e /workspace/v2d_droid_slam/lib
|
third-party/video_to_data/reconstruction/modules/v2d_droid_slam/docker/__init__.py
ADDED
|
@@ -0,0 +1,2 @@
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
|
| 2 |
+
# SPDX-License-Identifier: Apache-2.0
|
third-party/video_to_data/reconstruction/modules/v2d_droid_slam/docker/_config.py
ADDED
|
@@ -0,0 +1,6 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
|
| 2 |
+
# SPDX-License-Identifier: Apache-2.0
|
| 3 |
+
import os
|
| 4 |
+
|
| 5 |
+
IMAGE_NAME = "v2d_droid_slam"
|
| 6 |
+
MODULES_DIR = os.path.abspath(os.path.join(os.path.dirname(os.path.abspath(__file__)), "..", ".."))
|
third-party/video_to_data/reconstruction/modules/v2d_droid_slam/docker/build.py
ADDED
|
@@ -0,0 +1,19 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
|
| 2 |
+
# SPDX-License-Identifier: Apache-2.0
|
| 3 |
+
import os
|
| 4 |
+
import subprocess
|
| 5 |
+
|
| 6 |
+
IMAGE_NAME = "v2d_droid_slam"
|
| 7 |
+
|
| 8 |
+
current_dir = os.path.dirname(os.path.abspath(__file__))
|
| 9 |
+
module_dir = os.path.join(current_dir, "..")
|
| 10 |
+
root_dir = os.path.join(module_dir, "..")
|
| 11 |
+
dockerfile_path = os.path.join(current_dir, "Dockerfile")
|
| 12 |
+
|
| 13 |
+
|
| 14 |
+
def build_docker_image() -> None:
|
| 15 |
+
subprocess.run(["docker", "build", "-t", IMAGE_NAME, "-f", dockerfile_path, root_dir], check=True)
|
| 16 |
+
|
| 17 |
+
|
| 18 |
+
if __name__ == "__main__":
|
| 19 |
+
build_docker_image()
|
third-party/video_to_data/reconstruction/modules/v2d_droid_slam/docker/pyproject.toml
ADDED
|
@@ -0,0 +1,18 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
|
| 2 |
+
# SPDX-License-Identifier: Apache-2.0
|
| 3 |
+
[build-system]
|
| 4 |
+
requires = ["setuptools>=68.0", "wheel"]
|
| 5 |
+
build-backend = "setuptools.build_meta"
|
| 6 |
+
|
| 7 |
+
[project]
|
| 8 |
+
name = "v2d-droid-slam-docker"
|
| 9 |
+
version = "0.1.0"
|
| 10 |
+
description = "Docker orchestration scripts for DROID-SLAM"
|
| 11 |
+
requires-python = ">=3.10"
|
| 12 |
+
dependencies = ["v2d-docker"]
|
| 13 |
+
|
| 14 |
+
[tool.setuptools]
|
| 15 |
+
packages = ["v2d.droid_slam.docker"]
|
| 16 |
+
|
| 17 |
+
[tool.setuptools.package-dir]
|
| 18 |
+
"v2d.droid_slam.docker" = "."
|
third-party/video_to_data/reconstruction/modules/v2d_droid_slam/docker/run_download_weights.py
ADDED
|
@@ -0,0 +1,36 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
|
| 2 |
+
# SPDX-License-Identifier: Apache-2.0
|
| 3 |
+
import os
|
| 4 |
+
import subprocess
|
| 5 |
+
|
| 6 |
+
from v2d.droid_slam.docker._config import IMAGE_NAME, MODULES_DIR
|
| 7 |
+
|
| 8 |
+
|
| 9 |
+
def run_download(output_dir: str, dev: bool = False) -> None:
|
| 10 |
+
os.makedirs(output_dir, exist_ok=True)
|
| 11 |
+
output_dir = os.path.abspath(output_dir)
|
| 12 |
+
|
| 13 |
+
cmd = [
|
| 14 |
+
"docker", "run", "--rm",
|
| 15 |
+
"--user", f"{os.getuid()}:{os.getgid()}",
|
| 16 |
+
"-e", "HOME=/tmp",
|
| 17 |
+
"-v", f"{output_dir}:/data/weights",
|
| 18 |
+
]
|
| 19 |
+
if dev:
|
| 20 |
+
cmd += ["-v", f"{MODULES_DIR}:/workspace"]
|
| 21 |
+
cmd += [
|
| 22 |
+
IMAGE_NAME,
|
| 23 |
+
"python", "-m", "v2d.droid_slam.lib.download_weights",
|
| 24 |
+
"--output_dir", "/data/weights",
|
| 25 |
+
]
|
| 26 |
+
subprocess.run(cmd, check=True)
|
| 27 |
+
|
| 28 |
+
|
| 29 |
+
if __name__ == "__main__":
|
| 30 |
+
import argparse
|
| 31 |
+
|
| 32 |
+
parser = argparse.ArgumentParser(description="Download DROID-SLAM checkpoint")
|
| 33 |
+
parser.add_argument("--output_dir", type=str, required=True)
|
| 34 |
+
parser.add_argument("--dev", action="store_true")
|
| 35 |
+
args = parser.parse_args()
|
| 36 |
+
run_download(output_dir=args.output_dir, dev=args.dev)
|
third-party/video_to_data/reconstruction/modules/v2d_droid_slam/docker/run_image_list_to_slam.py
ADDED
|
@@ -0,0 +1,152 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
|
| 2 |
+
# SPDX-License-Identifier: Apache-2.0
|
| 3 |
+
from v2d.docker.container import run_in_container
|
| 4 |
+
from v2d.droid_slam.docker._config import IMAGE_NAME, MODULES_DIR
|
| 5 |
+
|
| 6 |
+
|
| 7 |
+
def run_image_list_to_slam(
|
| 8 |
+
image_folder: str,
|
| 9 |
+
poses_folder: str,
|
| 10 |
+
weights_path: str,
|
| 11 |
+
input_intrinsics_path: str = None,
|
| 12 |
+
input_intrinsics_folder: str = None,
|
| 13 |
+
input_depth_folder: str = None,
|
| 14 |
+
align_to_depth_folder: str = None,
|
| 15 |
+
depth_folder: str = None,
|
| 16 |
+
pointcloud_path: str = None,
|
| 17 |
+
trajectory_path: str = None,
|
| 18 |
+
stride: int = 1,
|
| 19 |
+
image_height: int = 384,
|
| 20 |
+
image_width: int = 512,
|
| 21 |
+
buffer_size: int = 512,
|
| 22 |
+
beta: float = 0.3,
|
| 23 |
+
filter_thresh: float = 2.4,
|
| 24 |
+
warmup: int = 8,
|
| 25 |
+
keyframe_thresh: float = 4.0,
|
| 26 |
+
frontend_thresh: float = 16.0,
|
| 27 |
+
frontend_window: int = 25,
|
| 28 |
+
frontend_radius: int = 2,
|
| 29 |
+
frontend_nms: int = 1,
|
| 30 |
+
backend_thresh: float = 22.0,
|
| 31 |
+
backend_radius: int = 2,
|
| 32 |
+
backend_nms: int = 3,
|
| 33 |
+
upsample: bool = False,
|
| 34 |
+
pointcloud_min_views: int = 2,
|
| 35 |
+
dev: bool = False,
|
| 36 |
+
) -> None:
|
| 37 |
+
inputs = {"image_folder": image_folder, "weights_path": weights_path}
|
| 38 |
+
if input_intrinsics_path is not None:
|
| 39 |
+
inputs["input_intrinsics_path"] = input_intrinsics_path
|
| 40 |
+
if input_intrinsics_folder is not None:
|
| 41 |
+
inputs["input_intrinsics_folder"] = input_intrinsics_folder
|
| 42 |
+
if input_depth_folder is not None:
|
| 43 |
+
inputs["input_depth_folder"] = input_depth_folder
|
| 44 |
+
if align_to_depth_folder is not None:
|
| 45 |
+
inputs["align_to_depth_folder"] = align_to_depth_folder
|
| 46 |
+
|
| 47 |
+
outputs = {"poses_folder": poses_folder}
|
| 48 |
+
if depth_folder is not None:
|
| 49 |
+
outputs["depth_folder"] = depth_folder
|
| 50 |
+
if pointcloud_path is not None:
|
| 51 |
+
outputs["pointcloud_path"] = pointcloud_path
|
| 52 |
+
if trajectory_path is not None:
|
| 53 |
+
outputs["trajectory_path"] = trajectory_path
|
| 54 |
+
|
| 55 |
+
extra_args = {
|
| 56 |
+
"stride": stride,
|
| 57 |
+
"image_height": image_height,
|
| 58 |
+
"image_width": image_width,
|
| 59 |
+
"buffer_size": buffer_size,
|
| 60 |
+
"beta": beta,
|
| 61 |
+
"filter_thresh": filter_thresh,
|
| 62 |
+
"warmup": warmup,
|
| 63 |
+
"keyframe_thresh": keyframe_thresh,
|
| 64 |
+
"frontend_thresh": frontend_thresh,
|
| 65 |
+
"frontend_window": frontend_window,
|
| 66 |
+
"frontend_radius": frontend_radius,
|
| 67 |
+
"frontend_nms": frontend_nms,
|
| 68 |
+
"backend_thresh": backend_thresh,
|
| 69 |
+
"backend_radius": backend_radius,
|
| 70 |
+
"backend_nms": backend_nms,
|
| 71 |
+
"upsample": upsample,
|
| 72 |
+
"pointcloud_min_views": pointcloud_min_views,
|
| 73 |
+
}
|
| 74 |
+
|
| 75 |
+
run_in_container(
|
| 76 |
+
image=IMAGE_NAME,
|
| 77 |
+
module="v2d.droid_slam.lib.image_list_to_slam",
|
| 78 |
+
inputs=inputs,
|
| 79 |
+
outputs=outputs,
|
| 80 |
+
extra_args=extra_args,
|
| 81 |
+
dev=dev,
|
| 82 |
+
modules_dir=MODULES_DIR,
|
| 83 |
+
gpus=True,
|
| 84 |
+
)
|
| 85 |
+
|
| 86 |
+
|
| 87 |
+
if __name__ == "__main__":
|
| 88 |
+
import argparse
|
| 89 |
+
|
| 90 |
+
parser = argparse.ArgumentParser(description="Run DROID-SLAM on a folder of frames")
|
| 91 |
+
parser.add_argument("--image_folder", required=True)
|
| 92 |
+
parser.add_argument("--poses_folder", required=True)
|
| 93 |
+
parser.add_argument("--weights_path", required=True)
|
| 94 |
+
parser.add_argument("--input_intrinsics_path", default=None)
|
| 95 |
+
parser.add_argument("--input_intrinsics_folder", default=None)
|
| 96 |
+
parser.add_argument("--input_depth_folder", default=None,
|
| 97 |
+
help="Per-frame metric depth fed into BA as a sensor prior.")
|
| 98 |
+
parser.add_argument("--align_to_depth_folder", default=None,
|
| 99 |
+
help="Per-frame metric depth used post-hoc for scale alignment only.")
|
| 100 |
+
parser.add_argument("--depth_folder", default=None)
|
| 101 |
+
parser.add_argument("--pointcloud_path", default=None)
|
| 102 |
+
parser.add_argument("--trajectory_path", default=None)
|
| 103 |
+
parser.add_argument("--stride", type=int, default=1)
|
| 104 |
+
parser.add_argument("--image_height", type=int, default=384)
|
| 105 |
+
parser.add_argument("--image_width", type=int, default=512)
|
| 106 |
+
parser.add_argument("--buffer_size", type=int, default=512)
|
| 107 |
+
parser.add_argument("--beta", type=float, default=0.3)
|
| 108 |
+
parser.add_argument("--filter_thresh", type=float, default=2.4)
|
| 109 |
+
parser.add_argument("--warmup", type=int, default=8)
|
| 110 |
+
parser.add_argument("--keyframe_thresh", type=float, default=4.0)
|
| 111 |
+
parser.add_argument("--frontend_thresh", type=float, default=16.0)
|
| 112 |
+
parser.add_argument("--frontend_window", type=int, default=25)
|
| 113 |
+
parser.add_argument("--frontend_radius", type=int, default=2)
|
| 114 |
+
parser.add_argument("--frontend_nms", type=int, default=1)
|
| 115 |
+
parser.add_argument("--backend_thresh", type=float, default=22.0)
|
| 116 |
+
parser.add_argument("--backend_radius", type=int, default=2)
|
| 117 |
+
parser.add_argument("--backend_nms", type=int, default=3)
|
| 118 |
+
parser.add_argument("--upsample", action="store_true")
|
| 119 |
+
parser.add_argument("--pointcloud_min_views", type=int, default=2)
|
| 120 |
+
parser.add_argument("--dev", action="store_true")
|
| 121 |
+
args = parser.parse_args()
|
| 122 |
+
|
| 123 |
+
run_image_list_to_slam(
|
| 124 |
+
image_folder=args.image_folder,
|
| 125 |
+
poses_folder=args.poses_folder,
|
| 126 |
+
weights_path=args.weights_path,
|
| 127 |
+
input_intrinsics_path=args.input_intrinsics_path,
|
| 128 |
+
input_intrinsics_folder=args.input_intrinsics_folder,
|
| 129 |
+
input_depth_folder=args.input_depth_folder,
|
| 130 |
+
align_to_depth_folder=args.align_to_depth_folder,
|
| 131 |
+
depth_folder=args.depth_folder,
|
| 132 |
+
pointcloud_path=args.pointcloud_path,
|
| 133 |
+
trajectory_path=args.trajectory_path,
|
| 134 |
+
stride=args.stride,
|
| 135 |
+
image_height=args.image_height,
|
| 136 |
+
image_width=args.image_width,
|
| 137 |
+
buffer_size=args.buffer_size,
|
| 138 |
+
beta=args.beta,
|
| 139 |
+
filter_thresh=args.filter_thresh,
|
| 140 |
+
warmup=args.warmup,
|
| 141 |
+
keyframe_thresh=args.keyframe_thresh,
|
| 142 |
+
frontend_thresh=args.frontend_thresh,
|
| 143 |
+
frontend_window=args.frontend_window,
|
| 144 |
+
frontend_radius=args.frontend_radius,
|
| 145 |
+
frontend_nms=args.frontend_nms,
|
| 146 |
+
backend_thresh=args.backend_thresh,
|
| 147 |
+
backend_radius=args.backend_radius,
|
| 148 |
+
backend_nms=args.backend_nms,
|
| 149 |
+
upsample=args.upsample,
|
| 150 |
+
pointcloud_min_views=args.pointcloud_min_views,
|
| 151 |
+
dev=args.dev,
|
| 152 |
+
)
|
third-party/video_to_data/reconstruction/modules/v2d_droid_slam/docker/run_video_to_slam.py
ADDED
|
@@ -0,0 +1,152 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
|
| 2 |
+
# SPDX-License-Identifier: Apache-2.0
|
| 3 |
+
from v2d.docker.container import run_in_container
|
| 4 |
+
from v2d.droid_slam.docker._config import IMAGE_NAME, MODULES_DIR
|
| 5 |
+
|
| 6 |
+
|
| 7 |
+
def run_video_to_slam(
|
| 8 |
+
video_path: str,
|
| 9 |
+
poses_folder: str,
|
| 10 |
+
weights_path: str,
|
| 11 |
+
input_intrinsics_path: str = None,
|
| 12 |
+
input_intrinsics_folder: str = None,
|
| 13 |
+
input_depth_folder: str = None,
|
| 14 |
+
align_to_depth_folder: str = None,
|
| 15 |
+
depth_folder: str = None,
|
| 16 |
+
pointcloud_path: str = None,
|
| 17 |
+
trajectory_path: str = None,
|
| 18 |
+
stride: int = 1,
|
| 19 |
+
image_height: int = 384,
|
| 20 |
+
image_width: int = 512,
|
| 21 |
+
buffer_size: int = 512,
|
| 22 |
+
beta: float = 0.3,
|
| 23 |
+
filter_thresh: float = 2.4,
|
| 24 |
+
warmup: int = 8,
|
| 25 |
+
keyframe_thresh: float = 4.0,
|
| 26 |
+
frontend_thresh: float = 16.0,
|
| 27 |
+
frontend_window: int = 25,
|
| 28 |
+
frontend_radius: int = 2,
|
| 29 |
+
frontend_nms: int = 1,
|
| 30 |
+
backend_thresh: float = 22.0,
|
| 31 |
+
backend_radius: int = 2,
|
| 32 |
+
backend_nms: int = 3,
|
| 33 |
+
upsample: bool = False,
|
| 34 |
+
pointcloud_min_views: int = 2,
|
| 35 |
+
dev: bool = False,
|
| 36 |
+
) -> None:
|
| 37 |
+
inputs = {"video_path": video_path, "weights_path": weights_path}
|
| 38 |
+
if input_intrinsics_path is not None:
|
| 39 |
+
inputs["input_intrinsics_path"] = input_intrinsics_path
|
| 40 |
+
if input_intrinsics_folder is not None:
|
| 41 |
+
inputs["input_intrinsics_folder"] = input_intrinsics_folder
|
| 42 |
+
if input_depth_folder is not None:
|
| 43 |
+
inputs["input_depth_folder"] = input_depth_folder
|
| 44 |
+
if align_to_depth_folder is not None:
|
| 45 |
+
inputs["align_to_depth_folder"] = align_to_depth_folder
|
| 46 |
+
|
| 47 |
+
outputs = {"poses_folder": poses_folder}
|
| 48 |
+
if depth_folder is not None:
|
| 49 |
+
outputs["depth_folder"] = depth_folder
|
| 50 |
+
if pointcloud_path is not None:
|
| 51 |
+
outputs["pointcloud_path"] = pointcloud_path
|
| 52 |
+
if trajectory_path is not None:
|
| 53 |
+
outputs["trajectory_path"] = trajectory_path
|
| 54 |
+
|
| 55 |
+
extra_args = {
|
| 56 |
+
"stride": stride,
|
| 57 |
+
"image_height": image_height,
|
| 58 |
+
"image_width": image_width,
|
| 59 |
+
"buffer_size": buffer_size,
|
| 60 |
+
"beta": beta,
|
| 61 |
+
"filter_thresh": filter_thresh,
|
| 62 |
+
"warmup": warmup,
|
| 63 |
+
"keyframe_thresh": keyframe_thresh,
|
| 64 |
+
"frontend_thresh": frontend_thresh,
|
| 65 |
+
"frontend_window": frontend_window,
|
| 66 |
+
"frontend_radius": frontend_radius,
|
| 67 |
+
"frontend_nms": frontend_nms,
|
| 68 |
+
"backend_thresh": backend_thresh,
|
| 69 |
+
"backend_radius": backend_radius,
|
| 70 |
+
"backend_nms": backend_nms,
|
| 71 |
+
"upsample": upsample,
|
| 72 |
+
"pointcloud_min_views": pointcloud_min_views,
|
| 73 |
+
}
|
| 74 |
+
|
| 75 |
+
run_in_container(
|
| 76 |
+
image=IMAGE_NAME,
|
| 77 |
+
module="v2d.droid_slam.lib.video_to_slam",
|
| 78 |
+
inputs=inputs,
|
| 79 |
+
outputs=outputs,
|
| 80 |
+
extra_args=extra_args,
|
| 81 |
+
dev=dev,
|
| 82 |
+
modules_dir=MODULES_DIR,
|
| 83 |
+
gpus=True,
|
| 84 |
+
)
|
| 85 |
+
|
| 86 |
+
|
| 87 |
+
if __name__ == "__main__":
|
| 88 |
+
import argparse
|
| 89 |
+
|
| 90 |
+
parser = argparse.ArgumentParser(description="Run DROID-SLAM on a video")
|
| 91 |
+
parser.add_argument("--video_path", required=True)
|
| 92 |
+
parser.add_argument("--poses_folder", required=True)
|
| 93 |
+
parser.add_argument("--weights_path", required=True)
|
| 94 |
+
parser.add_argument("--input_intrinsics_path", default=None)
|
| 95 |
+
parser.add_argument("--input_intrinsics_folder", default=None)
|
| 96 |
+
parser.add_argument("--input_depth_folder", default=None,
|
| 97 |
+
help="Per-frame metric depth fed into BA as a sensor prior.")
|
| 98 |
+
parser.add_argument("--align_to_depth_folder", default=None,
|
| 99 |
+
help="Per-frame metric depth used post-hoc for scale alignment only.")
|
| 100 |
+
parser.add_argument("--depth_folder", default=None)
|
| 101 |
+
parser.add_argument("--pointcloud_path", default=None)
|
| 102 |
+
parser.add_argument("--trajectory_path", default=None)
|
| 103 |
+
parser.add_argument("--stride", type=int, default=1)
|
| 104 |
+
parser.add_argument("--image_height", type=int, default=384)
|
| 105 |
+
parser.add_argument("--image_width", type=int, default=512)
|
| 106 |
+
parser.add_argument("--buffer_size", type=int, default=512)
|
| 107 |
+
parser.add_argument("--beta", type=float, default=0.3)
|
| 108 |
+
parser.add_argument("--filter_thresh", type=float, default=2.4)
|
| 109 |
+
parser.add_argument("--warmup", type=int, default=8)
|
| 110 |
+
parser.add_argument("--keyframe_thresh", type=float, default=4.0)
|
| 111 |
+
parser.add_argument("--frontend_thresh", type=float, default=16.0)
|
| 112 |
+
parser.add_argument("--frontend_window", type=int, default=25)
|
| 113 |
+
parser.add_argument("--frontend_radius", type=int, default=2)
|
| 114 |
+
parser.add_argument("--frontend_nms", type=int, default=1)
|
| 115 |
+
parser.add_argument("--backend_thresh", type=float, default=22.0)
|
| 116 |
+
parser.add_argument("--backend_radius", type=int, default=2)
|
| 117 |
+
parser.add_argument("--backend_nms", type=int, default=3)
|
| 118 |
+
parser.add_argument("--upsample", action="store_true")
|
| 119 |
+
parser.add_argument("--pointcloud_min_views", type=int, default=2)
|
| 120 |
+
parser.add_argument("--dev", action="store_true")
|
| 121 |
+
args = parser.parse_args()
|
| 122 |
+
|
| 123 |
+
run_video_to_slam(
|
| 124 |
+
video_path=args.video_path,
|
| 125 |
+
poses_folder=args.poses_folder,
|
| 126 |
+
weights_path=args.weights_path,
|
| 127 |
+
input_intrinsics_path=args.input_intrinsics_path,
|
| 128 |
+
input_intrinsics_folder=args.input_intrinsics_folder,
|
| 129 |
+
input_depth_folder=args.input_depth_folder,
|
| 130 |
+
align_to_depth_folder=args.align_to_depth_folder,
|
| 131 |
+
depth_folder=args.depth_folder,
|
| 132 |
+
pointcloud_path=args.pointcloud_path,
|
| 133 |
+
trajectory_path=args.trajectory_path,
|
| 134 |
+
stride=args.stride,
|
| 135 |
+
image_height=args.image_height,
|
| 136 |
+
image_width=args.image_width,
|
| 137 |
+
buffer_size=args.buffer_size,
|
| 138 |
+
beta=args.beta,
|
| 139 |
+
filter_thresh=args.filter_thresh,
|
| 140 |
+
warmup=args.warmup,
|
| 141 |
+
keyframe_thresh=args.keyframe_thresh,
|
| 142 |
+
frontend_thresh=args.frontend_thresh,
|
| 143 |
+
frontend_window=args.frontend_window,
|
| 144 |
+
frontend_radius=args.frontend_radius,
|
| 145 |
+
frontend_nms=args.frontend_nms,
|
| 146 |
+
backend_thresh=args.backend_thresh,
|
| 147 |
+
backend_radius=args.backend_radius,
|
| 148 |
+
backend_nms=args.backend_nms,
|
| 149 |
+
upsample=args.upsample,
|
| 150 |
+
pointcloud_min_views=args.pointcloud_min_views,
|
| 151 |
+
dev=args.dev,
|
| 152 |
+
)
|
third-party/video_to_data/reconstruction/modules/v2d_droid_slam/lib/__init__.py
ADDED
|
@@ -0,0 +1,2 @@
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
|
| 2 |
+
# SPDX-License-Identifier: Apache-2.0
|
third-party/video_to_data/reconstruction/modules/v2d_droid_slam/lib/_slam.py
ADDED
|
@@ -0,0 +1,350 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
|
| 2 |
+
# SPDX-License-Identifier: Apache-2.0
|
| 3 |
+
"""
|
| 4 |
+
Internal DROID-SLAM driver shared by video_to_slam and image_list_to_slam.
|
| 5 |
+
|
| 6 |
+
Loads the upstream Droid runner, drives tracking over a frame iterator,
|
| 7 |
+
optionally scale-aligns the result to a reference metric-depth source,
|
| 8 |
+
and writes outputs in the v2d common formats.
|
| 9 |
+
"""
|
| 10 |
+
from __future__ import annotations
|
| 11 |
+
|
| 12 |
+
import os
|
| 13 |
+
from dataclasses import dataclass
|
| 14 |
+
from types import SimpleNamespace
|
| 15 |
+
from typing import Callable, Iterator
|
| 16 |
+
|
| 17 |
+
import cv2
|
| 18 |
+
import numpy as np
|
| 19 |
+
import torch
|
| 20 |
+
|
| 21 |
+
from v2d.common.datatypes import CameraIntrinsics, DepthImage, Transform3d
|
| 22 |
+
|
| 23 |
+
|
| 24 |
+
@dataclass
|
| 25 |
+
class Frame:
|
| 26 |
+
frame_idx: int # source frame index (zero-padded filename stem)
|
| 27 |
+
image_bgr: np.ndarray # (H, W, 3) uint8
|
| 28 |
+
intrinsics: CameraIntrinsics # intrinsics at the source resolution
|
| 29 |
+
prior_depth: np.ndarray | None = None # (H, W) float32 metres — fed into BA as sensor prior
|
| 30 |
+
align_to_depth: np.ndarray | None = None # (H, W) float32 metres — used post-hoc for scale alignment
|
| 31 |
+
|
| 32 |
+
|
| 33 |
+
def _resize_for_droid(
|
| 34 |
+
image_bgr: np.ndarray,
|
| 35 |
+
fxfycxcy: np.ndarray,
|
| 36 |
+
image_size: tuple[int, int],
|
| 37 |
+
prior_depth: np.ndarray | None = None,
|
| 38 |
+
) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor | None]:
|
| 39 |
+
"""Resize a frame to DROID's network input and rescale intrinsics to match.
|
| 40 |
+
|
| 41 |
+
Returns image as (1, 3, H, W) uint8 BGR (upstream motion_filter adds its
|
| 42 |
+
own [None]+[2,1,0] reorder to get RGB internally), scaled intrinsics, and
|
| 43 |
+
optional depth resized to the network input resolution. Invalid (non-positive
|
| 44 |
+
or non-finite) depth pixels are zeroed; depth_video.append() interprets
|
| 45 |
+
zero as "no prior at this pixel".
|
| 46 |
+
"""
|
| 47 |
+
target_h, target_w = image_size
|
| 48 |
+
src_h, src_w = image_bgr.shape[:2]
|
| 49 |
+
image_bgr = cv2.resize(image_bgr, (target_w, target_h), interpolation=cv2.INTER_AREA)
|
| 50 |
+
image = torch.from_numpy(image_bgr).permute(2, 0, 1)[None] # (1, 3, H, W) uint8
|
| 51 |
+
|
| 52 |
+
sx = target_w / src_w
|
| 53 |
+
sy = target_h / src_h
|
| 54 |
+
fx, fy, cx, cy = fxfycxcy
|
| 55 |
+
scaled = torch.tensor([fx * sx, fy * sy, cx * sx, cy * sy], dtype=torch.float32)
|
| 56 |
+
|
| 57 |
+
depth_t: torch.Tensor | None = None
|
| 58 |
+
if prior_depth is not None:
|
| 59 |
+
d = prior_depth.astype(np.float32)
|
| 60 |
+
invalid = ~np.isfinite(d) | (d <= 0)
|
| 61 |
+
d[invalid] = 0.0
|
| 62 |
+
if d.shape != (target_h, target_w):
|
| 63 |
+
d = cv2.resize(d, (target_w, target_h), interpolation=cv2.INTER_NEAREST)
|
| 64 |
+
depth_t = torch.from_numpy(d)
|
| 65 |
+
|
| 66 |
+
return image, scaled, depth_t
|
| 67 |
+
|
| 68 |
+
|
| 69 |
+
def _load_droid_class():
|
| 70 |
+
"""Import the upstream Droid class lazily so module import stays cheap."""
|
| 71 |
+
from droid import Droid # provided by the DROID-SLAM repo on PYTHONPATH
|
| 72 |
+
return Droid
|
| 73 |
+
|
| 74 |
+
|
| 75 |
+
def _get_keyframe_disps(droid, upsample: bool) -> np.ndarray:
|
| 76 |
+
"""Return per-keyframe disparity. Upsampled to source resolution if available."""
|
| 77 |
+
video = droid.video
|
| 78 |
+
if upsample and hasattr(video, "disps_up"):
|
| 79 |
+
return video.disps_up.detach().cpu().numpy()
|
| 80 |
+
return video.disps.detach().cpu().numpy()
|
| 81 |
+
|
| 82 |
+
|
| 83 |
+
def _solve_global_scale(droid, frames_by_idx: dict[int, Frame], upsample: bool) -> float:
|
| 84 |
+
"""Compute a robust scale factor that maps DROID depth → reference depth.
|
| 85 |
+
|
| 86 |
+
Sampled at every keyframe where reference depth is available. Per-keyframe
|
| 87 |
+
median ratios are aggregated into a final global median.
|
| 88 |
+
"""
|
| 89 |
+
video = droid.video
|
| 90 |
+
n_kf = int(video.counter.value)
|
| 91 |
+
disps = _get_keyframe_disps(droid, upsample)
|
| 92 |
+
tstamps = video.tstamp.detach().cpu().numpy().astype(np.int64)
|
| 93 |
+
|
| 94 |
+
per_kf_scales: list[float] = []
|
| 95 |
+
for kf in range(n_kf):
|
| 96 |
+
frame_idx = int(tstamps[kf])
|
| 97 |
+
if frame_idx not in frames_by_idx:
|
| 98 |
+
continue
|
| 99 |
+
ref = frames_by_idx[frame_idx].align_to_depth
|
| 100 |
+
if ref is None:
|
| 101 |
+
continue
|
| 102 |
+
disp = disps[kf]
|
| 103 |
+
# DROID disparity is in network-resolution pixels; resize to source.
|
| 104 |
+
ref_h, ref_w = ref.shape[:2]
|
| 105 |
+
if disp.shape != (ref_h, ref_w):
|
| 106 |
+
disp = cv2.resize(disp, (ref_w, ref_h), interpolation=cv2.INTER_LINEAR)
|
| 107 |
+
valid = (disp > 1e-3) & (ref > 1e-3) & np.isfinite(ref)
|
| 108 |
+
if valid.sum() < 64:
|
| 109 |
+
continue
|
| 110 |
+
droid_depth = 1.0 / disp[valid]
|
| 111 |
+
ratios = ref[valid] / droid_depth
|
| 112 |
+
per_kf_scales.append(float(np.median(ratios)))
|
| 113 |
+
|
| 114 |
+
if not per_kf_scales:
|
| 115 |
+
return 1.0
|
| 116 |
+
return float(np.median(per_kf_scales))
|
| 117 |
+
|
| 118 |
+
|
| 119 |
+
def _write_pointcloud_ply(droid, scale: float, path: str,
|
| 120 |
+
min_views: int = 2,
|
| 121 |
+
filter_thresh: float = 0.005) -> None:
|
| 122 |
+
"""Dump the post-BA keyframe point cloud as a binary-little-endian PLY.
|
| 123 |
+
|
| 124 |
+
Uses upstream's depth_filter for multi-view consistency: a pixel is
|
| 125 |
+
kept only if its depth is consistent with at least ``min_views`` other
|
| 126 |
+
keyframes. This is what produces clean (non-fuzzy) clouds.
|
| 127 |
+
"""
|
| 128 |
+
import torch
|
| 129 |
+
import droid_backends
|
| 130 |
+
from lietorch import SE3
|
| 131 |
+
|
| 132 |
+
video = droid.video
|
| 133 |
+
n_kf = int(video.counter.value)
|
| 134 |
+
if n_kf == 0:
|
| 135 |
+
print("[droid-slam] no keyframes; skipping PLY")
|
| 136 |
+
return
|
| 137 |
+
|
| 138 |
+
# depth_filter inspects the FULL buffer using dirty_index to know which
|
| 139 |
+
# slots are valid, so we hand it the unsliced tensors as upstream does.
|
| 140 |
+
dirty_index = torch.arange(n_kf, device=video.poses.device)
|
| 141 |
+
thresh = filter_thresh * torch.ones(n_kf, device=video.poses.device)
|
| 142 |
+
count = droid_backends.depth_filter(
|
| 143 |
+
video.poses, video.disps, video.intrinsics[0], dirty_index, thresh
|
| 144 |
+
) # (N, h, w) per-pixel consistent-view count
|
| 145 |
+
|
| 146 |
+
poses = video.poses[:n_kf].detach()
|
| 147 |
+
disps = video.disps[:n_kf].detach()
|
| 148 |
+
images = video.images[:n_kf].detach()
|
| 149 |
+
intrinsics = video.intrinsics[0].detach()
|
| 150 |
+
|
| 151 |
+
cam_to_world = SE3(poses).inv()
|
| 152 |
+
points_world = droid_backends.iproj(cam_to_world.data, disps, intrinsics)
|
| 153 |
+
points_world = (points_world * scale).cpu().numpy() # (N, h, w, 3)
|
| 154 |
+
|
| 155 |
+
colors_rgb = images[:, [2, 1, 0], 3::8, 3::8]
|
| 156 |
+
colors_rgb = colors_rgb.permute(0, 2, 3, 1).cpu().numpy() # (N, h, w, 3) RGB
|
| 157 |
+
|
| 158 |
+
disp_np = disps.cpu().numpy()
|
| 159 |
+
disp_mean = disp_np.reshape(n_kf, -1).mean(axis=1).reshape(n_kf, 1, 1)
|
| 160 |
+
consistency_mask = count.cpu().numpy() >= min_views
|
| 161 |
+
mask = consistency_mask & (disp_np > 0.5 * disp_mean) & (disp_np > 1e-3)
|
| 162 |
+
|
| 163 |
+
points_arr = points_world[mask].astype(np.float32)
|
| 164 |
+
colors_arr = colors_rgb[mask].astype(np.uint8)
|
| 165 |
+
if points_arr.size == 0:
|
| 166 |
+
print("[droid-slam] no points passed consistency filter; skipping PLY")
|
| 167 |
+
return
|
| 168 |
+
|
| 169 |
+
t_arr = cam_to_world.data[:, :3].cpu().numpy()
|
| 170 |
+
n_total = int(mask.size)
|
| 171 |
+
print(f"[droid-slam] PLY: {n_kf} keyframes, {points_arr.shape[0]} / {n_total} points "
|
| 172 |
+
f"kept (min_views={min_views}); "
|
| 173 |
+
f"cam x∈[{t_arr[:,0].min():.3f},{t_arr[:,0].max():.3f}] "
|
| 174 |
+
f"y∈[{t_arr[:,1].min():.3f},{t_arr[:,1].max():.3f}] "
|
| 175 |
+
f"z∈[{t_arr[:,2].min():.3f},{t_arr[:,2].max():.3f}]")
|
| 176 |
+
|
| 177 |
+
os.makedirs(os.path.dirname(os.path.abspath(path)) or ".", exist_ok=True)
|
| 178 |
+
with open(path, "wb") as f:
|
| 179 |
+
header = (
|
| 180 |
+
"ply\n"
|
| 181 |
+
"format binary_little_endian 1.0\n"
|
| 182 |
+
f"element vertex {points_arr.shape[0]}\n"
|
| 183 |
+
"property float x\nproperty float y\nproperty float z\n"
|
| 184 |
+
"property uchar red\nproperty uchar green\nproperty uchar blue\n"
|
| 185 |
+
"end_header\n"
|
| 186 |
+
)
|
| 187 |
+
f.write(header.encode("ascii"))
|
| 188 |
+
interleaved = np.empty(points_arr.shape[0],
|
| 189 |
+
dtype=[("xyz", np.float32, 3), ("rgb", np.uint8, 3)])
|
| 190 |
+
interleaved["xyz"] = points_arr
|
| 191 |
+
interleaved["rgb"] = colors_arr
|
| 192 |
+
interleaved.tofile(f)
|
| 193 |
+
|
| 194 |
+
|
| 195 |
+
def _se3_quat_to_matrix(pose: np.ndarray) -> np.ndarray:
|
| 196 |
+
"""Convert DROID's [tx,ty,tz,qx,qy,qz,qw] world-to-camera into a 4×4 matrix."""
|
| 197 |
+
from scipy.spatial.transform import Rotation
|
| 198 |
+
tx, ty, tz, qx, qy, qz, qw = pose.tolist()
|
| 199 |
+
R = Rotation.from_quat([qx, qy, qz, qw]).as_matrix()
|
| 200 |
+
M = np.eye(4)
|
| 201 |
+
M[:3, :3] = R
|
| 202 |
+
M[:3, 3] = [tx, ty, tz]
|
| 203 |
+
return M
|
| 204 |
+
|
| 205 |
+
|
| 206 |
+
def run_droid_slam(
|
| 207 |
+
frame_iter: Callable[[], Iterator[Frame]],
|
| 208 |
+
weights_path: str,
|
| 209 |
+
poses_folder: str,
|
| 210 |
+
depth_folder: str | None = None,
|
| 211 |
+
pointcloud_path: str | None = None,
|
| 212 |
+
trajectory_path: str | None = None,
|
| 213 |
+
image_size: tuple[int, int] = (384, 512),
|
| 214 |
+
buffer_size: int = 512,
|
| 215 |
+
beta: float = 0.3,
|
| 216 |
+
filter_thresh: float = 2.4,
|
| 217 |
+
warmup: int = 8,
|
| 218 |
+
keyframe_thresh: float = 4.0,
|
| 219 |
+
frontend_thresh: float = 16.0,
|
| 220 |
+
frontend_window: int = 25,
|
| 221 |
+
frontend_radius: int = 2,
|
| 222 |
+
frontend_nms: int = 1,
|
| 223 |
+
backend_thresh: float = 22.0,
|
| 224 |
+
backend_radius: int = 2,
|
| 225 |
+
backend_nms: int = 3,
|
| 226 |
+
upsample: bool = False,
|
| 227 |
+
pointcloud_min_views: int = 2,
|
| 228 |
+
) -> None:
|
| 229 |
+
"""Run DROID-SLAM over a frame iterator and write outputs.
|
| 230 |
+
|
| 231 |
+
The frame iterator is invoked twice: once for tracking, then again for
|
| 232 |
+
scale alignment so we can correlate keyframes with their reference depth
|
| 233 |
+
without holding all frames in memory.
|
| 234 |
+
"""
|
| 235 |
+
os.makedirs(poses_folder, exist_ok=True)
|
| 236 |
+
if depth_folder is not None:
|
| 237 |
+
os.makedirs(depth_folder, exist_ok=True)
|
| 238 |
+
|
| 239 |
+
weights_file = os.path.join(weights_path, "droid.pth") \
|
| 240 |
+
if os.path.isdir(weights_path) else weights_path
|
| 241 |
+
if not os.path.exists(weights_file):
|
| 242 |
+
raise FileNotFoundError(f"droid.pth not found at {weights_file}")
|
| 243 |
+
|
| 244 |
+
args = SimpleNamespace(
|
| 245 |
+
weights=weights_file,
|
| 246 |
+
image_size=list(image_size),
|
| 247 |
+
buffer=buffer_size,
|
| 248 |
+
beta=beta,
|
| 249 |
+
filter_thresh=filter_thresh,
|
| 250 |
+
warmup=warmup,
|
| 251 |
+
keyframe_thresh=keyframe_thresh,
|
| 252 |
+
frontend_thresh=frontend_thresh,
|
| 253 |
+
frontend_window=frontend_window,
|
| 254 |
+
frontend_radius=frontend_radius,
|
| 255 |
+
frontend_nms=frontend_nms,
|
| 256 |
+
backend_thresh=backend_thresh,
|
| 257 |
+
backend_radius=backend_radius,
|
| 258 |
+
backend_nms=backend_nms,
|
| 259 |
+
upsample=upsample,
|
| 260 |
+
disable_vis=True,
|
| 261 |
+
stereo=False,
|
| 262 |
+
)
|
| 263 |
+
|
| 264 |
+
Droid = _load_droid_class()
|
| 265 |
+
droid: object | None = None
|
| 266 |
+
|
| 267 |
+
frames_by_idx: dict[int, Frame] = {}
|
| 268 |
+
ordered_indices: list[int] = []
|
| 269 |
+
|
| 270 |
+
for frame in frame_iter():
|
| 271 |
+
if droid is None:
|
| 272 |
+
droid = Droid(args)
|
| 273 |
+
fxfycxcy = np.array([frame.intrinsics.fx, frame.intrinsics.fy,
|
| 274 |
+
frame.intrinsics.cx, frame.intrinsics.cy], dtype=np.float32)
|
| 275 |
+
image_t, intr_t, depth_t = _resize_for_droid(
|
| 276 |
+
frame.image_bgr, fxfycxcy, image_size, prior_depth=frame.prior_depth,
|
| 277 |
+
)
|
| 278 |
+
droid.track(frame.frame_idx, image_t, depth=depth_t, intrinsics=intr_t)
|
| 279 |
+
frames_by_idx[frame.frame_idx] = frame
|
| 280 |
+
ordered_indices.append(frame.frame_idx)
|
| 281 |
+
|
| 282 |
+
if droid is None:
|
| 283 |
+
raise RuntimeError("frame_iter produced no frames")
|
| 284 |
+
|
| 285 |
+
# Reconstruct the stream for terminate() — used internally by DROID
|
| 286 |
+
# for the final global BA pass.
|
| 287 |
+
def replay():
|
| 288 |
+
for f in frame_iter():
|
| 289 |
+
fxfycxcy = np.array([f.intrinsics.fx, f.intrinsics.fy,
|
| 290 |
+
f.intrinsics.cx, f.intrinsics.cy], dtype=np.float32)
|
| 291 |
+
image_t, intr_t, _ = _resize_for_droid(
|
| 292 |
+
f.image_bgr, fxfycxcy, image_size, prior_depth=None,
|
| 293 |
+
)
|
| 294 |
+
yield (f.frame_idx, image_t, intr_t)
|
| 295 |
+
|
| 296 |
+
traj_est = droid.terminate(replay()) # (N_frames, 7) camera-to-world [tx,ty,tz,qx,qy,qz,qw]
|
| 297 |
+
|
| 298 |
+
scale = _solve_global_scale(droid, frames_by_idx, upsample)
|
| 299 |
+
if scale != 1.0:
|
| 300 |
+
print(f"[droid-slam] applying global scale {scale:.6f} from reference depth")
|
| 301 |
+
|
| 302 |
+
# Write per-frame poses.
|
| 303 |
+
from scipy.spatial.transform import Rotation
|
| 304 |
+
for row_i, frame_idx in enumerate(ordered_indices):
|
| 305 |
+
tx, ty, tz, qx, qy, qz, qw = traj_est[row_i].tolist()
|
| 306 |
+
M = np.eye(4)
|
| 307 |
+
M[:3, :3] = Rotation.from_quat([qx, qy, qz, qw]).as_matrix()
|
| 308 |
+
M[:3, 3] = [tx * scale, ty * scale, tz * scale]
|
| 309 |
+
Transform3d.from_matrix(M).save(
|
| 310 |
+
os.path.join(poses_folder, f"{frame_idx:06d}.json")
|
| 311 |
+
)
|
| 312 |
+
|
| 313 |
+
# Optional TUM trajectory.
|
| 314 |
+
if trajectory_path is not None:
|
| 315 |
+
os.makedirs(os.path.dirname(os.path.abspath(trajectory_path)) or ".", exist_ok=True)
|
| 316 |
+
with open(trajectory_path, "w") as f:
|
| 317 |
+
for row_i, frame_idx in enumerate(ordered_indices):
|
| 318 |
+
tx, ty, tz, qx, qy, qz, qw = traj_est[row_i].tolist()
|
| 319 |
+
f.write(f"{frame_idx} {tx*scale} {ty*scale} {tz*scale} "
|
| 320 |
+
f"{qx} {qy} {qz} {qw}\n")
|
| 321 |
+
|
| 322 |
+
# Optional per-keyframe depth output (scaled, upsampled to source resolution).
|
| 323 |
+
if depth_folder is not None:
|
| 324 |
+
video = droid.video
|
| 325 |
+
n_kf = int(video.counter.value)
|
| 326 |
+
disps = _get_keyframe_disps(droid, upsample)
|
| 327 |
+
tstamps = video.tstamp.detach().cpu().numpy().astype(np.int64)
|
| 328 |
+
|
| 329 |
+
for kf in range(n_kf):
|
| 330 |
+
disp = disps[kf]
|
| 331 |
+
frame_idx = int(tstamps[kf])
|
| 332 |
+
frame = frames_by_idx.get(frame_idx)
|
| 333 |
+
if frame is None:
|
| 334 |
+
continue
|
| 335 |
+
tgt_h, tgt_w = frame.intrinsics.height, frame.intrinsics.width
|
| 336 |
+
if disp.shape != (tgt_h, tgt_w):
|
| 337 |
+
disp = cv2.resize(disp, (tgt_w, tgt_h), interpolation=cv2.INTER_LINEAR)
|
| 338 |
+
# Dense depth output: every pixel gets a value. Tiny-disparity pixels
|
| 339 |
+
# (effectively "no information") map to large depth and therefore
|
| 340 |
+
# near-black in the inverse-depth PNG encoding — distinguishable
|
| 341 |
+
# from depth≈0, which would have been white and visually misleading.
|
| 342 |
+
safe_disp = np.maximum(disp, 1e-6)
|
| 343 |
+
depth = (1.0 / safe_disp) * scale
|
| 344 |
+
DepthImage(depth=depth.astype(np.float32)).to_pil_image().save(
|
| 345 |
+
os.path.join(depth_folder, f"{frame_idx:06d}.png")
|
| 346 |
+
)
|
| 347 |
+
|
| 348 |
+
if pointcloud_path is not None:
|
| 349 |
+
_write_pointcloud_ply(droid, scale, pointcloud_path,
|
| 350 |
+
min_views=pointcloud_min_views)
|
third-party/video_to_data/reconstruction/modules/v2d_droid_slam/lib/download_weights.py
ADDED
|
@@ -0,0 +1,32 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
|
| 2 |
+
# SPDX-License-Identifier: Apache-2.0
|
| 3 |
+
"""
|
| 4 |
+
Download the DROID-SLAM checkpoint (droid.pth) into a local weights folder.
|
| 5 |
+
|
| 6 |
+
Upstream hosts the file on Google Drive — we use gdown to fetch it.
|
| 7 |
+
"""
|
| 8 |
+
import argparse
|
| 9 |
+
import os
|
| 10 |
+
|
| 11 |
+
import gdown
|
| 12 |
+
|
| 13 |
+
DROID_GDRIVE_FILE_ID = "1PpqVt1H4maBa_GbPJp4NwxRsd9jk-elh"
|
| 14 |
+
|
| 15 |
+
|
| 16 |
+
def download_droid(output_dir: str) -> None:
|
| 17 |
+
os.makedirs(output_dir, exist_ok=True)
|
| 18 |
+
out_path = os.path.join(output_dir, "droid.pth")
|
| 19 |
+
if os.path.exists(out_path):
|
| 20 |
+
print(f"droid.pth already present at {out_path} — skipping download")
|
| 21 |
+
return
|
| 22 |
+
url = f"https://drive.google.com/uc?id={DROID_GDRIVE_FILE_ID}"
|
| 23 |
+
gdown.download(url, out_path, quiet=False)
|
| 24 |
+
print(f"DROID-SLAM checkpoint downloaded to {out_path}")
|
| 25 |
+
|
| 26 |
+
|
| 27 |
+
if __name__ == "__main__":
|
| 28 |
+
parser = argparse.ArgumentParser(description="Download DROID-SLAM checkpoint")
|
| 29 |
+
parser.add_argument("--output_dir", type=str, required=True,
|
| 30 |
+
help="Output directory for droid.pth")
|
| 31 |
+
args = parser.parse_args()
|
| 32 |
+
download_droid(args.output_dir)
|
third-party/video_to_data/reconstruction/modules/v2d_droid_slam/lib/image_list_to_slam.py
ADDED
|
@@ -0,0 +1,223 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
|
| 2 |
+
# SPDX-License-Identifier: Apache-2.0
|
| 3 |
+
"""
|
| 4 |
+
Run DROID-SLAM on a folder of frame images → per-frame camera poses
|
| 5 |
+
(+ optional depth, PLY). Sibling of video_to_slam with the same options.
|
| 6 |
+
|
| 7 |
+
Image folder may contain .png, .jpg, or .jpeg files. Frame index is parsed
|
| 8 |
+
from the filename stem as an integer (zero-padded names like 000123.png).
|
| 9 |
+
"""
|
| 10 |
+
from __future__ import annotations
|
| 11 |
+
|
| 12 |
+
import argparse
|
| 13 |
+
import os
|
| 14 |
+
from typing import Iterator
|
| 15 |
+
|
| 16 |
+
import cv2
|
| 17 |
+
import numpy as np
|
| 18 |
+
|
| 19 |
+
from v2d.common.datatypes import CameraIntrinsics, DepthImage
|
| 20 |
+
from v2d.droid_slam.lib._slam import Frame, run_droid_slam
|
| 21 |
+
|
| 22 |
+
|
| 23 |
+
_IMAGE_EXTS = (".png", ".jpg", ".jpeg")
|
| 24 |
+
|
| 25 |
+
|
| 26 |
+
def _list_image_files(image_folder: str) -> list[str]:
|
| 27 |
+
files = [
|
| 28 |
+
os.path.join(image_folder, f)
|
| 29 |
+
for f in os.listdir(image_folder)
|
| 30 |
+
if f.lower().endswith(_IMAGE_EXTS)
|
| 31 |
+
]
|
| 32 |
+
files.sort()
|
| 33 |
+
return files
|
| 34 |
+
|
| 35 |
+
|
| 36 |
+
def _frame_idx_from_path(path: str) -> int:
|
| 37 |
+
stem = os.path.splitext(os.path.basename(path))[0]
|
| 38 |
+
return int(stem)
|
| 39 |
+
|
| 40 |
+
|
| 41 |
+
def _load_intrinsics_for_frame(
|
| 42 |
+
input_intrinsics_path: str | None,
|
| 43 |
+
input_intrinsics_folder: str | None,
|
| 44 |
+
frame_idx: int,
|
| 45 |
+
fallback: CameraIntrinsics | None,
|
| 46 |
+
) -> CameraIntrinsics:
|
| 47 |
+
if input_intrinsics_folder is not None:
|
| 48 |
+
path = os.path.join(input_intrinsics_folder, f"{frame_idx:06d}.json")
|
| 49 |
+
if os.path.exists(path):
|
| 50 |
+
return CameraIntrinsics.load(path)
|
| 51 |
+
if fallback is None:
|
| 52 |
+
raise FileNotFoundError(
|
| 53 |
+
f"No intrinsics file for frame {frame_idx} at {path} and no fallback")
|
| 54 |
+
return fallback
|
| 55 |
+
assert fallback is not None
|
| 56 |
+
return fallback
|
| 57 |
+
|
| 58 |
+
|
| 59 |
+
def _depth_for_frame(folder: str | None, frame_idx: int) -> np.ndarray | None:
|
| 60 |
+
if folder is None:
|
| 61 |
+
return None
|
| 62 |
+
path = os.path.join(folder, f"{frame_idx:06d}.png")
|
| 63 |
+
if not os.path.exists(path):
|
| 64 |
+
return None
|
| 65 |
+
return DepthImage.load(path).depth.astype(np.float32)
|
| 66 |
+
|
| 67 |
+
|
| 68 |
+
def image_list_to_slam(
|
| 69 |
+
image_folder: str,
|
| 70 |
+
poses_folder: str,
|
| 71 |
+
weights_path: str,
|
| 72 |
+
input_intrinsics_path: str | None = None,
|
| 73 |
+
input_intrinsics_folder: str | None = None,
|
| 74 |
+
input_depth_folder: str | None = None,
|
| 75 |
+
align_to_depth_folder: str | None = None,
|
| 76 |
+
depth_folder: str | None = None,
|
| 77 |
+
pointcloud_path: str | None = None,
|
| 78 |
+
trajectory_path: str | None = None,
|
| 79 |
+
stride: int = 1,
|
| 80 |
+
image_size: tuple[int, int] = (384, 512),
|
| 81 |
+
buffer_size: int = 512,
|
| 82 |
+
beta: float = 0.3,
|
| 83 |
+
filter_thresh: float = 2.4,
|
| 84 |
+
warmup: int = 8,
|
| 85 |
+
keyframe_thresh: float = 4.0,
|
| 86 |
+
frontend_thresh: float = 16.0,
|
| 87 |
+
frontend_window: int = 25,
|
| 88 |
+
frontend_radius: int = 2,
|
| 89 |
+
frontend_nms: int = 1,
|
| 90 |
+
backend_thresh: float = 22.0,
|
| 91 |
+
backend_radius: int = 2,
|
| 92 |
+
backend_nms: int = 3,
|
| 93 |
+
upsample: bool = False,
|
| 94 |
+
pointcloud_min_views: int = 2,
|
| 95 |
+
) -> None:
|
| 96 |
+
if input_intrinsics_path is None and input_intrinsics_folder is None:
|
| 97 |
+
raise ValueError("Provide either --input_intrinsics_path or --input_intrinsics_folder")
|
| 98 |
+
|
| 99 |
+
fallback_intrinsics = None
|
| 100 |
+
if input_intrinsics_path is not None:
|
| 101 |
+
fallback_intrinsics = CameraIntrinsics.load(input_intrinsics_path)
|
| 102 |
+
elif input_intrinsics_folder is not None:
|
| 103 |
+
# Use the first available file as a fallback for any frame missing its own.
|
| 104 |
+
files = sorted(
|
| 105 |
+
os.path.join(input_intrinsics_folder, f)
|
| 106 |
+
for f in os.listdir(input_intrinsics_folder)
|
| 107 |
+
if f.endswith(".json")
|
| 108 |
+
)
|
| 109 |
+
if not files:
|
| 110 |
+
raise FileNotFoundError(f"No intrinsics JSONs in {input_intrinsics_folder}")
|
| 111 |
+
fallback_intrinsics = CameraIntrinsics.load(files[0])
|
| 112 |
+
|
| 113 |
+
image_paths = _list_image_files(image_folder)
|
| 114 |
+
if not image_paths:
|
| 115 |
+
raise FileNotFoundError(f"No images in {image_folder}")
|
| 116 |
+
|
| 117 |
+
def frame_iter() -> Iterator[Frame]:
|
| 118 |
+
for i, path in enumerate(image_paths):
|
| 119 |
+
if i % stride != 0:
|
| 120 |
+
continue
|
| 121 |
+
frame_idx = _frame_idx_from_path(path)
|
| 122 |
+
image_bgr = cv2.imread(path, cv2.IMREAD_COLOR)
|
| 123 |
+
if image_bgr is None:
|
| 124 |
+
raise IOError(f"Failed to read image {path}")
|
| 125 |
+
intr = _load_intrinsics_for_frame(
|
| 126 |
+
input_intrinsics_path, input_intrinsics_folder,
|
| 127 |
+
frame_idx, fallback_intrinsics,
|
| 128 |
+
)
|
| 129 |
+
yield Frame(
|
| 130 |
+
frame_idx=frame_idx,
|
| 131 |
+
image_bgr=image_bgr,
|
| 132 |
+
intrinsics=intr,
|
| 133 |
+
prior_depth=_depth_for_frame(input_depth_folder, frame_idx),
|
| 134 |
+
align_to_depth=_depth_for_frame(align_to_depth_folder, frame_idx),
|
| 135 |
+
)
|
| 136 |
+
|
| 137 |
+
run_droid_slam(
|
| 138 |
+
frame_iter=frame_iter,
|
| 139 |
+
weights_path=weights_path,
|
| 140 |
+
poses_folder=poses_folder,
|
| 141 |
+
depth_folder=depth_folder,
|
| 142 |
+
pointcloud_path=pointcloud_path,
|
| 143 |
+
trajectory_path=trajectory_path,
|
| 144 |
+
image_size=image_size,
|
| 145 |
+
buffer_size=buffer_size,
|
| 146 |
+
beta=beta,
|
| 147 |
+
filter_thresh=filter_thresh,
|
| 148 |
+
warmup=warmup,
|
| 149 |
+
keyframe_thresh=keyframe_thresh,
|
| 150 |
+
frontend_thresh=frontend_thresh,
|
| 151 |
+
frontend_window=frontend_window,
|
| 152 |
+
frontend_radius=frontend_radius,
|
| 153 |
+
frontend_nms=frontend_nms,
|
| 154 |
+
backend_thresh=backend_thresh,
|
| 155 |
+
backend_radius=backend_radius,
|
| 156 |
+
backend_nms=backend_nms,
|
| 157 |
+
upsample=upsample,
|
| 158 |
+
pointcloud_min_views=pointcloud_min_views,
|
| 159 |
+
)
|
| 160 |
+
|
| 161 |
+
|
| 162 |
+
if __name__ == "__main__":
|
| 163 |
+
parser = argparse.ArgumentParser(description="Run DROID-SLAM on a folder of frames")
|
| 164 |
+
parser.add_argument("--image_folder", required=True)
|
| 165 |
+
parser.add_argument("--poses_folder", required=True)
|
| 166 |
+
parser.add_argument("--weights_path", required=True)
|
| 167 |
+
parser.add_argument("--input_intrinsics_path", default=None)
|
| 168 |
+
parser.add_argument("--input_intrinsics_folder", default=None)
|
| 169 |
+
parser.add_argument("--input_depth_folder", default=None,
|
| 170 |
+
help="Per-frame metric depth fed into BA as a sensor prior.")
|
| 171 |
+
parser.add_argument("--align_to_depth_folder", default=None,
|
| 172 |
+
help="Per-frame metric depth used post-hoc for scale alignment only.")
|
| 173 |
+
parser.add_argument("--depth_folder", default=None)
|
| 174 |
+
parser.add_argument("--pointcloud_path", default=None)
|
| 175 |
+
parser.add_argument("--trajectory_path", default=None)
|
| 176 |
+
parser.add_argument("--stride", type=int, default=1)
|
| 177 |
+
parser.add_argument("--image_height", type=int, default=384)
|
| 178 |
+
parser.add_argument("--image_width", type=int, default=512)
|
| 179 |
+
parser.add_argument("--buffer_size", type=int, default=512)
|
| 180 |
+
parser.add_argument("--beta", type=float, default=0.3)
|
| 181 |
+
parser.add_argument("--filter_thresh", type=float, default=2.4)
|
| 182 |
+
parser.add_argument("--warmup", type=int, default=8)
|
| 183 |
+
parser.add_argument("--keyframe_thresh", type=float, default=4.0)
|
| 184 |
+
parser.add_argument("--frontend_thresh", type=float, default=16.0)
|
| 185 |
+
parser.add_argument("--frontend_window", type=int, default=25)
|
| 186 |
+
parser.add_argument("--frontend_radius", type=int, default=2)
|
| 187 |
+
parser.add_argument("--frontend_nms", type=int, default=1)
|
| 188 |
+
parser.add_argument("--backend_thresh", type=float, default=22.0)
|
| 189 |
+
parser.add_argument("--backend_radius", type=int, default=2)
|
| 190 |
+
parser.add_argument("--backend_nms", type=int, default=3)
|
| 191 |
+
parser.add_argument("--upsample", action="store_true")
|
| 192 |
+
parser.add_argument("--pointcloud_min_views", type=int, default=2,
|
| 193 |
+
help="Multi-view consistency threshold for PLY output.")
|
| 194 |
+
args = parser.parse_args()
|
| 195 |
+
|
| 196 |
+
image_list_to_slam(
|
| 197 |
+
image_folder=args.image_folder,
|
| 198 |
+
poses_folder=args.poses_folder,
|
| 199 |
+
weights_path=args.weights_path,
|
| 200 |
+
input_intrinsics_path=args.input_intrinsics_path,
|
| 201 |
+
input_intrinsics_folder=args.input_intrinsics_folder,
|
| 202 |
+
input_depth_folder=args.input_depth_folder,
|
| 203 |
+
align_to_depth_folder=args.align_to_depth_folder,
|
| 204 |
+
depth_folder=args.depth_folder,
|
| 205 |
+
pointcloud_path=args.pointcloud_path,
|
| 206 |
+
trajectory_path=args.trajectory_path,
|
| 207 |
+
stride=args.stride,
|
| 208 |
+
image_size=(args.image_height, args.image_width),
|
| 209 |
+
buffer_size=args.buffer_size,
|
| 210 |
+
beta=args.beta,
|
| 211 |
+
filter_thresh=args.filter_thresh,
|
| 212 |
+
warmup=args.warmup,
|
| 213 |
+
keyframe_thresh=args.keyframe_thresh,
|
| 214 |
+
frontend_thresh=args.frontend_thresh,
|
| 215 |
+
frontend_window=args.frontend_window,
|
| 216 |
+
frontend_radius=args.frontend_radius,
|
| 217 |
+
frontend_nms=args.frontend_nms,
|
| 218 |
+
backend_thresh=args.backend_thresh,
|
| 219 |
+
backend_radius=args.backend_radius,
|
| 220 |
+
backend_nms=args.backend_nms,
|
| 221 |
+
upsample=args.upsample,
|
| 222 |
+
pointcloud_min_views=args.pointcloud_min_views,
|
| 223 |
+
)
|
third-party/video_to_data/reconstruction/modules/v2d_droid_slam/lib/pyproject.toml
ADDED
|
@@ -0,0 +1,25 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
|
| 2 |
+
# SPDX-License-Identifier: Apache-2.0
|
| 3 |
+
[build-system]
|
| 4 |
+
requires = ["setuptools>=68.0", "wheel"]
|
| 5 |
+
build-backend = "setuptools.build_meta"
|
| 6 |
+
|
| 7 |
+
[project]
|
| 8 |
+
name = "v2d-droid-slam-lib"
|
| 9 |
+
version = "0.1.0"
|
| 10 |
+
description = "DROID-SLAM monocular SLAM library"
|
| 11 |
+
requires-python = ">=3.10"
|
| 12 |
+
dependencies = [
|
| 13 |
+
"numpy",
|
| 14 |
+
"scipy",
|
| 15 |
+
"opencv-python",
|
| 16 |
+
"Pillow",
|
| 17 |
+
"gdown",
|
| 18 |
+
"v2d-common",
|
| 19 |
+
]
|
| 20 |
+
|
| 21 |
+
[tool.setuptools]
|
| 22 |
+
packages = ["v2d.droid_slam.lib"]
|
| 23 |
+
|
| 24 |
+
[tool.setuptools.package-dir]
|
| 25 |
+
"v2d.droid_slam.lib" = "."
|
third-party/video_to_data/reconstruction/modules/v2d_droid_slam/lib/video_to_slam.py
ADDED
|
@@ -0,0 +1,217 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
|
| 2 |
+
# SPDX-License-Identifier: Apache-2.0
|
| 3 |
+
"""
|
| 4 |
+
Run DROID-SLAM on a video file → per-frame camera poses (+ optional depth, PLY).
|
| 5 |
+
|
| 6 |
+
Intrinsics can be supplied either as a single CameraIntrinsics JSON
|
| 7 |
+
(--input_intrinsics_path; reused for every frame) or as a folder of
|
| 8 |
+
per-frame intrinsics JSON files (--input_intrinsics_folder; values are
|
| 9 |
+
median-pooled into a single set, since DROID-SLAM uses a fixed intrinsic
|
| 10 |
+
for the whole sequence).
|
| 11 |
+
|
| 12 |
+
If --input_depth_folder is provided, per-frame depth (e.g. from MoGe) is
|
| 13 |
+
fed into DROID-SLAM's bundle adjustment as a metric prior — this directly
|
| 14 |
+
shapes the reconstructed geometry rather than rescaling it after the fact.
|
| 15 |
+
|
| 16 |
+
If --align_to_depth_folder is provided, the reconstructed poses and depths
|
| 17 |
+
are scale-aligned to that metric reference via a robust per-keyframe ratio
|
| 18 |
+
fit. Pure post-processing — does not affect SLAM behaviour.
|
| 19 |
+
|
| 20 |
+
The two flags are independent and may be combined: --input_depth_folder
|
| 21 |
+
shapes BA, --align_to_depth_folder rescales output. With a metric prior
|
| 22 |
+
provided, post-hoc rescaling is usually unnecessary.
|
| 23 |
+
"""
|
| 24 |
+
from __future__ import annotations
|
| 25 |
+
|
| 26 |
+
import argparse
|
| 27 |
+
import os
|
| 28 |
+
from typing import Iterator
|
| 29 |
+
|
| 30 |
+
import cv2
|
| 31 |
+
import numpy as np
|
| 32 |
+
|
| 33 |
+
from v2d.common.datatypes import CameraIntrinsics, DepthImage
|
| 34 |
+
from v2d.droid_slam.lib._slam import Frame, run_droid_slam
|
| 35 |
+
|
| 36 |
+
|
| 37 |
+
def _load_intrinsics(
|
| 38 |
+
input_intrinsics_path: str | None,
|
| 39 |
+
input_intrinsics_folder: str | None,
|
| 40 |
+
) -> CameraIntrinsics:
|
| 41 |
+
if input_intrinsics_path is None and input_intrinsics_folder is None:
|
| 42 |
+
raise ValueError("Provide either --input_intrinsics_path or --input_intrinsics_folder")
|
| 43 |
+
if input_intrinsics_path is not None:
|
| 44 |
+
return CameraIntrinsics.load(input_intrinsics_path)
|
| 45 |
+
# Per-frame intrinsics → median pool into one shared intrinsic for DROID.
|
| 46 |
+
files = sorted(
|
| 47 |
+
os.path.join(input_intrinsics_folder, f)
|
| 48 |
+
for f in os.listdir(input_intrinsics_folder)
|
| 49 |
+
if f.endswith(".json")
|
| 50 |
+
)
|
| 51 |
+
if not files:
|
| 52 |
+
raise FileNotFoundError(f"No intrinsics JSONs in {input_intrinsics_folder}")
|
| 53 |
+
fx, fy, cx, cy, w, h = [], [], [], [], [], []
|
| 54 |
+
for fp in files:
|
| 55 |
+
ci = CameraIntrinsics.load(fp)
|
| 56 |
+
fx.append(ci.fx); fy.append(ci.fy); cx.append(ci.cx); cy.append(ci.cy)
|
| 57 |
+
w.append(ci.width); h.append(ci.height)
|
| 58 |
+
return CameraIntrinsics(
|
| 59 |
+
fx=float(np.median(fx)), fy=float(np.median(fy)),
|
| 60 |
+
cx=float(np.median(cx)), cy=float(np.median(cy)),
|
| 61 |
+
width=int(np.median(w)), height=int(np.median(h)),
|
| 62 |
+
)
|
| 63 |
+
|
| 64 |
+
|
| 65 |
+
def _depth_for_frame(folder: str | None, frame_idx: int) -> np.ndarray | None:
|
| 66 |
+
if folder is None:
|
| 67 |
+
return None
|
| 68 |
+
path = os.path.join(folder, f"{frame_idx:06d}.png")
|
| 69 |
+
if not os.path.exists(path):
|
| 70 |
+
return None
|
| 71 |
+
return DepthImage.load(path).depth.astype(np.float32)
|
| 72 |
+
|
| 73 |
+
|
| 74 |
+
def video_to_slam(
|
| 75 |
+
video_path: str,
|
| 76 |
+
poses_folder: str,
|
| 77 |
+
weights_path: str,
|
| 78 |
+
input_intrinsics_path: str | None = None,
|
| 79 |
+
input_intrinsics_folder: str | None = None,
|
| 80 |
+
input_depth_folder: str | None = None,
|
| 81 |
+
align_to_depth_folder: str | None = None,
|
| 82 |
+
depth_folder: str | None = None,
|
| 83 |
+
pointcloud_path: str | None = None,
|
| 84 |
+
trajectory_path: str | None = None,
|
| 85 |
+
stride: int = 1,
|
| 86 |
+
image_size: tuple[int, int] = (384, 512),
|
| 87 |
+
buffer_size: int = 512,
|
| 88 |
+
beta: float = 0.3,
|
| 89 |
+
filter_thresh: float = 2.4,
|
| 90 |
+
warmup: int = 8,
|
| 91 |
+
keyframe_thresh: float = 4.0,
|
| 92 |
+
frontend_thresh: float = 16.0,
|
| 93 |
+
frontend_window: int = 25,
|
| 94 |
+
frontend_radius: int = 2,
|
| 95 |
+
frontend_nms: int = 1,
|
| 96 |
+
backend_thresh: float = 22.0,
|
| 97 |
+
backend_radius: int = 2,
|
| 98 |
+
backend_nms: int = 3,
|
| 99 |
+
upsample: bool = False,
|
| 100 |
+
pointcloud_min_views: int = 2,
|
| 101 |
+
) -> None:
|
| 102 |
+
intrinsics = _load_intrinsics(input_intrinsics_path, input_intrinsics_folder)
|
| 103 |
+
|
| 104 |
+
def frame_iter() -> Iterator[Frame]:
|
| 105 |
+
cap = cv2.VideoCapture(video_path)
|
| 106 |
+
try:
|
| 107 |
+
i = 0
|
| 108 |
+
while True:
|
| 109 |
+
ret, frame_bgr = cap.read()
|
| 110 |
+
if not ret:
|
| 111 |
+
break
|
| 112 |
+
if i % stride == 0:
|
| 113 |
+
yield Frame(
|
| 114 |
+
frame_idx=i,
|
| 115 |
+
image_bgr=frame_bgr,
|
| 116 |
+
intrinsics=intrinsics,
|
| 117 |
+
prior_depth=_depth_for_frame(input_depth_folder, i),
|
| 118 |
+
align_to_depth=_depth_for_frame(align_to_depth_folder, i),
|
| 119 |
+
)
|
| 120 |
+
i += 1
|
| 121 |
+
finally:
|
| 122 |
+
cap.release()
|
| 123 |
+
|
| 124 |
+
run_droid_slam(
|
| 125 |
+
frame_iter=frame_iter,
|
| 126 |
+
weights_path=weights_path,
|
| 127 |
+
poses_folder=poses_folder,
|
| 128 |
+
depth_folder=depth_folder,
|
| 129 |
+
pointcloud_path=pointcloud_path,
|
| 130 |
+
trajectory_path=trajectory_path,
|
| 131 |
+
image_size=image_size,
|
| 132 |
+
buffer_size=buffer_size,
|
| 133 |
+
beta=beta,
|
| 134 |
+
filter_thresh=filter_thresh,
|
| 135 |
+
warmup=warmup,
|
| 136 |
+
keyframe_thresh=keyframe_thresh,
|
| 137 |
+
frontend_thresh=frontend_thresh,
|
| 138 |
+
frontend_window=frontend_window,
|
| 139 |
+
frontend_radius=frontend_radius,
|
| 140 |
+
frontend_nms=frontend_nms,
|
| 141 |
+
backend_thresh=backend_thresh,
|
| 142 |
+
backend_radius=backend_radius,
|
| 143 |
+
backend_nms=backend_nms,
|
| 144 |
+
upsample=upsample,
|
| 145 |
+
pointcloud_min_views=pointcloud_min_views,
|
| 146 |
+
)
|
| 147 |
+
|
| 148 |
+
|
| 149 |
+
if __name__ == "__main__":
|
| 150 |
+
parser = argparse.ArgumentParser(description="Run DROID-SLAM on a video")
|
| 151 |
+
parser.add_argument("--video_path", required=True)
|
| 152 |
+
parser.add_argument("--poses_folder", required=True)
|
| 153 |
+
parser.add_argument("--weights_path", required=True)
|
| 154 |
+
parser.add_argument("--input_intrinsics_path", default=None)
|
| 155 |
+
parser.add_argument("--input_intrinsics_folder", default=None)
|
| 156 |
+
parser.add_argument("--input_depth_folder", default=None,
|
| 157 |
+
help="Per-frame metric depth fed into BA as a sensor prior "
|
| 158 |
+
"(e.g. MoGe output). Shapes the reconstruction.")
|
| 159 |
+
parser.add_argument("--align_to_depth_folder", default=None,
|
| 160 |
+
help="Per-frame metric depth used post-hoc for scale "
|
| 161 |
+
"alignment only. Does not influence BA.")
|
| 162 |
+
parser.add_argument("--depth_folder", default=None,
|
| 163 |
+
help="Optional output: per-keyframe DROID depth (scale-aligned)")
|
| 164 |
+
parser.add_argument("--pointcloud_path", default=None,
|
| 165 |
+
help="Optional output: fused .ply of keyframe points")
|
| 166 |
+
parser.add_argument("--trajectory_path", default=None,
|
| 167 |
+
help="Optional output: TUM-format trajectory .txt")
|
| 168 |
+
parser.add_argument("--stride", type=int, default=1)
|
| 169 |
+
parser.add_argument("--image_height", type=int, default=384)
|
| 170 |
+
parser.add_argument("--image_width", type=int, default=512)
|
| 171 |
+
parser.add_argument("--buffer_size", type=int, default=512)
|
| 172 |
+
parser.add_argument("--beta", type=float, default=0.3)
|
| 173 |
+
parser.add_argument("--filter_thresh", type=float, default=2.4)
|
| 174 |
+
parser.add_argument("--warmup", type=int, default=8)
|
| 175 |
+
parser.add_argument("--keyframe_thresh", type=float, default=4.0)
|
| 176 |
+
parser.add_argument("--frontend_thresh", type=float, default=16.0)
|
| 177 |
+
parser.add_argument("--frontend_window", type=int, default=25)
|
| 178 |
+
parser.add_argument("--frontend_radius", type=int, default=2)
|
| 179 |
+
parser.add_argument("--frontend_nms", type=int, default=1)
|
| 180 |
+
parser.add_argument("--backend_thresh", type=float, default=22.0)
|
| 181 |
+
parser.add_argument("--backend_radius", type=int, default=2)
|
| 182 |
+
parser.add_argument("--backend_nms", type=int, default=3)
|
| 183 |
+
parser.add_argument("--upsample", action="store_true")
|
| 184 |
+
parser.add_argument("--pointcloud_min_views", type=int, default=2,
|
| 185 |
+
help="Multi-view consistency threshold for PLY output. "
|
| 186 |
+
"1 = keep all pixels above the disparity threshold "
|
| 187 |
+
"(dense, noisier); 2 = upstream default (clean, sparse).")
|
| 188 |
+
args = parser.parse_args()
|
| 189 |
+
|
| 190 |
+
video_to_slam(
|
| 191 |
+
video_path=args.video_path,
|
| 192 |
+
poses_folder=args.poses_folder,
|
| 193 |
+
weights_path=args.weights_path,
|
| 194 |
+
input_intrinsics_path=args.input_intrinsics_path,
|
| 195 |
+
input_intrinsics_folder=args.input_intrinsics_folder,
|
| 196 |
+
input_depth_folder=args.input_depth_folder,
|
| 197 |
+
align_to_depth_folder=args.align_to_depth_folder,
|
| 198 |
+
depth_folder=args.depth_folder,
|
| 199 |
+
pointcloud_path=args.pointcloud_path,
|
| 200 |
+
trajectory_path=args.trajectory_path,
|
| 201 |
+
stride=args.stride,
|
| 202 |
+
image_size=(args.image_height, args.image_width),
|
| 203 |
+
buffer_size=args.buffer_size,
|
| 204 |
+
beta=args.beta,
|
| 205 |
+
filter_thresh=args.filter_thresh,
|
| 206 |
+
warmup=args.warmup,
|
| 207 |
+
keyframe_thresh=args.keyframe_thresh,
|
| 208 |
+
frontend_thresh=args.frontend_thresh,
|
| 209 |
+
frontend_window=args.frontend_window,
|
| 210 |
+
frontend_radius=args.frontend_radius,
|
| 211 |
+
frontend_nms=args.frontend_nms,
|
| 212 |
+
backend_thresh=args.backend_thresh,
|
| 213 |
+
backend_radius=args.backend_radius,
|
| 214 |
+
backend_nms=args.backend_nms,
|
| 215 |
+
upsample=args.upsample,
|
| 216 |
+
pointcloud_min_views=args.pointcloud_min_views,
|
| 217 |
+
)
|
third-party/video_to_data/reconstruction/modules/v2d_droid_slam/tools/poses_to_frustums.py
ADDED
|
@@ -0,0 +1,125 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
|
| 2 |
+
# SPDX-License-Identifier: Apache-2.0
|
| 3 |
+
"""
|
| 4 |
+
Convert a folder of Transform3d (camera-to-world) JSONs into a PLY of camera
|
| 5 |
+
frustum wireframes. Open this PLY alongside the point cloud in MeshLab (or
|
| 6 |
+
any PLY viewer) to see where each camera is pointing.
|
| 7 |
+
|
| 8 |
+
Usage:
|
| 9 |
+
python modules/v2d_droid_slam/tools/poses_to_frustums.py \
|
| 10 |
+
--poses_folder data/clean/agent_90_undist/output/droid_slam/poses \
|
| 11 |
+
--intrinsics_path data/clean/agent_90_undist/undistorted_intrinsics.json \
|
| 12 |
+
--output_path data/clean/agent_90_undist/output/droid_slam/cameras.ply \
|
| 13 |
+
[--frustum_size 0.05] # near-plane distance in scene units
|
| 14 |
+
[--stride 1] # skip frames
|
| 15 |
+
|
| 16 |
+
Open in MeshLab (drag both files into the same window):
|
| 17 |
+
meshlab data/clean/agent_90_undist/output/droid_slam/pointcloud.ply \
|
| 18 |
+
data/clean/agent_90_undist/output/droid_slam/cameras.ply
|
| 19 |
+
"""
|
| 20 |
+
import argparse
|
| 21 |
+
import json
|
| 22 |
+
import os
|
| 23 |
+
import sys
|
| 24 |
+
|
| 25 |
+
import numpy as np
|
| 26 |
+
|
| 27 |
+
# Make `v2d.common.datatypes` importable without installing anything.
|
| 28 |
+
_REPO_MODULES = os.path.abspath(os.path.join(os.path.dirname(__file__), "..", ".."))
|
| 29 |
+
sys.path.insert(0, os.path.join(_REPO_MODULES, "v2d_common"))
|
| 30 |
+
from datatypes import CameraIntrinsics, Transform3d # noqa: E402
|
| 31 |
+
|
| 32 |
+
|
| 33 |
+
def _frustum_vertices(K: np.ndarray, T_cw: np.ndarray, near: float,
|
| 34 |
+
width: int, height: int) -> np.ndarray:
|
| 35 |
+
"""Return 5 vertices (world frame): camera centre + 4 near-plane corners."""
|
| 36 |
+
fx, fy = K[0, 0], K[1, 1]
|
| 37 |
+
cx, cy = K[0, 2], K[1, 2]
|
| 38 |
+
corners_pix = np.array([
|
| 39 |
+
[0, 0], [width, 0], [width, height], [0, height],
|
| 40 |
+
], dtype=np.float64)
|
| 41 |
+
rays_cam = np.stack([
|
| 42 |
+
(corners_pix[:, 0] - cx) / fx,
|
| 43 |
+
(corners_pix[:, 1] - cy) / fy,
|
| 44 |
+
np.ones(4),
|
| 45 |
+
], axis=1) * near
|
| 46 |
+
pts_cam = np.concatenate([np.zeros((1, 3)), rays_cam], axis=0) # (5, 3)
|
| 47 |
+
pts_world = (T_cw[:3, :3] @ pts_cam.T + T_cw[:3, 3:4]).T
|
| 48 |
+
return pts_world
|
| 49 |
+
|
| 50 |
+
|
| 51 |
+
_FRUSTUM_EDGES = [
|
| 52 |
+
(0, 1), (0, 2), (0, 3), (0, 4), # apex → corners
|
| 53 |
+
(1, 2), (2, 3), (3, 4), (4, 1), # near-plane rectangle
|
| 54 |
+
]
|
| 55 |
+
|
| 56 |
+
|
| 57 |
+
def _rgb_for_index(i: int, n: int) -> tuple[int, int, int]:
|
| 58 |
+
"""Linearly interpolate red → green → blue across the trajectory."""
|
| 59 |
+
t = i / max(n - 1, 1)
|
| 60 |
+
if t < 0.5:
|
| 61 |
+
r = int(255 * (1 - 2 * t))
|
| 62 |
+
g = int(255 * (2 * t))
|
| 63 |
+
b = 0
|
| 64 |
+
else:
|
| 65 |
+
r = 0
|
| 66 |
+
g = int(255 * (2 * (1 - t)))
|
| 67 |
+
b = int(255 * (2 * t - 1))
|
| 68 |
+
return r, g, b
|
| 69 |
+
|
| 70 |
+
|
| 71 |
+
def main():
|
| 72 |
+
parser = argparse.ArgumentParser()
|
| 73 |
+
parser.add_argument("--poses_folder", required=True)
|
| 74 |
+
parser.add_argument("--intrinsics_path", required=True)
|
| 75 |
+
parser.add_argument("--output_path", required=True)
|
| 76 |
+
parser.add_argument("--frustum_size", type=float, default=0.05,
|
| 77 |
+
help="Near-plane distance in scene units")
|
| 78 |
+
parser.add_argument("--stride", type=int, default=1)
|
| 79 |
+
args = parser.parse_args()
|
| 80 |
+
|
| 81 |
+
intr = CameraIntrinsics.load(args.intrinsics_path)
|
| 82 |
+
K = intr.to_matrix()
|
| 83 |
+
pose_files = sorted(f for f in os.listdir(args.poses_folder) if f.endswith(".json"))
|
| 84 |
+
pose_files = pose_files[::args.stride]
|
| 85 |
+
if not pose_files:
|
| 86 |
+
raise FileNotFoundError(f"No pose JSONs in {args.poses_folder}")
|
| 87 |
+
|
| 88 |
+
verts, edges, edge_colors = [], [], []
|
| 89 |
+
n = len(pose_files)
|
| 90 |
+
for i, fn in enumerate(pose_files):
|
| 91 |
+
T_cw = Transform3d.load(os.path.join(args.poses_folder, fn)).to_matrix()
|
| 92 |
+
v = _frustum_vertices(K, T_cw, args.frustum_size, intr.width, intr.height)
|
| 93 |
+
base = i * 5
|
| 94 |
+
verts.append(v)
|
| 95 |
+
rgb = _rgb_for_index(i, n)
|
| 96 |
+
for a, b in _FRUSTUM_EDGES:
|
| 97 |
+
edges.append((base + a, base + b))
|
| 98 |
+
edge_colors.append(rgb)
|
| 99 |
+
|
| 100 |
+
verts_arr = np.concatenate(verts, axis=0).astype(np.float32)
|
| 101 |
+
n_v = verts_arr.shape[0]
|
| 102 |
+
n_e = len(edges)
|
| 103 |
+
|
| 104 |
+
os.makedirs(os.path.dirname(os.path.abspath(args.output_path)) or ".", exist_ok=True)
|
| 105 |
+
with open(args.output_path, "w") as f:
|
| 106 |
+
f.write(
|
| 107 |
+
f"ply\nformat ascii 1.0\n"
|
| 108 |
+
f"element vertex {n_v}\n"
|
| 109 |
+
"property float x\nproperty float y\nproperty float z\n"
|
| 110 |
+
f"element edge {n_e}\n"
|
| 111 |
+
"property int vertex1\nproperty int vertex2\n"
|
| 112 |
+
"property uchar red\nproperty uchar green\nproperty uchar blue\n"
|
| 113 |
+
"end_header\n"
|
| 114 |
+
)
|
| 115 |
+
for x, y, z in verts_arr:
|
| 116 |
+
f.write(f"{x} {y} {z}\n")
|
| 117 |
+
for (a, b), (r, g, bl) in zip(edges, edge_colors):
|
| 118 |
+
f.write(f"{a} {b} {r} {g} {bl}\n")
|
| 119 |
+
|
| 120 |
+
print(f"wrote {args.output_path}: {n} frustums, {n_v} vertices, {n_e} edges")
|
| 121 |
+
print(f"View with: meshlab <pointcloud.ply> {args.output_path}")
|
| 122 |
+
|
| 123 |
+
|
| 124 |
+
if __name__ == "__main__":
|
| 125 |
+
main()
|
third-party/video_to_data/reconstruction/modules/v2d_ego_hand_reconstruction/.gitignore
ADDED
|
@@ -0,0 +1,4 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
vendor/
|
| 2 |
+
__pycache__/
|
| 3 |
+
*.egg-info/
|
| 4 |
+
|
third-party/video_to_data/reconstruction/modules/v2d_ego_hand_reconstruction/LICENSE
ADDED
|
@@ -0,0 +1,15 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Apache License 2.0
|
| 2 |
+
|
| 3 |
+
Copyright 2025 NVIDIA CORPORATION
|
| 4 |
+
|
| 5 |
+
Licensed under the Apache License, Version 2.0 (the "License");
|
| 6 |
+
you may not use this file except in compliance with the License.
|
| 7 |
+
You may obtain a copy of the License at
|
| 8 |
+
|
| 9 |
+
http://www.apache.org/licenses/LICENSE-2.0
|
| 10 |
+
|
| 11 |
+
Unless required by applicable law or agreed to in writing, software
|
| 12 |
+
distributed under the License is distributed on an "AS IS" BASIS,
|
| 13 |
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 14 |
+
See the License for the specific language governing permissions and
|
| 15 |
+
limitations under the License.
|
third-party/video_to_data/reconstruction/modules/v2d_ego_hand_reconstruction/README.md
ADDED
|
@@ -0,0 +1,115 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
<!--
|
| 2 |
+
SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
|
| 3 |
+
SPDX-License-Identifier: Apache-2.0
|
| 4 |
+
-->
|
| 5 |
+
|
| 6 |
+
# Egocentric Hand Reconstruction
|
| 7 |
+
|
| 8 |
+
Automated pipeline for 4D hand and camera pose reconstruction from egocentric videos. Integrates ViPE and Dyn-HaMR in containerized environments.
|
| 9 |
+
|
| 10 |
+
## Setup
|
| 11 |
+
|
| 12 |
+
Fetch vendored sources from [IsaacTeleop](https://github.com/NVIDIA/IsaacTeleop):
|
| 13 |
+
|
| 14 |
+
```bash
|
| 15 |
+
./sync.sh
|
| 16 |
+
```
|
| 17 |
+
|
| 18 |
+
Install the host-side orchestration package:
|
| 19 |
+
|
| 20 |
+
```bash
|
| 21 |
+
pip install -e docker/
|
| 22 |
+
```
|
| 23 |
+
|
| 24 |
+
Build both Docker images (ViPE + Dyn-HaMR):
|
| 25 |
+
|
| 26 |
+
```bash
|
| 27 |
+
python -m v2d_ego_hand_reconstruction.docker.build
|
| 28 |
+
```
|
| 29 |
+
|
| 30 |
+
Place required data in your weights directory before running (see [Isaac Teleop Documentation](https://nvidia.github.io/IsaacTeleop/main/references/egocentric_hand_reconstruction.html)).
|
| 31 |
+
The layout follows the manotorch convention so the same directory is shared with `v2d_hamer`:
|
| 32 |
+
|
| 33 |
+
```
|
| 34 |
+
<weights_dir>/
|
| 35 |
+
├── models/
|
| 36 |
+
│ └── MANO_RIGHT.pkl # from https://mano.is.tue.mpg.de/
|
| 37 |
+
└── BMC/
|
| 38 |
+
└── *.npy # from the Hand-BMC-pytorch repo
|
| 39 |
+
```
|
| 40 |
+
|
| 41 |
+
## Usage
|
| 42 |
+
|
| 43 |
+
**Python (programmatic):**
|
| 44 |
+
|
| 45 |
+
```python
|
| 46 |
+
from v2d_ego_hand_reconstruction.docker.run_reconstruction import run_reconstruction
|
| 47 |
+
|
| 48 |
+
run_reconstruction(
|
| 49 |
+
video_input="path/to/video.mp4",
|
| 50 |
+
output_dir="data/outputs/ego_hand",
|
| 51 |
+
)
|
| 52 |
+
```
|
| 53 |
+
|
| 54 |
+
**CLI:**
|
| 55 |
+
|
| 56 |
+
```bash
|
| 57 |
+
python -m v2d_ego_hand_reconstruction.docker.run_reconstruction \
|
| 58 |
+
--video_input path/to/video.mp4 \
|
| 59 |
+
--output_dir data/outputs/ego_hand
|
| 60 |
+
```
|
| 61 |
+
|
| 62 |
+
Remote videos (S3/Swift) are also supported:
|
| 63 |
+
|
| 64 |
+
Set environment variables ACCESS_KEY_ID and SECRET_ACCESS_KEY for S3/Swift permission.
|
| 65 |
+
|
| 66 |
+
```bash
|
| 67 |
+
export ACCESS_KEY_ID=XXX SECRET_ACCESS_KEY=XXX
|
| 68 |
+
```
|
| 69 |
+
|
| 70 |
+
Please check [Isaac Teleop Documentation](https://nvidia.github.io/IsaacTeleop/main/references/egocentric_hand_reconstruction.html) for detail.
|
| 71 |
+
|
| 72 |
+
```bash
|
| 73 |
+
python -m v2d_ego_hand_reconstruction.docker.run_reconstruction \
|
| 74 |
+
--video_input s3://bucket/video.mp4 \
|
| 75 |
+
--output_dir data/outputs/ego_hand
|
| 76 |
+
```
|
| 77 |
+
|
| 78 |
+
Results are saved to `<output_dir>/logs/`.
|
| 79 |
+
|
| 80 |
+
### Hand mesh generation
|
| 81 |
+
|
| 82 |
+
After running reconstruction, export per-track MANO hand mesh trajectories from every run under `<output_dir>/logs/`:
|
| 83 |
+
|
| 84 |
+
```python
|
| 85 |
+
from v2d_ego_hand_reconstruction.docker.run_mesh_generation import run_mesh_generation
|
| 86 |
+
|
| 87 |
+
run_mesh_generation(output_dir="data/outputs/ego_hand")
|
| 88 |
+
```
|
| 89 |
+
|
| 90 |
+
CLI:
|
| 91 |
+
|
| 92 |
+
```bash
|
| 93 |
+
python -m v2d_ego_hand_reconstruction.docker.run_mesh_generation \
|
| 94 |
+
--output_dir data/outputs/ego_hand
|
| 95 |
+
```
|
| 96 |
+
|
| 97 |
+
Results land at `<output_dir>/logs/.../smooth_fit/<seq>_hand_mesh_traj_<iter>.npz`.
|
| 98 |
+
|
| 99 |
+
## Upstream Diff
|
| 100 |
+
|
| 101 |
+
To see local modifications vs upstream IsaacTeleop:
|
| 102 |
+
|
| 103 |
+
```bash
|
| 104 |
+
./diff.sh # summary
|
| 105 |
+
./diff.sh --full # full unified diff
|
| 106 |
+
```
|
| 107 |
+
|
| 108 |
+
## Structure
|
| 109 |
+
|
| 110 |
+
```
|
| 111 |
+
docker/ Native Python orchestration (tracked in git)
|
| 112 |
+
vendor/ Upstream content from IsaacTeleop (gitignored, populated by sync.sh)
|
| 113 |
+
sync.sh Fetch/update vendored sources
|
| 114 |
+
diff.sh Compare vendor/ against upstream
|
| 115 |
+
```
|
third-party/video_to_data/reconstruction/modules/v2d_ego_hand_reconstruction/__init__.py
ADDED
|
@@ -0,0 +1,2 @@
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
|
| 2 |
+
# SPDX-License-Identifier: Apache-2.0
|
third-party/video_to_data/reconstruction/modules/v2d_ego_hand_reconstruction/diff.sh
ADDED
|
@@ -0,0 +1,44 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/bin/bash
|
| 2 |
+
# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
|
| 3 |
+
# SPDX-License-Identifier: Apache-2.0
|
| 4 |
+
# Show local modifications to vendored content vs upstream IsaacTeleop.
|
| 5 |
+
# Usage: ./diff.sh (summary of changed files)
|
| 6 |
+
# ./diff.sh --full (full unified diff)
|
| 7 |
+
# ./diff.sh --patch (git-format patch, apply with: git apply <patch>)
|
| 8 |
+
set -euo pipefail
|
| 9 |
+
|
| 10 |
+
SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)"
|
| 11 |
+
VENDOR_DIR="$SCRIPT_DIR/vendor"
|
| 12 |
+
REPO="https://github.com/NVIDIA/IsaacTeleop.git"
|
| 13 |
+
BRANCH="main"
|
| 14 |
+
DIR="src/postprocessing/egocentric_hand_reconstruction"
|
| 15 |
+
|
| 16 |
+
if [ ! -d "$VENDOR_DIR" ]; then
|
| 17 |
+
echo "vendor/ not found. Run ./sync.sh first." >&2
|
| 18 |
+
exit 1
|
| 19 |
+
fi
|
| 20 |
+
|
| 21 |
+
tmp=$(mktemp -d)
|
| 22 |
+
trap 'rm -rf "$tmp"' EXIT
|
| 23 |
+
|
| 24 |
+
echo "Fetching upstream ($BRANCH)..." >&2
|
| 25 |
+
git clone --filter=blob:none --sparse --branch "$BRANCH" --depth 1 "$REPO" "$tmp/repo" 2>/dev/null
|
| 26 |
+
cd "$tmp/repo" && git sparse-checkout set "$DIR" 2>/dev/null && cd - > /dev/null
|
| 27 |
+
|
| 28 |
+
upstream="$tmp/repo/$DIR"
|
| 29 |
+
|
| 30 |
+
case "${1:-}" in
|
| 31 |
+
--patch)
|
| 32 |
+
# Produce a git-format patch with paths relative to the IsaacTeleop repo root.
|
| 33 |
+
# Apply in an IsaacTeleop clone with: git apply <patch>
|
| 34 |
+
cp -r "$VENDOR_DIR/." "$tmp/repo/$DIR/"
|
| 35 |
+
cd "$tmp/repo"
|
| 36 |
+
git diff || true
|
| 37 |
+
;;
|
| 38 |
+
--full)
|
| 39 |
+
diff -ru "$upstream/" "$VENDOR_DIR/" || true
|
| 40 |
+
;;
|
| 41 |
+
*)
|
| 42 |
+
diff -rq "$upstream/" "$VENDOR_DIR/" && echo "(no differences)" || true
|
| 43 |
+
;;
|
| 44 |
+
esac
|
third-party/video_to_data/reconstruction/modules/v2d_ego_hand_reconstruction/docker/__init__.py
ADDED
|
@@ -0,0 +1,2 @@
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
|
| 2 |
+
# SPDX-License-Identifier: Apache-2.0
|
third-party/video_to_data/reconstruction/modules/v2d_ego_hand_reconstruction/docker/_config.py
ADDED
|
@@ -0,0 +1,6 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
|
| 2 |
+
# SPDX-License-Identifier: Apache-2.0
|
| 3 |
+
import os
|
| 4 |
+
|
| 5 |
+
MODULE_DIR = os.path.abspath(os.path.join(os.path.dirname(__file__), ".."))
|
| 6 |
+
VENDOR_DIR = os.path.join(MODULE_DIR, "vendor")
|
third-party/video_to_data/reconstruction/modules/v2d_ego_hand_reconstruction/docker/build.py
ADDED
|
@@ -0,0 +1,48 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
|
| 2 |
+
# SPDX-License-Identifier: Apache-2.0
|
| 3 |
+
"""Build Docker images for ego hand reconstruction (ViPE + Dyn-HaMR).
|
| 4 |
+
|
| 5 |
+
Delegates to the vendored shell scripts so build flags stay in sync with
|
| 6 |
+
upstream IsaacTeleop.
|
| 7 |
+
"""
|
| 8 |
+
|
| 9 |
+
import subprocess
|
| 10 |
+
from pathlib import Path
|
| 11 |
+
|
| 12 |
+
from v2d_ego_hand_reconstruction.docker._config import MODULE_DIR, VENDOR_DIR
|
| 13 |
+
|
| 14 |
+
|
| 15 |
+
def _sync_vendor() -> None:
|
| 16 |
+
"""Fetch vendored sources from IsaacTeleop if not already present."""
|
| 17 |
+
subprocess.run([str(Path(MODULE_DIR) / "sync.sh")], check=True)
|
| 18 |
+
|
| 19 |
+
|
| 20 |
+
def _run_vendor_script(script: str, *args: str) -> None:
|
| 21 |
+
vendor = Path(VENDOR_DIR)
|
| 22 |
+
if not vendor.is_dir():
|
| 23 |
+
print(f"{vendor} not found. Running sync.sh to fetch vendored sources...")
|
| 24 |
+
_sync_vendor()
|
| 25 |
+
subprocess.run(
|
| 26 |
+
[str(vendor / "docker" / script), *args],
|
| 27 |
+
check=True,
|
| 28 |
+
)
|
| 29 |
+
|
| 30 |
+
|
| 31 |
+
def build_vipe() -> None:
|
| 32 |
+
"""Build the ViPE camera estimation image."""
|
| 33 |
+
_run_vendor_script("vipe.sh", "build")
|
| 34 |
+
|
| 35 |
+
|
| 36 |
+
def build_dynhamr() -> None:
|
| 37 |
+
"""Build the Dyn-HaMR hand reconstruction image."""
|
| 38 |
+
_run_vendor_script("dynhamr.sh", "build")
|
| 39 |
+
|
| 40 |
+
|
| 41 |
+
def build_all() -> None:
|
| 42 |
+
"""Build both ViPE and Dyn-HaMR images."""
|
| 43 |
+
build_vipe()
|
| 44 |
+
build_dynhamr()
|
| 45 |
+
|
| 46 |
+
|
| 47 |
+
if __name__ == "__main__":
|
| 48 |
+
build_all()
|
third-party/video_to_data/reconstruction/modules/v2d_ego_hand_reconstruction/docker/pyproject.toml
ADDED
|
@@ -0,0 +1,19 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
|
| 2 |
+
# SPDX-License-Identifier: Apache-2.0
|
| 3 |
+
[build-system]
|
| 4 |
+
requires = ["setuptools>=68.0", "wheel"]
|
| 5 |
+
build-backend = "setuptools.build_meta"
|
| 6 |
+
|
| 7 |
+
[project]
|
| 8 |
+
name = "v2d-ego-hand-reconstruction-docker"
|
| 9 |
+
version = "0.1.0"
|
| 10 |
+
description = "Docker orchestration for ego hand reconstruction (ViPE + Dyn-HaMR)"
|
| 11 |
+
requires-python = ">=3.10"
|
| 12 |
+
dependencies = ["boto3"]
|
| 13 |
+
|
| 14 |
+
[tool.setuptools]
|
| 15 |
+
packages = ["v2d_ego_hand_reconstruction", "v2d_ego_hand_reconstruction.docker"]
|
| 16 |
+
|
| 17 |
+
[tool.setuptools.package-dir]
|
| 18 |
+
"v2d_ego_hand_reconstruction" = ".."
|
| 19 |
+
"v2d_ego_hand_reconstruction.docker" = "."
|
third-party/video_to_data/reconstruction/modules/v2d_ego_hand_reconstruction/docker/run_mesh_generation.py
ADDED
|
@@ -0,0 +1,72 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
|
| 2 |
+
# SPDX-License-Identifier: Apache-2.0
|
| 3 |
+
"""Export per-track MANO hand meshes and joint trajectories from Dyn-HaMR results.
|
| 4 |
+
|
| 5 |
+
Delegates to the vendored ``run_mesh_generation.sh`` so mesh export logic stays
|
| 6 |
+
in sync with upstream IsaacTeleop.
|
| 7 |
+
|
| 8 |
+
Prerequisites:
|
| 9 |
+
- Dyn-HaMR Docker image must be built (``python -m v2d_ego_hand_reconstruction.docker.build``).
|
| 10 |
+
- MANO_RIGHT.pkl must be placed in *output_dir*.
|
| 11 |
+
"""
|
| 12 |
+
|
| 13 |
+
import os
|
| 14 |
+
import subprocess
|
| 15 |
+
|
| 16 |
+
from v2d_ego_hand_reconstruction.docker._config import VENDOR_DIR
|
| 17 |
+
|
| 18 |
+
|
| 19 |
+
def run_mesh_generation(
|
| 20 |
+
output_dir: str,
|
| 21 |
+
*,
|
| 22 |
+
phase: str = "smooth_fit",
|
| 23 |
+
gpu: int = 0,
|
| 24 |
+
no_temporal_smooth: bool = False,
|
| 25 |
+
no_smooth_trans: bool = False,
|
| 26 |
+
) -> None:
|
| 27 |
+
"""Run hand mesh export over every Dyn-HaMR run under *output_dir*.
|
| 28 |
+
|
| 29 |
+
Args:
|
| 30 |
+
output_dir: Directory containing Dyn-HaMR
|
| 31 |
+
``logs/.../smooth_fit/*_world_results.npz``.
|
| 32 |
+
phase: Phase subdir under each run dir (default: ``smooth_fit``).
|
| 33 |
+
gpu: GPU index inside the container.
|
| 34 |
+
no_temporal_smooth: Disable OneEuro smoothing on poses.
|
| 35 |
+
no_smooth_trans: Smooth pose only, not translation.
|
| 36 |
+
"""
|
| 37 |
+
output_dir = os.path.abspath(output_dir)
|
| 38 |
+
os.makedirs(output_dir, exist_ok=True)
|
| 39 |
+
|
| 40 |
+
env = {
|
| 41 |
+
**os.environ,
|
| 42 |
+
"OUTPUTS_DIR": output_dir,
|
| 43 |
+
"PHASE": phase,
|
| 44 |
+
"GPU": str(gpu),
|
| 45 |
+
"NO_TEMPORAL_SMOOTH": "1" if no_temporal_smooth else "0",
|
| 46 |
+
"NO_SMOOTH_TRANS": "1" if no_smooth_trans else "0",
|
| 47 |
+
}
|
| 48 |
+
|
| 49 |
+
subprocess.run(
|
| 50 |
+
[os.path.join(VENDOR_DIR, "scripts", "run_mesh_generation.sh")],
|
| 51 |
+
env=env,
|
| 52 |
+
check=True,
|
| 53 |
+
)
|
| 54 |
+
|
| 55 |
+
|
| 56 |
+
if __name__ == "__main__":
|
| 57 |
+
import argparse
|
| 58 |
+
|
| 59 |
+
parser = argparse.ArgumentParser(description=__doc__)
|
| 60 |
+
parser.add_argument("--output_dir", required=True, help="Output directory (contains logs/)")
|
| 61 |
+
parser.add_argument("--phase", default="smooth_fit")
|
| 62 |
+
parser.add_argument("--gpu", type=int, default=0)
|
| 63 |
+
parser.add_argument("--no_temporal_smooth", action="store_true")
|
| 64 |
+
parser.add_argument("--no_smooth_trans", action="store_true")
|
| 65 |
+
args = parser.parse_args()
|
| 66 |
+
run_mesh_generation(
|
| 67 |
+
args.output_dir,
|
| 68 |
+
phase=args.phase,
|
| 69 |
+
gpu=args.gpu,
|
| 70 |
+
no_temporal_smooth=args.no_temporal_smooth,
|
| 71 |
+
no_smooth_trans=args.no_smooth_trans,
|
| 72 |
+
)
|