diff --git a/third-party/video_to_data/reconstruction/modules/v2d_detectron2/docker/__init__.py b/third-party/video_to_data/reconstruction/modules/v2d_detectron2/docker/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..52a7a9daf028f654d6a02f65c99cc609a57b492f --- /dev/null +++ b/third-party/video_to_data/reconstruction/modules/v2d_detectron2/docker/__init__.py @@ -0,0 +1,2 @@ +# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 diff --git a/third-party/video_to_data/reconstruction/modules/v2d_detectron2/docker/_config.py b/third-party/video_to_data/reconstruction/modules/v2d_detectron2/docker/_config.py new file mode 100644 index 0000000000000000000000000000000000000000..eb97a8b12e31665c0942f743df421b0def43ac28 --- /dev/null +++ b/third-party/video_to_data/reconstruction/modules/v2d_detectron2/docker/_config.py @@ -0,0 +1,6 @@ +# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 +import os + +IMAGE_NAME = "v2d_detectron2" +MODULES_DIR = os.path.abspath(os.path.join(os.path.dirname(os.path.abspath(__file__)), "..", "..")) diff --git a/third-party/video_to_data/reconstruction/modules/v2d_detectron2/docker/build.py b/third-party/video_to_data/reconstruction/modules/v2d_detectron2/docker/build.py new file mode 100644 index 0000000000000000000000000000000000000000..122bc23efa38d9bff7895ca4251dd2148a7f1830 --- /dev/null +++ b/third-party/video_to_data/reconstruction/modules/v2d_detectron2/docker/build.py @@ -0,0 +1,19 @@ +# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 +import subprocess +import os + +IMAGE_NAME = "v2d_detectron2" + +current_dir = os.path.dirname(os.path.abspath(__file__)) +module_dir = os.path.join(current_dir, "..") +root_dir = os.path.join(module_dir, "..") +dockerfile_path = os.path.join(current_dir, "Dockerfile") + + +def build_docker_image() -> None: + subprocess.run(["docker", "build", "-t", IMAGE_NAME, "-f", dockerfile_path, root_dir], check=True) + + +if __name__ == "__main__": + build_docker_image() diff --git a/third-party/video_to_data/reconstruction/modules/v2d_detectron2/docker/pyproject.toml b/third-party/video_to_data/reconstruction/modules/v2d_detectron2/docker/pyproject.toml new file mode 100644 index 0000000000000000000000000000000000000000..40f06f46b5b956ad1456074778d0dbc264df220a --- /dev/null +++ b/third-party/video_to_data/reconstruction/modules/v2d_detectron2/docker/pyproject.toml @@ -0,0 +1,18 @@ +# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 +[build-system] +requires = ["setuptools>=68.0", "wheel"] +build-backend = "setuptools.build_meta" + +[project] +name = "v2d-detectron2-docker" +version = "0.1.0" +description = "Docker orchestration scripts for Detectron2 tracking" +requires-python = ">=3.10" +dependencies = ["v2d-docker", "omegaconf"] + +[tool.setuptools] +packages = ["v2d.detectron2.docker"] + +[tool.setuptools.package-dir] +"v2d.detectron2.docker" = "." diff --git a/third-party/video_to_data/reconstruction/modules/v2d_detectron2/docker/run_download_weights.py b/third-party/video_to_data/reconstruction/modules/v2d_detectron2/docker/run_download_weights.py new file mode 100644 index 0000000000000000000000000000000000000000..51e3632ba27f7bfcaa08d935b3b10d0aa3837c7c --- /dev/null +++ b/third-party/video_to_data/reconstruction/modules/v2d_detectron2/docker/run_download_weights.py @@ -0,0 +1,41 @@ +# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 +import os +import subprocess +from v2d.detectron2.docker._config import IMAGE_NAME, MODULES_DIR + + +def run_download_weights( + output_dir: str, + model_sizes: list[str] | None = None, + dev: bool = False, +) -> None: + if not os.path.exists(output_dir): + os.makedirs(output_dir) + output_dir = os.path.abspath(output_dir) + + cmd = [ + "docker", "run", "--rm", + "--user", f"{os.getuid()}:{os.getgid()}", + "-v", f"{output_dir}:/data/weights", + ] + if dev: + cmd += ["-v", f"{MODULES_DIR}:/workspace"] + cmd += [IMAGE_NAME, "python", "-m", "v2d.detectron2.lib.download_weights", + "--output_dir", "/data/weights"] + if model_sizes: + cmd += ["--model_sizes"] + model_sizes + + subprocess.run(cmd, check=True) + + +if __name__ == "__main__": + import argparse + + parser = argparse.ArgumentParser(description="Download ViTDet checkpoints") + parser.add_argument("--output_dir", type=str, required=True) + parser.add_argument("--model_sizes", type=str, nargs="+", default=["b"], choices=["b", "l", "h"]) + parser.add_argument("--dev", action="store_true") + args = parser.parse_args() + + run_download_weights(args.output_dir, args.model_sizes, dev=args.dev) diff --git a/third-party/video_to_data/reconstruction/modules/v2d_detectron2/docker/run_mv_track_bboxes.py b/third-party/video_to_data/reconstruction/modules/v2d_detectron2/docker/run_mv_track_bboxes.py new file mode 100644 index 0000000000000000000000000000000000000000..c1b52a2e83f82f8bd7a1f845584d953203d3db1f --- /dev/null +++ b/third-party/video_to_data/reconstruction/modules/v2d_detectron2/docker/run_mv_track_bboxes.py @@ -0,0 +1,70 @@ +# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 +from pathlib import Path + +from v2d.docker.container import run_in_container +from v2d.detectron2.docker._config import IMAGE_NAME, MODULES_DIR + +_LIB_CONFIG = Path(__file__).parent.parent / "lib" / "mv_track_bboxes.yaml" + + +def run_mv_track_bboxes( + rgb_dir: str, + weights_dir: str, + output_dir: str, + labeled_bbox_dir: str | None = None, + config_path: str = str(_LIB_CONFIG), + debug: int = -1, + dev: bool = False, +) -> None: + inputs = { + "rgb_dir": rgb_dir, + "weights_dir": weights_dir, + "config_path": config_path, + } + if labeled_bbox_dir: + inputs["labeled_bbox_dir"] = labeled_bbox_dir + + outputs = {"output_dir": output_dir} + + run_in_container( + image=IMAGE_NAME, + module="v2d.detectron2.lib.mv_track_bboxes", + inputs=inputs, + outputs=outputs, + extra_args={"debug": debug if debug >= 0 else None}, + dev=dev, + modules_dir=MODULES_DIR, + gpus=True, + env={ + "PYTHONUNBUFFERED": "1", + }, + ) + + +if __name__ == "__main__": + import argparse + + parser = argparse.ArgumentParser(description="Run multi-view bbox tracking") + parser.add_argument("--rgb_dir", type=str, required=True, help="Directory containing input frames") + parser.add_argument("--weights_dir", type=str, required=True, help="Directory containing model weights") + parser.add_argument("--output_dir", type=str, required=True, help="Directory for outputs") + parser.add_argument( + "--labeled_bbox_dir", type=str, default=None, + help="Optional directory with per-camera labeled object bbox JSONs " + "(anchors primary person selection to the object bbox).", + ) + parser.add_argument("--config_path", type=str, default=str(_LIB_CONFIG), help="Path to mv_track_bboxes.yaml") + parser.add_argument("--debug", type=int, default=-1, help="Debug level") + parser.add_argument("--dev", action="store_true") + args = parser.parse_args() + + run_mv_track_bboxes( + rgb_dir=args.rgb_dir, + weights_dir=args.weights_dir, + output_dir=args.output_dir, + labeled_bbox_dir=args.labeled_bbox_dir, + config_path=args.config_path, + debug=args.debug, + dev=args.dev, + ) diff --git a/third-party/video_to_data/reconstruction/modules/v2d_detectron2/docker/run_shell.py b/third-party/video_to_data/reconstruction/modules/v2d_detectron2/docker/run_shell.py new file mode 100644 index 0000000000000000000000000000000000000000..8a83d6aecb738f71e5561d5cd0d77669d5839d3e --- /dev/null +++ b/third-party/video_to_data/reconstruction/modules/v2d_detectron2/docker/run_shell.py @@ -0,0 +1,26 @@ +# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 +import subprocess +import os +from v2d.detectron2.docker._config import IMAGE_NAME, MODULES_DIR + + +def run_shell(dev: bool = False) -> None: + cmd = [ + "docker", "run", "-it", "--rm", + "--gpus", "all", + "--user", f"{os.getuid()}:{os.getgid()}", + ] + if dev: + cmd += ["-v", f"{MODULES_DIR}:/workspace"] + cmd += [IMAGE_NAME, "bash"] + subprocess.run(cmd, check=True) + + +if __name__ == "__main__": + import argparse + + parser = argparse.ArgumentParser(description="Run shell in v2d_detectron2 container") + parser.add_argument("--dev", action="store_true", help="Mount local modules for development") + args = parser.parse_args() + run_shell(dev=args.dev) diff --git a/third-party/video_to_data/reconstruction/modules/v2d_detectron2/docker/run_track_bboxes.py b/third-party/video_to_data/reconstruction/modules/v2d_detectron2/docker/run_track_bboxes.py new file mode 100644 index 0000000000000000000000000000000000000000..4b7cee9a434b20174292b1ab3e4e9396d5c7949f --- /dev/null +++ b/third-party/video_to_data/reconstruction/modules/v2d_detectron2/docker/run_track_bboxes.py @@ -0,0 +1,78 @@ +# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 +from v2d.docker.container import run_in_container +from v2d.detectron2.docker._config import IMAGE_NAME, MODULES_DIR + + +def run_track_bboxes( + rgb_path: str, + weights_dir: str, + output_path: str, + model_size: str = "b", + bbox_thr: float = 0.5, + iou_threshold: float = 0.3, + max_lost: int = 30, + min_hits: int = 3, + batch_size: int = 1, + debug: int = 0, + dev: bool = False, +) -> None: + inputs = { + "rgb_path": rgb_path, + "weights_dir": weights_dir, + } + + run_in_container( + image=IMAGE_NAME, + module="v2d.detectron2.lib.track_bboxes", + inputs=inputs, + outputs={"output_path": output_path}, + extra_args={ + "model_size": model_size, + "bbox_thr": bbox_thr, + "iou_threshold": iou_threshold, + "max_lost": max_lost, + "min_hits": min_hits, + "batch_size": batch_size, + "debug": debug if debug > 0 else None, + }, + dev=dev, + modules_dir=MODULES_DIR, + gpus=True, + env={ + "PYTHONUNBUFFERED": "1", + }, + ) + + +if __name__ == "__main__": + import argparse + + parser = argparse.ArgumentParser(description="Run bbox tracking (single camera)") + parser.add_argument("--rgb_path", type=str, required=True, + help="Path to input frames (image dir, .h5, or video file)") + parser.add_argument("--weights_dir", type=str, required=True) + parser.add_argument("--output_path", type=str, required=True, help="Output .pt file path") + parser.add_argument("--model_size", type=str, default="b", choices=["b", "l", "h"]) + parser.add_argument("--bbox_thr", type=float, default=0.5) + parser.add_argument("--iou_threshold", type=float, default=0.3) + parser.add_argument("--max_lost", type=int, default=30) + parser.add_argument("--min_hits", type=int, default=3) + parser.add_argument("--batch_size", type=int, default=1) + parser.add_argument("--debug", type=int, default=0) + parser.add_argument("--dev", action="store_true") + args = parser.parse_args() + + run_track_bboxes( + rgb_path=args.rgb_path, + weights_dir=args.weights_dir, + output_path=args.output_path, + model_size=args.model_size, + bbox_thr=args.bbox_thr, + iou_threshold=args.iou_threshold, + max_lost=args.max_lost, + min_hits=args.min_hits, + batch_size=args.batch_size, + debug=args.debug, + dev=args.dev, + ) diff --git a/third-party/video_to_data/reconstruction/modules/v2d_detectron2/lib/__init__.py b/third-party/video_to_data/reconstruction/modules/v2d_detectron2/lib/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..52a7a9daf028f654d6a02f65c99cc609a57b492f --- /dev/null +++ b/third-party/video_to_data/reconstruction/modules/v2d_detectron2/lib/__init__.py @@ -0,0 +1,2 @@ +# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 diff --git a/third-party/video_to_data/reconstruction/modules/v2d_detectron2/lib/build_detector.py b/third-party/video_to_data/reconstruction/modules/v2d_detectron2/lib/build_detector.py new file mode 100644 index 0000000000000000000000000000000000000000..5e2d102768e4dac4d44ad81f74dd0c54f216b95f --- /dev/null +++ b/third-party/video_to_data/reconstruction/modules/v2d_detectron2/lib/build_detector.py @@ -0,0 +1,188 @@ +# Copyright (c) Meta Platforms, Inc. and affiliates. + +import os +from pathlib import Path + +import numpy as np +import torch + + +class Detector: + def __init__( + self, + name="vitdet", + device="cuda", + model_size="b", + test_score_thresh: float = 0.25, + **kwargs, + ): + self.device = device + + if name == "vitdet": + print(f"Loading ViTDet-{model_size.upper()} detector...") + self.detector = load_detectron2_vitdet( + model_size=model_size, + test_score_thresh=test_score_thresh, + **kwargs, + ) + self.detector_func = run_detectron2_vitdet + self.batch_func = run_detectron2_vitdet_batch + + self.detector = self.detector.to(self.device) + self.detector.eval() + else: + raise NotImplementedError + + def run_detection(self, img, **kwargs): + return self.detector_func(self.detector, img, **kwargs) + + def run_detection_batch(self, images: list[np.ndarray], **kwargs) -> list[tuple[np.ndarray, np.ndarray]]: + return self.batch_func(self.detector, images, **kwargs) + + +VITDET_VARIANTS = { + "b": { + "config": "cascade_mask_rcnn_vitdet_b_100ep.py", + "checkpoint_url": "https://dl.fbaipublicfiles.com/detectron2/ViTDet/COCO/cascade_mask_rcnn_vitdet_b/f325358525/model_final_435fa9.pkl", + "checkpoint_file": "model_final_435fa9.pkl", + }, + "l": { + "config": "cascade_mask_rcnn_vitdet_l_100ep.py", + "checkpoint_url": "https://dl.fbaipublicfiles.com/detectron2/ViTDet/COCO/cascade_mask_rcnn_vitdet_l/f328021305/model_final_1a9f28.pkl", + "checkpoint_file": "model_final_1a9f28.pkl", + }, + "h": { + "config": "cascade_mask_rcnn_vitdet_h_75ep.py", + "checkpoint_url": "https://dl.fbaipublicfiles.com/detectron2/ViTDet/COCO/cascade_mask_rcnn_vitdet_h/f328730692/model_final_f05665.pkl", + "checkpoint_file": "model_final_f05665.pkl", + }, +} + + +def load_detectron2_vitdet( + path: str = "", + model_size: str = "b", + test_score_thresh: float = 0.25, +): + """Load a ViTDet Cascade Mask R-CNN detector. + + Args: + path: Directory containing the checkpoint file. If empty, downloads + from the detectron2 model zoo. + model_size: One of "b" (ViT-Base, fastest), "l" (ViT-Large), + "h" (ViT-Huge, most accurate). + test_score_thresh: Internal NMS score threshold. Detections below this + are discarded before they leave the model. Lower for ByteTrack + (e.g. 0.1) to retain partial-occlusion detections. + """ + from detectron2.checkpoint import DetectionCheckpointer + from detectron2.config import instantiate, LazyConfig + + if model_size not in VITDET_VARIANTS: + raise ValueError(f"Unknown model_size '{model_size}', expected one of {list(VITDET_VARIANTS)}") + variant = VITDET_VARIANTS[model_size] + + cfg_path = Path(__file__).parent / variant["config"] + if not cfg_path.exists(): + raise FileNotFoundError(f"Config file not found at {cfg_path}") + + detectron2_cfg = LazyConfig.load(str(cfg_path)) + detectron2_cfg.train.init_checkpoint = ( + variant["checkpoint_url"] + if path == "" + else os.path.join(path, variant["checkpoint_file"]) + ) + for i in range(3): + detectron2_cfg.model.roi_heads.box_predictors[i].test_score_thresh = test_score_thresh + detector = instantiate(detectron2_cfg.model) + checkpointer = DetectionCheckpointer(detector) + checkpointer.load(detectron2_cfg.train.init_checkpoint) + + detector.eval() + return detector + + +def run_detectron2_vitdet( + detector, + img, + det_cat_id: int = 0, # 0: person + bbox_thr: float = 0.5, + default_to_full_image: bool = True, +): + import detectron2.data.transforms as T + + height, width = img.shape[:2] + + IMAGE_SIZE = 1024 + transforms = T.ResizeShortestEdge(short_edge_length=IMAGE_SIZE, max_size=IMAGE_SIZE) + img_transformed = transforms(T.AugInput(img)).apply_image(img) + img_transformed = torch.as_tensor( + img_transformed.astype("float32").transpose(2, 0, 1) + ) + inputs = {"image": img_transformed, "height": height, "width": width} + + with torch.no_grad(): + det_out = detector([inputs]) + + det_instances = det_out[0]["instances"] + valid_idx = (det_instances.pred_classes == det_cat_id) & ( + det_instances.scores > bbox_thr + ) + if valid_idx.sum() == 0 and default_to_full_image: + boxes = np.array([0, 0, width, height]).reshape(1, 4) + scores = np.array([1.0]) + else: + boxes = det_instances.pred_boxes.tensor[valid_idx].cpu().numpy() + scores = det_instances.scores[valid_idx].cpu().numpy() + + sorted_indices = np.argsort(scores)[::-1] + return boxes[sorted_indices].reshape(-1, 4), scores[sorted_indices] + + +def run_detectron2_vitdet_batch( + detector, + images: list[np.ndarray], + det_cat_id: int = 0, + bbox_thr: float = 0.5, + default_to_full_image: bool = True, +) -> list[tuple[np.ndarray, np.ndarray]]: + """Run ViTDet detection on a batch of images in a single forward pass. + + Memory scales linearly with batch size (~2-3 GB per image for ViTDet-B + at 1024px). Batch sizes of 4-8 are practical on a 24 GB GPU. + """ + import detectron2.data.transforms as T + + IMAGE_SIZE = 768 + transforms = T.ResizeShortestEdge(short_edge_length=IMAGE_SIZE, max_size=IMAGE_SIZE) + + inputs = [] + for img in images: + height, width = img.shape[:2] + img_transformed = transforms(T.AugInput(img)).apply_image(img) + img_transformed = torch.as_tensor( + img_transformed.astype("float32").transpose(2, 0, 1) + ) + inputs.append({"image": img_transformed, "height": height, "width": width}) + + with torch.no_grad(): + det_outputs = detector(inputs) + + results = [] + for img, det_out in zip(images, det_outputs): + height, width = img.shape[:2] + det_instances = det_out["instances"] + valid_idx = (det_instances.pred_classes == det_cat_id) & ( + det_instances.scores > bbox_thr + ) + if valid_idx.sum() == 0 and default_to_full_image: + boxes = np.array([0, 0, width, height]).reshape(1, 4) + scores = np.array([1.0]) + else: + boxes = det_instances.pred_boxes.tensor[valid_idx].cpu().numpy() + scores = det_instances.scores[valid_idx].cpu().numpy() + + sorted_indices = np.argsort(scores)[::-1] + results.append((boxes[sorted_indices].reshape(-1, 4), scores[sorted_indices])) + + return results diff --git a/third-party/video_to_data/reconstruction/modules/v2d_detectron2/lib/bytetracker.py b/third-party/video_to_data/reconstruction/modules/v2d_detectron2/lib/bytetracker.py new file mode 100644 index 0000000000000000000000000000000000000000..e9252afa8c7d6c1fa057dca62a713b3ec23792aa --- /dev/null +++ b/third-party/video_to_data/reconstruction/modules/v2d_detectron2/lib/bytetracker.py @@ -0,0 +1,286 @@ +# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 +"""ByteTrack multi-object tracker. + +Implements the two-stage association strategy from: + Zhang et al., "ByteTrack: Multi-Object Tracking by Associating Every Detection Box", ECCV 2022. + +Key idea: low-confidence detections (from partial occlusion) are used in a second +association pass to maintain tracks that would otherwise be lost. + +Uses a Kalman filter with constant-velocity model for bbox state prediction. +""" + +from __future__ import annotations + +import numpy as np + +from .tracker import Track, TrackState, bbox_iou_matrix, hungarian_assign + + +def _bbox_to_z(bbox: np.ndarray) -> np.ndarray: + """Convert [x1, y1, x2, y2] to Kalman measurement [cx, cy, a, h].""" + w = bbox[2] - bbox[0] + h = bbox[3] - bbox[1] + cx = bbox[0] + w / 2 + cy = bbox[1] + h / 2 + a = w / (h + 1e-6) + return np.array([cx, cy, a, h]) + + +def _z_to_bbox(z: np.ndarray) -> np.ndarray: + """Convert Kalman measurement [cx, cy, a, h] to [x1, y1, x2, y2].""" + w = z[2] * z[3] + h = z[3] + return np.array([ + z[0] - w / 2, + z[1] - h / 2, + z[0] + w / 2, + z[1] + h / 2, + ]) + + +class KalmanBoxTracker: + """Per-track Kalman filter over [cx, cy, aspect_ratio, h, vcx, vcy, va, vh].""" + + _DIM_Z = 4 + _DIM_X = 8 + + def __init__(self, bbox: np.ndarray): + self.x = np.zeros(self._DIM_X) + self.x[:self._DIM_Z] = _bbox_to_z(bbox) + + # State transition (constant velocity) + self.F = np.eye(self._DIM_X) + for i in range(self._DIM_Z): + self.F[i, self._DIM_Z + i] = 1.0 + + # Measurement matrix + self.H = np.zeros((self._DIM_Z, self._DIM_X)) + self.H[:self._DIM_Z, :self._DIM_Z] = np.eye(self._DIM_Z) + + # Covariance + self.P = np.eye(self._DIM_X) * 10.0 + self.P[self._DIM_Z:, self._DIM_Z:] *= 1000.0 + + # Process noise + self.Q = np.eye(self._DIM_X) + self.Q[self._DIM_Z:, self._DIM_Z:] *= 0.01 + + # Measurement noise + self.R = np.eye(self._DIM_Z) + self.R[2, 2] *= 10.0 # aspect ratio is less certain + + def predict(self) -> np.ndarray: + """Advance state and return predicted bbox [x1, y1, x2, y2].""" + # Prevent negative height + if self.x[3] + self.x[7] <= 0: + self.x[7] = 0.0 + + self.x = self.F @ self.x + self.P = self.F @ self.P @ self.F.T + self.Q + return self.get_bbox() + + def update(self, bbox: np.ndarray) -> None: + """Correct state with observed bbox.""" + z = _bbox_to_z(bbox) + y = z - self.H @ self.x + S = self.H @ self.P @ self.H.T + self.R + K = self.P @ self.H.T @ np.linalg.inv(S) + self.x = self.x + K @ y + I_KH = np.eye(self._DIM_X) - K @ self.H + self.P = I_KH @ self.P + + def get_bbox(self) -> np.ndarray: + """Current state as [x1, y1, x2, y2].""" + return _z_to_bbox(self.x[:self._DIM_Z]) + + +class _STrack: + """Internal tracked object pairing a Track with its Kalman state.""" + + def __init__(self, track: Track, kalman: KalmanBoxTracker): + self.track = track + self.kalman = kalman + + +class ByteTracker: + """ByteTrack multi-object tracker with two-stage association. + + Args: + track_thresh: Confidence split between high and low detections. + match_thresh: IoU threshold for first (high-confidence) association. + second_match_thresh: IoU threshold for second (low-confidence) association. + max_lost: Frames a track survives without a match before removal. + min_hits: Minimum detections before a tentative track is confirmed. + """ + + def __init__( + self, + track_thresh: float = 0.6, + match_thresh: float = 0.8, + second_match_thresh: float = 0.5, + max_lost: int = 30, + min_hits: int = 3, + ): + self.track_thresh = track_thresh + self.match_thresh = match_thresh + self.second_match_thresh = second_match_thresh + self.max_lost = max_lost + self.min_hits = min_hits + + self._next_id = 0 + self._active: list[_STrack] = [] + self._lost: list[_STrack] = [] + self._tentative: list[_STrack] = [] + self._finished: list[_STrack] = [] + + def _new_strack(self, frame_idx: int, bbox: np.ndarray, score: float) -> _STrack: + track = Track(track_id=self._next_id, state=TrackState.TENTATIVE) + track.append(frame_idx, bbox, score) + kalman = KalmanBoxTracker(bbox) + self._next_id += 1 + return _STrack(track, kalman) + + def _predicted_bboxes(self, stracks: list[_STrack]) -> np.ndarray: + if not stracks: + return np.empty((0, 4)) + return np.array([st.kalman.predict() for st in stracks]) + + def update(self, frame_idx: int, bboxes: np.ndarray, scores: np.ndarray): + """Process one frame of detections (all above det_thresh). + + The caller should pass ALL detections above det_thresh; this method + splits them into high/low confidence internally. + """ + # Split detections by confidence + high_mask = scores >= self.track_thresh + low_mask = ~high_mask + + high_bboxes = bboxes[high_mask] if high_mask.any() else np.empty((0, 4)) + high_scores = scores[high_mask] if high_mask.any() else np.empty(0) + low_bboxes = bboxes[low_mask] if low_mask.any() else np.empty((0, 4)) + low_scores = scores[low_mask] if low_mask.any() else np.empty(0) + + # Predict positions for all tracked objects + established = self._active + self._lost + pred_bboxes = self._predicted_bboxes(established) + + # --- First association: high-confidence detections vs all tracks --- + if len(established) > 0 and len(high_bboxes) > 0: + iou = bbox_iou_matrix(pred_bboxes, high_bboxes) + matches_1, unmatched_t_1, unmatched_d_1 = hungarian_assign( + iou, self.match_thresh + ) + elif len(established) > 0: + matches_1 = [] + unmatched_t_1 = list(range(len(established))) + unmatched_d_1 = [] + else: + matches_1 = [] + unmatched_t_1 = [] + unmatched_d_1 = list(range(len(high_bboxes))) + + new_active: list[_STrack] = [] + + for t_idx, d_idx in matches_1: + st = established[t_idx] + st.kalman.update(high_bboxes[d_idx]) + st.track.append(frame_idx, high_bboxes[d_idx], float(high_scores[d_idx])) + new_active.append(st) + + # --- Second association: low-confidence detections vs unmatched tracks --- + remaining_stracks = [established[i] for i in unmatched_t_1] + + if len(remaining_stracks) > 0 and len(low_bboxes) > 0: + remaining_pred = np.array([st.kalman.get_bbox() for st in remaining_stracks]) + iou_2 = bbox_iou_matrix(remaining_pred, low_bboxes) + matches_2, unmatched_t_2, _ = hungarian_assign( + iou_2, self.second_match_thresh + ) + elif len(remaining_stracks) > 0: + matches_2 = [] + unmatched_t_2 = list(range(len(remaining_stracks))) + else: + matches_2 = [] + unmatched_t_2 = [] + + for t_idx, d_idx in matches_2: + st = remaining_stracks[t_idx] + st.kalman.update(low_bboxes[d_idx]) + st.track.append(frame_idx, low_bboxes[d_idx], float(low_scores[d_idx])) + new_active.append(st) + + # Handle tracks that matched neither stage + new_lost: list[_STrack] = [] + for t_idx in unmatched_t_2: + st = remaining_stracks[t_idx] + st.track.frames_since_match += 1 + if st.track.frames_since_match > self.max_lost: + st.track.state = TrackState.FINISHED + self._finished.append(st) + else: + st.track.state = TrackState.LOST + new_lost.append(st) + + # --- Tentative track association with unmatched high-conf detections --- + unmatched_high_bboxes = high_bboxes[unmatched_d_1] if unmatched_d_1 else np.empty((0, 4)) + unmatched_high_scores = high_scores[unmatched_d_1] if unmatched_d_1 else np.empty(0) + + new_tentative: list[_STrack] = [] + + if len(self._tentative) > 0 and len(unmatched_high_bboxes) > 0: + tent_pred = self._predicted_bboxes(self._tentative) + iou_3 = bbox_iou_matrix(tent_pred, unmatched_high_bboxes) + matches_3, unmatched_tent, unmatched_d_3 = hungarian_assign( + iou_3, self.match_thresh + ) + elif len(self._tentative) > 0: + matches_3 = [] + unmatched_tent = list(range(len(self._tentative))) + unmatched_d_3 = [] + else: + matches_3 = [] + unmatched_tent = [] + unmatched_d_3 = list(range(len(unmatched_high_bboxes))) + + for t_idx, d_idx in matches_3: + st = self._tentative[t_idx] + st.kalman.update(unmatched_high_bboxes[d_idx]) + st.track.append( + frame_idx, unmatched_high_bboxes[d_idx], + float(unmatched_high_scores[d_idx]), + ) + if st.track.length >= self.min_hits: + st.track.state = TrackState.ACTIVE + new_active.append(st) + else: + new_tentative.append(st) + + for t_idx in unmatched_tent: + st = self._tentative[t_idx] + st.track.state = TrackState.FINISHED + self._finished.append(st) + + # Only high-confidence unmatched detections start new tracks + for d_idx in unmatched_d_3: + new_tentative.append( + self._new_strack( + frame_idx, + unmatched_high_bboxes[d_idx], + float(unmatched_high_scores[d_idx]), + ) + ) + + self._active = new_active + self._lost = new_lost + self._tentative = new_tentative + + def finalize(self) -> list[Track]: + """Return all tracks sorted by track_id.""" + all_stracks = ( + self._finished + self._active + self._lost + self._tentative + ) + tracks = [st.track for st in all_stracks] + tracks.sort(key=lambda t: t.track_id) + return tracks diff --git a/third-party/video_to_data/reconstruction/modules/v2d_detectron2/lib/cascade_mask_rcnn_vitdet_b_100ep.py b/third-party/video_to_data/reconstruction/modules/v2d_detectron2/lib/cascade_mask_rcnn_vitdet_b_100ep.py new file mode 100644 index 0000000000000000000000000000000000000000..70ffc69936015b54bbed55d87d889aef13948ab6 --- /dev/null +++ b/third-party/video_to_data/reconstruction/modules/v2d_detectron2/lib/cascade_mask_rcnn_vitdet_b_100ep.py @@ -0,0 +1,101 @@ +# Copyright (c) Meta Platforms, Inc. and affiliates. +# Cascade Mask R-CNN with ViT-B backbone (100 epochs). +# Adapted from detectron2 model zoo: projects/ViTDet/configs/COCO/ + +## coco_loader_lsj.py + +import detectron2.data.transforms as T +from detectron2 import model_zoo +from detectron2.config import LazyCall as L + +# Data using LSJ +image_size = 1024 +dataloader = model_zoo.get_config("common/data/coco.py").dataloader +dataloader.train.mapper.augmentations = [ + L(T.RandomFlip)(horizontal=True), # flip first + L(T.ResizeScale)( + min_scale=0.1, max_scale=2.0, target_height=image_size, target_width=image_size + ), + L(T.FixedSizeCrop)(crop_size=(image_size, image_size), pad=False), +] +dataloader.train.mapper.image_format = "RGB" +dataloader.train.total_batch_size = 64 +dataloader.train.mapper.recompute_boxes = True + +dataloader.test.mapper.augmentations = [ + L(T.ResizeShortestEdge)(short_edge_length=image_size, max_size=image_size), +] + +from functools import partial +from fvcore.common.param_scheduler import MultiStepParamScheduler + +from detectron2 import model_zoo +from detectron2.config import LazyCall as L +from detectron2.solver import WarmupParamScheduler +from detectron2.modeling.backbone.vit import get_vit_lr_decay_rate + +## mask_rcnn_vitdet_b_100ep.py + +model = model_zoo.get_config("common/models/mask_rcnn_vitdet.py").model + +train = model_zoo.get_config("common/train.py").train +train.amp.enabled = True +train.ddp.fp16_compression = True +train.init_checkpoint = "detectron2://ImageNetPretrained/MAE/mae_pretrain_vit_base.pth" + +train.max_iter = 184375 + +lr_multiplier = L(WarmupParamScheduler)( + scheduler=L(MultiStepParamScheduler)( + values=[1.0, 0.1, 0.01], + milestones=[163889, 177546], + num_updates=train.max_iter, + ), + warmup_length=250 / train.max_iter, + warmup_factor=0.001, +) + +optimizer = model_zoo.get_config("common/optim.py").AdamW +optimizer.params.lr_factor_func = partial(get_vit_lr_decay_rate, num_layers=12, lr_decay_rate=0.7) +optimizer.params.overrides = {"pos_embed": {"weight_decay": 0.0}} + +## cascade_mask_rcnn_vitdet_b_100ep.py + +from detectron2.config import LazyCall as L +from detectron2.layers import ShapeSpec +from detectron2.modeling.box_regression import Box2BoxTransform +from detectron2.modeling.matcher import Matcher +from detectron2.modeling.roi_heads import ( + FastRCNNOutputLayers, + FastRCNNConvFCHead, + CascadeROIHeads, +) + +[model.roi_heads.pop(k) for k in ["box_head", "box_predictor", "proposal_matcher"]] + +model.roi_heads.update( + _target_=CascadeROIHeads, + box_heads=[ + L(FastRCNNConvFCHead)( + input_shape=ShapeSpec(channels=256, height=7, width=7), + conv_dims=[256, 256, 256, 256], + fc_dims=[1024], + conv_norm="LN", + ) + for _ in range(3) + ], + box_predictors=[ + L(FastRCNNOutputLayers)( + input_shape=ShapeSpec(channels=1024), + test_score_thresh=0.05, + box2box_transform=L(Box2BoxTransform)(weights=(w1, w1, w2, w2)), + cls_agnostic_bbox_reg=True, + num_classes="${...num_classes}", + ) + for (w1, w2) in [(10, 5), (20, 10), (30, 15)] + ], + proposal_matchers=[ + L(Matcher)(thresholds=[th], labels=[0, 1], allow_low_quality_matches=False) + for th in [0.5, 0.6, 0.7] + ], +) diff --git a/third-party/video_to_data/reconstruction/modules/v2d_detectron2/lib/cascade_mask_rcnn_vitdet_h_75ep.py b/third-party/video_to_data/reconstruction/modules/v2d_detectron2/lib/cascade_mask_rcnn_vitdet_h_75ep.py new file mode 100644 index 0000000000000000000000000000000000000000..9fcb3ee18a9bd3e768ec20c6019d059728d69e96 --- /dev/null +++ b/third-party/video_to_data/reconstruction/modules/v2d_detectron2/lib/cascade_mask_rcnn_vitdet_h_75ep.py @@ -0,0 +1,131 @@ +# Copyright (c) Meta Platforms, Inc. and affiliates. + +## coco_loader_lsj.py + +import detectron2.data.transforms as T +from detectron2 import model_zoo +from detectron2.config import LazyCall as L + +# Data using LSJ +image_size = 1024 +dataloader = model_zoo.get_config("common/data/coco.py").dataloader +dataloader.train.mapper.augmentations = [ + L(T.RandomFlip)(horizontal=True), # flip first + L(T.ResizeScale)( + min_scale=0.1, max_scale=2.0, target_height=image_size, target_width=image_size + ), + L(T.FixedSizeCrop)(crop_size=(image_size, image_size), pad=False), +] +dataloader.train.mapper.image_format = "RGB" +dataloader.train.total_batch_size = 64 +# recompute boxes due to cropping +dataloader.train.mapper.recompute_boxes = True + +dataloader.test.mapper.augmentations = [ + L(T.ResizeShortestEdge)(short_edge_length=image_size, max_size=image_size), +] + +from functools import partial +from fvcore.common.param_scheduler import MultiStepParamScheduler + +from detectron2 import model_zoo +from detectron2.config import LazyCall as L +from detectron2.solver import WarmupParamScheduler +from detectron2.modeling.backbone.vit import get_vit_lr_decay_rate + +# mask_rcnn_vitdet_b_100ep.py + +model = model_zoo.get_config("common/models/mask_rcnn_vitdet.py").model + +# Initialization and trainer settings +train = model_zoo.get_config("common/train.py").train +train.amp.enabled = True +train.ddp.fp16_compression = True +train.init_checkpoint = "detectron2://ImageNetPretrained/MAE/mae_pretrain_vit_base.pth" + + +# Schedule +# 100 ep = 184375 iters * 64 images/iter / 118000 images/ep +train.max_iter = 184375 + +lr_multiplier = L(WarmupParamScheduler)( + scheduler=L(MultiStepParamScheduler)( + values=[1.0, 0.1, 0.01], + milestones=[163889, 177546], + num_updates=train.max_iter, + ), + warmup_length=250 / train.max_iter, + warmup_factor=0.001, +) + +# Optimizer +optimizer = model_zoo.get_config("common/optim.py").AdamW +optimizer.params.lr_factor_func = partial(get_vit_lr_decay_rate, num_layers=12, lr_decay_rate=0.7) +optimizer.params.overrides = {"pos_embed": {"weight_decay": 0.0}} + +# cascade_mask_rcnn_vitdet_b_100ep.py + +from detectron2.config import LazyCall as L +from detectron2.layers import ShapeSpec +from detectron2.modeling.box_regression import Box2BoxTransform +from detectron2.modeling.matcher import Matcher +from detectron2.modeling.roi_heads import ( + FastRCNNOutputLayers, + FastRCNNConvFCHead, + CascadeROIHeads, +) + +# arguments that don't exist for Cascade R-CNN +[model.roi_heads.pop(k) for k in ["box_head", "box_predictor", "proposal_matcher"]] + +model.roi_heads.update( + _target_=CascadeROIHeads, + box_heads=[ + L(FastRCNNConvFCHead)( + input_shape=ShapeSpec(channels=256, height=7, width=7), + conv_dims=[256, 256, 256, 256], + fc_dims=[1024], + conv_norm="LN", + ) + for _ in range(3) + ], + box_predictors=[ + L(FastRCNNOutputLayers)( + input_shape=ShapeSpec(channels=1024), + test_score_thresh=0.05, + box2box_transform=L(Box2BoxTransform)(weights=(w1, w1, w2, w2)), + cls_agnostic_bbox_reg=True, + num_classes="${...num_classes}", + ) + for (w1, w2) in [(10, 5), (20, 10), (30, 15)] + ], + proposal_matchers=[ + L(Matcher)(thresholds=[th], labels=[0, 1], allow_low_quality_matches=False) + for th in [0.5, 0.6, 0.7] + ], +) + +# cascade_mask_rcnn_vitdet_h_75ep.py + +from functools import partial + +train.init_checkpoint = "detectron2://ImageNetPretrained/MAE/mae_pretrain_vit_huge_p14to16.pth" + +model.backbone.net.embed_dim = 1280 +model.backbone.net.depth = 32 +model.backbone.net.num_heads = 16 +model.backbone.net.drop_path_rate = 0.5 +# 7, 15, 23, 31 for global attention +model.backbone.net.window_block_indexes = ( + list(range(0, 7)) + list(range(8, 15)) + list(range(16, 23)) + list(range(24, 31)) +) + +optimizer.params.lr_factor_func = partial(get_vit_lr_decay_rate, lr_decay_rate=0.9, num_layers=32) +optimizer.params.overrides = {} +optimizer.params.weight_decay_norm = None + +train.max_iter = train.max_iter * 3 // 4 # 100ep -> 75ep +lr_multiplier.scheduler.milestones = [ + milestone * 3 // 4 for milestone in lr_multiplier.scheduler.milestones +] +lr_multiplier.scheduler.num_updates = train.max_iter diff --git a/third-party/video_to_data/reconstruction/modules/v2d_detectron2/lib/cascade_mask_rcnn_vitdet_l_100ep.py b/third-party/video_to_data/reconstruction/modules/v2d_detectron2/lib/cascade_mask_rcnn_vitdet_l_100ep.py new file mode 100644 index 0000000000000000000000000000000000000000..987e1fcf42e3a8b262e498cff5f32eb93cb06f09 --- /dev/null +++ b/third-party/video_to_data/reconstruction/modules/v2d_detectron2/lib/cascade_mask_rcnn_vitdet_l_100ep.py @@ -0,0 +1,112 @@ +# Copyright (c) Meta Platforms, Inc. and affiliates. +# Cascade Mask R-CNN with ViT-L backbone (100 epochs). +# Adapted from detectron2 model zoo: projects/ViTDet/configs/COCO/ + +## coco_loader_lsj.py + +import detectron2.data.transforms as T +from detectron2 import model_zoo +from detectron2.config import LazyCall as L + +# Data using LSJ +image_size = 1024 +dataloader = model_zoo.get_config("common/data/coco.py").dataloader +dataloader.train.mapper.augmentations = [ + L(T.RandomFlip)(horizontal=True), # flip first + L(T.ResizeScale)( + min_scale=0.1, max_scale=2.0, target_height=image_size, target_width=image_size + ), + L(T.FixedSizeCrop)(crop_size=(image_size, image_size), pad=False), +] +dataloader.train.mapper.image_format = "RGB" +dataloader.train.total_batch_size = 64 +dataloader.train.mapper.recompute_boxes = True + +dataloader.test.mapper.augmentations = [ + L(T.ResizeShortestEdge)(short_edge_length=image_size, max_size=image_size), +] + +from functools import partial +from fvcore.common.param_scheduler import MultiStepParamScheduler + +from detectron2 import model_zoo +from detectron2.config import LazyCall as L +from detectron2.solver import WarmupParamScheduler +from detectron2.modeling.backbone.vit import get_vit_lr_decay_rate + +## mask_rcnn_vitdet_b_100ep.py (base) + +model = model_zoo.get_config("common/models/mask_rcnn_vitdet.py").model + +train = model_zoo.get_config("common/train.py").train +train.amp.enabled = True +train.ddp.fp16_compression = True +train.init_checkpoint = "detectron2://ImageNetPretrained/MAE/mae_pretrain_vit_large.pth?matching_heuristics=True" + +train.max_iter = 184375 + +lr_multiplier = L(WarmupParamScheduler)( + scheduler=L(MultiStepParamScheduler)( + values=[1.0, 0.1, 0.01], + milestones=[163889, 177546], + num_updates=train.max_iter, + ), + warmup_length=250 / train.max_iter, + warmup_factor=0.001, +) + +optimizer = model_zoo.get_config("common/optim.py").AdamW +optimizer.params.lr_factor_func = partial(get_vit_lr_decay_rate, lr_decay_rate=0.8, num_layers=24) +optimizer.params.overrides = {"pos_embed": {"weight_decay": 0.0}} + +## cascade_mask_rcnn_vitdet_b_100ep.py (cascade heads) + +from detectron2.config import LazyCall as L +from detectron2.layers import ShapeSpec +from detectron2.modeling.box_regression import Box2BoxTransform +from detectron2.modeling.matcher import Matcher +from detectron2.modeling.roi_heads import ( + FastRCNNOutputLayers, + FastRCNNConvFCHead, + CascadeROIHeads, +) + +[model.roi_heads.pop(k) for k in ["box_head", "box_predictor", "proposal_matcher"]] + +model.roi_heads.update( + _target_=CascadeROIHeads, + box_heads=[ + L(FastRCNNConvFCHead)( + input_shape=ShapeSpec(channels=256, height=7, width=7), + conv_dims=[256, 256, 256, 256], + fc_dims=[1024], + conv_norm="LN", + ) + for _ in range(3) + ], + box_predictors=[ + L(FastRCNNOutputLayers)( + input_shape=ShapeSpec(channels=1024), + test_score_thresh=0.05, + box2box_transform=L(Box2BoxTransform)(weights=(w1, w1, w2, w2)), + cls_agnostic_bbox_reg=True, + num_classes="${...num_classes}", + ) + for (w1, w2) in [(10, 5), (20, 10), (30, 15)] + ], + proposal_matchers=[ + L(Matcher)(thresholds=[th], labels=[0, 1], allow_low_quality_matches=False) + for th in [0.5, 0.6, 0.7] + ], +) + +## cascade_mask_rcnn_vitdet_l_100ep.py (ViT-L backbone overrides) + +model.backbone.net.embed_dim = 1024 +model.backbone.net.depth = 24 +model.backbone.net.num_heads = 16 +model.backbone.net.drop_path_rate = 0.4 +# 5, 11, 17, 23 for global attention +model.backbone.net.window_block_indexes = ( + list(range(0, 5)) + list(range(6, 11)) + list(range(12, 17)) + list(range(18, 23)) +) diff --git a/third-party/video_to_data/reconstruction/modules/v2d_detectron2/lib/download_weights.py b/third-party/video_to_data/reconstruction/modules/v2d_detectron2/lib/download_weights.py new file mode 100644 index 0000000000000000000000000000000000000000..2e3b9ca1d6796cf55f602dfaee63f3f4125e95ef --- /dev/null +++ b/third-party/video_to_data/reconstruction/modules/v2d_detectron2/lib/download_weights.py @@ -0,0 +1,53 @@ +# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 +import argparse +import urllib.request +from pathlib import Path + +VITDET_VARIANTS = { + "b": { + "url": "https://dl.fbaipublicfiles.com/detectron2/ViTDet/COCO/cascade_mask_rcnn_vitdet_b/f325358525/model_final_435fa9.pkl", + "file": "model_final_435fa9.pkl", + }, + "l": { + "url": "https://dl.fbaipublicfiles.com/detectron2/ViTDet/COCO/cascade_mask_rcnn_vitdet_l/f328021305/model_final_1a9f28.pkl", + "file": "model_final_1a9f28.pkl", + }, + "h": { + "url": "https://dl.fbaipublicfiles.com/detectron2/ViTDet/COCO/cascade_mask_rcnn_vitdet_h/f328730692/model_final_f05665.pkl", + "file": "model_final_f05665.pkl", + }, +} + + +def download_weights(output_dir: str, model_sizes: list[str] | None = None): + if model_sizes is None: + model_sizes = ["b"] + + for size in model_sizes: + if size not in VITDET_VARIANTS: + raise ValueError(f"Unknown model size '{size}', expected one of {list(VITDET_VARIANTS)}") + + variant = VITDET_VARIANTS[size] + dest_dir = Path(output_dir) / f"cascade_mask_rcnn_vitdet_{size}" + dest_dir.mkdir(parents=True, exist_ok=True) + dest_file = dest_dir / variant["file"] + + if dest_file.exists(): + print(f"ViTDet-{size.upper()} checkpoint already exists at {dest_file}") + continue + + print(f"Downloading ViTDet-{size.upper()} checkpoint to {dest_file}...") + urllib.request.urlretrieve(variant["url"], dest_file) + print("Done.") + + +if __name__ == "__main__": + parser = argparse.ArgumentParser(description="Download ViTDet checkpoints") + parser.add_argument("--output_dir", type=str, required=True, help="Directory to save checkpoints") + parser.add_argument( + "--model_sizes", type=str, nargs="+", default=["b"], choices=["b", "l", "h"], + help="Which model sizes to download (default: b)", + ) + args = parser.parse_args() + download_weights(args.output_dir, args.model_sizes) diff --git a/third-party/video_to_data/reconstruction/modules/v2d_detectron2/lib/mv_track_bboxes.py b/third-party/video_to_data/reconstruction/modules/v2d_detectron2/lib/mv_track_bboxes.py new file mode 100644 index 0000000000000000000000000000000000000000..d151dbf40a5b56801e91bcf3f4ee65d371a88286 --- /dev/null +++ b/third-party/video_to_data/reconstruction/modules/v2d_detectron2/lib/mv_track_bboxes.py @@ -0,0 +1,111 @@ +# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 +from pathlib import Path + +import torch + +from v2d.mv.rig import RigConfig + +from .build_detector import Detector +from .track_bboxes import ( + ByteTrackerConfig, + DetectorConfig, + IoUTrackerConfig, + track_bboxes, +) + + +DEVICE = torch.device("cuda" if torch.cuda.is_available() else "cpu") + + +def mv_track_bboxes_from_config(cfg): + """Run detection + tracking across multiple cameras defined by a rig config.""" + rig = RigConfig(cfg.rig_config) + + detector_cfg = DetectorConfig( + model_size=cfg.detector.model_size, + weights_dir=cfg.detector.weights_dir, + det_cat_id=cfg.detector.det_cat_id, + bbox_thr=cfg.detector.bbox_thr, + default_to_full_image=cfg.detector.default_to_full_image, + test_score_thresh=cfg.detector.get("test_score_thresh", 0.25), + ) + tracker_type = cfg.get("tracker_type", "iou") + if tracker_type == "byte": + bt = cfg.byte_tracker + tracker_cfg = ByteTrackerConfig( + track_thresh=bt.get("track_thresh", 0.6), + det_thresh=bt.get("det_thresh", 0.1), + match_thresh=bt.get("match_thresh", 0.8), + second_match_thresh=bt.get("second_match_thresh", 0.5), + max_lost=bt.get("max_lost", 30), + min_hits=bt.get("min_hits", 3), + merge_max_gap=bt.get("merge_max_gap", 60), + merge_iou_threshold=bt.get("merge_iou_threshold", 0.3), + ) + else: + it = cfg.iou_tracker + tracker_cfg = IoUTrackerConfig( + iou_threshold=it.get("iou_threshold", 0.3), + max_lost=it.get("max_lost", 30), + min_hits=it.get("min_hits", 3), + merge_max_gap=it.get("merge_max_gap", 10), + merge_iou_threshold=it.get("merge_iou_threshold", 0.5), + ) + + weights_path = f"{detector_cfg.weights_dir}/cascade_mask_rcnn_vitdet_{detector_cfg.model_size}" + detector = Detector( + name="vitdet", + device=DEVICE, + model_size=detector_cfg.model_size, + path=weights_path, + test_score_thresh=detector_cfg.test_score_thresh, + ) + + batch_size = cfg.get("batch_size", 1) + + for cam_id in cfg.cameras: + cam = rig.get_camera(cam_id) + print(f"Running Detectron2 bbox tracking for camera: {cam.name}") + + rgb_path = Path(cfg.rgb_path_template.format(cam_name=cam.name)) + output_path = Path(cfg.output_path_template.format(cam_name=cam.name)) + + track_bboxes( + rgb_path=rgb_path, + output_path=output_path, + detector_cfg=detector_cfg, + tracker_cfg=tracker_cfg, + batch_size=batch_size, + detector=detector, + debug=cfg.debug, + ) + + +if __name__ == "__main__": + import argparse + + from omegaconf import OmegaConf + + parser = argparse.ArgumentParser(description="Run multi-view detection + tracking") + parser.add_argument("--rgb_dir", type=str, required=True, help="Directory containing input frames") + parser.add_argument("--weights_dir", type=str, required=True, help="Directory containing model weights") + parser.add_argument("--output_dir", type=str, required=True, help="Directory for outputs") + parser.add_argument("--config_path", type=str, default=None, + help="Optional override config (merged on top of defaults)") + parser.add_argument("--debug", type=int, default=None, help="Debug level override") + args = parser.parse_args() + + cfg = OmegaConf.load(Path(__file__).parent / "mv_track_bboxes.yaml") + if args.config_path: + cfg = OmegaConf.merge(cfg, OmegaConf.load(args.config_path)) + overrides: dict = { + "rgb_dir": args.rgb_dir, + "detector": {"weights_dir": args.weights_dir}, + "output_dir": args.output_dir, + } + if args.debug is not None: + overrides["debug"] = args.debug + + cfg = OmegaConf.merge(cfg, overrides) + mv_track_bboxes_from_config(cfg) diff --git a/third-party/video_to_data/reconstruction/modules/v2d_detectron2/lib/mv_track_bboxes.yaml b/third-party/video_to_data/reconstruction/modules/v2d_detectron2/lib/mv_track_bboxes.yaml new file mode 100644 index 0000000000000000000000000000000000000000..de12fa32bc25945e25c7147190842624bf3e3e23 --- /dev/null +++ b/third-party/video_to_data/reconstruction/modules/v2d_detectron2/lib/mv_track_bboxes.yaml @@ -0,0 +1,41 @@ +# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 +rgb_dir: ??? +output_dir: ??? + +rig_config: stereo-4 +cameras: [0, 2, 4, 6] + +rgb_path_template: "${rgb_dir}/{cam_name}" +output_path_template: "${output_dir}/{cam_name}_bbox_track.pt" + +batch_size: 2 + +detector: + weights_dir: ??? + model_size: b # "b" (ViT-Base, fastest), "l" (ViT-Large), "h" (ViT-Huge, most accurate) + det_cat_id: 0 # 0: person + bbox_thr: 0.5 # minimum confidence score for a detection to be considered valid + default_to_full_image: True # if no valid detections, return the full image as a detection + test_score_thresh: 0.1 # model-internal NMS threshold; lower for ByteTrack (0.1), default IoU (0.25) + +tracker_type: byte # "iou" or "byte" + +iou_tracker: + iou_threshold: 0.3 + max_lost: 30 + min_hits: 3 + merge_max_gap: 10 + merge_iou_threshold: 0.5 + +byte_tracker: + track_thresh: 0.6 # high confidence threshold (first association) + det_thresh: 0.1 # low confidence threshold (second association) + match_thresh: 0.8 # IoU threshold for first association + second_match_thresh: 0.5 # IoU threshold for second association + max_lost: 30 + min_hits: 3 + merge_max_gap: 60 # frames gap tolerance for merging fragmented tracks + merge_iou_threshold: 0.3 # IoU threshold for merging (lower = more aggressive) + +debug: 2 diff --git a/third-party/video_to_data/reconstruction/modules/v2d_detectron2/lib/pyproject.toml b/third-party/video_to_data/reconstruction/modules/v2d_detectron2/lib/pyproject.toml new file mode 100644 index 0000000000000000000000000000000000000000..02d6398a381434a5b8ed95e9ffa259b35663de78 --- /dev/null +++ b/third-party/video_to_data/reconstruction/modules/v2d_detectron2/lib/pyproject.toml @@ -0,0 +1,31 @@ +# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 +[build-system] +requires = ["setuptools>=68.0", "wheel"] +build-backend = "setuptools.build_meta" + +[project] +name = "v2d-detectron2-lib" +version = "0.1.0" +description = "Detectron2-based human detection and tracking" +requires-python = ">=3.10" +dependencies = [ + "numpy", + "scipy", + "opencv-python", + "imageio[pyav]", + "av", + "tqdm", + "torch", + "omegaconf", + "v2d-mv[io,math]", +] + +[tool.setuptools] +packages = ["v2d.detectron2.lib"] + +[tool.setuptools.package-data] +"v2d.detectron2.lib" = ["*.yaml"] + +[tool.setuptools.package-dir] +"v2d.detectron2.lib" = "." diff --git a/third-party/video_to_data/reconstruction/modules/v2d_detectron2/lib/track_bboxes.py b/third-party/video_to_data/reconstruction/modules/v2d_detectron2/lib/track_bboxes.py new file mode 100644 index 0000000000000000000000000000000000000000..e7868bdec0a02d6e02ba1bb85c51627d9fb752b6 --- /dev/null +++ b/third-party/video_to_data/reconstruction/modules/v2d_detectron2/lib/track_bboxes.py @@ -0,0 +1,245 @@ +# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 +from __future__ import annotations + +import argparse +from dataclasses import dataclass +from pathlib import Path +import time + +import cv2 +import imageio.v3 as iio +import torch +from tqdm import tqdm + +from v2d.common.video import FrameSource, get_video_writer + +from .build_detector import Detector +from .bytetracker import ByteTracker +from .tracker import IoUTracker + +DEVICE = torch.device("cuda" if torch.cuda.is_available() else "cpu") + + +@dataclass +class DetectorConfig: + model_size: str = "b" + weights_dir: str = "" + det_cat_id: int = 0 + bbox_thr: float = 0.5 + default_to_full_image: bool = True + test_score_thresh: float = 0.25 + + +@dataclass +class IoUTrackerConfig: + iou_threshold: float = 0.3 + max_lost: int = 30 + min_hits: int = 3 + merge_max_gap: int = 10 + merge_iou_threshold: float = 0.5 + + +@dataclass +class ByteTrackerConfig: + track_thresh: float = 0.6 + det_thresh: float = 0.1 + match_thresh: float = 0.8 + second_match_thresh: float = 0.5 + max_lost: int = 30 + min_hits: int = 3 + merge_max_gap: int = 60 + merge_iou_threshold: float = 0.3 + + +TrackerConfig = IoUTrackerConfig | ByteTrackerConfig + + +def track_bboxes( + rgb_path: Path, + output_path: str | Path, + detector_cfg: DetectorConfig | None = None, + tracker_cfg: TrackerConfig | None = None, + batch_size: int = 1, + debug: int = 0, + detector: Detector | None = None, +) -> dict: + """Run detection + tracking on a single camera's frames. + + Saves a .pt dict to *output_path* and returns it. + + Debug levels: + 0 — no debug output + 1 — print track info, save per-frame detection images (every 30th frame) + 2 — also render bbox_track overlay video + """ + if detector_cfg is None: + detector_cfg = DetectorConfig() + if tracker_cfg is None: + tracker_cfg = IoUTrackerConfig() + + use_byte = isinstance(tracker_cfg, ByteTrackerConfig) + + output_path = Path(output_path).resolve() + output_path.parent.mkdir(parents=True, exist_ok=True) + + frame_source = FrameSource.from_path(rgb_path) + n_frames = frame_source.n_frames + image_size = frame_source.image_size + + effective_bbox_thr = tracker_cfg.det_thresh if use_byte else detector_cfg.bbox_thr + + if detector is None: + weights_path = f"{detector_cfg.weights_dir}/cascade_mask_rcnn_vitdet_{detector_cfg.model_size}" + detector = Detector( + name="vitdet", + device=DEVICE, + model_size=detector_cfg.model_size, + path=weights_path, + test_score_thresh=detector_cfg.test_score_thresh, + ) + + if debug > 0: + debug_det_dir = output_path.parent / f"{output_path.stem}_detections" + debug_det_dir.mkdir(parents=True, exist_ok=True) + + det_kwargs = dict( + det_cat_id=detector_cfg.det_cat_id, + bbox_thr=effective_bbox_thr, + default_to_full_image=detector_cfg.default_to_full_image, + ) + + if use_byte: + tracker: IoUTracker | ByteTracker = ByteTracker( + track_thresh=tracker_cfg.track_thresh, + match_thresh=tracker_cfg.match_thresh, + second_match_thresh=tracker_cfg.second_match_thresh, + max_lost=tracker_cfg.max_lost, + min_hits=tracker_cfg.min_hits, + ) + print(f"Using ByteTracker (track_thresh={tracker_cfg.track_thresh}, " + f"det_thresh={tracker_cfg.det_thresh})") + else: + tracker = IoUTracker( + iou_threshold=tracker_cfg.iou_threshold, + max_lost=tracker_cfg.max_lost, + min_hits=tracker_cfg.min_hits, + ) + print(f"Using IoUTracker (iou_threshold={tracker_cfg.iou_threshold})") + + n_batches = (n_frames + batch_size - 1) // batch_size + for batch_start, batch_frames in tqdm(frame_source.iter_batches(batch_size), + total=n_batches, desc="Running detection"): + start_time = time.time() + if len(batch_frames) == 1: + batch_results = [detector.run_detection(batch_frames[0], **det_kwargs)] + else: + batch_results = detector.run_detection_batch(batch_frames, **det_kwargs) + + for offset, (bboxes, scores) in enumerate(batch_results): + frame_idx = batch_start + offset + tracker.update(frame_idx, bboxes, scores) + + if debug > 0 and frame_idx % 30 == 0: + elapsed = time.time() - start_time + tqdm.write(f"Frame {frame_idx} detection time: {elapsed:.3f}s") + image = batch_frames[offset].copy() + H_img, W_img = image.shape[:2] + label = f"Frame {frame_idx}" + (tw, th), _ = cv2.getTextSize(label, cv2.FONT_HERSHEY_SIMPLEX, 1.0, 2) + cv2.putText(image, label, (W_img - tw - 10, th + 10), + cv2.FONT_HERSHEY_SIMPLEX, 1.0, (0, 255, 0), 2) + bboxes_int = bboxes.astype(int) + for j, bbox in enumerate(bboxes_int): + cv2.rectangle(image, (bbox[0], bbox[1]), (bbox[2], bbox[3]), (0, 255, 255), 2) + cv2.putText(image, f"Score: {scores[j]:.2f}", (bbox[0], bbox[1] - 10), + cv2.FONT_HERSHEY_SIMPLEX, 0.5, (0, 255, 255), 2) + iio.imwrite(debug_det_dir / f"bbox_{frame_idx:06d}.png", image) + + tracks = tracker.finalize() + tracks = IoUTracker.merge_fragmented_tracks( + tracks, + max_gap=tracker_cfg.merge_max_gap, + iou_threshold=tracker_cfg.merge_iou_threshold, + ) + if debug > 0: + print("=== Tracking Results ===") + for track in tracks: + print(track) + + primary_track = IoUTracker.select_primary_track(tracks, image_size) + primary_track.interpolate(n_frames) + bbox_track = primary_track.get_bboxes() + scores = primary_track.get_scores() + print(f"Primary bbox track: {primary_track}") + + result = { + "det_cat_id": detector_cfg.det_cat_id, + "scores": scores, + "bbox_track": bbox_track, + } + torch.save(result, output_path) + print(f"Saved bbox track ({n_frames} frames) to {output_path}") + + if debug > 1: + debug_video_path = output_path.with_suffix(".mp4") + writer = get_video_writer(debug_video_path, fps=30, crf=23) + for i, image in tqdm(enumerate(frame_source.iter_frames()), + total=n_frames, desc="Rendering debug video"): + H_img, W_img = image.shape[:2] + label = f"Frame {i}" + (tw, th), _ = cv2.getTextSize(label, cv2.FONT_HERSHEY_SIMPLEX, 1.0, 2) + cv2.putText(image, label, (W_img - tw - 10, th + 10), + cv2.FONT_HERSHEY_SIMPLEX, 1.0, (0, 255, 0), 2) + bbox = bbox_track[i].astype(int) + cv2.rectangle(image, (bbox[0], bbox[1]), (bbox[2], bbox[3]), (0, 255, 255), 2) + cv2.putText(image, f"Score: {scores[i]:.2f}", (bbox[0], bbox[1] - 10), + cv2.FONT_HERSHEY_SIMPLEX, 0.5, (0, 255, 255), 2) + writer.write_frame(image) + writer.close() + print(f"Saved debug video to {debug_video_path}") + + return result + + +if __name__ == "__main__": + parser = argparse.ArgumentParser(description="Run person detection + tracking on a single camera") + parser.add_argument("--rgb_path", type=str, required=True, + help="Path to input frames (image dir, .h5, or video file)") + parser.add_argument("--output_path", type=str, required=True, help="Output .pt file path") + + det = parser.add_argument_group("detector") + det.add_argument("--model_size", type=str, default="b", choices=["b", "l", "h"]) + det.add_argument("--weights_dir", type=str, default="") + det.add_argument("--det_cat_id", type=int, default=0, help="COCO category id (0=person)") + det.add_argument("--bbox_thr", type=float, default=0.5) + det.add_argument("--no_default_to_full_image", action="store_true") + + trk = parser.add_argument_group("tracker") + trk.add_argument("--iou_threshold", type=float, default=0.3) + trk.add_argument("--max_lost", type=int, default=30) + trk.add_argument("--min_hits", type=int, default=3) + + parser.add_argument("--batch_size", type=int, default=1) + parser.add_argument("--debug", type=int, default=0) + + args = parser.parse_args() + + track_bboxes( + rgb_path=args.rgb_path, + output_path=args.output_path, + detector_cfg=DetectorConfig( + model_size=args.model_size, + weights_dir=args.weights_dir, + det_cat_id=args.det_cat_id, + bbox_thr=args.bbox_thr, + default_to_full_image=not args.no_default_to_full_image, + ), + tracker_cfg=IoUTrackerConfig( + iou_threshold=args.iou_threshold, + max_lost=args.max_lost, + min_hits=args.min_hits, + ), + batch_size=args.batch_size, + debug=args.debug, + ) diff --git a/third-party/video_to_data/reconstruction/modules/v2d_detectron2/lib/tracker.py b/third-party/video_to_data/reconstruction/modules/v2d_detectron2/lib/tracker.py new file mode 100644 index 0000000000000000000000000000000000000000..15091bd86fac2a1e1f0b3422d0be1964a052f4c9 --- /dev/null +++ b/third-party/video_to_data/reconstruction/modules/v2d_detectron2/lib/tracker.py @@ -0,0 +1,503 @@ +# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 +from __future__ import annotations + +from dataclasses import dataclass, field +from enum import Enum, auto + +import numpy as np +from scipy.optimize import linear_sum_assignment + +from v2d.mv.math.numpy_fn import linear_one_euro_filter + + +class TrackState(Enum): + TENTATIVE = auto() + ACTIVE = auto() + LOST = auto() + FINISHED = auto() + + +@dataclass +class Track: + track_id: int + state: TrackState = TrackState.ACTIVE + frames_since_match: int = 0 + history: list[tuple[int, np.ndarray, float]] = field(default_factory=list) + + @property + def first_bbox(self) -> np.ndarray: + return self.history[0][1] + + @property + def last_bbox(self) -> np.ndarray: + return self.history[-1][1] + + @property + def last_score(self) -> float: + return self.history[-1][2] + + @property + def start_frame(self) -> int: + return self.history[0][0] + + @property + def end_frame(self) -> int: + return self.history[-1][0] + + @property + def length(self) -> int: + return len(self.history) + + def __repr__(self) -> str: + motion = self.total_motion() + return ( + f"Track(id={self.track_id}, frames={self.length}, " + f"span={self.start_frame}-{self.end_frame}, " + f"motion={motion:.0f}px, state={self.state.name})" + ) + + def append(self, frame_idx: int, bbox: np.ndarray, score: float): + self.history.append((frame_idx, bbox, score)) + self.state = TrackState.ACTIVE + self.frames_since_match = 0 + + def get_bboxes(self) -> np.ndarray: + """Return (N, 4) array of all bboxes in this track.""" + return np.array([h[1] for h in self.history]) + + def get_scores(self) -> np.ndarray: + return np.array([h[2] for h in self.history]) + + def get_frame_indices(self) -> np.ndarray: + return np.array([h[0] for h in self.history]) + + def interpolate(self, total_frames: int): + """Fill gaps in-place with linearly interpolated bboxes (score=-1). + + After calling, self.history has exactly total_frames entries + covering frames 0..total_frames-1. Interpolated entries use score=-1 + to distinguish them from real detections. Frames before the first or + after the last observation are held (nearest bbox, score=-1). + """ + frame_indices = self.get_frame_indices() + bboxes = self.get_bboxes() + scores = self.get_scores() + + observed = {int(f): (b, s) for f, b, s in zip(frame_indices, bboxes, scores)} + first, last = int(frame_indices[0]), int(frame_indices[-1]) + + new_history: list[tuple[int, np.ndarray, float]] = [] + + for f in range(total_frames): + if f in observed: + new_history.append((f, observed[f][0], float(observed[f][1]))) + elif f < first: + new_history.append((f, bboxes[0].copy(), -1.0)) + elif f > last: + new_history.append((f, bboxes[-1].copy(), -1.0)) + else: + # Find surrounding observations + lo = max(fi for fi in frame_indices if fi < f) + hi = min(fi for fi in frame_indices if fi > f) + t = (f - lo) / (hi - lo) + bbox = observed[lo][0] * (1 - t) + observed[hi][0] * t + new_history.append((f, bbox, -1.0)) + + self.history = new_history + + def _smoothed_centers(self, f_cutoff: float = 5.0, f_sample: float = 30.0) -> np.ndarray: + """Bbox centers low-passed by a One Euro filter with beta=0 (plain low-pass). + + f_cutoff defaults high (5 Hz at 30 fps) so only very-high-frequency noise — + e.g. bbox flicker from intermittent occlusion — is removed; real person + motion (sub-Hz) passes through. + """ + bboxes = self.get_bboxes() + centers = np.column_stack([ + (bboxes[:, 0] + bboxes[:, 2]) / 2, + (bboxes[:, 1] + bboxes[:, 3]) / 2, + ]) + if centers.shape[0] < 2: + return centers + # linear_one_euro_filter expects time on the last axis -> (2, T) + smoothed = linear_one_euro_filter( + centers.T, min_f_cutoff=f_cutoff, beta=0.0, f_sample=f_sample, + ).T + return smoothed + + def total_motion(self) -> float: + """Sum of frame-to-frame bbox center displacements (in pixels), after smoothing. + + Centers are low-passed first so occlusion-induced bbox flicker doesn't inflate + the score. A truly stationary (but jittery) track yields ~0. + """ + if self.length < 2: + return 0.0 + centers = self._smoothed_centers() + deltas = np.diff(centers, axis=0) + return float(np.sum(np.linalg.norm(deltas, axis=1))) + + def trajectory_span(self) -> float: + """Diagonal of the axis-aligned bbox enclosing (smoothed) bbox centers. + + Unlike total_motion, this is immune to back-and-forth flicker: a track that + jitters in one spot has near-zero span regardless of cumulative motion. + """ + if self.length < 1: + return 0.0 + centers = self._smoothed_centers() + return float(np.hypot(np.ptp(centers[:, 0]), np.ptp(centers[:, 1]))) + + + +def bbox_iou_matrix(boxes_a: np.ndarray, boxes_b: np.ndarray) -> np.ndarray: + """Compute pairwise IoU between two sets of [x1, y1, x2, y2] boxes. + + Returns shape (len(boxes_a), len(boxes_b)). + """ + x1 = np.maximum(boxes_a[:, None, 0], boxes_b[None, :, 0]) + y1 = np.maximum(boxes_a[:, None, 1], boxes_b[None, :, 1]) + x2 = np.minimum(boxes_a[:, None, 2], boxes_b[None, :, 2]) + y2 = np.minimum(boxes_a[:, None, 3], boxes_b[None, :, 3]) + + inter = np.maximum(0, x2 - x1) * np.maximum(0, y2 - y1) + area_a = (boxes_a[:, 2] - boxes_a[:, 0]) * (boxes_a[:, 3] - boxes_a[:, 1]) + area_b = (boxes_b[:, 2] - boxes_b[:, 0]) * (boxes_b[:, 3] - boxes_b[:, 1]) + union = area_a[:, None] + area_b[None, :] - inter + + return inter / (union + 1e-6) + + +def greedy_assign( + iou_matrix: np.ndarray, threshold: float +) -> tuple[list[tuple[int, int]], list[int], list[int]]: + """Greedy matching by descending IoU. + + Returns (matches, unmatched_track_indices, unmatched_det_indices). + """ + if iou_matrix.size == 0: + return ( + [], + list(range(iou_matrix.shape[0])), + list(range(iou_matrix.shape[1])), + ) + + matches = [] + matched_tracks = set() + matched_dets = set() + + flat_order = np.argsort(iou_matrix.ravel())[::-1] + n_cols = iou_matrix.shape[1] + + for idx in flat_order: + t = int(idx // n_cols) + d = int(idx % n_cols) + if iou_matrix[t, d] < threshold: + break + if t in matched_tracks or d in matched_dets: + continue + matches.append((t, d)) + matched_tracks.add(t) + matched_dets.add(d) + + unmatched_tracks = [i for i in range(iou_matrix.shape[0]) if i not in matched_tracks] + unmatched_dets = [i for i in range(iou_matrix.shape[1]) if i not in matched_dets] + return matches, unmatched_tracks, unmatched_dets + + +def hungarian_assign( + iou_matrix: np.ndarray, threshold: float +) -> tuple[list[tuple[int, int]], list[int], list[int]]: + """Optimal matching via the Hungarian algorithm on an IoU cost matrix. + + Returns (matches, unmatched_track_indices, unmatched_det_indices). + """ + if iou_matrix.size == 0: + return ( + [], + list(range(iou_matrix.shape[0])), + list(range(iou_matrix.shape[1])), + ) + + cost = 1.0 - iou_matrix + row_indices, col_indices = linear_sum_assignment(cost) + + matches = [] + matched_tracks = set() + matched_dets = set() + for r, c in zip(row_indices, col_indices): + if iou_matrix[r, c] >= threshold: + matches.append((int(r), int(c))) + matched_tracks.add(int(r)) + matched_dets.add(int(c)) + + unmatched_tracks = [i for i in range(iou_matrix.shape[0]) if i not in matched_tracks] + unmatched_dets = [i for i in range(iou_matrix.shape[1]) if i not in matched_dets] + return matches, unmatched_tracks, unmatched_dets + + +class IoUTracker: + """Simple IoU-based multi-object tracker with lost-track buffer. + + Args: + iou_threshold: Minimum IoU to match a detection to a track. + max_lost: Frames a track survives without a match before removal. + """ + + def __init__( + self, + iou_threshold: float = 0.3, + max_lost: int = 30, + min_hits: int = 3, + ): + self.iou_threshold = iou_threshold + self.max_lost = max_lost + self.min_hits = min_hits + self._next_id = 0 + self.active_tracks: list[Track] = [] + self.lost_tracks: list[Track] = [] + self.tentative_tracks: list[Track] = [] + self.finished_tracks: list[Track] = [] + + def _new_track(self, frame_idx: int, bbox: np.ndarray, score: float) -> Track: + track = Track(track_id=self._next_id, state=TrackState.TENTATIVE) + track.append(frame_idx, bbox, score) + self._next_id += 1 + return track + + def update(self, frame_idx: int, bboxes: np.ndarray, scores: np.ndarray): + """Process one frame of detections. + + Two-stage matching: + 1. Match detections against active + lost tracks (established tracks + get priority). + 2. Match remaining detections against tentative tracks. + Unmatched detections from stage 2 create new tentative tracks. + Tentative tracks that reach *min_hits* consecutive matches are promoted + to active. + + Args: + frame_idx: Current frame number. + bboxes: (M, 4) array of [x1, y1, x2, y2] detections. + scores: (M,) confidence scores. + """ + # Stage 1: match against established (active + lost) tracks + established = self.active_tracks + self.lost_tracks + + if len(established) > 0 and len(bboxes) > 0: + track_boxes = np.array([t.last_bbox for t in established]) + iou = bbox_iou_matrix(track_boxes, bboxes) + matches_1, unmatched_t_1, unmatched_d_1 = greedy_assign(iou, self.iou_threshold) + elif len(established) > 0: + matches_1, unmatched_t_1, unmatched_d_1 = [], list(range(len(established))), [] + else: + matches_1, unmatched_t_1, unmatched_d_1 = [], [], list(range(len(bboxes))) + + new_active = [] + new_lost = [] + + for t_idx, d_idx in matches_1: + track = established[t_idx] + track.append(frame_idx, bboxes[d_idx], scores[d_idx]) + new_active.append(track) + + for t_idx in unmatched_t_1: + track = established[t_idx] + track.frames_since_match += 1 + if track.frames_since_match > self.max_lost: + track.state = TrackState.FINISHED + self.finished_tracks.append(track) + else: + track.state = TrackState.LOST + new_lost.append(track) + + # Stage 2: match remaining detections against tentative tracks + remaining_bboxes = bboxes[unmatched_d_1] if len(unmatched_d_1) > 0 else np.empty((0, 4)) + remaining_scores = scores[unmatched_d_1] if len(unmatched_d_1) > 0 else np.empty(0) + + new_tentative = [] + + if len(self.tentative_tracks) > 0 and len(remaining_bboxes) > 0: + tent_boxes = np.array([t.last_bbox for t in self.tentative_tracks]) + iou_2 = bbox_iou_matrix(tent_boxes, remaining_bboxes) + matches_2, unmatched_t_2, unmatched_d_2 = greedy_assign(iou_2, self.iou_threshold) + elif len(self.tentative_tracks) > 0: + matches_2, unmatched_t_2, unmatched_d_2 = [], list(range(len(self.tentative_tracks))), [] + else: + matches_2, unmatched_t_2, unmatched_d_2 = [], [], list(range(len(remaining_bboxes))) + + for t_idx, d_idx in matches_2: + track = self.tentative_tracks[t_idx] + track.append(frame_idx, remaining_bboxes[d_idx], float(remaining_scores[d_idx])) + if track.length >= self.min_hits: + track.state = TrackState.ACTIVE + new_active.append(track) + else: + new_tentative.append(track) + + # Unmatched tentative tracks are dropped immediately + for t_idx in unmatched_t_2: + track = self.tentative_tracks[t_idx] + track.state = TrackState.FINISHED + self.finished_tracks.append(track) + + # Unmatched detections start new tentative tracks + for d_idx in unmatched_d_2: + new_tentative.append( + self._new_track(frame_idx, remaining_bboxes[d_idx], float(remaining_scores[d_idx])) + ) + + self.active_tracks = new_active + self.lost_tracks = new_lost + self.tentative_tracks = new_tentative + + def finalize(self) -> list[Track]: + """Return all tracks (active + lost + tentative + finished), sorted by track_id.""" + all_tracks = ( + self.finished_tracks + self.active_tracks + + self.lost_tracks + self.tentative_tracks + ) + all_tracks.sort(key=lambda t: t.track_id) + return all_tracks + + @staticmethod + def _track_merge_score(a: Track, b: Track) -> float: + """Compute merge affinity between two tracks. + + For overlapping tracks: mean IoU across shared frames. + For non-overlapping tracks: IoU between A's last bbox and B's first bbox. + Returns -1 if tracks have no overlapping frames and no observations to compare. + """ + a_by_frame = {int(h[0]): h[1] for h in a.history} + b_by_frame = {int(h[0]): h[1] for h in b.history} + shared_frames = sorted(set(a_by_frame) & set(b_by_frame)) + + if shared_frames: + a_boxes = np.array([a_by_frame[f] for f in shared_frames]) + b_boxes = np.array([b_by_frame[f] for f in shared_frames]) + ious = bbox_iou_matrix(a_boxes, b_boxes) + return float(np.mean(np.diag(ious))) + + return float(bbox_iou_matrix( + a.last_bbox.reshape(1, 4), + b.first_bbox.reshape(1, 4), + )[0, 0]) + + @staticmethod + def merge_fragmented_tracks( + tracks: list[Track], + max_gap: int = 10, + iou_threshold: float = 0.5, + ) -> list[Track]: + """Merge tracks that likely represent the same object across ID switches. + + Two tracks are merged when: + - Track A ends within *max_gap* frames of track B starting (or they overlap) + - Their merge score (mean IoU over shared frames, or boundary IoU + if no overlap) >= *iou_threshold* + + Merging is greedy: the best pair (highest score) is merged first, then + the search repeats until no more pairs qualify. + + Returns a new list of tracks (merged tracks get the earlier track's ID). + """ + tracks = list(tracks) + changed = True + while changed: + changed = False + tracks.sort(key=lambda t: t.start_frame) + best_score = -1.0 + best_pair = None + for i in range(len(tracks)): + for j in range(i + 1, len(tracks)): + a, b = tracks[i], tracks[j] + gap = b.start_frame - a.end_frame + if gap > max_gap: + continue + score = IoUTracker._track_merge_score(a, b) + if score >= iou_threshold and score > best_score: + best_score = score + best_pair = (i, j) + + if best_pair is not None: + i, j = best_pair + a, b = tracks[i], tracks[j] + # For overlapping frames, keep A's observation (earlier track) + b_frames = {int(h[0]) for h in b.history} + a_frames = {int(h[0]) for h in a.history} + a.history.extend(h for h in b.history if int(h[0]) not in a_frames) + a.history.sort(key=lambda h: h[0]) + tracks.pop(j) + changed = True + + return tracks + + @staticmethod + def select_primary_track( + tracks: list[Track], + image_size: tuple[int, int] | None = None, + method: str = "combined", + weights: dict[str, float] | None = None, + ) -> Track: + """Select the primary subject from a set of tracks. + + Args: + tracks: List of completed tracks. + image_size: (height, width) of the frames, needed for center-based methods. + method: + "longest" — track with the most frames. + "center" — track whose avg bbox center is closest to image center. + "motion" — track with the most total bbox-center displacement. + "combined" — weighted sum of normalized length, center proximity, + motion, and trajectory span. Tune via *weights* dict. + weights: Weights for "combined" mode. + Keys: "length", "center", "motion", "span". + Defaults to {"length": 0.2, "center": 0.2, "motion": 0.3, "span": 0.3}. + """ + if not tracks: + raise ValueError("No tracks to select from") + + if method == "longest": + return max(tracks, key=lambda t: t.length) + + if method == "motion": + return max(tracks, key=lambda t: t.total_motion()) + + if method in ("center", "combined"): + if image_size is None: + raise ValueError("image_size required for center-based selection") + + h, w = image_size + img_cx, img_cy = w / 2, h / 2 + + def center_dist(t: Track) -> float: + bboxes = t.get_bboxes() + cx = (bboxes[:, 0] + bboxes[:, 2]) / 2 + cy = (bboxes[:, 1] + bboxes[:, 3]) / 2 + return float(np.mean(np.sqrt((cx - img_cx) ** 2 + (cy - img_cy) ** 2))) + + if method == "center": + return min(tracks, key=center_dist) + + if method == "combined": + w_cfg = weights or {"length": 0.2, "center": 0.2, "motion": 0.3, "span": 0.3} + + lengths = np.array([t.length for t in tracks], dtype=float) + dists = np.array([center_dist(t) for t in tracks], dtype=float) + motions = np.array([t.total_motion() for t in tracks], dtype=float) + spans = np.array([t.trajectory_span() for t in tracks], dtype=float) + + def normalize(a: np.ndarray) -> np.ndarray: + r = a.max() - a.min() + return (a - a.min()) / r if r > 0 else np.zeros_like(a) + + scores = ( + w_cfg.get("length", 0) * normalize(lengths) + + w_cfg.get("center", 0) * (1.0 - normalize(dists)) + + w_cfg.get("motion", 0) * normalize(motions) + + w_cfg.get("span", 0) * normalize(spans) + ) + return tracks[int(np.argmax(scores))] + + raise ValueError(f"Unknown selection method: {method}") diff --git a/third-party/video_to_data/reconstruction/modules/v2d_docker/LICENSE b/third-party/video_to_data/reconstruction/modules/v2d_docker/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..10caffae439b956cdda2b1ded9ecbe51ac10befb --- /dev/null +++ b/third-party/video_to_data/reconstruction/modules/v2d_docker/LICENSE @@ -0,0 +1,15 @@ +# Apache License 2.0 + +Copyright 2025 NVIDIA CORPORATION + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. diff --git a/third-party/video_to_data/reconstruction/modules/v2d_docker/__init__.py b/third-party/video_to_data/reconstruction/modules/v2d_docker/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..4ce4bf90677e1622d582d03e0034e112e5e1be9f --- /dev/null +++ b/third-party/video_to_data/reconstruction/modules/v2d_docker/__init__.py @@ -0,0 +1,5 @@ +# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 +from v2d.docker.container import run_in_container + +__all__ = ["run_in_container"] diff --git a/third-party/video_to_data/reconstruction/modules/v2d_docker/container.py b/third-party/video_to_data/reconstruction/modules/v2d_docker/container.py new file mode 100644 index 0000000000000000000000000000000000000000..d22567605eb7f6187abe4711586b28a47bc1d39a --- /dev/null +++ b/third-party/video_to_data/reconstruction/modules/v2d_docker/container.py @@ -0,0 +1,103 @@ +# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 +import os +import subprocess +from pathlib import Path + + +def _base_dir(path: str) -> str: + """ + Return the deepest directory component of path that contains no glob characters. + For plain paths this equals dirname(path). For paths like /out/*/*.glb it + returns /out, so the container mount covers the full glob subtree. + """ + parts = Path(path).parts + clean = [] + for part in parts[:-1]: # skip the filename/last component + if '*' in part or '?' in part: + break + clean.append(part) + return str(Path(*clean)) if clean else str(Path(path).parent) + + +def run_in_container( + image: str, + module: str, + inputs: dict[str, str], + outputs: dict[str, str], + extra_args: dict[str, object] | None = None, + dev: bool = False, + modules_dir: str | None = None, + gpus: bool = False, + env: dict[str, str] | None = None, + extra_volumes: list[str] | None = None, +) -> None: + """ + Run a Python module inside a Docker container with file arguments. + + inputs: arg_name → host_path (read file mounts; None values are skipped) + outputs: arg_name → host_path (write file mounts; parent dirs created; None skipped) + extra_args: arg_name → value (non-path CLI args) + None or False → omit entirely + True → add as a bare flag (--arg_name, no value) + other → add as --arg_name str(value) + env: extra environment variables passed via -e + extra_volumes: raw -v arguments appended after all other mounts (e.g. + anonymous volumes to preserve image-built artifacts under a dev mount) + + Each unique host directory gets one volume mount at /data/, where the + arg_name is taken from the first argument that references that directory. Subsequent + arguments in the same directory reuse the same mount. + """ + inputs = {k: os.path.abspath(v) for k, v in inputs.items() if v is not None} + outputs = {k: os.path.abspath(v) for k, v in outputs.items() if v is not None} + + for path in outputs.values(): + os.makedirs(_base_dir(path), exist_ok=True) + + # Map each unique host directory to a container mount point. + # First arg to reference a directory claims the mount name. + dir_to_mount: dict[str, str] = {} + for arg_name, path in {**inputs, **outputs}.items(): + host_dir = _base_dir(path) + if host_dir not in dir_to_mount: + dir_to_mount[host_dir] = f"/data/{arg_name}" + + cmd = ["docker", "run", "--rm"] + if gpus: + cmd += ["--runtime=nvidia", "--gpus", "all"] + cmd += [ + "--user", f"{os.getuid()}:{os.getgid()}", + "-e", "HOME=/tmp", + ] + if env: + for key, value in env.items(): + cmd += ["-e", f"{key}={value}"] + for host_dir, container_dir in dir_to_mount.items(): + cmd += ["-v", f"{host_dir}:{container_dir}"] + if dev: + if modules_dir is None: + raise ValueError("modules_dir must be provided when dev=True") + cmd += ["-v", f"{modules_dir}:/workspace"] + if extra_volumes: + for vol in extra_volumes: + cmd += ["-v", vol] + + cmd += [image, "python", "-m", module] + + for arg_name, path in {**inputs, **outputs}.items(): + host_dir = _base_dir(path) + rel = os.path.relpath(path, host_dir) + container_path = f"{dir_to_mount[host_dir]}/{rel}" + cmd += [f"--{arg_name}", container_path] + + if extra_args: + for arg_name, value in extra_args.items(): + if value is None or value is False: + pass + elif value is True: + cmd += [f"--{arg_name}"] + else: + cmd += [f"--{arg_name}", str(value)] + + subprocess.run(cmd, check=True) diff --git a/third-party/video_to_data/reconstruction/modules/v2d_docker/pyproject.toml b/third-party/video_to_data/reconstruction/modules/v2d_docker/pyproject.toml new file mode 100644 index 0000000000000000000000000000000000000000..69a573e062fb96ae3679d446d70ac88730415c67 --- /dev/null +++ b/third-party/video_to_data/reconstruction/modules/v2d_docker/pyproject.toml @@ -0,0 +1,18 @@ +# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 +[build-system] +requires = ["setuptools>=68.0", "wheel"] +build-backend = "setuptools.build_meta" + +[project] +name = "v2d-docker" +version = "0.1.0" +description = "Shared Docker container orchestration utilities for v2d modules" +requires-python = ">=3.10" +dependencies = [] + +[tool.setuptools] +packages = ["v2d.docker"] + +[tool.setuptools.package-dir] +"v2d.docker" = "." diff --git a/third-party/video_to_data/reconstruction/modules/v2d_droid_slam/LICENSE b/third-party/video_to_data/reconstruction/modules/v2d_droid_slam/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..10caffae439b956cdda2b1ded9ecbe51ac10befb --- /dev/null +++ b/third-party/video_to_data/reconstruction/modules/v2d_droid_slam/LICENSE @@ -0,0 +1,15 @@ +# Apache License 2.0 + +Copyright 2025 NVIDIA CORPORATION + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. diff --git a/third-party/video_to_data/reconstruction/modules/v2d_droid_slam/docker/Dockerfile b/third-party/video_to_data/reconstruction/modules/v2d_droid_slam/docker/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..6c7304387305b0c1e91de899b5f422f9870a4d09 --- /dev/null +++ b/third-party/video_to_data/reconstruction/modules/v2d_droid_slam/docker/Dockerfile @@ -0,0 +1,43 @@ +FROM pytorch/pytorch:2.5.1-cuda12.4-cudnn9-devel +ENV DEBIAN_FRONTEND=noninteractive +WORKDIR /app + +RUN apt-get update && apt-get install -y \ + git \ + wget \ + libgl1 \ + libglib2.0-0 \ + build-essential \ + cmake \ + ninja-build \ + libeigen3-dev \ + && rm -rf /var/lib/apt/lists/* + +RUN pip install --no-cache-dir \ + numpy \ + scipy \ + opencv-python \ + Pillow \ + pyyaml \ + tqdm \ + matplotlib \ + einops \ + evo \ + gdown \ + open3d + +RUN pip install --no-cache-dir torch-scatter -f https://data.pyg.org/whl/torch-2.5.1+cu124.html + +RUN git clone --recursive https://github.com/princeton-vl/DROID-SLAM.git /opt/droid-slam + +RUN cd /opt/droid-slam/thirdparty/lietorch && \ + TORCH_CUDA_ARCH_LIST="8.0 8.6 8.9 9.0" pip install --no-build-isolation -e . + +RUN cd /opt/droid-slam && \ + TORCH_CUDA_ARCH_LIST="8.0 8.6 8.9 9.0" pip install --no-build-isolation -e . + +ENV PYTHONPATH=/opt/droid-slam:/opt/droid-slam/droid_slam:${PYTHONPATH} + +COPY . /workspace + +RUN pip install -e /workspace/v2d_common -e /workspace/v2d_droid_slam/lib diff --git a/third-party/video_to_data/reconstruction/modules/v2d_droid_slam/docker/__init__.py b/third-party/video_to_data/reconstruction/modules/v2d_droid_slam/docker/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..52a7a9daf028f654d6a02f65c99cc609a57b492f --- /dev/null +++ b/third-party/video_to_data/reconstruction/modules/v2d_droid_slam/docker/__init__.py @@ -0,0 +1,2 @@ +# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 diff --git a/third-party/video_to_data/reconstruction/modules/v2d_droid_slam/docker/_config.py b/third-party/video_to_data/reconstruction/modules/v2d_droid_slam/docker/_config.py new file mode 100644 index 0000000000000000000000000000000000000000..a8704bd050fc9a1406827a60e21b99efca412981 --- /dev/null +++ b/third-party/video_to_data/reconstruction/modules/v2d_droid_slam/docker/_config.py @@ -0,0 +1,6 @@ +# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 +import os + +IMAGE_NAME = "v2d_droid_slam" +MODULES_DIR = os.path.abspath(os.path.join(os.path.dirname(os.path.abspath(__file__)), "..", "..")) diff --git a/third-party/video_to_data/reconstruction/modules/v2d_droid_slam/docker/build.py b/third-party/video_to_data/reconstruction/modules/v2d_droid_slam/docker/build.py new file mode 100644 index 0000000000000000000000000000000000000000..8ca363261767167ba7670363d32276362e929b70 --- /dev/null +++ b/third-party/video_to_data/reconstruction/modules/v2d_droid_slam/docker/build.py @@ -0,0 +1,19 @@ +# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 +import os +import subprocess + +IMAGE_NAME = "v2d_droid_slam" + +current_dir = os.path.dirname(os.path.abspath(__file__)) +module_dir = os.path.join(current_dir, "..") +root_dir = os.path.join(module_dir, "..") +dockerfile_path = os.path.join(current_dir, "Dockerfile") + + +def build_docker_image() -> None: + subprocess.run(["docker", "build", "-t", IMAGE_NAME, "-f", dockerfile_path, root_dir], check=True) + + +if __name__ == "__main__": + build_docker_image() diff --git a/third-party/video_to_data/reconstruction/modules/v2d_droid_slam/docker/pyproject.toml b/third-party/video_to_data/reconstruction/modules/v2d_droid_slam/docker/pyproject.toml new file mode 100644 index 0000000000000000000000000000000000000000..5f6b0bb1ed4cb66778eb3b4a04d36cd106abc043 --- /dev/null +++ b/third-party/video_to_data/reconstruction/modules/v2d_droid_slam/docker/pyproject.toml @@ -0,0 +1,18 @@ +# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 +[build-system] +requires = ["setuptools>=68.0", "wheel"] +build-backend = "setuptools.build_meta" + +[project] +name = "v2d-droid-slam-docker" +version = "0.1.0" +description = "Docker orchestration scripts for DROID-SLAM" +requires-python = ">=3.10" +dependencies = ["v2d-docker"] + +[tool.setuptools] +packages = ["v2d.droid_slam.docker"] + +[tool.setuptools.package-dir] +"v2d.droid_slam.docker" = "." diff --git a/third-party/video_to_data/reconstruction/modules/v2d_droid_slam/docker/run_download_weights.py b/third-party/video_to_data/reconstruction/modules/v2d_droid_slam/docker/run_download_weights.py new file mode 100644 index 0000000000000000000000000000000000000000..d2308c6a276a2820bc2caa05bb95147a779bf0e5 --- /dev/null +++ b/third-party/video_to_data/reconstruction/modules/v2d_droid_slam/docker/run_download_weights.py @@ -0,0 +1,36 @@ +# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 +import os +import subprocess + +from v2d.droid_slam.docker._config import IMAGE_NAME, MODULES_DIR + + +def run_download(output_dir: str, dev: bool = False) -> None: + os.makedirs(output_dir, exist_ok=True) + output_dir = os.path.abspath(output_dir) + + cmd = [ + "docker", "run", "--rm", + "--user", f"{os.getuid()}:{os.getgid()}", + "-e", "HOME=/tmp", + "-v", f"{output_dir}:/data/weights", + ] + if dev: + cmd += ["-v", f"{MODULES_DIR}:/workspace"] + cmd += [ + IMAGE_NAME, + "python", "-m", "v2d.droid_slam.lib.download_weights", + "--output_dir", "/data/weights", + ] + subprocess.run(cmd, check=True) + + +if __name__ == "__main__": + import argparse + + parser = argparse.ArgumentParser(description="Download DROID-SLAM checkpoint") + parser.add_argument("--output_dir", type=str, required=True) + parser.add_argument("--dev", action="store_true") + args = parser.parse_args() + run_download(output_dir=args.output_dir, dev=args.dev) diff --git a/third-party/video_to_data/reconstruction/modules/v2d_droid_slam/docker/run_image_list_to_slam.py b/third-party/video_to_data/reconstruction/modules/v2d_droid_slam/docker/run_image_list_to_slam.py new file mode 100644 index 0000000000000000000000000000000000000000..9917e4196bd7be33bcdfaa74e92159e456b5545a --- /dev/null +++ b/third-party/video_to_data/reconstruction/modules/v2d_droid_slam/docker/run_image_list_to_slam.py @@ -0,0 +1,152 @@ +# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 +from v2d.docker.container import run_in_container +from v2d.droid_slam.docker._config import IMAGE_NAME, MODULES_DIR + + +def run_image_list_to_slam( + image_folder: str, + poses_folder: str, + weights_path: str, + input_intrinsics_path: str = None, + input_intrinsics_folder: str = None, + input_depth_folder: str = None, + align_to_depth_folder: str = None, + depth_folder: str = None, + pointcloud_path: str = None, + trajectory_path: str = None, + stride: int = 1, + image_height: int = 384, + image_width: int = 512, + buffer_size: int = 512, + beta: float = 0.3, + filter_thresh: float = 2.4, + warmup: int = 8, + keyframe_thresh: float = 4.0, + frontend_thresh: float = 16.0, + frontend_window: int = 25, + frontend_radius: int = 2, + frontend_nms: int = 1, + backend_thresh: float = 22.0, + backend_radius: int = 2, + backend_nms: int = 3, + upsample: bool = False, + pointcloud_min_views: int = 2, + dev: bool = False, +) -> None: + inputs = {"image_folder": image_folder, "weights_path": weights_path} + if input_intrinsics_path is not None: + inputs["input_intrinsics_path"] = input_intrinsics_path + if input_intrinsics_folder is not None: + inputs["input_intrinsics_folder"] = input_intrinsics_folder + if input_depth_folder is not None: + inputs["input_depth_folder"] = input_depth_folder + if align_to_depth_folder is not None: + inputs["align_to_depth_folder"] = align_to_depth_folder + + outputs = {"poses_folder": poses_folder} + if depth_folder is not None: + outputs["depth_folder"] = depth_folder + if pointcloud_path is not None: + outputs["pointcloud_path"] = pointcloud_path + if trajectory_path is not None: + outputs["trajectory_path"] = trajectory_path + + extra_args = { + "stride": stride, + "image_height": image_height, + "image_width": image_width, + "buffer_size": buffer_size, + "beta": beta, + "filter_thresh": filter_thresh, + "warmup": warmup, + "keyframe_thresh": keyframe_thresh, + "frontend_thresh": frontend_thresh, + "frontend_window": frontend_window, + "frontend_radius": frontend_radius, + "frontend_nms": frontend_nms, + "backend_thresh": backend_thresh, + "backend_radius": backend_radius, + "backend_nms": backend_nms, + "upsample": upsample, + "pointcloud_min_views": pointcloud_min_views, + } + + run_in_container( + image=IMAGE_NAME, + module="v2d.droid_slam.lib.image_list_to_slam", + inputs=inputs, + outputs=outputs, + extra_args=extra_args, + dev=dev, + modules_dir=MODULES_DIR, + gpus=True, + ) + + +if __name__ == "__main__": + import argparse + + parser = argparse.ArgumentParser(description="Run DROID-SLAM on a folder of frames") + parser.add_argument("--image_folder", required=True) + parser.add_argument("--poses_folder", required=True) + parser.add_argument("--weights_path", required=True) + parser.add_argument("--input_intrinsics_path", default=None) + parser.add_argument("--input_intrinsics_folder", default=None) + parser.add_argument("--input_depth_folder", default=None, + help="Per-frame metric depth fed into BA as a sensor prior.") + parser.add_argument("--align_to_depth_folder", default=None, + help="Per-frame metric depth used post-hoc for scale alignment only.") + parser.add_argument("--depth_folder", default=None) + parser.add_argument("--pointcloud_path", default=None) + parser.add_argument("--trajectory_path", default=None) + parser.add_argument("--stride", type=int, default=1) + parser.add_argument("--image_height", type=int, default=384) + parser.add_argument("--image_width", type=int, default=512) + parser.add_argument("--buffer_size", type=int, default=512) + parser.add_argument("--beta", type=float, default=0.3) + parser.add_argument("--filter_thresh", type=float, default=2.4) + parser.add_argument("--warmup", type=int, default=8) + parser.add_argument("--keyframe_thresh", type=float, default=4.0) + parser.add_argument("--frontend_thresh", type=float, default=16.0) + parser.add_argument("--frontend_window", type=int, default=25) + parser.add_argument("--frontend_radius", type=int, default=2) + parser.add_argument("--frontend_nms", type=int, default=1) + parser.add_argument("--backend_thresh", type=float, default=22.0) + parser.add_argument("--backend_radius", type=int, default=2) + parser.add_argument("--backend_nms", type=int, default=3) + parser.add_argument("--upsample", action="store_true") + parser.add_argument("--pointcloud_min_views", type=int, default=2) + parser.add_argument("--dev", action="store_true") + args = parser.parse_args() + + run_image_list_to_slam( + image_folder=args.image_folder, + poses_folder=args.poses_folder, + weights_path=args.weights_path, + input_intrinsics_path=args.input_intrinsics_path, + input_intrinsics_folder=args.input_intrinsics_folder, + input_depth_folder=args.input_depth_folder, + align_to_depth_folder=args.align_to_depth_folder, + depth_folder=args.depth_folder, + pointcloud_path=args.pointcloud_path, + trajectory_path=args.trajectory_path, + stride=args.stride, + image_height=args.image_height, + image_width=args.image_width, + buffer_size=args.buffer_size, + beta=args.beta, + filter_thresh=args.filter_thresh, + warmup=args.warmup, + keyframe_thresh=args.keyframe_thresh, + frontend_thresh=args.frontend_thresh, + frontend_window=args.frontend_window, + frontend_radius=args.frontend_radius, + frontend_nms=args.frontend_nms, + backend_thresh=args.backend_thresh, + backend_radius=args.backend_radius, + backend_nms=args.backend_nms, + upsample=args.upsample, + pointcloud_min_views=args.pointcloud_min_views, + dev=args.dev, + ) diff --git a/third-party/video_to_data/reconstruction/modules/v2d_droid_slam/docker/run_video_to_slam.py b/third-party/video_to_data/reconstruction/modules/v2d_droid_slam/docker/run_video_to_slam.py new file mode 100644 index 0000000000000000000000000000000000000000..1431bcf459e192960cad0380de848617ba2691a5 --- /dev/null +++ b/third-party/video_to_data/reconstruction/modules/v2d_droid_slam/docker/run_video_to_slam.py @@ -0,0 +1,152 @@ +# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 +from v2d.docker.container import run_in_container +from v2d.droid_slam.docker._config import IMAGE_NAME, MODULES_DIR + + +def run_video_to_slam( + video_path: str, + poses_folder: str, + weights_path: str, + input_intrinsics_path: str = None, + input_intrinsics_folder: str = None, + input_depth_folder: str = None, + align_to_depth_folder: str = None, + depth_folder: str = None, + pointcloud_path: str = None, + trajectory_path: str = None, + stride: int = 1, + image_height: int = 384, + image_width: int = 512, + buffer_size: int = 512, + beta: float = 0.3, + filter_thresh: float = 2.4, + warmup: int = 8, + keyframe_thresh: float = 4.0, + frontend_thresh: float = 16.0, + frontend_window: int = 25, + frontend_radius: int = 2, + frontend_nms: int = 1, + backend_thresh: float = 22.0, + backend_radius: int = 2, + backend_nms: int = 3, + upsample: bool = False, + pointcloud_min_views: int = 2, + dev: bool = False, +) -> None: + inputs = {"video_path": video_path, "weights_path": weights_path} + if input_intrinsics_path is not None: + inputs["input_intrinsics_path"] = input_intrinsics_path + if input_intrinsics_folder is not None: + inputs["input_intrinsics_folder"] = input_intrinsics_folder + if input_depth_folder is not None: + inputs["input_depth_folder"] = input_depth_folder + if align_to_depth_folder is not None: + inputs["align_to_depth_folder"] = align_to_depth_folder + + outputs = {"poses_folder": poses_folder} + if depth_folder is not None: + outputs["depth_folder"] = depth_folder + if pointcloud_path is not None: + outputs["pointcloud_path"] = pointcloud_path + if trajectory_path is not None: + outputs["trajectory_path"] = trajectory_path + + extra_args = { + "stride": stride, + "image_height": image_height, + "image_width": image_width, + "buffer_size": buffer_size, + "beta": beta, + "filter_thresh": filter_thresh, + "warmup": warmup, + "keyframe_thresh": keyframe_thresh, + "frontend_thresh": frontend_thresh, + "frontend_window": frontend_window, + "frontend_radius": frontend_radius, + "frontend_nms": frontend_nms, + "backend_thresh": backend_thresh, + "backend_radius": backend_radius, + "backend_nms": backend_nms, + "upsample": upsample, + "pointcloud_min_views": pointcloud_min_views, + } + + run_in_container( + image=IMAGE_NAME, + module="v2d.droid_slam.lib.video_to_slam", + inputs=inputs, + outputs=outputs, + extra_args=extra_args, + dev=dev, + modules_dir=MODULES_DIR, + gpus=True, + ) + + +if __name__ == "__main__": + import argparse + + parser = argparse.ArgumentParser(description="Run DROID-SLAM on a video") + parser.add_argument("--video_path", required=True) + parser.add_argument("--poses_folder", required=True) + parser.add_argument("--weights_path", required=True) + parser.add_argument("--input_intrinsics_path", default=None) + parser.add_argument("--input_intrinsics_folder", default=None) + parser.add_argument("--input_depth_folder", default=None, + help="Per-frame metric depth fed into BA as a sensor prior.") + parser.add_argument("--align_to_depth_folder", default=None, + help="Per-frame metric depth used post-hoc for scale alignment only.") + parser.add_argument("--depth_folder", default=None) + parser.add_argument("--pointcloud_path", default=None) + parser.add_argument("--trajectory_path", default=None) + parser.add_argument("--stride", type=int, default=1) + parser.add_argument("--image_height", type=int, default=384) + parser.add_argument("--image_width", type=int, default=512) + parser.add_argument("--buffer_size", type=int, default=512) + parser.add_argument("--beta", type=float, default=0.3) + parser.add_argument("--filter_thresh", type=float, default=2.4) + parser.add_argument("--warmup", type=int, default=8) + parser.add_argument("--keyframe_thresh", type=float, default=4.0) + parser.add_argument("--frontend_thresh", type=float, default=16.0) + parser.add_argument("--frontend_window", type=int, default=25) + parser.add_argument("--frontend_radius", type=int, default=2) + parser.add_argument("--frontend_nms", type=int, default=1) + parser.add_argument("--backend_thresh", type=float, default=22.0) + parser.add_argument("--backend_radius", type=int, default=2) + parser.add_argument("--backend_nms", type=int, default=3) + parser.add_argument("--upsample", action="store_true") + parser.add_argument("--pointcloud_min_views", type=int, default=2) + parser.add_argument("--dev", action="store_true") + args = parser.parse_args() + + run_video_to_slam( + video_path=args.video_path, + poses_folder=args.poses_folder, + weights_path=args.weights_path, + input_intrinsics_path=args.input_intrinsics_path, + input_intrinsics_folder=args.input_intrinsics_folder, + input_depth_folder=args.input_depth_folder, + align_to_depth_folder=args.align_to_depth_folder, + depth_folder=args.depth_folder, + pointcloud_path=args.pointcloud_path, + trajectory_path=args.trajectory_path, + stride=args.stride, + image_height=args.image_height, + image_width=args.image_width, + buffer_size=args.buffer_size, + beta=args.beta, + filter_thresh=args.filter_thresh, + warmup=args.warmup, + keyframe_thresh=args.keyframe_thresh, + frontend_thresh=args.frontend_thresh, + frontend_window=args.frontend_window, + frontend_radius=args.frontend_radius, + frontend_nms=args.frontend_nms, + backend_thresh=args.backend_thresh, + backend_radius=args.backend_radius, + backend_nms=args.backend_nms, + upsample=args.upsample, + pointcloud_min_views=args.pointcloud_min_views, + dev=args.dev, + ) diff --git a/third-party/video_to_data/reconstruction/modules/v2d_droid_slam/lib/__init__.py b/third-party/video_to_data/reconstruction/modules/v2d_droid_slam/lib/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..52a7a9daf028f654d6a02f65c99cc609a57b492f --- /dev/null +++ b/third-party/video_to_data/reconstruction/modules/v2d_droid_slam/lib/__init__.py @@ -0,0 +1,2 @@ +# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 diff --git a/third-party/video_to_data/reconstruction/modules/v2d_droid_slam/lib/_slam.py b/third-party/video_to_data/reconstruction/modules/v2d_droid_slam/lib/_slam.py new file mode 100644 index 0000000000000000000000000000000000000000..9779f7dd60aa72872b33cb463a628e467a467b82 --- /dev/null +++ b/third-party/video_to_data/reconstruction/modules/v2d_droid_slam/lib/_slam.py @@ -0,0 +1,350 @@ +# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 +""" +Internal DROID-SLAM driver shared by video_to_slam and image_list_to_slam. + +Loads the upstream Droid runner, drives tracking over a frame iterator, +optionally scale-aligns the result to a reference metric-depth source, +and writes outputs in the v2d common formats. +""" +from __future__ import annotations + +import os +from dataclasses import dataclass +from types import SimpleNamespace +from typing import Callable, Iterator + +import cv2 +import numpy as np +import torch + +from v2d.common.datatypes import CameraIntrinsics, DepthImage, Transform3d + + +@dataclass +class Frame: + frame_idx: int # source frame index (zero-padded filename stem) + image_bgr: np.ndarray # (H, W, 3) uint8 + intrinsics: CameraIntrinsics # intrinsics at the source resolution + prior_depth: np.ndarray | None = None # (H, W) float32 metres — fed into BA as sensor prior + align_to_depth: np.ndarray | None = None # (H, W) float32 metres — used post-hoc for scale alignment + + +def _resize_for_droid( + image_bgr: np.ndarray, + fxfycxcy: np.ndarray, + image_size: tuple[int, int], + prior_depth: np.ndarray | None = None, +) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor | None]: + """Resize a frame to DROID's network input and rescale intrinsics to match. + + Returns image as (1, 3, H, W) uint8 BGR (upstream motion_filter adds its + own [None]+[2,1,0] reorder to get RGB internally), scaled intrinsics, and + optional depth resized to the network input resolution. Invalid (non-positive + or non-finite) depth pixels are zeroed; depth_video.append() interprets + zero as "no prior at this pixel". + """ + target_h, target_w = image_size + src_h, src_w = image_bgr.shape[:2] + image_bgr = cv2.resize(image_bgr, (target_w, target_h), interpolation=cv2.INTER_AREA) + image = torch.from_numpy(image_bgr).permute(2, 0, 1)[None] # (1, 3, H, W) uint8 + + sx = target_w / src_w + sy = target_h / src_h + fx, fy, cx, cy = fxfycxcy + scaled = torch.tensor([fx * sx, fy * sy, cx * sx, cy * sy], dtype=torch.float32) + + depth_t: torch.Tensor | None = None + if prior_depth is not None: + d = prior_depth.astype(np.float32) + invalid = ~np.isfinite(d) | (d <= 0) + d[invalid] = 0.0 + if d.shape != (target_h, target_w): + d = cv2.resize(d, (target_w, target_h), interpolation=cv2.INTER_NEAREST) + depth_t = torch.from_numpy(d) + + return image, scaled, depth_t + + +def _load_droid_class(): + """Import the upstream Droid class lazily so module import stays cheap.""" + from droid import Droid # provided by the DROID-SLAM repo on PYTHONPATH + return Droid + + +def _get_keyframe_disps(droid, upsample: bool) -> np.ndarray: + """Return per-keyframe disparity. Upsampled to source resolution if available.""" + video = droid.video + if upsample and hasattr(video, "disps_up"): + return video.disps_up.detach().cpu().numpy() + return video.disps.detach().cpu().numpy() + + +def _solve_global_scale(droid, frames_by_idx: dict[int, Frame], upsample: bool) -> float: + """Compute a robust scale factor that maps DROID depth → reference depth. + + Sampled at every keyframe where reference depth is available. Per-keyframe + median ratios are aggregated into a final global median. + """ + video = droid.video + n_kf = int(video.counter.value) + disps = _get_keyframe_disps(droid, upsample) + tstamps = video.tstamp.detach().cpu().numpy().astype(np.int64) + + per_kf_scales: list[float] = [] + for kf in range(n_kf): + frame_idx = int(tstamps[kf]) + if frame_idx not in frames_by_idx: + continue + ref = frames_by_idx[frame_idx].align_to_depth + if ref is None: + continue + disp = disps[kf] + # DROID disparity is in network-resolution pixels; resize to source. + ref_h, ref_w = ref.shape[:2] + if disp.shape != (ref_h, ref_w): + disp = cv2.resize(disp, (ref_w, ref_h), interpolation=cv2.INTER_LINEAR) + valid = (disp > 1e-3) & (ref > 1e-3) & np.isfinite(ref) + if valid.sum() < 64: + continue + droid_depth = 1.0 / disp[valid] + ratios = ref[valid] / droid_depth + per_kf_scales.append(float(np.median(ratios))) + + if not per_kf_scales: + return 1.0 + return float(np.median(per_kf_scales)) + + +def _write_pointcloud_ply(droid, scale: float, path: str, + min_views: int = 2, + filter_thresh: float = 0.005) -> None: + """Dump the post-BA keyframe point cloud as a binary-little-endian PLY. + + Uses upstream's depth_filter for multi-view consistency: a pixel is + kept only if its depth is consistent with at least ``min_views`` other + keyframes. This is what produces clean (non-fuzzy) clouds. + """ + import torch + import droid_backends + from lietorch import SE3 + + video = droid.video + n_kf = int(video.counter.value) + if n_kf == 0: + print("[droid-slam] no keyframes; skipping PLY") + return + + # depth_filter inspects the FULL buffer using dirty_index to know which + # slots are valid, so we hand it the unsliced tensors as upstream does. + dirty_index = torch.arange(n_kf, device=video.poses.device) + thresh = filter_thresh * torch.ones(n_kf, device=video.poses.device) + count = droid_backends.depth_filter( + video.poses, video.disps, video.intrinsics[0], dirty_index, thresh + ) # (N, h, w) per-pixel consistent-view count + + poses = video.poses[:n_kf].detach() + disps = video.disps[:n_kf].detach() + images = video.images[:n_kf].detach() + intrinsics = video.intrinsics[0].detach() + + cam_to_world = SE3(poses).inv() + points_world = droid_backends.iproj(cam_to_world.data, disps, intrinsics) + points_world = (points_world * scale).cpu().numpy() # (N, h, w, 3) + + colors_rgb = images[:, [2, 1, 0], 3::8, 3::8] + colors_rgb = colors_rgb.permute(0, 2, 3, 1).cpu().numpy() # (N, h, w, 3) RGB + + disp_np = disps.cpu().numpy() + disp_mean = disp_np.reshape(n_kf, -1).mean(axis=1).reshape(n_kf, 1, 1) + consistency_mask = count.cpu().numpy() >= min_views + mask = consistency_mask & (disp_np > 0.5 * disp_mean) & (disp_np > 1e-3) + + points_arr = points_world[mask].astype(np.float32) + colors_arr = colors_rgb[mask].astype(np.uint8) + if points_arr.size == 0: + print("[droid-slam] no points passed consistency filter; skipping PLY") + return + + t_arr = cam_to_world.data[:, :3].cpu().numpy() + n_total = int(mask.size) + print(f"[droid-slam] PLY: {n_kf} keyframes, {points_arr.shape[0]} / {n_total} points " + f"kept (min_views={min_views}); " + f"cam x∈[{t_arr[:,0].min():.3f},{t_arr[:,0].max():.3f}] " + f"y∈[{t_arr[:,1].min():.3f},{t_arr[:,1].max():.3f}] " + f"z∈[{t_arr[:,2].min():.3f},{t_arr[:,2].max():.3f}]") + + os.makedirs(os.path.dirname(os.path.abspath(path)) or ".", exist_ok=True) + with open(path, "wb") as f: + header = ( + "ply\n" + "format binary_little_endian 1.0\n" + f"element vertex {points_arr.shape[0]}\n" + "property float x\nproperty float y\nproperty float z\n" + "property uchar red\nproperty uchar green\nproperty uchar blue\n" + "end_header\n" + ) + f.write(header.encode("ascii")) + interleaved = np.empty(points_arr.shape[0], + dtype=[("xyz", np.float32, 3), ("rgb", np.uint8, 3)]) + interleaved["xyz"] = points_arr + interleaved["rgb"] = colors_arr + interleaved.tofile(f) + + +def _se3_quat_to_matrix(pose: np.ndarray) -> np.ndarray: + """Convert DROID's [tx,ty,tz,qx,qy,qz,qw] world-to-camera into a 4×4 matrix.""" + from scipy.spatial.transform import Rotation + tx, ty, tz, qx, qy, qz, qw = pose.tolist() + R = Rotation.from_quat([qx, qy, qz, qw]).as_matrix() + M = np.eye(4) + M[:3, :3] = R + M[:3, 3] = [tx, ty, tz] + return M + + +def run_droid_slam( + frame_iter: Callable[[], Iterator[Frame]], + weights_path: str, + poses_folder: str, + depth_folder: str | None = None, + pointcloud_path: str | None = None, + trajectory_path: str | None = None, + image_size: tuple[int, int] = (384, 512), + buffer_size: int = 512, + beta: float = 0.3, + filter_thresh: float = 2.4, + warmup: int = 8, + keyframe_thresh: float = 4.0, + frontend_thresh: float = 16.0, + frontend_window: int = 25, + frontend_radius: int = 2, + frontend_nms: int = 1, + backend_thresh: float = 22.0, + backend_radius: int = 2, + backend_nms: int = 3, + upsample: bool = False, + pointcloud_min_views: int = 2, +) -> None: + """Run DROID-SLAM over a frame iterator and write outputs. + + The frame iterator is invoked twice: once for tracking, then again for + scale alignment so we can correlate keyframes with their reference depth + without holding all frames in memory. + """ + os.makedirs(poses_folder, exist_ok=True) + if depth_folder is not None: + os.makedirs(depth_folder, exist_ok=True) + + weights_file = os.path.join(weights_path, "droid.pth") \ + if os.path.isdir(weights_path) else weights_path + if not os.path.exists(weights_file): + raise FileNotFoundError(f"droid.pth not found at {weights_file}") + + args = SimpleNamespace( + weights=weights_file, + image_size=list(image_size), + buffer=buffer_size, + beta=beta, + filter_thresh=filter_thresh, + warmup=warmup, + keyframe_thresh=keyframe_thresh, + frontend_thresh=frontend_thresh, + frontend_window=frontend_window, + frontend_radius=frontend_radius, + frontend_nms=frontend_nms, + backend_thresh=backend_thresh, + backend_radius=backend_radius, + backend_nms=backend_nms, + upsample=upsample, + disable_vis=True, + stereo=False, + ) + + Droid = _load_droid_class() + droid: object | None = None + + frames_by_idx: dict[int, Frame] = {} + ordered_indices: list[int] = [] + + for frame in frame_iter(): + if droid is None: + droid = Droid(args) + fxfycxcy = np.array([frame.intrinsics.fx, frame.intrinsics.fy, + frame.intrinsics.cx, frame.intrinsics.cy], dtype=np.float32) + image_t, intr_t, depth_t = _resize_for_droid( + frame.image_bgr, fxfycxcy, image_size, prior_depth=frame.prior_depth, + ) + droid.track(frame.frame_idx, image_t, depth=depth_t, intrinsics=intr_t) + frames_by_idx[frame.frame_idx] = frame + ordered_indices.append(frame.frame_idx) + + if droid is None: + raise RuntimeError("frame_iter produced no frames") + + # Reconstruct the stream for terminate() — used internally by DROID + # for the final global BA pass. + def replay(): + for f in frame_iter(): + fxfycxcy = np.array([f.intrinsics.fx, f.intrinsics.fy, + f.intrinsics.cx, f.intrinsics.cy], dtype=np.float32) + image_t, intr_t, _ = _resize_for_droid( + f.image_bgr, fxfycxcy, image_size, prior_depth=None, + ) + yield (f.frame_idx, image_t, intr_t) + + traj_est = droid.terminate(replay()) # (N_frames, 7) camera-to-world [tx,ty,tz,qx,qy,qz,qw] + + scale = _solve_global_scale(droid, frames_by_idx, upsample) + if scale != 1.0: + print(f"[droid-slam] applying global scale {scale:.6f} from reference depth") + + # Write per-frame poses. + from scipy.spatial.transform import Rotation + for row_i, frame_idx in enumerate(ordered_indices): + tx, ty, tz, qx, qy, qz, qw = traj_est[row_i].tolist() + M = np.eye(4) + M[:3, :3] = Rotation.from_quat([qx, qy, qz, qw]).as_matrix() + M[:3, 3] = [tx * scale, ty * scale, tz * scale] + Transform3d.from_matrix(M).save( + os.path.join(poses_folder, f"{frame_idx:06d}.json") + ) + + # Optional TUM trajectory. + if trajectory_path is not None: + os.makedirs(os.path.dirname(os.path.abspath(trajectory_path)) or ".", exist_ok=True) + with open(trajectory_path, "w") as f: + for row_i, frame_idx in enumerate(ordered_indices): + tx, ty, tz, qx, qy, qz, qw = traj_est[row_i].tolist() + f.write(f"{frame_idx} {tx*scale} {ty*scale} {tz*scale} " + f"{qx} {qy} {qz} {qw}\n") + + # Optional per-keyframe depth output (scaled, upsampled to source resolution). + if depth_folder is not None: + video = droid.video + n_kf = int(video.counter.value) + disps = _get_keyframe_disps(droid, upsample) + tstamps = video.tstamp.detach().cpu().numpy().astype(np.int64) + + for kf in range(n_kf): + disp = disps[kf] + frame_idx = int(tstamps[kf]) + frame = frames_by_idx.get(frame_idx) + if frame is None: + continue + tgt_h, tgt_w = frame.intrinsics.height, frame.intrinsics.width + if disp.shape != (tgt_h, tgt_w): + disp = cv2.resize(disp, (tgt_w, tgt_h), interpolation=cv2.INTER_LINEAR) + # Dense depth output: every pixel gets a value. Tiny-disparity pixels + # (effectively "no information") map to large depth and therefore + # near-black in the inverse-depth PNG encoding — distinguishable + # from depth≈0, which would have been white and visually misleading. + safe_disp = np.maximum(disp, 1e-6) + depth = (1.0 / safe_disp) * scale + DepthImage(depth=depth.astype(np.float32)).to_pil_image().save( + os.path.join(depth_folder, f"{frame_idx:06d}.png") + ) + + if pointcloud_path is not None: + _write_pointcloud_ply(droid, scale, pointcloud_path, + min_views=pointcloud_min_views) diff --git a/third-party/video_to_data/reconstruction/modules/v2d_droid_slam/lib/download_weights.py b/third-party/video_to_data/reconstruction/modules/v2d_droid_slam/lib/download_weights.py new file mode 100644 index 0000000000000000000000000000000000000000..0a9c8571d7d43789efa6af7c27617688a047f799 --- /dev/null +++ b/third-party/video_to_data/reconstruction/modules/v2d_droid_slam/lib/download_weights.py @@ -0,0 +1,32 @@ +# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 +""" +Download the DROID-SLAM checkpoint (droid.pth) into a local weights folder. + +Upstream hosts the file on Google Drive — we use gdown to fetch it. +""" +import argparse +import os + +import gdown + +DROID_GDRIVE_FILE_ID = "1PpqVt1H4maBa_GbPJp4NwxRsd9jk-elh" + + +def download_droid(output_dir: str) -> None: + os.makedirs(output_dir, exist_ok=True) + out_path = os.path.join(output_dir, "droid.pth") + if os.path.exists(out_path): + print(f"droid.pth already present at {out_path} — skipping download") + return + url = f"https://drive.google.com/uc?id={DROID_GDRIVE_FILE_ID}" + gdown.download(url, out_path, quiet=False) + print(f"DROID-SLAM checkpoint downloaded to {out_path}") + + +if __name__ == "__main__": + parser = argparse.ArgumentParser(description="Download DROID-SLAM checkpoint") + parser.add_argument("--output_dir", type=str, required=True, + help="Output directory for droid.pth") + args = parser.parse_args() + download_droid(args.output_dir) diff --git a/third-party/video_to_data/reconstruction/modules/v2d_droid_slam/lib/image_list_to_slam.py b/third-party/video_to_data/reconstruction/modules/v2d_droid_slam/lib/image_list_to_slam.py new file mode 100644 index 0000000000000000000000000000000000000000..c2c5e9df89c9715f3aa8aaa21c783b72c26ab765 --- /dev/null +++ b/third-party/video_to_data/reconstruction/modules/v2d_droid_slam/lib/image_list_to_slam.py @@ -0,0 +1,223 @@ +# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 +""" +Run DROID-SLAM on a folder of frame images → per-frame camera poses +(+ optional depth, PLY). Sibling of video_to_slam with the same options. + +Image folder may contain .png, .jpg, or .jpeg files. Frame index is parsed +from the filename stem as an integer (zero-padded names like 000123.png). +""" +from __future__ import annotations + +import argparse +import os +from typing import Iterator + +import cv2 +import numpy as np + +from v2d.common.datatypes import CameraIntrinsics, DepthImage +from v2d.droid_slam.lib._slam import Frame, run_droid_slam + + +_IMAGE_EXTS = (".png", ".jpg", ".jpeg") + + +def _list_image_files(image_folder: str) -> list[str]: + files = [ + os.path.join(image_folder, f) + for f in os.listdir(image_folder) + if f.lower().endswith(_IMAGE_EXTS) + ] + files.sort() + return files + + +def _frame_idx_from_path(path: str) -> int: + stem = os.path.splitext(os.path.basename(path))[0] + return int(stem) + + +def _load_intrinsics_for_frame( + input_intrinsics_path: str | None, + input_intrinsics_folder: str | None, + frame_idx: int, + fallback: CameraIntrinsics | None, +) -> CameraIntrinsics: + if input_intrinsics_folder is not None: + path = os.path.join(input_intrinsics_folder, f"{frame_idx:06d}.json") + if os.path.exists(path): + return CameraIntrinsics.load(path) + if fallback is None: + raise FileNotFoundError( + f"No intrinsics file for frame {frame_idx} at {path} and no fallback") + return fallback + assert fallback is not None + return fallback + + +def _depth_for_frame(folder: str | None, frame_idx: int) -> np.ndarray | None: + if folder is None: + return None + path = os.path.join(folder, f"{frame_idx:06d}.png") + if not os.path.exists(path): + return None + return DepthImage.load(path).depth.astype(np.float32) + + +def image_list_to_slam( + image_folder: str, + poses_folder: str, + weights_path: str, + input_intrinsics_path: str | None = None, + input_intrinsics_folder: str | None = None, + input_depth_folder: str | None = None, + align_to_depth_folder: str | None = None, + depth_folder: str | None = None, + pointcloud_path: str | None = None, + trajectory_path: str | None = None, + stride: int = 1, + image_size: tuple[int, int] = (384, 512), + buffer_size: int = 512, + beta: float = 0.3, + filter_thresh: float = 2.4, + warmup: int = 8, + keyframe_thresh: float = 4.0, + frontend_thresh: float = 16.0, + frontend_window: int = 25, + frontend_radius: int = 2, + frontend_nms: int = 1, + backend_thresh: float = 22.0, + backend_radius: int = 2, + backend_nms: int = 3, + upsample: bool = False, + pointcloud_min_views: int = 2, +) -> None: + if input_intrinsics_path is None and input_intrinsics_folder is None: + raise ValueError("Provide either --input_intrinsics_path or --input_intrinsics_folder") + + fallback_intrinsics = None + if input_intrinsics_path is not None: + fallback_intrinsics = CameraIntrinsics.load(input_intrinsics_path) + elif input_intrinsics_folder is not None: + # Use the first available file as a fallback for any frame missing its own. + files = sorted( + os.path.join(input_intrinsics_folder, f) + for f in os.listdir(input_intrinsics_folder) + if f.endswith(".json") + ) + if not files: + raise FileNotFoundError(f"No intrinsics JSONs in {input_intrinsics_folder}") + fallback_intrinsics = CameraIntrinsics.load(files[0]) + + image_paths = _list_image_files(image_folder) + if not image_paths: + raise FileNotFoundError(f"No images in {image_folder}") + + def frame_iter() -> Iterator[Frame]: + for i, path in enumerate(image_paths): + if i % stride != 0: + continue + frame_idx = _frame_idx_from_path(path) + image_bgr = cv2.imread(path, cv2.IMREAD_COLOR) + if image_bgr is None: + raise IOError(f"Failed to read image {path}") + intr = _load_intrinsics_for_frame( + input_intrinsics_path, input_intrinsics_folder, + frame_idx, fallback_intrinsics, + ) + yield Frame( + frame_idx=frame_idx, + image_bgr=image_bgr, + intrinsics=intr, + prior_depth=_depth_for_frame(input_depth_folder, frame_idx), + align_to_depth=_depth_for_frame(align_to_depth_folder, frame_idx), + ) + + run_droid_slam( + frame_iter=frame_iter, + weights_path=weights_path, + poses_folder=poses_folder, + depth_folder=depth_folder, + pointcloud_path=pointcloud_path, + trajectory_path=trajectory_path, + image_size=image_size, + buffer_size=buffer_size, + beta=beta, + filter_thresh=filter_thresh, + warmup=warmup, + keyframe_thresh=keyframe_thresh, + frontend_thresh=frontend_thresh, + frontend_window=frontend_window, + frontend_radius=frontend_radius, + frontend_nms=frontend_nms, + backend_thresh=backend_thresh, + backend_radius=backend_radius, + backend_nms=backend_nms, + upsample=upsample, + pointcloud_min_views=pointcloud_min_views, + ) + + +if __name__ == "__main__": + parser = argparse.ArgumentParser(description="Run DROID-SLAM on a folder of frames") + parser.add_argument("--image_folder", required=True) + parser.add_argument("--poses_folder", required=True) + parser.add_argument("--weights_path", required=True) + parser.add_argument("--input_intrinsics_path", default=None) + parser.add_argument("--input_intrinsics_folder", default=None) + parser.add_argument("--input_depth_folder", default=None, + help="Per-frame metric depth fed into BA as a sensor prior.") + parser.add_argument("--align_to_depth_folder", default=None, + help="Per-frame metric depth used post-hoc for scale alignment only.") + parser.add_argument("--depth_folder", default=None) + parser.add_argument("--pointcloud_path", default=None) + parser.add_argument("--trajectory_path", default=None) + parser.add_argument("--stride", type=int, default=1) + parser.add_argument("--image_height", type=int, default=384) + parser.add_argument("--image_width", type=int, default=512) + parser.add_argument("--buffer_size", type=int, default=512) + parser.add_argument("--beta", type=float, default=0.3) + parser.add_argument("--filter_thresh", type=float, default=2.4) + parser.add_argument("--warmup", type=int, default=8) + parser.add_argument("--keyframe_thresh", type=float, default=4.0) + parser.add_argument("--frontend_thresh", type=float, default=16.0) + parser.add_argument("--frontend_window", type=int, default=25) + parser.add_argument("--frontend_radius", type=int, default=2) + parser.add_argument("--frontend_nms", type=int, default=1) + parser.add_argument("--backend_thresh", type=float, default=22.0) + parser.add_argument("--backend_radius", type=int, default=2) + parser.add_argument("--backend_nms", type=int, default=3) + parser.add_argument("--upsample", action="store_true") + parser.add_argument("--pointcloud_min_views", type=int, default=2, + help="Multi-view consistency threshold for PLY output.") + args = parser.parse_args() + + image_list_to_slam( + image_folder=args.image_folder, + poses_folder=args.poses_folder, + weights_path=args.weights_path, + input_intrinsics_path=args.input_intrinsics_path, + input_intrinsics_folder=args.input_intrinsics_folder, + input_depth_folder=args.input_depth_folder, + align_to_depth_folder=args.align_to_depth_folder, + depth_folder=args.depth_folder, + pointcloud_path=args.pointcloud_path, + trajectory_path=args.trajectory_path, + stride=args.stride, + image_size=(args.image_height, args.image_width), + buffer_size=args.buffer_size, + beta=args.beta, + filter_thresh=args.filter_thresh, + warmup=args.warmup, + keyframe_thresh=args.keyframe_thresh, + frontend_thresh=args.frontend_thresh, + frontend_window=args.frontend_window, + frontend_radius=args.frontend_radius, + frontend_nms=args.frontend_nms, + backend_thresh=args.backend_thresh, + backend_radius=args.backend_radius, + backend_nms=args.backend_nms, + upsample=args.upsample, + pointcloud_min_views=args.pointcloud_min_views, + ) diff --git a/third-party/video_to_data/reconstruction/modules/v2d_droid_slam/lib/pyproject.toml b/third-party/video_to_data/reconstruction/modules/v2d_droid_slam/lib/pyproject.toml new file mode 100644 index 0000000000000000000000000000000000000000..af07e822885481fc7a41361b209f172abc0ca39b --- /dev/null +++ b/third-party/video_to_data/reconstruction/modules/v2d_droid_slam/lib/pyproject.toml @@ -0,0 +1,25 @@ +# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 +[build-system] +requires = ["setuptools>=68.0", "wheel"] +build-backend = "setuptools.build_meta" + +[project] +name = "v2d-droid-slam-lib" +version = "0.1.0" +description = "DROID-SLAM monocular SLAM library" +requires-python = ">=3.10" +dependencies = [ + "numpy", + "scipy", + "opencv-python", + "Pillow", + "gdown", + "v2d-common", +] + +[tool.setuptools] +packages = ["v2d.droid_slam.lib"] + +[tool.setuptools.package-dir] +"v2d.droid_slam.lib" = "." diff --git a/third-party/video_to_data/reconstruction/modules/v2d_droid_slam/lib/video_to_slam.py b/third-party/video_to_data/reconstruction/modules/v2d_droid_slam/lib/video_to_slam.py new file mode 100644 index 0000000000000000000000000000000000000000..7a35bbdf74bb15fff985f78b8de25d2e2786c614 --- /dev/null +++ b/third-party/video_to_data/reconstruction/modules/v2d_droid_slam/lib/video_to_slam.py @@ -0,0 +1,217 @@ +# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 +""" +Run DROID-SLAM on a video file → per-frame camera poses (+ optional depth, PLY). + +Intrinsics can be supplied either as a single CameraIntrinsics JSON +(--input_intrinsics_path; reused for every frame) or as a folder of +per-frame intrinsics JSON files (--input_intrinsics_folder; values are +median-pooled into a single set, since DROID-SLAM uses a fixed intrinsic +for the whole sequence). + +If --input_depth_folder is provided, per-frame depth (e.g. from MoGe) is +fed into DROID-SLAM's bundle adjustment as a metric prior — this directly +shapes the reconstructed geometry rather than rescaling it after the fact. + +If --align_to_depth_folder is provided, the reconstructed poses and depths +are scale-aligned to that metric reference via a robust per-keyframe ratio +fit. Pure post-processing — does not affect SLAM behaviour. + +The two flags are independent and may be combined: --input_depth_folder +shapes BA, --align_to_depth_folder rescales output. With a metric prior +provided, post-hoc rescaling is usually unnecessary. +""" +from __future__ import annotations + +import argparse +import os +from typing import Iterator + +import cv2 +import numpy as np + +from v2d.common.datatypes import CameraIntrinsics, DepthImage +from v2d.droid_slam.lib._slam import Frame, run_droid_slam + + +def _load_intrinsics( + input_intrinsics_path: str | None, + input_intrinsics_folder: str | None, +) -> CameraIntrinsics: + if input_intrinsics_path is None and input_intrinsics_folder is None: + raise ValueError("Provide either --input_intrinsics_path or --input_intrinsics_folder") + if input_intrinsics_path is not None: + return CameraIntrinsics.load(input_intrinsics_path) + # Per-frame intrinsics → median pool into one shared intrinsic for DROID. + files = sorted( + os.path.join(input_intrinsics_folder, f) + for f in os.listdir(input_intrinsics_folder) + if f.endswith(".json") + ) + if not files: + raise FileNotFoundError(f"No intrinsics JSONs in {input_intrinsics_folder}") + fx, fy, cx, cy, w, h = [], [], [], [], [], [] + for fp in files: + ci = CameraIntrinsics.load(fp) + fx.append(ci.fx); fy.append(ci.fy); cx.append(ci.cx); cy.append(ci.cy) + w.append(ci.width); h.append(ci.height) + return CameraIntrinsics( + fx=float(np.median(fx)), fy=float(np.median(fy)), + cx=float(np.median(cx)), cy=float(np.median(cy)), + width=int(np.median(w)), height=int(np.median(h)), + ) + + +def _depth_for_frame(folder: str | None, frame_idx: int) -> np.ndarray | None: + if folder is None: + return None + path = os.path.join(folder, f"{frame_idx:06d}.png") + if not os.path.exists(path): + return None + return DepthImage.load(path).depth.astype(np.float32) + + +def video_to_slam( + video_path: str, + poses_folder: str, + weights_path: str, + input_intrinsics_path: str | None = None, + input_intrinsics_folder: str | None = None, + input_depth_folder: str | None = None, + align_to_depth_folder: str | None = None, + depth_folder: str | None = None, + pointcloud_path: str | None = None, + trajectory_path: str | None = None, + stride: int = 1, + image_size: tuple[int, int] = (384, 512), + buffer_size: int = 512, + beta: float = 0.3, + filter_thresh: float = 2.4, + warmup: int = 8, + keyframe_thresh: float = 4.0, + frontend_thresh: float = 16.0, + frontend_window: int = 25, + frontend_radius: int = 2, + frontend_nms: int = 1, + backend_thresh: float = 22.0, + backend_radius: int = 2, + backend_nms: int = 3, + upsample: bool = False, + pointcloud_min_views: int = 2, +) -> None: + intrinsics = _load_intrinsics(input_intrinsics_path, input_intrinsics_folder) + + def frame_iter() -> Iterator[Frame]: + cap = cv2.VideoCapture(video_path) + try: + i = 0 + while True: + ret, frame_bgr = cap.read() + if not ret: + break + if i % stride == 0: + yield Frame( + frame_idx=i, + image_bgr=frame_bgr, + intrinsics=intrinsics, + prior_depth=_depth_for_frame(input_depth_folder, i), + align_to_depth=_depth_for_frame(align_to_depth_folder, i), + ) + i += 1 + finally: + cap.release() + + run_droid_slam( + frame_iter=frame_iter, + weights_path=weights_path, + poses_folder=poses_folder, + depth_folder=depth_folder, + pointcloud_path=pointcloud_path, + trajectory_path=trajectory_path, + image_size=image_size, + buffer_size=buffer_size, + beta=beta, + filter_thresh=filter_thresh, + warmup=warmup, + keyframe_thresh=keyframe_thresh, + frontend_thresh=frontend_thresh, + frontend_window=frontend_window, + frontend_radius=frontend_radius, + frontend_nms=frontend_nms, + backend_thresh=backend_thresh, + backend_radius=backend_radius, + backend_nms=backend_nms, + upsample=upsample, + pointcloud_min_views=pointcloud_min_views, + ) + + +if __name__ == "__main__": + parser = argparse.ArgumentParser(description="Run DROID-SLAM on a video") + parser.add_argument("--video_path", required=True) + parser.add_argument("--poses_folder", required=True) + parser.add_argument("--weights_path", required=True) + parser.add_argument("--input_intrinsics_path", default=None) + parser.add_argument("--input_intrinsics_folder", default=None) + parser.add_argument("--input_depth_folder", default=None, + help="Per-frame metric depth fed into BA as a sensor prior " + "(e.g. MoGe output). Shapes the reconstruction.") + parser.add_argument("--align_to_depth_folder", default=None, + help="Per-frame metric depth used post-hoc for scale " + "alignment only. Does not influence BA.") + parser.add_argument("--depth_folder", default=None, + help="Optional output: per-keyframe DROID depth (scale-aligned)") + parser.add_argument("--pointcloud_path", default=None, + help="Optional output: fused .ply of keyframe points") + parser.add_argument("--trajectory_path", default=None, + help="Optional output: TUM-format trajectory .txt") + parser.add_argument("--stride", type=int, default=1) + parser.add_argument("--image_height", type=int, default=384) + parser.add_argument("--image_width", type=int, default=512) + parser.add_argument("--buffer_size", type=int, default=512) + parser.add_argument("--beta", type=float, default=0.3) + parser.add_argument("--filter_thresh", type=float, default=2.4) + parser.add_argument("--warmup", type=int, default=8) + parser.add_argument("--keyframe_thresh", type=float, default=4.0) + parser.add_argument("--frontend_thresh", type=float, default=16.0) + parser.add_argument("--frontend_window", type=int, default=25) + parser.add_argument("--frontend_radius", type=int, default=2) + parser.add_argument("--frontend_nms", type=int, default=1) + parser.add_argument("--backend_thresh", type=float, default=22.0) + parser.add_argument("--backend_radius", type=int, default=2) + parser.add_argument("--backend_nms", type=int, default=3) + parser.add_argument("--upsample", action="store_true") + parser.add_argument("--pointcloud_min_views", type=int, default=2, + help="Multi-view consistency threshold for PLY output. " + "1 = keep all pixels above the disparity threshold " + "(dense, noisier); 2 = upstream default (clean, sparse).") + args = parser.parse_args() + + video_to_slam( + video_path=args.video_path, + poses_folder=args.poses_folder, + weights_path=args.weights_path, + input_intrinsics_path=args.input_intrinsics_path, + input_intrinsics_folder=args.input_intrinsics_folder, + input_depth_folder=args.input_depth_folder, + align_to_depth_folder=args.align_to_depth_folder, + depth_folder=args.depth_folder, + pointcloud_path=args.pointcloud_path, + trajectory_path=args.trajectory_path, + stride=args.stride, + image_size=(args.image_height, args.image_width), + buffer_size=args.buffer_size, + beta=args.beta, + filter_thresh=args.filter_thresh, + warmup=args.warmup, + keyframe_thresh=args.keyframe_thresh, + frontend_thresh=args.frontend_thresh, + frontend_window=args.frontend_window, + frontend_radius=args.frontend_radius, + frontend_nms=args.frontend_nms, + backend_thresh=args.backend_thresh, + backend_radius=args.backend_radius, + backend_nms=args.backend_nms, + upsample=args.upsample, + pointcloud_min_views=args.pointcloud_min_views, + ) diff --git a/third-party/video_to_data/reconstruction/modules/v2d_droid_slam/tools/poses_to_frustums.py b/third-party/video_to_data/reconstruction/modules/v2d_droid_slam/tools/poses_to_frustums.py new file mode 100644 index 0000000000000000000000000000000000000000..20571cb63a6a318d78234a933d5cb8f6f82e51ad --- /dev/null +++ b/third-party/video_to_data/reconstruction/modules/v2d_droid_slam/tools/poses_to_frustums.py @@ -0,0 +1,125 @@ +# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 +""" +Convert a folder of Transform3d (camera-to-world) JSONs into a PLY of camera +frustum wireframes. Open this PLY alongside the point cloud in MeshLab (or +any PLY viewer) to see where each camera is pointing. + +Usage: + python modules/v2d_droid_slam/tools/poses_to_frustums.py \ + --poses_folder data/clean/agent_90_undist/output/droid_slam/poses \ + --intrinsics_path data/clean/agent_90_undist/undistorted_intrinsics.json \ + --output_path data/clean/agent_90_undist/output/droid_slam/cameras.ply \ + [--frustum_size 0.05] # near-plane distance in scene units + [--stride 1] # skip frames + +Open in MeshLab (drag both files into the same window): + meshlab data/clean/agent_90_undist/output/droid_slam/pointcloud.ply \ + data/clean/agent_90_undist/output/droid_slam/cameras.ply +""" +import argparse +import json +import os +import sys + +import numpy as np + +# Make `v2d.common.datatypes` importable without installing anything. +_REPO_MODULES = os.path.abspath(os.path.join(os.path.dirname(__file__), "..", "..")) +sys.path.insert(0, os.path.join(_REPO_MODULES, "v2d_common")) +from datatypes import CameraIntrinsics, Transform3d # noqa: E402 + + +def _frustum_vertices(K: np.ndarray, T_cw: np.ndarray, near: float, + width: int, height: int) -> np.ndarray: + """Return 5 vertices (world frame): camera centre + 4 near-plane corners.""" + fx, fy = K[0, 0], K[1, 1] + cx, cy = K[0, 2], K[1, 2] + corners_pix = np.array([ + [0, 0], [width, 0], [width, height], [0, height], + ], dtype=np.float64) + rays_cam = np.stack([ + (corners_pix[:, 0] - cx) / fx, + (corners_pix[:, 1] - cy) / fy, + np.ones(4), + ], axis=1) * near + pts_cam = np.concatenate([np.zeros((1, 3)), rays_cam], axis=0) # (5, 3) + pts_world = (T_cw[:3, :3] @ pts_cam.T + T_cw[:3, 3:4]).T + return pts_world + + +_FRUSTUM_EDGES = [ + (0, 1), (0, 2), (0, 3), (0, 4), # apex → corners + (1, 2), (2, 3), (3, 4), (4, 1), # near-plane rectangle +] + + +def _rgb_for_index(i: int, n: int) -> tuple[int, int, int]: + """Linearly interpolate red → green → blue across the trajectory.""" + t = i / max(n - 1, 1) + if t < 0.5: + r = int(255 * (1 - 2 * t)) + g = int(255 * (2 * t)) + b = 0 + else: + r = 0 + g = int(255 * (2 * (1 - t))) + b = int(255 * (2 * t - 1)) + return r, g, b + + +def main(): + parser = argparse.ArgumentParser() + parser.add_argument("--poses_folder", required=True) + parser.add_argument("--intrinsics_path", required=True) + parser.add_argument("--output_path", required=True) + parser.add_argument("--frustum_size", type=float, default=0.05, + help="Near-plane distance in scene units") + parser.add_argument("--stride", type=int, default=1) + args = parser.parse_args() + + intr = CameraIntrinsics.load(args.intrinsics_path) + K = intr.to_matrix() + pose_files = sorted(f for f in os.listdir(args.poses_folder) if f.endswith(".json")) + pose_files = pose_files[::args.stride] + if not pose_files: + raise FileNotFoundError(f"No pose JSONs in {args.poses_folder}") + + verts, edges, edge_colors = [], [], [] + n = len(pose_files) + for i, fn in enumerate(pose_files): + T_cw = Transform3d.load(os.path.join(args.poses_folder, fn)).to_matrix() + v = _frustum_vertices(K, T_cw, args.frustum_size, intr.width, intr.height) + base = i * 5 + verts.append(v) + rgb = _rgb_for_index(i, n) + for a, b in _FRUSTUM_EDGES: + edges.append((base + a, base + b)) + edge_colors.append(rgb) + + verts_arr = np.concatenate(verts, axis=0).astype(np.float32) + n_v = verts_arr.shape[0] + n_e = len(edges) + + os.makedirs(os.path.dirname(os.path.abspath(args.output_path)) or ".", exist_ok=True) + with open(args.output_path, "w") as f: + f.write( + f"ply\nformat ascii 1.0\n" + f"element vertex {n_v}\n" + "property float x\nproperty float y\nproperty float z\n" + f"element edge {n_e}\n" + "property int vertex1\nproperty int vertex2\n" + "property uchar red\nproperty uchar green\nproperty uchar blue\n" + "end_header\n" + ) + for x, y, z in verts_arr: + f.write(f"{x} {y} {z}\n") + for (a, b), (r, g, bl) in zip(edges, edge_colors): + f.write(f"{a} {b} {r} {g} {bl}\n") + + print(f"wrote {args.output_path}: {n} frustums, {n_v} vertices, {n_e} edges") + print(f"View with: meshlab {args.output_path}") + + +if __name__ == "__main__": + main() diff --git a/third-party/video_to_data/reconstruction/modules/v2d_ego_hand_reconstruction/.gitignore b/third-party/video_to_data/reconstruction/modules/v2d_ego_hand_reconstruction/.gitignore new file mode 100644 index 0000000000000000000000000000000000000000..6db559d0712ef826b6b6c161ac6bff3d1527d7fa --- /dev/null +++ b/third-party/video_to_data/reconstruction/modules/v2d_ego_hand_reconstruction/.gitignore @@ -0,0 +1,4 @@ +vendor/ +__pycache__/ +*.egg-info/ + diff --git a/third-party/video_to_data/reconstruction/modules/v2d_ego_hand_reconstruction/LICENSE b/third-party/video_to_data/reconstruction/modules/v2d_ego_hand_reconstruction/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..10caffae439b956cdda2b1ded9ecbe51ac10befb --- /dev/null +++ b/third-party/video_to_data/reconstruction/modules/v2d_ego_hand_reconstruction/LICENSE @@ -0,0 +1,15 @@ +# Apache License 2.0 + +Copyright 2025 NVIDIA CORPORATION + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. diff --git a/third-party/video_to_data/reconstruction/modules/v2d_ego_hand_reconstruction/README.md b/third-party/video_to_data/reconstruction/modules/v2d_ego_hand_reconstruction/README.md new file mode 100644 index 0000000000000000000000000000000000000000..c499deb55e9a6526dde47928453d29dc94fe2dff --- /dev/null +++ b/third-party/video_to_data/reconstruction/modules/v2d_ego_hand_reconstruction/README.md @@ -0,0 +1,115 @@ + + +# Egocentric Hand Reconstruction + +Automated pipeline for 4D hand and camera pose reconstruction from egocentric videos. Integrates ViPE and Dyn-HaMR in containerized environments. + +## Setup + +Fetch vendored sources from [IsaacTeleop](https://github.com/NVIDIA/IsaacTeleop): + +```bash +./sync.sh +``` + +Install the host-side orchestration package: + +```bash +pip install -e docker/ +``` + +Build both Docker images (ViPE + Dyn-HaMR): + +```bash +python -m v2d_ego_hand_reconstruction.docker.build +``` + +Place required data in your weights directory before running (see [Isaac Teleop Documentation](https://nvidia.github.io/IsaacTeleop/main/references/egocentric_hand_reconstruction.html)). +The layout follows the manotorch convention so the same directory is shared with `v2d_hamer`: + +``` +/ +├── models/ +│ └── MANO_RIGHT.pkl # from https://mano.is.tue.mpg.de/ +└── BMC/ + └── *.npy # from the Hand-BMC-pytorch repo +``` + +## Usage + +**Python (programmatic):** + +```python +from v2d_ego_hand_reconstruction.docker.run_reconstruction import run_reconstruction + +run_reconstruction( + video_input="path/to/video.mp4", + output_dir="data/outputs/ego_hand", +) +``` + +**CLI:** + +```bash +python -m v2d_ego_hand_reconstruction.docker.run_reconstruction \ + --video_input path/to/video.mp4 \ + --output_dir data/outputs/ego_hand +``` + +Remote videos (S3/Swift) are also supported: + +Set environment variables ACCESS_KEY_ID and SECRET_ACCESS_KEY for S3/Swift permission. + +```bash +export ACCESS_KEY_ID=XXX SECRET_ACCESS_KEY=XXX +``` + +Please check [Isaac Teleop Documentation](https://nvidia.github.io/IsaacTeleop/main/references/egocentric_hand_reconstruction.html) for detail. + +```bash +python -m v2d_ego_hand_reconstruction.docker.run_reconstruction \ + --video_input s3://bucket/video.mp4 \ + --output_dir data/outputs/ego_hand +``` + +Results are saved to `/logs/`. + +### Hand mesh generation + +After running reconstruction, export per-track MANO hand mesh trajectories from every run under `/logs/`: + +```python +from v2d_ego_hand_reconstruction.docker.run_mesh_generation import run_mesh_generation + +run_mesh_generation(output_dir="data/outputs/ego_hand") +``` + +CLI: + +```bash +python -m v2d_ego_hand_reconstruction.docker.run_mesh_generation \ + --output_dir data/outputs/ego_hand +``` + +Results land at `/logs/.../smooth_fit/_hand_mesh_traj_.npz`. + +## Upstream Diff + +To see local modifications vs upstream IsaacTeleop: + +```bash +./diff.sh # summary +./diff.sh --full # full unified diff +``` + +## Structure + +``` +docker/ Native Python orchestration (tracked in git) +vendor/ Upstream content from IsaacTeleop (gitignored, populated by sync.sh) +sync.sh Fetch/update vendored sources +diff.sh Compare vendor/ against upstream +``` diff --git a/third-party/video_to_data/reconstruction/modules/v2d_ego_hand_reconstruction/__init__.py b/third-party/video_to_data/reconstruction/modules/v2d_ego_hand_reconstruction/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..52a7a9daf028f654d6a02f65c99cc609a57b492f --- /dev/null +++ b/third-party/video_to_data/reconstruction/modules/v2d_ego_hand_reconstruction/__init__.py @@ -0,0 +1,2 @@ +# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 diff --git a/third-party/video_to_data/reconstruction/modules/v2d_ego_hand_reconstruction/diff.sh b/third-party/video_to_data/reconstruction/modules/v2d_ego_hand_reconstruction/diff.sh new file mode 100644 index 0000000000000000000000000000000000000000..80c71ad931d5bfa4c1aed522ffcbb508f9e0f073 --- /dev/null +++ b/third-party/video_to_data/reconstruction/modules/v2d_ego_hand_reconstruction/diff.sh @@ -0,0 +1,44 @@ +#!/bin/bash +# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 +# Show local modifications to vendored content vs upstream IsaacTeleop. +# Usage: ./diff.sh (summary of changed files) +# ./diff.sh --full (full unified diff) +# ./diff.sh --patch (git-format patch, apply with: git apply ) +set -euo pipefail + +SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)" +VENDOR_DIR="$SCRIPT_DIR/vendor" +REPO="https://github.com/NVIDIA/IsaacTeleop.git" +BRANCH="main" +DIR="src/postprocessing/egocentric_hand_reconstruction" + +if [ ! -d "$VENDOR_DIR" ]; then + echo "vendor/ not found. Run ./sync.sh first." >&2 + exit 1 +fi + +tmp=$(mktemp -d) +trap 'rm -rf "$tmp"' EXIT + +echo "Fetching upstream ($BRANCH)..." >&2 +git clone --filter=blob:none --sparse --branch "$BRANCH" --depth 1 "$REPO" "$tmp/repo" 2>/dev/null +cd "$tmp/repo" && git sparse-checkout set "$DIR" 2>/dev/null && cd - > /dev/null + +upstream="$tmp/repo/$DIR" + +case "${1:-}" in + --patch) + # Produce a git-format patch with paths relative to the IsaacTeleop repo root. + # Apply in an IsaacTeleop clone with: git apply + cp -r "$VENDOR_DIR/." "$tmp/repo/$DIR/" + cd "$tmp/repo" + git diff || true + ;; + --full) + diff -ru "$upstream/" "$VENDOR_DIR/" || true + ;; + *) + diff -rq "$upstream/" "$VENDOR_DIR/" && echo "(no differences)" || true + ;; +esac diff --git a/third-party/video_to_data/reconstruction/modules/v2d_ego_hand_reconstruction/docker/__init__.py b/third-party/video_to_data/reconstruction/modules/v2d_ego_hand_reconstruction/docker/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..52a7a9daf028f654d6a02f65c99cc609a57b492f --- /dev/null +++ b/third-party/video_to_data/reconstruction/modules/v2d_ego_hand_reconstruction/docker/__init__.py @@ -0,0 +1,2 @@ +# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 diff --git a/third-party/video_to_data/reconstruction/modules/v2d_ego_hand_reconstruction/docker/_config.py b/third-party/video_to_data/reconstruction/modules/v2d_ego_hand_reconstruction/docker/_config.py new file mode 100644 index 0000000000000000000000000000000000000000..175ee81994e4d9827c302056bbaa01070dc1044c --- /dev/null +++ b/third-party/video_to_data/reconstruction/modules/v2d_ego_hand_reconstruction/docker/_config.py @@ -0,0 +1,6 @@ +# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 +import os + +MODULE_DIR = os.path.abspath(os.path.join(os.path.dirname(__file__), "..")) +VENDOR_DIR = os.path.join(MODULE_DIR, "vendor") diff --git a/third-party/video_to_data/reconstruction/modules/v2d_ego_hand_reconstruction/docker/build.py b/third-party/video_to_data/reconstruction/modules/v2d_ego_hand_reconstruction/docker/build.py new file mode 100644 index 0000000000000000000000000000000000000000..e9e69944e9deeec4fa3c74c07f006ed4267a0b33 --- /dev/null +++ b/third-party/video_to_data/reconstruction/modules/v2d_ego_hand_reconstruction/docker/build.py @@ -0,0 +1,48 @@ +# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 +"""Build Docker images for ego hand reconstruction (ViPE + Dyn-HaMR). + +Delegates to the vendored shell scripts so build flags stay in sync with +upstream IsaacTeleop. +""" + +import subprocess +from pathlib import Path + +from v2d_ego_hand_reconstruction.docker._config import MODULE_DIR, VENDOR_DIR + + +def _sync_vendor() -> None: + """Fetch vendored sources from IsaacTeleop if not already present.""" + subprocess.run([str(Path(MODULE_DIR) / "sync.sh")], check=True) + + +def _run_vendor_script(script: str, *args: str) -> None: + vendor = Path(VENDOR_DIR) + if not vendor.is_dir(): + print(f"{vendor} not found. Running sync.sh to fetch vendored sources...") + _sync_vendor() + subprocess.run( + [str(vendor / "docker" / script), *args], + check=True, + ) + + +def build_vipe() -> None: + """Build the ViPE camera estimation image.""" + _run_vendor_script("vipe.sh", "build") + + +def build_dynhamr() -> None: + """Build the Dyn-HaMR hand reconstruction image.""" + _run_vendor_script("dynhamr.sh", "build") + + +def build_all() -> None: + """Build both ViPE and Dyn-HaMR images.""" + build_vipe() + build_dynhamr() + + +if __name__ == "__main__": + build_all() diff --git a/third-party/video_to_data/reconstruction/modules/v2d_ego_hand_reconstruction/docker/pyproject.toml b/third-party/video_to_data/reconstruction/modules/v2d_ego_hand_reconstruction/docker/pyproject.toml new file mode 100644 index 0000000000000000000000000000000000000000..d3d720dca38e5f4b5cdd908024e4f2ab2d8d7b96 --- /dev/null +++ b/third-party/video_to_data/reconstruction/modules/v2d_ego_hand_reconstruction/docker/pyproject.toml @@ -0,0 +1,19 @@ +# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 +[build-system] +requires = ["setuptools>=68.0", "wheel"] +build-backend = "setuptools.build_meta" + +[project] +name = "v2d-ego-hand-reconstruction-docker" +version = "0.1.0" +description = "Docker orchestration for ego hand reconstruction (ViPE + Dyn-HaMR)" +requires-python = ">=3.10" +dependencies = ["boto3"] + +[tool.setuptools] +packages = ["v2d_ego_hand_reconstruction", "v2d_ego_hand_reconstruction.docker"] + +[tool.setuptools.package-dir] +"v2d_ego_hand_reconstruction" = ".." +"v2d_ego_hand_reconstruction.docker" = "." diff --git a/third-party/video_to_data/reconstruction/modules/v2d_ego_hand_reconstruction/docker/run_mesh_generation.py b/third-party/video_to_data/reconstruction/modules/v2d_ego_hand_reconstruction/docker/run_mesh_generation.py new file mode 100644 index 0000000000000000000000000000000000000000..7a8816b77b0e55d9778192fd27ce284a06ce1617 --- /dev/null +++ b/third-party/video_to_data/reconstruction/modules/v2d_ego_hand_reconstruction/docker/run_mesh_generation.py @@ -0,0 +1,72 @@ +# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 +"""Export per-track MANO hand meshes and joint trajectories from Dyn-HaMR results. + +Delegates to the vendored ``run_mesh_generation.sh`` so mesh export logic stays +in sync with upstream IsaacTeleop. + +Prerequisites: + - Dyn-HaMR Docker image must be built (``python -m v2d_ego_hand_reconstruction.docker.build``). + - MANO_RIGHT.pkl must be placed in *output_dir*. +""" + +import os +import subprocess + +from v2d_ego_hand_reconstruction.docker._config import VENDOR_DIR + + +def run_mesh_generation( + output_dir: str, + *, + phase: str = "smooth_fit", + gpu: int = 0, + no_temporal_smooth: bool = False, + no_smooth_trans: bool = False, +) -> None: + """Run hand mesh export over every Dyn-HaMR run under *output_dir*. + + Args: + output_dir: Directory containing Dyn-HaMR + ``logs/.../smooth_fit/*_world_results.npz``. + phase: Phase subdir under each run dir (default: ``smooth_fit``). + gpu: GPU index inside the container. + no_temporal_smooth: Disable OneEuro smoothing on poses. + no_smooth_trans: Smooth pose only, not translation. + """ + output_dir = os.path.abspath(output_dir) + os.makedirs(output_dir, exist_ok=True) + + env = { + **os.environ, + "OUTPUTS_DIR": output_dir, + "PHASE": phase, + "GPU": str(gpu), + "NO_TEMPORAL_SMOOTH": "1" if no_temporal_smooth else "0", + "NO_SMOOTH_TRANS": "1" if no_smooth_trans else "0", + } + + subprocess.run( + [os.path.join(VENDOR_DIR, "scripts", "run_mesh_generation.sh")], + env=env, + check=True, + ) + + +if __name__ == "__main__": + import argparse + + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("--output_dir", required=True, help="Output directory (contains logs/)") + parser.add_argument("--phase", default="smooth_fit") + parser.add_argument("--gpu", type=int, default=0) + parser.add_argument("--no_temporal_smooth", action="store_true") + parser.add_argument("--no_smooth_trans", action="store_true") + args = parser.parse_args() + run_mesh_generation( + args.output_dir, + phase=args.phase, + gpu=args.gpu, + no_temporal_smooth=args.no_temporal_smooth, + no_smooth_trans=args.no_smooth_trans, + ) diff --git a/third-party/video_to_data/reconstruction/modules/v2d_ego_hand_reconstruction/docker/run_reconstruction.py b/third-party/video_to_data/reconstruction/modules/v2d_ego_hand_reconstruction/docker/run_reconstruction.py new file mode 100644 index 0000000000000000000000000000000000000000..2e7f281dc725e2934fe84ee0ec03001f497b89e0 --- /dev/null +++ b/third-party/video_to_data/reconstruction/modules/v2d_ego_hand_reconstruction/docker/run_reconstruction.py @@ -0,0 +1,74 @@ +# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 +"""Run ego hand reconstruction pipeline (ViPE camera estimation + Dyn-HaMR). + +Delegates to the vendored ``run_reconstruction.sh`` so pipeline logic stays in +sync with upstream IsaacTeleop. + +Prerequisites: + - Both Docker images must be built (``python -m v2d_ego_hand_reconstruction.docker.build``). + - ``weights_dir`` must contain ``models/MANO_RIGHT.pkl`` and ``BMC/*.npy`` + (manotorch layout; see https://nvidia.github.io/IsaacTeleop/main/references/egocentric_hand_reconstruction.html for download instructions). +""" + +import os +import shutil +import subprocess + +from v2d_ego_hand_reconstruction.docker._config import VENDOR_DIR + + +def run_reconstruction( + video_input: str, + output_dir: str, + weights_dir: str, +) -> None: + """Run the full ego hand reconstruction pipeline. + + Args: + video_input: Local file path, or ``s3://`` / ``swift://`` URL. + output_dir: Directory for all pipeline outputs. + weights_dir: Directory containing ``models/MANO_RIGHT.pkl`` and ``BMC/`` + (manotorch layout — shared with v2d_hamer). + """ + output_dir = os.path.abspath(output_dir) + weights_dir = os.path.abspath(weights_dir) + os.makedirs(output_dir, exist_ok=True) + + # The vendored Dyn-HaMR container reads MANO_RIGHT.pkl from the top of + # output_dir, so copy it out of the manotorch-style models/ subdir. + # Symlinking doesn't work because the target is outside the container's mount. + mano_src = os.path.join(weights_dir, "models", "MANO_RIGHT.pkl") + mano_dst = os.path.join(output_dir, "MANO_RIGHT.pkl") + if not os.path.exists(mano_dst): + shutil.copy2(mano_src, mano_dst) + + bmc_src = os.path.join(weights_dir, "BMC") + bmc_dst = os.path.join(output_dir, "BMC") + if not os.path.exists(bmc_dst): + shutil.copytree(bmc_src, bmc_dst) + + # Resolve local paths to absolute so the vendored script can find them + if not video_input.startswith(("s3://", "swift://")): + video_input = os.path.abspath(video_input) + + subprocess.run( + [os.path.join(VENDOR_DIR, "scripts", "run_reconstruction.sh"), video_input], + env={**os.environ, "OUTPUTS_DIR": output_dir}, + check=True, + ) + + +if __name__ == "__main__": + import argparse + + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument( + "--video_input", + required=True, + help="Local path or s3:///swift:// URL", + ) + parser.add_argument("--output_dir", required=True, help="Output directory") + parser.add_argument("--weights_dir", required=True, help="Directory with models/MANO_RIGHT.pkl and BMC/") + args = parser.parse_args() + run_reconstruction(args.video_input, args.output_dir, args.weights_dir) diff --git a/third-party/video_to_data/reconstruction/modules/v2d_ego_hand_reconstruction/sync.sh b/third-party/video_to_data/reconstruction/modules/v2d_ego_hand_reconstruction/sync.sh new file mode 100644 index 0000000000000000000000000000000000000000..445fdbf89080db3c57d69922d1af187bc768cec7 --- /dev/null +++ b/third-party/video_to_data/reconstruction/modules/v2d_ego_hand_reconstruction/sync.sh @@ -0,0 +1,27 @@ +#!/bin/bash +# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 +set -euo pipefail + +SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)" +REPO="https://github.com/NVIDIA/IsaacTeleop.git" +BRANCH="main" +DIR="src/postprocessing/egocentric_hand_reconstruction" + +VENDOR_DIR="$SCRIPT_DIR/vendor" + +echo "Syncing $DIR from $REPO ($BRANCH) into vendor/..." + +tmp=$(mktemp -d) +trap 'rm -rf "$tmp"' EXIT + +git clone --filter=blob:none --sparse --branch "$BRANCH" --depth 1 "$REPO" "$tmp" +cd "$tmp" +git sparse-checkout set "$DIR" +cd - > /dev/null + +rm -rf "$VENDOR_DIR" +mkdir -p "$VENDOR_DIR" +cp -r "$tmp/$DIR/." "$VENDOR_DIR/" + +echo "Done. Files synced to $VENDOR_DIR/" diff --git a/third-party/video_to_data/reconstruction/modules/v2d_foundation_pose/.gitignore b/third-party/video_to_data/reconstruction/modules/v2d_foundation_pose/.gitignore new file mode 100644 index 0000000000000000000000000000000000000000..b00246a9d6e6946cfad18f627c50d906357c3327 --- /dev/null +++ b/third-party/video_to_data/reconstruction/modules/v2d_foundation_pose/.gitignore @@ -0,0 +1,8 @@ +data/ +*.pt +*.pth +*.mp4 +*.zip +*.glb +*.obj +__pycache__/ diff --git a/third-party/video_to_data/reconstruction/modules/v2d_foundation_pose/docker/Dockerfile b/third-party/video_to_data/reconstruction/modules/v2d_foundation_pose/docker/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..78738b16fc945f6d971e365b5a70ed08ef121508 --- /dev/null +++ b/third-party/video_to_data/reconstruction/modules/v2d_foundation_pose/docker/Dockerfile @@ -0,0 +1,93 @@ +FROM pytorch/pytorch:2.5.1-cuda12.4-cudnn9-devel +ENV DEBIAN_FRONTEND=noninteractive +WORKDIR /app + +RUN apt-get update && apt-get install -y \ + python3-pip \ + python3-dev \ + git \ + libgl1 \ + libglib2.0-0 \ + zip \ + && rm -rf /var/lib/apt/lists/* + +ENV TZ=US/Pacific +RUN ln -snf /usr/share/zoneinfo/$TZ /etc/localtime && echo $TZ > /etc/timezone + +RUN apt-get update --fix-missing && \ + apt-get install -y libgtk2.0-dev wget bzip2 ca-certificates curl git vim tmux \ + g++ gcc build-essential cmake checkinstall gfortran libjpeg8-dev libtiff5-dev \ + pkg-config yasm libavcodec-dev libavformat-dev libswscale-dev libxine2-dev \ + libv4l-dev libgtk2.0-dev libtbb-dev libatlas-base-dev libfaac-dev libmp3lame-dev \ + libtheora-dev libvorbis-dev libxvidcore-dev libopencore-amrnb-dev \ + libopencore-amrwb-dev x264 v4l-utils libprotobuf-dev protobuf-compiler \ + libgoogle-glog-dev libgflags-dev libgphoto2-dev libhdf5-dev doxygen libflann-dev \ + libboost-all-dev proj-data libproj-dev libyaml-cpp-dev cmake-curses-gui \ + libzmq3-dev freeglut3-dev libxrender1 libxext6 libsm6 libx11-6 libegl1-mesa \ + libgles2-mesa libgbm1 + +RUN cd / && git clone https://github.com/pybind/pybind11 && \ + cd pybind11 && git checkout v2.10.0 && \ + mkdir build && cd build && cmake .. -DCMAKE_BUILD_TYPE=Release -DPYBIND11_INSTALL=ON -DPYBIND11_TEST=OFF && \ + make -j6 && make install + +RUN cd / && wget https://gitlab.com/libeigen/eigen/-/archive/3.4.0/eigen-3.4.0.tar.gz && \ + tar xvzf ./eigen-3.4.0.tar.gz && \ + cd eigen-3.4.0 && \ + mkdir build && cd build && cmake .. && make install + +RUN pip install \ + scipy \ + joblib \ + scikit-learn \ + ruamel.yaml \ + trimesh \ + pyyaml \ + opencv-python \ + imageio \ + open3d \ + transformations \ + warp-lang \ + einops \ + kornia \ + pyrender + +RUN pip install kaolin==0.18.0 -f https://nvidia-kaolin.s3.us-east-2.amazonaws.com/torch-2.5.1_cu124.html + +RUN TORCH_CUDA_ARCH_LIST="8.0 8.6 8.9 9.0" pip3 install "git+https://github.com/facebookresearch/pytorch3d.git" + +RUN git clone https://github.com/NVlabs/nvdiffrast /workspace/third_party/nvdiffrast && \ + cd /workspace/third_party/nvdiffrast && \ + pip install setuptools wheel ninja && \ + TORCH_CUDA_ARCH_LIST="8.0 8.6 8.9 9.0" pip install . --no-build-isolation + +ENV OPENCV_IO_ENABLE_OPENEXR=1 + +RUN pip install \ + scikit-image \ + meshcat \ + webdataset \ + omegaconf \ + pypng \ + roma \ + seaborn \ + opencv-contrib-python \ + openpyxl \ + wandb + +RUN pip install h5py fast_simplification gdown + +COPY v2d_foundation_pose/lib/FoundationPose/mycpp /workspace/v2d_foundation_pose/lib/FoundationPose/mycpp +COPY v2d_foundation_pose/lib/FoundationPose/bundlesdf/mycuda /workspace/v2d_foundation_pose/lib/FoundationPose/bundlesdf/mycuda + +RUN cd /workspace/v2d_foundation_pose/lib/FoundationPose/mycpp \ + && mkdir -p build && cd build && cmake .. -DPYTHON_EXECUTABLE=$(which python) && make -j11 + +RUN cd /workspace/v2d_foundation_pose/lib/FoundationPose/bundlesdf/mycuda && \ + TORCH_CUDA_ARCH_LIST="8.0 8.6 8.9 9.0" pip install -e . + +COPY . /workspace + +RUN pip install -e "/workspace/v2d_common[io]" \ + -e "/workspace/v2d_mv[math]" \ + -e /workspace/v2d_mesh/lib -e /workspace/v2d_foundation_pose/lib diff --git a/third-party/video_to_data/reconstruction/modules/v2d_foundation_pose/docker/__init__.py b/third-party/video_to_data/reconstruction/modules/v2d_foundation_pose/docker/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..52a7a9daf028f654d6a02f65c99cc609a57b492f --- /dev/null +++ b/third-party/video_to_data/reconstruction/modules/v2d_foundation_pose/docker/__init__.py @@ -0,0 +1,2 @@ +# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 diff --git a/third-party/video_to_data/reconstruction/modules/v2d_foundation_pose/docker/_config.py b/third-party/video_to_data/reconstruction/modules/v2d_foundation_pose/docker/_config.py new file mode 100644 index 0000000000000000000000000000000000000000..371bbbb3fa36d61c2b16746d82f98726bf45dc0f --- /dev/null +++ b/third-party/video_to_data/reconstruction/modules/v2d_foundation_pose/docker/_config.py @@ -0,0 +1,11 @@ +# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 +import os + +IMAGE_NAME = "v2d_foundation_pose" +MODULES_DIR = os.path.abspath(os.path.join(os.path.dirname(os.path.abspath(__file__)), "..", "..")) + +DEV_PRESERVE_VOLUMES = [ + "/workspace/v2d_foundation_pose/lib/FoundationPose/mycpp/build", + "/workspace/v2d_foundation_pose/lib/FoundationPose/bundlesdf/mycuda", +] diff --git a/third-party/video_to_data/reconstruction/modules/v2d_foundation_pose/docker/build.py b/third-party/video_to_data/reconstruction/modules/v2d_foundation_pose/docker/build.py new file mode 100644 index 0000000000000000000000000000000000000000..54a81ff2633c16610967517c2d091080b83bc09b --- /dev/null +++ b/third-party/video_to_data/reconstruction/modules/v2d_foundation_pose/docker/build.py @@ -0,0 +1,17 @@ +# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 +import subprocess +import os + +IMAGE_NAME = "v2d_foundation_pose" + +current_dir = os.path.dirname(os.path.abspath(__file__)) +module_dir = os.path.join(current_dir, "..") +root_dir = os.path.join(module_dir, "..") +dockerfile_path = os.path.join(current_dir, "Dockerfile") + +def build_docker_image() -> None: + subprocess.run(["docker", "build", "-t", IMAGE_NAME, "-f", dockerfile_path, root_dir], check=True) + +if __name__ == "__main__": + build_docker_image() diff --git a/third-party/video_to_data/reconstruction/modules/v2d_foundation_pose/docker/pyproject.toml b/third-party/video_to_data/reconstruction/modules/v2d_foundation_pose/docker/pyproject.toml new file mode 100644 index 0000000000000000000000000000000000000000..7cebcde74883b6c296acb420f8a17b610c34507c --- /dev/null +++ b/third-party/video_to_data/reconstruction/modules/v2d_foundation_pose/docker/pyproject.toml @@ -0,0 +1,18 @@ +# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 +[build-system] +requires = ["setuptools>=68.0", "wheel"] +build-backend = "setuptools.build_meta" + +[project] +name = "v2d-foundation-pose-docker" +version = "0.1.0" +description = "Docker orchestration scripts for FoundationPose" +requires-python = ">=3.10" +dependencies = ["v2d-docker"] + +[tool.setuptools] +packages = ["v2d.foundation_pose.docker"] + +[tool.setuptools.package-dir] +"v2d.foundation_pose.docker" = "." diff --git a/third-party/video_to_data/reconstruction/modules/v2d_foundation_pose/docker/run_align_depth_to_object.py b/third-party/video_to_data/reconstruction/modules/v2d_foundation_pose/docker/run_align_depth_to_object.py new file mode 100644 index 0000000000000000000000000000000000000000..3c28dd3f853ce627852eb5e444f560110061cf84 --- /dev/null +++ b/third-party/video_to_data/reconstruction/modules/v2d_foundation_pose/docker/run_align_depth_to_object.py @@ -0,0 +1,94 @@ +# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 +import os +from v2d.docker.container import run_in_container +from v2d.foundation_pose.docker._config import DEV_PRESERVE_VOLUMES, IMAGE_NAME, MODULES_DIR + + +def run_align_depth_to_object( + mesh_path: str, + rgb_path: str, + depth_path: str, + mask_path: str, + intrinsics_path: str, + weights_dir: str, + output_depth_path: str, + scale_lo: float = 0.5, + scale_hi: float = 2.0, + shift_lo: float = -0.5, + shift_hi: float = 0.5, + n_scale_samples: int = 7, + n_shift_samples: int = 5, + n_levels: int = 3, + iou_weight: float = 1.0, + depth_weight: float = 1.0, + registration_iterations: int = 5, + dev: bool = False, +) -> None: + weights_abs = os.path.abspath(weights_dir) + weights_container = f"/data/weights_dir/{os.path.basename(weights_abs)}" + run_in_container( + image=IMAGE_NAME, + module="v2d.foundation_pose.lib.run_align_depth_to_object", + inputs={ + "mesh_path": mesh_path, + "rgb_path": rgb_path, + "depth_path": depth_path, + "mask_path": mask_path, + "intrinsics_path": intrinsics_path, + "weights_dir": weights_dir, + }, + outputs={"output_depth_path": output_depth_path}, + extra_args={ + "scale_lo": scale_lo, + "scale_hi": scale_hi, + "shift_lo": shift_lo, + "shift_hi": shift_hi, + "n_scale_samples": n_scale_samples, + "n_shift_samples": n_shift_samples, + "n_levels": n_levels, + "iou_weight": iou_weight, + "depth_weight": depth_weight, + "registration_iterations": registration_iterations, + }, + dev=dev, + modules_dir=MODULES_DIR, + gpus=True, + env={"FOUNDATIONPOSE_WEIGHTS_DIR": weights_container}, + extra_volumes=DEV_PRESERVE_VOLUMES if dev else None, + ) + + +if __name__ == "__main__": + import argparse + + parser = argparse.ArgumentParser(description="Align depth to object mesh via FP affine grid search in Docker") + parser.add_argument("--mesh_path", required=True) + parser.add_argument("--rgb_path", required=True) + parser.add_argument("--depth_path", required=True) + parser.add_argument("--mask_path", required=True) + parser.add_argument("--intrinsics_path", required=True) + parser.add_argument("--weights_dir", required=True) + parser.add_argument("--output_depth_path", required=True) + parser.add_argument("--scale_lo", type=float, default=0.5) + parser.add_argument("--scale_hi", type=float, default=2.0) + parser.add_argument("--shift_lo", type=float, default=-0.5) + parser.add_argument("--shift_hi", type=float, default=0.5) + parser.add_argument("--n_scale_samples", type=int, default=7) + parser.add_argument("--n_shift_samples", type=int, default=5) + parser.add_argument("--n_levels", type=int, default=3) + parser.add_argument("--iou_weight", type=float, default=1.0) + parser.add_argument("--depth_weight", type=float, default=1.0) + parser.add_argument("--registration_iterations", type=int, default=5) + parser.add_argument("--dev", action="store_true") + args = parser.parse_args() + run_align_depth_to_object( + args.mesh_path, args.rgb_path, args.depth_path, args.mask_path, + args.intrinsics_path, args.weights_dir, args.output_depth_path, + scale_lo=args.scale_lo, scale_hi=args.scale_hi, + shift_lo=args.shift_lo, shift_hi=args.shift_hi, + n_scale_samples=args.n_scale_samples, n_shift_samples=args.n_shift_samples, + n_levels=args.n_levels, iou_weight=args.iou_weight, depth_weight=args.depth_weight, + registration_iterations=args.registration_iterations, + dev=args.dev, + ) diff --git a/third-party/video_to_data/reconstruction/modules/v2d_foundation_pose/docker/run_align_depth_to_reference_depth.py b/third-party/video_to_data/reconstruction/modules/v2d_foundation_pose/docker/run_align_depth_to_reference_depth.py new file mode 100644 index 0000000000000000000000000000000000000000..9a72053efeaff0cda93779cd5b64e018cbf1a283 --- /dev/null +++ b/third-party/video_to_data/reconstruction/modules/v2d_foundation_pose/docker/run_align_depth_to_reference_depth.py @@ -0,0 +1,70 @@ +# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 +import os +from v2d.docker.container import run_in_container +from v2d.foundation_pose.docker._config import DEV_PRESERVE_VOLUMES, IMAGE_NAME, MODULES_DIR + + +def run_align_depth_to_reference_depth( + depth_folder: str, + depth_reference_path: str, + intrinsics_path: str, + output_folder: str, + masks_folder: str = None, + reference_mask_path: str = None, + n_iterations: int = 3, + outlier_trim_ratio: float = 0.2, + max_points: int = 20000, + dev: bool = False, +) -> None: + inputs = { + "depth_folder": depth_folder, + "depth_reference_path": depth_reference_path, + "intrinsics_path": intrinsics_path, + } + if masks_folder is not None: + inputs["masks_folder"] = masks_folder + if reference_mask_path is not None: + inputs["reference_mask_path"] = reference_mask_path + run_in_container( + image=IMAGE_NAME, + module="v2d.foundation_pose.lib.run_align_depth_to_reference_depth", + inputs=inputs, + outputs={"output_folder": output_folder}, + extra_args={ + "n_iterations": n_iterations, + "outlier_trim_ratio": outlier_trim_ratio, + "max_points": max_points, + }, + dev=dev, + modules_dir=MODULES_DIR, + gpus=False, + extra_volumes=DEV_PRESERVE_VOLUMES if dev else None, + ) + + +if __name__ == "__main__": + import argparse + + parser = argparse.ArgumentParser(description="Align depth folder to reference depth via ICP + affine in Docker") + parser.add_argument("--depth_folder", required=True) + parser.add_argument("--depth_reference_path", required=True) + parser.add_argument("--intrinsics_path", required=True) + parser.add_argument("--output_folder", required=True) + parser.add_argument("--masks_folder", default=None) + parser.add_argument("--reference_mask_path", default=None) + parser.add_argument("--n_iterations", type=int, default=3) + parser.add_argument("--outlier_trim_ratio", type=float, default=0.2) + parser.add_argument("--max_points", type=int, default=20000) + parser.add_argument("--dev", action="store_true") + args = parser.parse_args() + run_align_depth_to_reference_depth( + args.depth_folder, args.depth_reference_path, args.intrinsics_path, + args.output_folder, + masks_folder=args.masks_folder, + reference_mask_path=args.reference_mask_path, + n_iterations=args.n_iterations, + outlier_trim_ratio=args.outlier_trim_ratio, + max_points=args.max_points, + dev=args.dev, + ) diff --git a/third-party/video_to_data/reconstruction/modules/v2d_foundation_pose/docker/run_correct_depth_scale.py b/third-party/video_to_data/reconstruction/modules/v2d_foundation_pose/docker/run_correct_depth_scale.py new file mode 100644 index 0000000000000000000000000000000000000000..dbbbc27e835c106cc3c9e2d5e770c6fcc69b4cf1 --- /dev/null +++ b/third-party/video_to_data/reconstruction/modules/v2d_foundation_pose/docker/run_correct_depth_scale.py @@ -0,0 +1,71 @@ +# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 +import os +from v2d.docker.container import run_in_container +from v2d.foundation_pose.docker._config import DEV_PRESERVE_VOLUMES, IMAGE_NAME, MODULES_DIR + + +def run_correct_depth_scale( + poses_dir: str, + mesh_path: str, + depth_folder: str, + intrinsics_path: str, + output_folder: str, + masks_folder: str = None, + smoothing_window: int = 11, + min_valid_pixels: int = 50, + batch_size: int = 32, + dev: bool = False, +) -> None: + inputs = { + "poses_dir": poses_dir, + "mesh_path": mesh_path, + "depth_folder": depth_folder, + "intrinsics_path": intrinsics_path, + } + if masks_folder is not None: + inputs["masks_folder"] = masks_folder + run_in_container( + image=IMAGE_NAME, + module="v2d.foundation_pose.lib.run_correct_depth_scale", + inputs=inputs, + outputs={"output_folder": output_folder}, + extra_args={ + "smoothing_window": smoothing_window, + "min_valid_pixels": min_valid_pixels, + "batch_size": batch_size, + }, + dev=dev, + modules_dir=MODULES_DIR, + gpus=True, + extra_volumes=DEV_PRESERVE_VOLUMES if dev else None, + ) + + +if __name__ == "__main__": + import argparse + + parser = argparse.ArgumentParser(description="FP-guided depth scale correction in Docker") + parser.add_argument("--poses_dir", required=True) + parser.add_argument("--mesh_path", required=True) + parser.add_argument("--depth_folder", required=True) + parser.add_argument("--intrinsics_path", required=True) + parser.add_argument("--output_folder", required=True) + parser.add_argument("--masks_folder", default=None) + parser.add_argument("--smoothing_window", type=int, default=11) + parser.add_argument("--min_valid_pixels", type=int, default=50) + parser.add_argument("--batch_size", type=int, default=32) + parser.add_argument("--dev", action="store_true") + args = parser.parse_args() + run_correct_depth_scale( + args.poses_dir, + args.mesh_path, + args.depth_folder, + args.intrinsics_path, + args.output_folder, + masks_folder=args.masks_folder, + smoothing_window=args.smoothing_window, + min_valid_pixels=args.min_valid_pixels, + batch_size=args.batch_size, + dev=args.dev, + ) diff --git a/third-party/video_to_data/reconstruction/modules/v2d_foundation_pose/docker/run_download_weights.py b/third-party/video_to_data/reconstruction/modules/v2d_foundation_pose/docker/run_download_weights.py new file mode 100644 index 0000000000000000000000000000000000000000..6c3f3037efeb375e2a832e304f062eb3c2667a15 --- /dev/null +++ b/third-party/video_to_data/reconstruction/modules/v2d_foundation_pose/docker/run_download_weights.py @@ -0,0 +1,35 @@ +# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 +import subprocess +import os +from v2d.foundation_pose.docker._config import IMAGE_NAME, MODULES_DIR + + +def run_download(output_dir: str, dev: bool = False) -> None: + os.makedirs(output_dir, exist_ok=True) + output_dir = os.path.abspath(output_dir) + + cmd = [ + "docker", "run", "--rm", + "--user", f"{os.getuid()}:{os.getgid()}", + "-e", "HOME=/tmp", + "-v", f"{output_dir}:/data/weights", + ] + if dev: + cmd += ["-v", f"{MODULES_DIR}:/workspace"] + cmd += [ + IMAGE_NAME, + "python", "-m", "v2d.foundation_pose.lib.download_weights", + "--output_dir", "/data/weights", + ] + subprocess.run(cmd, check=True) + + +if __name__ == "__main__": + import argparse + + parser = argparse.ArgumentParser(description="Download FoundationPose weights") + parser.add_argument("--output_dir", type=str, required=True, help="Output directory for weights") + parser.add_argument("--dev", action="store_true", help="Mount local modules for development") + args = parser.parse_args() + run_download(output_dir=args.output_dir, dev=args.dev) diff --git a/third-party/video_to_data/reconstruction/modules/v2d_foundation_pose/docker/run_ekf_smoothing.py b/third-party/video_to_data/reconstruction/modules/v2d_foundation_pose/docker/run_ekf_smoothing.py new file mode 100644 index 0000000000000000000000000000000000000000..4f3263ab660ff6f2945cb61171011d4eacd67294 --- /dev/null +++ b/third-party/video_to_data/reconstruction/modules/v2d_foundation_pose/docker/run_ekf_smoothing.py @@ -0,0 +1,90 @@ +# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 +import os +from v2d.docker.container import run_in_container +from v2d.foundation_pose.docker._config import DEV_PRESERVE_VOLUMES, IMAGE_NAME, MODULES_DIR + + +def run_ekf_smoothing( + poses_dir: str, + mesh_path: str, + intrinsics_path: str, + weights_dir: str, + output_dir: str, + masks_folder: str = None, + process_noise_xy: float = 0.005, + process_noise_z: float = 0.005, + process_noise_r: float = 0.01, + measurement_noise_xy: float = 0.02, + measurement_noise_z: float = 0.1, + measurement_noise_r: float = 0.05, + min_iou: float = 0.1, + dev: bool = False, +) -> None: + weights_abs = os.path.abspath(weights_dir) + weights_container = f"/data/weights_dir/{os.path.basename(weights_abs)}" + inputs = { + "poses_dir": poses_dir, + "mesh_path": mesh_path, + "intrinsics_path": intrinsics_path, + "weights_dir": weights_dir, + } + if masks_folder is not None: + inputs["masks_folder"] = masks_folder + run_in_container( + image=IMAGE_NAME, + module="v2d.foundation_pose.lib.run_ekf_smoothing", + inputs=inputs, + outputs={"output_dir": output_dir}, + extra_args={ + "process_noise_xy": process_noise_xy, + "process_noise_z": process_noise_z, + "process_noise_r": process_noise_r, + "measurement_noise_xy": measurement_noise_xy, + "measurement_noise_z": measurement_noise_z, + "measurement_noise_r": measurement_noise_r, + "min_iou": min_iou, + }, + dev=dev, + modules_dir=MODULES_DIR, + gpus=True, + env={"FOUNDATIONPOSE_WEIGHTS_DIR": weights_container}, + extra_volumes=DEV_PRESERVE_VOLUMES if dev else None, + ) + + +if __name__ == "__main__": + import argparse + + parser = argparse.ArgumentParser(description="ESKF + RTS pose smoother in Docker") + parser.add_argument("--poses_dir", required=True) + parser.add_argument("--mesh_path", required=True) + parser.add_argument("--intrinsics_path", required=True) + parser.add_argument("--weights_dir", required=True) + parser.add_argument("--output_dir", required=True) + parser.add_argument("--masks_folder", default=None) + parser.add_argument("--process_noise_xy", type=float, default=0.005) + parser.add_argument("--process_noise_z", type=float, default=0.005) + parser.add_argument("--process_noise_r", type=float, default=0.01) + parser.add_argument("--measurement_noise_xy", type=float, default=0.02) + parser.add_argument("--measurement_noise_z", type=float, default=0.1) + parser.add_argument("--measurement_noise_r", type=float, default=0.05) + parser.add_argument("--min_iou", type=float, default=0.1) + parser.add_argument("--dev", action="store_true") + args = parser.parse_args() + run_ekf_smoothing( + args.poses_dir, + args.mesh_path, + args.intrinsics_path, + args.weights_dir, + args.output_dir, + masks_folder=args.masks_folder, + process_noise_xy=args.process_noise_xy, + process_noise_z=args.process_noise_z, + process_noise_r=args.process_noise_r, + measurement_noise_xy=args.measurement_noise_xy, + measurement_noise_z=args.measurement_noise_z, + measurement_noise_r=args.measurement_noise_r, + min_iou=args.min_iou, + dev=args.dev, + ) diff --git a/third-party/video_to_data/reconstruction/modules/v2d_foundation_pose/docker/run_estimate_mesh_scale.py b/third-party/video_to_data/reconstruction/modules/v2d_foundation_pose/docker/run_estimate_mesh_scale.py new file mode 100644 index 0000000000000000000000000000000000000000..0099184ffb9df65c3e9a83390eb281f95e85afd4 --- /dev/null +++ b/third-party/video_to_data/reconstruction/modules/v2d_foundation_pose/docker/run_estimate_mesh_scale.py @@ -0,0 +1,111 @@ +# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 +import os +from v2d.docker.container import run_in_container +from v2d.foundation_pose.docker._config import DEV_PRESERVE_VOLUMES, IMAGE_NAME, MODULES_DIR + + +def run_estimate_mesh_scale( + mesh_path: str, + rgb_path: str, + depth_path: str, + mask_path: str, + intrinsics_path: str, + weights_dir: str, + scale_path: str, + rescaled_mesh_path: str = None, + pose_path: str = None, + lo: float = 0.5, + hi: float = 2.0, + n_samples: int = 7, + n_levels: int = 3, + iou_weight: float = 1.0, + depth_weight: float = 1.0, + chamfer_weight: float = 0.0, + registration_iterations: int = 5, + dev: bool = False, +) -> None: + weights_abs = os.path.abspath(weights_dir) + weights_container = f"/data/weights_dir/{os.path.basename(weights_abs)}" + inputs = { + "mesh_path": mesh_path, + "rgb_path": rgb_path, + "depth_path": depth_path, + "mask_path": mask_path, + "intrinsics_path": intrinsics_path, + "weights_dir": weights_dir, + } + outputs = {"scale_path": scale_path} + if rescaled_mesh_path is not None: + outputs["rescaled_mesh_path"] = rescaled_mesh_path + if pose_path is not None: + outputs["pose_path"] = pose_path + run_in_container( + image=IMAGE_NAME, + module="v2d.foundation_pose.lib.run_estimate_mesh_scale", + inputs=inputs, + outputs=outputs, + extra_args={ + "lo": lo, + "hi": hi, + "n_samples": n_samples, + "n_levels": n_levels, + "iou_weight": iou_weight, + "depth_weight": depth_weight, + "chamfer_weight": chamfer_weight, + "registration_iterations": registration_iterations, + }, + dev=dev, + modules_dir=MODULES_DIR, + gpus=True, + env={ + "FOUNDATIONPOSE_WEIGHTS_DIR": weights_container, + "PYTORCH_CUDA_ALLOC_CONF": "expandable_segments:True", + }, + extra_volumes=DEV_PRESERVE_VOLUMES if dev else None, + ) + + +if __name__ == "__main__": + import argparse + + parser = argparse.ArgumentParser(description="Estimate mesh scale via coarse-to-fine grid search in Docker") + parser.add_argument("--mesh_path", required=True) + parser.add_argument("--rgb_path", required=True) + parser.add_argument("--depth_path", required=True) + parser.add_argument("--mask_path", required=True) + parser.add_argument("--intrinsics_path", required=True) + parser.add_argument("--weights_dir", required=True) + parser.add_argument("--scale_path", required=True) + parser.add_argument("--rescaled_mesh_path", default=None) + parser.add_argument("--pose_path", default=None) + parser.add_argument("--lo", type=float, default=0.5) + parser.add_argument("--hi", type=float, default=2.0) + parser.add_argument("--n_samples", type=int, default=7) + parser.add_argument("--n_levels", type=int, default=3) + parser.add_argument("--iou_weight", type=float, default=1.0) + parser.add_argument("--depth_weight", type=float, default=1.0) + parser.add_argument("--chamfer_weight", type=float, default=0.0) + parser.add_argument("--registration_iterations", type=int, default=5) + parser.add_argument("--dev", action="store_true") + args = parser.parse_args() + run_estimate_mesh_scale( + args.mesh_path, + args.rgb_path, + args.depth_path, + args.mask_path, + args.intrinsics_path, + args.weights_dir, + args.scale_path, + rescaled_mesh_path=args.rescaled_mesh_path, + pose_path=args.pose_path, + lo=args.lo, + hi=args.hi, + n_samples=args.n_samples, + n_levels=args.n_levels, + iou_weight=args.iou_weight, + depth_weight=args.depth_weight, + chamfer_weight=args.chamfer_weight, + registration_iterations=args.registration_iterations, + dev=args.dev, + ) diff --git a/third-party/video_to_data/reconstruction/modules/v2d_foundation_pose/docker/run_mv_videos_to_poses.py b/third-party/video_to_data/reconstruction/modules/v2d_foundation_pose/docker/run_mv_videos_to_poses.py new file mode 100644 index 0000000000000000000000000000000000000000..54702c2fa03a0670ee19026404dc85ae21d1ef71 --- /dev/null +++ b/third-party/video_to_data/reconstruction/modules/v2d_foundation_pose/docker/run_mv_videos_to_poses.py @@ -0,0 +1,86 @@ +# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 +from pathlib import Path + +from v2d.docker.container import run_in_container +from v2d.foundation_pose.docker._config import DEV_PRESERVE_VOLUMES, IMAGE_NAME, MODULES_DIR + +_LIB_CONFIG = Path(__file__).parent.parent / "lib" / "mv_videos_to_poses.yaml" + + +def run_mv_videos_to_poses( + camera_params_path: str, + rgb_dir: str, + depth_dir: str, + mask_dir: str, + mesh_path: str, + weights_dir: str, + output_dir: str, + symmetry_path: str | None = None, + config_path: str = str(_LIB_CONFIG), + debug: int = -1, + dev: bool = False, +) -> None: + inputs = { + "camera_params_path": camera_params_path, + "rgb_dir": rgb_dir, + "depth_dir": depth_dir, + "mask_dir": mask_dir, + "mesh_path": mesh_path, + "symmetry_path": symmetry_path, + "weights_dir": weights_dir, + "config_path": config_path, + } + + outputs = {"output_dir": output_dir} + + weights_abs = Path(weights_dir).resolve() + weights_container = f"/data/weights_dir/{weights_abs.name}" + run_in_container( + image=IMAGE_NAME, + module="v2d.foundation_pose.lib.mv_videos_to_poses", + inputs=inputs, + outputs=outputs, + extra_args={"debug": debug if debug >= 0 else None}, + dev=dev, + modules_dir=MODULES_DIR, + gpus=True, + env={ + "PYTHONUNBUFFERED": "1", + "FOUNDATIONPOSE_WEIGHTS_DIR": weights_container, + }, + extra_volumes=DEV_PRESERVE_VOLUMES if dev else None, + ) + + +if __name__ == "__main__": + import argparse + + parser = argparse.ArgumentParser(description="Run multi-view FoundationPose tracking") + parser.add_argument("--rgb_dir", type=str, required=True, help="Directory containing input frames") + parser.add_argument("--camera_params_path", type=str, required=True, help="Path to camera parameters") + parser.add_argument("--depth_dir", type=str, required=True, help="Directory containing depth maps") + parser.add_argument("--mask_dir", type=str, required=True, help="Directory containing object masks") + parser.add_argument("--mesh_path", type=str, required=True, help="Path to object mesh file") + parser.add_argument("--symmetry_path", type=str, default=None, + help="Optional BOP-style symmetry JSON; defaults to /output_symmetry.json if present") + parser.add_argument("--weights_dir", type=str, required=True, help="Directory containing FoundationPose weights") + parser.add_argument("--output_dir", type=str, required=True, help="Directory for output poses") + parser.add_argument("--config_path", type=str, default=str(_LIB_CONFIG), help="Path to config YAML") + parser.add_argument("--debug", type=int, default=-1, help="Debug level") + parser.add_argument("--dev", action="store_true") + args = parser.parse_args() + + run_mv_videos_to_poses( + camera_params_path=args.camera_params_path, + rgb_dir=args.rgb_dir, + depth_dir=args.depth_dir, + mask_dir=args.mask_dir, + mesh_path=args.mesh_path, + symmetry_path=args.symmetry_path, + weights_dir=args.weights_dir, + output_dir=args.output_dir, + config_path=args.config_path, + debug=args.debug, + dev=args.dev, + ) diff --git a/third-party/video_to_data/reconstruction/modules/v2d_foundation_pose/docker/run_render_poses.py b/third-party/video_to_data/reconstruction/modules/v2d_foundation_pose/docker/run_render_poses.py new file mode 100644 index 0000000000000000000000000000000000000000..98a69f34d69c4d20b11b2f153271bb681dd1a3e3 --- /dev/null +++ b/third-party/video_to_data/reconstruction/modules/v2d_foundation_pose/docker/run_render_poses.py @@ -0,0 +1,62 @@ +# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 +import os +from v2d.docker.container import run_in_container +from v2d.foundation_pose.docker._config import DEV_PRESERVE_VOLUMES, IMAGE_NAME, MODULES_DIR + + +def run_render_poses( + mesh_path: str, + poses_dir: str, + frames_dir: str, + intrinsics_path: str, + output_dir: str, + batch_size: int = 32, + use_light: bool = True, + dev: bool = False, +) -> None: + run_in_container( + image=IMAGE_NAME, + module="v2d.foundation_pose.lib.run_render_poses", + inputs={ + "mesh_path": mesh_path, + "poses_dir": poses_dir, + "frames_dir": frames_dir, + "intrinsics_path": intrinsics_path, + }, + outputs={"output_dir": output_dir}, + extra_args={ + "batch_size": batch_size, + "use_light": use_light, + }, + dev=dev, + modules_dir=MODULES_DIR, + gpus=True, + extra_volumes=DEV_PRESERVE_VOLUMES if dev else None, + ) + + +if __name__ == "__main__": + import argparse + + parser = argparse.ArgumentParser(description="GPU-batched mesh overlay renderer in Docker") + parser.add_argument("--mesh_path", required=True) + parser.add_argument("--poses_dir", required=True) + parser.add_argument("--frames_dir", required=True) + parser.add_argument("--intrinsics_path", required=True) + parser.add_argument("--output_dir", required=True) + parser.add_argument("--batch_size", type=int, default=32) + parser.add_argument("--use_light", action="store_true", default=True) + parser.add_argument("--no_light", dest="use_light", action="store_false") + parser.add_argument("--dev", action="store_true") + args = parser.parse_args() + run_render_poses( + args.mesh_path, + args.poses_dir, + args.frames_dir, + args.intrinsics_path, + args.output_dir, + batch_size=args.batch_size, + use_light=args.use_light, + dev=args.dev, + ) diff --git a/third-party/video_to_data/reconstruction/modules/v2d_foundation_pose/docker/run_shell.py b/third-party/video_to_data/reconstruction/modules/v2d_foundation_pose/docker/run_shell.py new file mode 100644 index 0000000000000000000000000000000000000000..4cee58db3bc7bacd4ce4e77d12445d8a67d8f54e --- /dev/null +++ b/third-party/video_to_data/reconstruction/modules/v2d_foundation_pose/docker/run_shell.py @@ -0,0 +1,27 @@ +# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 +import subprocess +import os +from v2d.foundation_pose.docker._config import IMAGE_NAME, MODULES_DIR + + +def run_shell(dev: bool = False) -> None: + cmd = [ + "docker", "run", "-it", "--rm", + "--gpus", "all", + "--user", f"{os.getuid()}:{os.getgid()}", + "-e", "HOME=/tmp", + ] + if dev: + cmd += ["-v", f"{MODULES_DIR}:/workspace"] + cmd += [IMAGE_NAME, "bash"] + subprocess.run(cmd, check=True) + + +if __name__ == "__main__": + import argparse + + parser = argparse.ArgumentParser(description="Run shell in v2d_foundation_pose container") + parser.add_argument("--dev", action="store_true", help="Mount local modules for development") + args = parser.parse_args() + run_shell(dev=args.dev) diff --git a/third-party/video_to_data/reconstruction/modules/v2d_foundation_pose/docker/run_video_to_poses.py b/third-party/video_to_data/reconstruction/modules/v2d_foundation_pose/docker/run_video_to_poses.py new file mode 100644 index 0000000000000000000000000000000000000000..f4a843bc032e0a054268457a9099fc80a34adee2 --- /dev/null +++ b/third-party/video_to_data/reconstruction/modules/v2d_foundation_pose/docker/run_video_to_poses.py @@ -0,0 +1,99 @@ +# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 +import os +from v2d.docker.container import run_in_container +from v2d.foundation_pose.docker._config import DEV_PRESERVE_VOLUMES, IMAGE_NAME, MODULES_DIR + + +def run_video_to_poses( + video_path: str, + depth_folder: str, + masks_folder: str, + camera_intrinsics_path: str, + mesh_path: str, + poses_dir: str, + weights_dir: str, + reference_frame: int = 0, + target_width: int = None, + target_height: int = None, + reregister_iou_thresh: float = None, + register_iteration: int = 10, + track_iteration: int = 5, + n_particles: int = 1, + particle_process_noise_t: float = 0.005, + particle_process_noise_r: float = 0.02, + particle_iteration: int = 3, + particle_mask_iou_weight: float = 1.0, + mask_depth: bool = False, + dev: bool = False, +) -> None: + weights_abs = os.path.abspath(weights_dir) + weights_container = f"/data/weights_dir/{os.path.basename(weights_abs)}" + run_in_container( + image=IMAGE_NAME, + module="v2d.foundation_pose.lib.run_video_to_poses", + inputs={"video_path": video_path, "depth_folder": depth_folder, "masks_folder": masks_folder, "camera_intrinsics_path": camera_intrinsics_path, "mesh_path": mesh_path, "weights_dir": weights_dir}, + outputs={"poses_dir": poses_dir}, + extra_args={ + "reference_frame": reference_frame, + "target_width": target_width, + "target_height": target_height, + "reregister_iou_thresh": reregister_iou_thresh, + "register_iteration": register_iteration, + "track_iteration": track_iteration, + "n_particles": n_particles, + "particle_process_noise_t": particle_process_noise_t, + "particle_process_noise_r": particle_process_noise_r, + "particle_iteration": particle_iteration, + "particle_mask_iou_weight": particle_mask_iou_weight, + "mask_depth": mask_depth, + }, + dev=dev, + modules_dir=MODULES_DIR, + gpus=True, + env={"FOUNDATIONPOSE_WEIGHTS_DIR": weights_container}, + extra_volumes=DEV_PRESERVE_VOLUMES if dev else None, + ) + + +if __name__ == "__main__": + import argparse + + parser = argparse.ArgumentParser(description="Run FoundationPose video to poses in Docker") + parser.add_argument("--video_path", required=True) + parser.add_argument("--depth_folder", required=True) + parser.add_argument("--masks_folder", required=True) + parser.add_argument("--camera_intrinsics_path", required=True) + parser.add_argument("--mesh_path", required=True) + parser.add_argument("--poses_dir", required=True) + parser.add_argument("--weights_dir", required=True) + parser.add_argument("--reference_frame", type=int, default=0) + parser.add_argument("--target_width", type=int, default=None) + parser.add_argument("--target_height", type=int, default=None) + parser.add_argument("--reregister_iou_thresh", type=float, default=None) + parser.add_argument("--register_iteration", type=int, default=10) + parser.add_argument("--track_iteration", type=int, default=5) + parser.add_argument("--n_particles", type=int, default=1) + parser.add_argument("--particle_process_noise_t", type=float, default=0.005) + parser.add_argument("--particle_process_noise_r", type=float, default=0.02) + parser.add_argument("--particle_iteration", type=int, default=3) + parser.add_argument("--particle_mask_iou_weight", type=float, default=1.0) + parser.add_argument("--mask_depth", action="store_true") + parser.add_argument("--dev", action="store_true") + args = parser.parse_args() + run_video_to_poses( + args.video_path, args.depth_folder, args.masks_folder, + args.camera_intrinsics_path, args.mesh_path, args.poses_dir, + args.weights_dir, reference_frame=args.reference_frame, + target_width=args.target_width, target_height=args.target_height, + reregister_iou_thresh=args.reregister_iou_thresh, + register_iteration=args.register_iteration, + track_iteration=args.track_iteration, + n_particles=args.n_particles, + particle_process_noise_t=args.particle_process_noise_t, + particle_process_noise_r=args.particle_process_noise_r, + particle_iteration=args.particle_iteration, + particle_mask_iou_weight=args.particle_mask_iou_weight, + mask_depth=args.mask_depth, + dev=args.dev, + ) diff --git a/third-party/video_to_data/reconstruction/modules/v2d_foundation_pose/lib/FoundationPose/.gitignore b/third-party/video_to_data/reconstruction/modules/v2d_foundation_pose/lib/FoundationPose/.gitignore new file mode 100644 index 0000000000000000000000000000000000000000..cc59bdd934c1ca5e79be63449e4790c20fd31d36 --- /dev/null +++ b/third-party/video_to_data/reconstruction/modules/v2d_foundation_pose/lib/FoundationPose/.gitignore @@ -0,0 +1,158 @@ +# Byte-compiled / optimized / DLL files +__pycache__/ +.history +exp/ +*.py[cod] +*$py.class +# C extensions +*.so +BundleTrack/build +# Distribution / packaging +.Python +foundationpose/ +build/ +develop-eggs/ +*.zip +demo_data/* +dist/ +# *.png +# *.jpg +debug/ +weights/* +downloads/ +eggs/ +.eggs/ +lib/ +lib64/ +parts/ +sdist/ +var/ +.vscode/ +wheels/ +wandb/ +*.blend1 +*.tar.* +*.zip +*.svg +sacred/ +artifacts/ +pip-wheel-metadata/ +share/python-wheels/ +*.egg-info/ +.installed.cfg +*.egg +MANIFEST + +# PyInstaller +# Usually these files are written by a python script from a template +# before PyInstaller builds the exe, so as to inject date/other infos into it. +*.manifest +*.spec + +# Installer logs +pip-log.txt +pip-delete-this-directory.txt + +# Unit test / coverage reports +htmlcov/ +.tox/ +.nox/ +.coverage +.coverage.* +.cache +nosetests.xml +demo_data/ +debug/ +coverage.xml +*.cover +demo_data/ +debug/ +weights/ +*.py,cover +.hypothesis/ +.pytest_cache/ +*.pth +weights/ +# Translations +*.mo +*.pot + +# Django stuff: +*.log +local_settings.py +db.sqlite3 +db.sqlite3-journal + +# Flask stuff: +instance/ +.webassets-cache +cosypose/experiments + +# Scrapy stuff: +.scrapy + +# Sphinx documentation +docs/_build/ + +# PyBuilder +target/ + +# Jupyter Notebook +.ipynb_checkpoints + +# IPython +profile_default/ +ipython_config.py + +# pyenv +.python-version + +# pipenv +# According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control. +# However, in case of collaboration, if having platform-specific dependencies or dependencies +# having no cross-platform support, pipenv may install dependencies that don't work, or not +# install all needed dependencies. +#Pipfile.lock + +# PEP 582; used by e.g. github.com/David-OConnor/pyflow +__pypackages__/ + +# Celery stuff +celerybeat-schedule +celerybeat.pid + +# SageMath parsed files +*.sage.py + +# Environments +.env +.venv +env/ +venv/ +ENV/ +env.bak/ +venv.bak/ + +# Spyder project settings +.spyderproject +.spyproject + +# Rope project settings +.ropeproject + +# mkdocs documentation +/site + +# mypy +.mypy_cache/ +.dmypy.json +dmypy.json + +# Pyre type checker +.pyre/ + +# Datasets +data/ +logs/ +!BundleTrack/XMem/inference/data +run_used.yml \ No newline at end of file diff --git a/third-party/video_to_data/reconstruction/modules/v2d_foundation_pose/lib/FoundationPose/LICENSE b/third-party/video_to_data/reconstruction/modules/v2d_foundation_pose/lib/FoundationPose/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..6704932cd8979da01a39360783279b9c4b506305 --- /dev/null +++ b/third-party/video_to_data/reconstruction/modules/v2d_foundation_pose/lib/FoundationPose/LICENSE @@ -0,0 +1,94 @@ +Copyright (c) 2022-Present, NVIDIA Corporation & affiliates. All rights reserved. + + +======================================================================= + +1. Definitions + +"Licensor" means any person or entity that distributes its Work. + +"Software" means the original work of authorship made available under +this License. + +"Work" means the Software and any additions to or derivative works of +the Software that are made available under this License. + +The terms "reproduce," "reproduction," "derivative works," and +"distribution" have the meaning as provided under U.S. copyright law; +provided, however, that for the purposes of this License, derivative +works shall not include works that remain separable from, or merely +link (or bind by name) to the interfaces of, the Work. + +Works, including the Software, are "made available" under this License +by including in or with the Work either (a) a copyright notice +referencing the applicability of this License to the Work, or (b) a +copy of this License. + +2. License Grants + + 2.1 Copyright Grant. Subject to the terms and conditions of this + License, each Licensor grants to you a perpetual, worldwide, + non-exclusive, royalty-free, copyright license to reproduce, + prepare derivative works of, publicly display, publicly perform, + sublicense and distribute its Work and any resulting derivative + works in any form. + +3. Limitations + + 3.1 Redistribution. You may reproduce or distribute the Work only + if (a) you do so under this License, (b) you include a complete + copy of this License with your distribution, and (c) you retain + without modification any copyright, patent, trademark, or + attribution notices that are present in the Work. + + 3.2 Derivative Works. You may specify that additional or different + terms apply to the use, reproduction, and distribution of your + derivative works of the Work ("Your Terms") only if (a) Your Terms + provide that the use limitation in Section 3.3 applies to your + derivative works, and (b) you identify the specific derivative + works that are subject to Your Terms. Notwithstanding Your Terms, + this License (including the redistribution requirements in Section + 3.1) will continue to apply to the Work itself. + + 3.3 Use Limitation. The Work and any derivative works thereof only + may be used or intended for use non-commercially. Notwithstanding + the foregoing, NVIDIA and its affiliates may use the Work and any + derivative works commercially. As used herein, "non-commercially" + means for research or evaluation purposes only. + + 3.4 Patent Claims. If you bring or threaten to bring a patent claim + against any Licensor (including any claim, cross-claim or + counterclaim in a lawsuit) to enforce any patents that you allege + are infringed by any Work, then your rights under this License from + such Licensor (including the grant in Section 2.1) will terminate + immediately. + + 3.5 Trademarks. This License does not grant any rights to use any + Licensor�s or its affiliates� names, logos, or trademarks, except + as necessary to reproduce the notices described in this License. + + 3.6 Termination. If you violate any term of this License, then your + rights under this License (including the grant in Section 2.1) will + terminate immediately. + +4. Disclaimer of Warranty. + +THE WORK IS PROVIDED "AS IS" WITHOUT WARRANTIES OR CONDITIONS OF ANY +KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WARRANTIES OR CONDITIONS OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, TITLE OR +NON-INFRINGEMENT. YOU BEAR THE RISK OF UNDERTAKING ANY ACTIVITIES UNDER +THIS LICENSE. + +5. Limitation of Liability. + +EXCEPT AS PROHIBITED BY APPLICABLE LAW, IN NO EVENT AND UNDER NO LEGAL +THEORY, WHETHER IN TORT (INCLUDING NEGLIGENCE), CONTRACT, OR OTHERWISE +SHALL ANY LICENSOR BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY DIRECT, +INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES ARISING OUT OF +OR RELATED TO THIS LICENSE, THE USE OR INABILITY TO USE THE WORK +(INCLUDING BUT NOT LIMITED TO LOSS OF GOODWILL, BUSINESS INTERRUPTION, +LOST PROFITS OR DATA, COMPUTER FAILURE OR MALFUNCTION, OR ANY OTHER +COMMERCIAL DAMAGES OR LOSSES), EVEN IF THE LICENSOR HAS BEEN ADVISED OF +THE POSSIBILITY OF SUCH DAMAGES. + +======================================================================= diff --git a/third-party/video_to_data/reconstruction/modules/v2d_foundation_pose/lib/FoundationPose/Utils.py b/third-party/video_to_data/reconstruction/modules/v2d_foundation_pose/lib/FoundationPose/Utils.py new file mode 100644 index 0000000000000000000000000000000000000000..cb7edac37ca0bf55d615d1676b9a50dcccd1ae8d --- /dev/null +++ b/third-party/video_to_data/reconstruction/modules/v2d_foundation_pose/lib/FoundationPose/Utils.py @@ -0,0 +1,1020 @@ +# Copyright (c) 2023, NVIDIA CORPORATION. All rights reserved. +# +# NVIDIA CORPORATION and its licensors retain all intellectual property +# and proprietary rights in and to this software, related documentation +# and any modifications thereto. Any use, reproduction, disclosure or +# distribution of this software and related documentation without an express +# license agreement from NVIDIA CORPORATION is strictly prohibited. + + +import os, sys, time,torch,pickle,trimesh,itertools,pdb,zipfile,datetime,imageio,gzip,logging,joblib,importlib,uuid,signal,multiprocessing,psutil,subprocess,tarfile,scipy,argparse +from pytorch3d.transforms import so3_log_map,so3_exp_map,se3_exp_map,se3_log_map,matrix_to_axis_angle,matrix_to_euler_angles,euler_angles_to_matrix, rotation_6d_to_matrix +from pytorch3d.renderer import FoVPerspectiveCameras, PerspectiveCameras, look_at_view_transform, look_at_rotation, RasterizationSettings, MeshRenderer, MeshRasterizer, BlendParams, SoftSilhouetteShader, HardPhongShader, PointLights, TexturesVertex +from pytorch3d.renderer.mesh.rasterize_meshes import barycentric_coordinates +from pytorch3d.renderer.mesh.shader import SoftDepthShader, HardFlatShader +from pytorch3d.renderer.mesh.textures import Textures +from pytorch3d.structures import Meshes +from scipy.interpolate import griddata +import nvdiffrast.torch as dr +import torch.nn.functional as F +import torchvision +import torch.nn as nn +from functools import partial +import pandas as pd +import open3d as o3d +from uuid import uuid4 +import cv2 +from PIL import Image +import numpy as np +from collections import defaultdict +import multiprocessing as mp +import matplotlib.pyplot as plt +import math,glob,re,copy +from transformations import * +from scipy.spatial import cKDTree +from collections import OrderedDict +import ruamel.yaml +yaml = ruamel.yaml.YAML() +code_dir = os.path.dirname(os.path.realpath(__file__)) +sys.path.append(code_dir) +# sys.path.append(f"{code_dir}/mycpp/build") +try: + import kornia +except: + kornia = None +try: + import mycpp.build.mycpp as mycpp +except: + mycpp = None +try: + from bundlesdf.mycuda import common +except: + common = None +try: + import warp as wp + wp.init() +except: + wp = None +enable_timer = 0 + +def NestDict(): + return defaultdict(NestDict) + +to8b = lambda x : (255*np.clip(x,0,1)).astype(np.uint8) + +BAD_DEPTH = 99 +BAD_COLOR = 0 + +glcam_in_cvcam = np.array([[1,0,0,0], + [0,-1,0,0], + [0,0,-1,0], + [0,0,0,1]]).astype(float) + +COLOR_MAP=np.array([[0, 0, 0], #Ignore + [128,0,0], #Background + [0,128,0], #Wall + [128,128,0], #Floor + [0,0,128], #Ceiling + [128,0,128], #Table + [0,128,128], #Chair + [128,128,128], #Window + [64,0,0], #Door + [192,0,0], #Monitor + [64, 128, 0], # 11th + [192, 0, 128], + [64, 128, 128], + [192, 128, 128], + [0, 64, 0], + [128, 64, 0], + [0, 192, 0], + [128, 192, 0], + ]) + + +def set_logging_format(level=logging.INFO): + importlib.reload(logging) + FORMAT = '[%(funcName)s()] %(message)s' + logging.basicConfig(level=level, format=FORMAT) + +set_logging_format() + + + + +def make_mesh_tensors(mesh, device='cuda', max_tex_size=None): + mesh_tensors = {} + if isinstance(mesh.visual, trimesh.visual.texture.TextureVisuals): + img = np.array(mesh.visual.material.image.convert('RGB')) + img = img[...,:3] + if max_tex_size is not None: + max_size = max(img.shape[0], img.shape[1]) + if max_size>max_tex_size: + scale = 1/max_size * max_tex_size + img = cv2.resize(img, fx=scale, fy=scale, dsize=None) + mesh_tensors['tex'] = torch.as_tensor(img, device=device, dtype=torch.float)[None]/255.0 + mesh_tensors['uv_idx'] = torch.as_tensor(mesh.faces, device=device, dtype=torch.int) + uv = torch.as_tensor(mesh.visual.uv, device=device, dtype=torch.float) + uv[:,1] = 1 - uv[:,1] + mesh_tensors['uv'] = uv + else: + if mesh.visual.vertex_colors is None: + logging.info(f"WARN: mesh doesn't have vertex_colors, assigning a pure color") + mesh.visual.vertex_colors = np.tile(np.array([128,128,128]).reshape(1,3), (len(mesh.vertices), 1)) + mesh_tensors['vertex_color'] = torch.as_tensor(mesh.visual.vertex_colors[...,:3], device=device, dtype=torch.float)/255.0 + + mesh_tensors.update({ + 'pos': torch.tensor(mesh.vertices, device=device, dtype=torch.float), + 'faces': torch.tensor(mesh.faces, device=device, dtype=torch.int), + 'vnormals': torch.tensor(mesh.vertex_normals, device=device, dtype=torch.float), + }) + return mesh_tensors + + +def nvdiffrast_render(K=None, H=None, W=None, ob_in_cams=None, glctx=None, context='cuda', get_normal=False, mesh_tensors=None, mesh=None, projection_mat=None, bbox2d=None, output_size=None, use_light=False, light_color=None, light_dir=np.array([0,0,1]), light_pos=np.array([0,0,0]), w_ambient=0.8, w_diffuse=0.5, extra={}): + '''Just plain rendering, not support any gradient + @K: (3,3) np array + @ob_in_cams: (N,4,4) torch tensor, openCV camera + @projection_mat: np array (4,4) + @output_size: (height, width) + @bbox2d: (N,4) (umin,vmin,umax,vmax) if only roi need to render. + @light_dir: in cam space + @light_pos: in cam space + ''' + if glctx is None: + if context == 'gl': + glctx = dr.RasterizeGLContext() + elif context=='cuda': + glctx = dr.RasterizeCudaContext() + else: + raise NotImplementedError + logging.info("created context") + + if mesh_tensors is None: + mesh_tensors = make_mesh_tensors(mesh) + pos = mesh_tensors['pos'] + vnormals = mesh_tensors['vnormals'] + pos_idx = mesh_tensors['faces'] + has_tex = 'tex' in mesh_tensors + + ob_in_glcams = torch.tensor(glcam_in_cvcam, device='cuda', dtype=torch.float)[None]@ob_in_cams + if projection_mat is None: + projection_mat = projection_matrix_from_intrinsics(K, height=H, width=W, znear=0.001, zfar=100) + projection_mat = torch.as_tensor(projection_mat.reshape(-1,4,4), device='cuda', dtype=torch.float) + mtx = projection_mat@ob_in_glcams + + if output_size is None: + output_size = np.asarray([H,W]) + + pts_cam = transform_pts(pos, ob_in_cams) + pos_homo = to_homo_torch(pos) + pos_clip = (mtx[:,None]@pos_homo[None,...,None])[...,0] + if bbox2d is not None: + l = bbox2d[:,0] + t = H-bbox2d[:,1] + r = bbox2d[:,2] + b = H-bbox2d[:,3] + tf = torch.eye(4, dtype=torch.float, device='cuda').reshape(1,4,4).expand(len(ob_in_cams),4,4).contiguous() + tf[:,0,0] = W/(r-l) + tf[:,1,1] = H/(t-b) + tf[:,3,0] = (W-r-l)/(r-l) + tf[:,3,1] = (H-t-b)/(t-b) + pos_clip = pos_clip@tf + rast_out, _ = dr.rasterize(glctx, pos_clip, pos_idx, resolution=np.asarray(output_size)) + xyz_map, _ = dr.interpolate(pts_cam, rast_out, pos_idx) + depth = xyz_map[...,2] + if has_tex: + texc, _ = dr.interpolate(mesh_tensors['uv'], rast_out, mesh_tensors['uv_idx']) + color = dr.texture(mesh_tensors['tex'], texc, filter_mode='linear') + else: + color, _ = dr.interpolate(mesh_tensors['vertex_color'], rast_out, pos_idx) + + if use_light: + get_normal = True + if get_normal: + vnormals_cam = transform_dirs(vnormals, ob_in_cams) + normal_map, _ = dr.interpolate(vnormals_cam, rast_out, pos_idx) + normal_map = F.normalize(normal_map, dim=-1) + normal_map = torch.flip(normal_map, dims=[1]) + else: + normal_map = None + + if use_light: + if light_dir is not None: + light_dir_neg = -torch.as_tensor(light_dir, dtype=torch.float, device='cuda') + else: + light_dir_neg = torch.as_tensor(light_pos, dtype=torch.float, device='cuda').reshape(1,1,3) - pts_cam + diffuse_intensity = (F.normalize(vnormals_cam, dim=-1) * F.normalize(light_dir_neg, dim=-1)).sum(dim=-1).clip(0, 1)[...,None] + diffuse_intensity_map, _ = dr.interpolate(diffuse_intensity, rast_out, pos_idx) # (N_pose, H, W, 1) + if light_color is None: + light_color = color + else: + light_color = torch.as_tensor(light_color, device='cuda', dtype=torch.float) + color = color*w_ambient + diffuse_intensity_map*light_color*w_diffuse + + color = color.clip(0,1) + color = color * torch.clamp(rast_out[..., -1:], 0, 1) # Mask out background using alpha + color = torch.flip(color, dims=[1]) # Flip Y coordinates + depth = torch.flip(depth, dims=[1]) + extra['xyz_map'] = torch.flip(xyz_map, dims=[1]) + return color, depth, normal_map + + +def set_seed(random_seed): + import torch,random + np.random.seed(random_seed) + random.seed(random_seed) + torch.manual_seed(random_seed) + torch.cuda.manual_seed_all(random_seed) + torch.backends.cudnn.deterministic = True + torch.backends.cudnn.benchmark = False + + +def add_err(pred,gt,model_pts,symetry_tfs=np.eye(4)[None]): + """ + Average Distance of Model Points for objects with no indistinguishable views + - by Hinterstoisser et al. (ACCV 2012). + """ + pred_pts = transform_pts(model_pts, pred) + gt_pts = transform_pts(model_pts, gt) + e = np.linalg.norm(pred_pts - gt_pts, axis=-1).mean() + return e + +def adds_err(pred,gt,model_pts): + """ + @pred: 4x4 mat + @gt: + @model: (N,3) + """ + pred_pts = transform_pts(model_pts, pred) + gt_pts = transform_pts(model_pts, gt) + nn_index = cKDTree(pred_pts) + nn_dists, _ = nn_index.query(gt_pts, k=1, workers=-1) + e = nn_dists.mean() + return e + +def compute_auc_sklearn(errs, max_val=0.1, step=0.001): + from sklearn import metrics + errs = np.sort(np.array(errs)) + X = np.arange(0, max_val+step, step) + Y = np.ones(len(X)) + for i,x in enumerate(X): + y = (errs<=x).sum()/len(errs) + Y[i] = y + if y>=1: + break + auc = metrics.auc(X, Y) / (max_val*1) + return auc + + + +def normalizeRotation(pose): + '''Assume no shear case + ''' + new_pose = pose.copy() + scales = np.linalg.norm(pose[:3,:3],axis=0) + new_pose[:3,:3] /= scales.reshape(1,3) + return new_pose + + + +def toOpen3dCloud(points,colors=None,normals=None): + cloud = o3d.geometry.PointCloud() + cloud.points = o3d.utility.Vector3dVector(points.astype(np.float64)) + if colors is not None: + if colors.max()>1: + colors = colors/255.0 + cloud.colors = o3d.utility.Vector3dVector(colors.astype(np.float64)) + if normals is not None: + cloud.normals = o3d.utility.Vector3dVector(normals.astype(np.float64)) + return cloud + + + +def make_grid_image(imgs, nrow, padding=5, pad_value=255): + ''' + @imgs: (B,H,W,C) np array + @nrow: num of images per row + ''' + grid = torchvision.utils.make_grid(torch.as_tensor(np.asarray(imgs)).permute(0,3,1,2), nrow=nrow, padding=padding, pad_value=pad_value) + grid = grid.permute(1,2,0).contiguous().data.cpu().numpy().astype(np.uint8) + return grid + + +if wp is not None: + @wp.kernel(enable_backward=False) + def bilateral_filter_depth_kernel(depth:wp.array(dtype=float, ndim=2), out:wp.array(dtype=float, ndim=2), radius:int, zfar:float, sigmaD:float, sigmaR:float): + h,w = wp.tid() + H = depth.shape[0] + W = depth.shape[1] + if w>=W or h>=H: + return + out[h,w] = 0.0 + mean_depth = float(0.0) + num_valid = int(0) + for u in range(w-radius, w+radius+1): + if u<0 or u>=W: + continue + for v in range(h-radius, h+radius+1): + if v<0 or v>=H: + continue + cur_depth = depth[v,u] + if cur_depth>=0.001 and cur_depth=W: + continue + for v in range(h-radius, h+radius+1): + if v<0 or v>=H: + continue + cur_depth = depth[v,u] + if cur_depth>=0.001 and cur_depth0 and num_valid>0: + out[h,w] = sum/sum_weight + + def bilateral_filter_depth(depth, radius=2, zfar=100, sigmaD=2, sigmaR=100000, device='cuda'): + if isinstance(depth, np.ndarray): + depth_wp = wp.array(depth, dtype=float, device=device) + else: + depth_wp = wp.from_torch(depth) + out_wp = wp.zeros(depth.shape, dtype=float, device=device) + wp.launch(kernel=bilateral_filter_depth_kernel, device=device, dim=[depth.shape[0], depth.shape[1]], inputs=[depth_wp, out_wp, radius, zfar, sigmaD, sigmaR]) + depth_out = wp.to_torch(out_wp) + + if isinstance(depth, np.ndarray): + depth_out = depth_out.data.cpu().numpy() + return depth_out + + + @wp.kernel(enable_backward=False) + def erode_depth_kernel(depth:wp.array(dtype=float, ndim=2), out:wp.array(dtype=float, ndim=2), radius:int, depth_diff_thres:float, ratio_thres:float, zfar:float): + h,w = wp.tid() + H = depth.shape[0] + W = depth.shape[1] + if w>=W or h>=H: + return + d_ori = depth[h,w] + if d_ori<0.001 or d_ori>=zfar: + out[h,w] = 0.0 + bad_cnt = float(0) + total = float(0) + for u in range(w-radius, w+radius+1): + if u<0 or u>=W: + continue + for v in range(h-radius, h+radius+1): + if v<0 or v>=H: + continue + cur_depth = depth[v,u] + total += 1.0 + if cur_depth<0.001 or cur_depth>=zfar or abs(cur_depth-d_ori)>depth_diff_thres: + bad_cnt += 1.0 + if bad_cnt/total>ratio_thres: + out[h,w] = 0.0 + else: + out[h,w] = d_ori + + + def erode_depth(depth, radius=2, depth_diff_thres=0.001, ratio_thres=0.8, zfar=100, device='cuda'): + depth_wp = wp.from_torch(torch.as_tensor(depth, dtype=torch.float, device=device)) + out_wp = wp.zeros(depth.shape, dtype=float, device=device) + wp.launch(kernel=erode_depth_kernel, device=device, dim=[depth.shape[0], depth.shape[1]], inputs=[depth_wp, out_wp, radius, depth_diff_thres, ratio_thres, zfar],) + depth_out = wp.to_torch(out_wp) + + if isinstance(depth, np.ndarray): + depth_out = depth_out.data.cpu().numpy() + return depth_out + + + +def depth2xyzmap(depth, K, uvs=None): + invalid_mask = (depth<0.001) + H,W = depth.shape[:2] + if uvs is None: + vs,us = np.meshgrid(np.arange(0,H),np.arange(0,W), sparse=False, indexing='ij') + vs = vs.reshape(-1) + us = us.reshape(-1) + else: + uvs = uvs.round().astype(int) + us = uvs[:,0] + vs = uvs[:,1] + zs = depth[vs,us] + xs = (us-K[0,2])*zs/K[0,0] + ys = (vs-K[1,2])*zs/K[1,1] + pts = np.stack((xs.reshape(-1),ys.reshape(-1),zs.reshape(-1)), 1) #(N,3) + xyz_map = np.zeros((H,W,3), dtype=np.float32) + xyz_map[vs,us] = pts + xyz_map[invalid_mask] = 0 + return xyz_map + + +def depth2xyzmap_batch(depths, Ks, zfar): + ''' + @depths: torch tensor (B,H,W) + @Ks: torch tensor (B,3,3) + ''' + bs = depths.shape[0] + invalid_mask = (depths<0.001) | (depths>zfar) + H,W = depths.shape[-2:] + vs,us = torch.meshgrid(torch.arange(0,H),torch.arange(0,W), indexing='ij') + vs = vs.reshape(-1).float().cuda()[None].expand(bs,-1) + us = us.reshape(-1).float().cuda()[None].expand(bs,-1) + zs = depths.reshape(bs,-1) + Ks = Ks[:,None].expand(bs,zs.shape[-1],3,3) + xs = (us-Ks[...,0,2])*zs/Ks[...,0,0] #(B,N) + ys = (vs-Ks[...,1,2])*zs/Ks[...,1,1] + pts = torch.stack([xs,ys,zs], dim=-1) #(B,N,3) + xyz_maps = pts.reshape(bs,H,W,3) + xyz_maps[invalid_mask] = 0 + return xyz_maps + + + +def rle_to_mask(rle: dict) -> np.ndarray: + """Compute a binary mask from an uncompressed RLE.""" + h, w = rle["size"] + mask = np.empty(h * w, dtype=bool) + idx = 0 + parity = False + for count in rle["counts"]: + mask[idx : idx + count] = parity + idx += count + parity ^= True + mask = mask.reshape(w, h) + return mask.transpose() # Put in C order + + +def depth_to_vis(depth, zmin=None, zmax=None, mode='rgb', inverse=True): + if zmin is None: + zmin = depth.min() + if zmax is None: + zmax = depth.max() + + if inverse: + invalid = depth<0.001 + vis = zmin/(depth+1e-8) + vis[invalid] = 0 + else: + depth = depth.clip(zmin, zmax) + invalid = (depth==zmin) | (depth==zmax) + vis = (depth-zmin)/(zmax-zmin) + vis[invalid] = 1 + + if mode=='gray': + vis = (vis*255).clip(0, 255).astype(np.uint8) + elif mode=='rgb': + vis = cv2.applyColorMap((vis*255).astype(np.uint8), cv2.COLORMAP_JET)[...,::-1] + else: + raise RuntimeError + + return vis + + + +def sample_views_icosphere(n_views, subdivisions=None, radius=1): + if subdivisions is not None: + mesh = trimesh.creation.icosphere(subdivisions=subdivisions, radius=radius) + else: + subdivision = 1 + while 1: + mesh = trimesh.creation.icosphere(subdivisions=subdivision, radius=radius) + if mesh.vertices.shape[0]>=n_views: + break + subdivision += 1 + cam_in_obs = np.tile(np.eye(4)[None], (len(mesh.vertices),1,1)) + cam_in_obs[:,:3,3] = mesh.vertices + up = np.array([0,0,1]) + z_axis = -cam_in_obs[:,:3,3] #(N,3) + z_axis /= np.linalg.norm(z_axis, axis=-1).reshape(-1,1) + x_axis = np.cross(up.reshape(1,3), z_axis) + invalid = (x_axis==0).all(axis=-1) + x_axis[invalid] = [1,0,0] + x_axis /= np.linalg.norm(x_axis, axis=-1).reshape(-1,1) + y_axis = np.cross(z_axis, x_axis) + y_axis /= np.linalg.norm(y_axis, axis=-1).reshape(-1,1) + cam_in_obs[:,:3,0] = x_axis + cam_in_obs[:,:3,1] = y_axis + cam_in_obs[:,:3,2] = z_axis + return cam_in_obs + + + +def to_homo(pts): + ''' + @pts: (N,3 or 2) will homogeneliaze the last dimension + ''' + assert len(pts.shape)==2, f'pts.shape: {pts.shape}' + homo = np.concatenate((pts, np.ones((pts.shape[0],1))),axis=-1) + return homo + + +def to_homo_torch(pts): + ''' + @pts: shape can be (...,N,3 or 2) or (N,3) will homogeneliaze the last dimension + ''' + ones = torch.ones((*pts.shape[:-1],1), dtype=torch.float, device=pts.device) + homo = torch.cat((pts, ones),dim=-1) + return homo + + +def transform_pts(pts,tf): + """Transform 2d or 3d points + @pts: (...,N_pts,3) + @tf: (...,4,4) + """ + if len(tf.shape)>=3 and tf.shape[-3]!=pts.shape[-2]: + tf = tf[...,None,:,:] + return (tf[...,:-1,:-1]@pts[...,None] + tf[...,:-1,-1:])[...,0] + + +def transform_dirs(dirs,tf): + """ + @dirs: (...,3) + @tf: (...,4,4) + """ + if len(tf.shape)>=3 and tf.shape[-3]!=dirs.shape[-2]: + tf = tf[...,None,:,:] + return (tf[...,:3,:3]@dirs[...,None])[...,0] + + + +def random_direction(): + '''https://stackoverflow.com/questions/33976911/generate-a-random-sample-of-points-distributed-on-the-surface-of-a-unit-sphere + ''' + vec = np.random.randn(3).reshape(3) + vec /= np.linalg.norm(vec) + return vec + + + +def compute_mesh_diameter(model_pts=None, mesh=None, n_sample=1000): + from sklearn.decomposition import TruncatedSVD + if mesh is not None: + u, s, vh = scipy.linalg.svd(mesh.vertices, full_matrices=False) + pts = u@s + diameter = np.linalg.norm(pts.max(axis=0)-pts.min(axis=0)) + return float(diameter) + + if n_sample is None: + pts = model_pts + else: + ids = np.random.choice(len(model_pts), size=min(n_sample, len(model_pts)), replace=False) + pts = model_pts[ids] + dists = np.linalg.norm(pts[None]-pts[:,None], axis=-1) + diameter = dists.max() + return diameter + + +def compute_crop_window_tf_batch(pts=None, H=None, W=None, poses=None, K=None, crop_ratio=1.2, out_size=None, rgb=None, uvs=None, method='min_box', mesh_diameter=None): + '''Project the points and find the cropping transform + @pts: (N,3) + @poses: (B,4,4) tensor + @min_box: min_box/min_circle + @scale: scale to apply to the tightly enclosing roi + ''' + def compute_tf_batch(left, right, top, bottom): + B = len(left) + left = left.round() + right = right.round() + top = top.round() + bottom = bottom.round() + + tf = torch.eye(3)[None].expand(B,-1,-1).contiguous() + tf[:,0,2] = -left + tf[:,1,2] = -top + new_tf = torch.eye(3)[None].expand(B,-1,-1).contiguous() + new_tf[:,0,0] = out_size[0]/(right-left) + new_tf[:,1,1] = out_size[1]/(bottom-top) + tf = new_tf@tf + return tf + + B = len(poses) + torch.set_default_tensor_type('torch.cuda.FloatTensor') + if method=='box_3d': + radius = mesh_diameter*crop_ratio/2 + offsets = torch.tensor([0,0,0, + radius,0,0, + -radius,0,0, + 0,radius,0, + 0,-radius,0]).reshape(-1,3) + pts = poses[:,:3,3].reshape(-1,1,3)+offsets.reshape(1,-1,3) + K = torch.as_tensor(K).to(pts.dtype) + projected = (K@pts.reshape(-1,3).T).T + uvs = projected[:,:2]/projected[:,2:3] + uvs = uvs.reshape(B, -1, 2) + center = uvs[:,0] #(B,2) + radius = torch.abs(uvs-center.reshape(-1,1,2)).reshape(B,-1).max(axis=-1)[0].reshape(-1) #(B) + left = center[:,0]-radius + right = center[:,0]+radius + top = center[:,1]-radius + bottom = center[:,1]+radius + tfs = compute_tf_batch(left, right, top, bottom) + return tfs + + else: + raise RuntimeError + + return tf + + + +def cv_draw_text(img,text,uv_top_left,color=(255, 255, 255),fontScale=0.5,thickness=1,fontFace=cv2.FONT_HERSHEY_SIMPLEX,outline_color=None,line_spacing=1.5): + H,W = img.shape[:2] + uv_top_left = np.array(uv_top_left, dtype=float) + assert uv_top_left.shape == (2,) + + for line in text.splitlines(): + (w, h), _ = cv2.getTextSize(text=line,fontFace=fontFace,fontScale=fontScale,thickness=thickness,) + uv_bottom_left_i = uv_top_left + [0, h] + + ############# Ensure inside image + while uv_bottom_left_i[0]<0: + uv_bottom_left_i[0] += 1 + while uv_bottom_left_i[0]+w>=W: + uv_bottom_left_i[0] -= 1 + while uv_bottom_left_i[1]>=H: + uv_bottom_left_i[1] -= 1 + while uv_bottom_left_i[1]-h<0: + uv_bottom_left_i[1] += 1 + + org = tuple(uv_bottom_left_i.astype(int)) + + if outline_color is not None: + cv2.putText(img,text=line,org=org,fontFace=fontFace,fontScale=fontScale,color=outline_color,thickness=thickness,lineType=cv2.LINE_AA,) + cv2.putText(img,text=line,org=org,fontFace=fontFace,fontScale=fontScale,color=color,thickness=thickness,lineType=cv2.LINE_AA,) + uv_top_left[1] = uv_bottom_left_i[1]-h+h*line_spacing + return img + + +def trimesh_add_pure_colored_texture(mesh, color=np.array([255,255,255]), resolution=5): + tex_img = np.tile(color.reshape(1,1,3), (resolution, resolution, 1)).astype(np.uint8) + mesh = mesh.unwrap() + mesh.visual = trimesh.visual.texture.TextureVisuals(uv=mesh.visual.uv,image=Image.fromarray(tex_img)) + return mesh + + + + +def project_3d_to_2d(pt,K,ob_in_cam): + pt = pt.reshape(4,1) + projected = K @ ((ob_in_cam@pt)[:3,:]) + projected = projected.reshape(-1) + projected = projected/projected[2] + return projected.reshape(-1)[:2].round().astype(int) + + +def draw_xyz_axis(color, ob_in_cam, scale=0.1, K=np.eye(3), thickness=3, transparency=0,is_input_rgb=False): + ''' + @color: BGR + ''' + if is_input_rgb: + color = cv2.cvtColor(color,cv2.COLOR_RGB2BGR) + xx = np.array([1,0,0,1]).astype(float) + yy = np.array([0,1,0,1]).astype(float) + zz = np.array([0,0,1,1]).astype(float) + xx[:3] = xx[:3]*scale + yy[:3] = yy[:3]*scale + zz[:3] = zz[:3]*scale + origin = tuple(project_3d_to_2d(np.array([0,0,0,1]), K, ob_in_cam)) + xx = tuple(project_3d_to_2d(xx, K, ob_in_cam)) + yy = tuple(project_3d_to_2d(yy, K, ob_in_cam)) + zz = tuple(project_3d_to_2d(zz, K, ob_in_cam)) + line_type = cv2.LINE_AA + arrow_len = 0 + tmp = color.copy() + tmp1 = tmp.copy() + tmp1 = cv2.arrowedLine(tmp1, origin, xx, color=(0,0,255), thickness=thickness,line_type=line_type, tipLength=arrow_len) + mask = np.linalg.norm(tmp1-tmp, axis=-1)>0 + tmp[mask] = tmp[mask]*transparency + tmp1[mask]*(1-transparency) + tmp1 = tmp.copy() + tmp1 = cv2.arrowedLine(tmp1, origin, yy, color=(0,255,0), thickness=thickness,line_type=line_type, tipLength=arrow_len) + mask = np.linalg.norm(tmp1-tmp, axis=-1)>0 + tmp[mask] = tmp[mask]*transparency + tmp1[mask]*(1-transparency) + tmp1 = tmp.copy() + tmp1 = cv2.arrowedLine(tmp1, origin, zz, color=(255,0,0), thickness=thickness,line_type=line_type, tipLength=arrow_len) + mask = np.linalg.norm(tmp1-tmp, axis=-1)>0 + tmp[mask] = tmp[mask]*transparency + tmp1[mask]*(1-transparency) + tmp = tmp.astype(np.uint8) + if is_input_rgb: + tmp = cv2.cvtColor(tmp,cv2.COLOR_BGR2RGB) + + return tmp + + +def draw_posed_3d_box(K, img, ob_in_cam, bbox, line_color=(0,255,0), linewidth=2): + '''Revised from 6pack dataset/inference_dataset_nocs.py::projection + @bbox: (2,3) min/max + @line_color: RGB + ''' + min_xyz = bbox.min(axis=0) + xmin, ymin, zmin = min_xyz + max_xyz = bbox.max(axis=0) + xmax, ymax, zmax = max_xyz + + def draw_line3d(start,end,img): + pts = np.stack((start,end),axis=0).reshape(-1,3) + pts = (ob_in_cam@to_homo(pts).T).T[:,:3] #(2,3) + projected = (K@pts.T).T + uv = np.round(projected[:,:2]/projected[:,2].reshape(-1,1)).astype(int) #(2,2) + img = cv2.line(img, uv[0].tolist(), uv[1].tolist(), color=line_color, thickness=linewidth, lineType=cv2.LINE_AA) + return img + + for y in [ymin,ymax]: + for z in [zmin,zmax]: + start = np.array([xmin,y,z]) + end = start+np.array([xmax-xmin,0,0]) + img = draw_line3d(start,end,img) + + for x in [xmin,xmax]: + for z in [zmin,zmax]: + start = np.array([x,ymin,z]) + end = start+np.array([0,ymax-ymin,0]) + img = draw_line3d(start,end,img) + + for x in [xmin,xmax]: + for y in [ymin,ymax]: + start = np.array([x,y,zmin]) + end = start+np.array([0,0,zmax-zmin]) + img = draw_line3d(start,end,img) + + return img + + +def projection_matrix_from_intrinsics(K, height, width, znear, zfar, window_coords='y_down'): + """Conversion of Hartley-Zisserman intrinsic matrix to OpenGL proj. matrix. + + Ref: + 1) https://strawlab.org/2011/11/05/augmented-reality-with-OpenGL + 2) https://github.com/strawlab/opengl-hz/blob/master/src/calib_test_utils.py + + :param K: 3x3 ndarray with the intrinsic camera matrix. + :param x0 The X coordinate of the camera image origin (typically 0). + :param y0: The Y coordinate of the camera image origin (typically 0). + :param w: Image width. + :param h: Image height. + :param nc: Near clipping plane. + :param fc: Far clipping plane. + :param window_coords: 'y_up' or 'y_down'. + :return: 4x4 ndarray with the OpenGL projection matrix. + """ + x0 = 0 + y0 = 0 + w = width + h = height + nc = znear + fc = zfar + + depth = float(fc - nc) + q = -(fc + nc) / depth + qn = -2 * (fc * nc) / depth + + # Draw our images upside down, so that all the pixel-based coordinate + # systems are the same. + if window_coords == 'y_up': + proj = np.array([ + [2 * K[0, 0] / w, -2 * K[0, 1] / w, (-2 * K[0, 2] + w + 2 * x0) / w, 0], + [0, -2 * K[1, 1] / h, (-2 * K[1, 2] + h + 2 * y0) / h, 0], + [0, 0, q, qn], # Sets near and far planes (glPerspective). + [0, 0, -1, 0] + ]) + + # Draw the images upright and modify the projection matrix so that OpenGL + # will generate window coords that compensate for the flipped image coords. + elif window_coords == 'y_down': + proj = np.array([ + [2 * K[0, 0] / w, -2 * K[0, 1] / w, (-2 * K[0, 2] + w + 2 * x0) / w, 0], + [0, 2 * K[1, 1] / h, (2 * K[1, 2] - h + 2 * y0) / h, 0], + [0, 0, q, qn], # Sets near and far planes (glPerspective). + [0, 0, -1, 0] + ]) + else: + raise NotImplementedError + + return proj + + + +def symmetry_tfs_from_info(info, rot_angle_discrete=5): + symmetry_tfs = [np.eye(4)] + if 'symmetries_discrete' in info: + tfs = np.array(info['symmetries_discrete']).reshape(-1,4,4) + tfs[...,:3,3] *= 0.001 + symmetry_tfs = [np.eye(4)] + symmetry_tfs += list(tfs) + if 'symmetries_continuous' in info: + axis = np.array(info['symmetries_continuous'][0]['axis']).reshape(3) + offset = info['symmetries_continuous'][0]['offset'] + rxs = [0] + rys = [0] + rzs = [0] + if axis[0]>0: + rxs = np.arange(0,360,rot_angle_discrete)/180.0*np.pi + elif axis[1]>0: + rys = np.arange(0,360,rot_angle_discrete)/180.0*np.pi + elif axis[2]>0: + rzs = np.arange(0,360,rot_angle_discrete)/180.0*np.pi + for rx in rxs: + for ry in rys: + for rz in rzs: + tf = euler_matrix(rx, ry, rz) + tf[:3,3] = offset + symmetry_tfs.append(tf) + if len(symmetry_tfs)==0: + symmetry_tfs = [np.eye(4)] + symmetry_tfs = np.array(symmetry_tfs) + return symmetry_tfs + + + +def pose_to_egocentric_delta_pose(A_in_cam, B_in_cam): + '''Used for Pose Refinement. Given the object's two poses in camera, convert them to relative poses in camera's egocentric view + @A_in_cam: (B,4,4) torch tensor + ''' + trans_delta = B_in_cam[:,:3,3] - A_in_cam[:,:3,3] + rot_mat_delta = B_in_cam[:,:3,:3]@A_in_cam[:,:3,:3].permute(0,2,1) + return trans_delta, rot_mat_delta + + + +def egocentric_delta_pose_to_pose(A_in_cam, trans_delta, rot_mat_delta): + '''Used for Pose Refinement. Given the object's two poses in camera, convert them to relative poses in camera's egocentric view + @A_in_cam: (B,4,4) torch tensor + ''' + B_in_cam = torch.eye(4, dtype=torch.float, device=A_in_cam.device)[None].expand(len(A_in_cam),-1,-1).contiguous() + B_in_cam[:,:3,3] = A_in_cam[:,:3,3]+trans_delta + B_in_cam[:,:3,:3] = rot_mat_delta@A_in_cam[:,:3,:3] + return B_in_cam + + +def sdg_load_bounding_box(file_path: str): + """Load bounding boxes. + Args: + file_path: Path of the bounding box. + + Returns: + A dictionary of the bounding boxes. + """ + bbox_dict = {} + bbox_array = np.load(file_path) + for id, x_min, y_min, x_max, y_max, occlusion_ratio in zip( + bbox_array["semanticId"], + bbox_array["x_min"], + bbox_array["y_min"], + bbox_array["x_max"], + bbox_array["y_max"], + bbox_array["occlusionRatio"], + ): + bbox_dict[id] = { + "x_min": x_min, + "y_min": y_min, + "x_max": x_max, + "y_max": y_max, + "occlusion_ratio": occlusion_ratio, + } + return bbox_dict + + +def texture_map_interpolation(tex_image_numpy): + all_channels = [] + mask = np.all(tex_image_numpy == 0, axis=2) + x = np.arange(0, tex_image_numpy.shape[1]) + y = np.arange(0, tex_image_numpy.shape[0]) + xx, yy = np.meshgrid(x, y) + for each_channel in range(tex_image_numpy.shape[2]): + curr_channel = tex_image_numpy[:,:,each_channel] + x1 = xx[~mask] + y1 = yy[~mask] + newarr = curr_channel[~mask] + GD1 = griddata((x1, y1), newarr.ravel(), (xx, yy), method='nearest') + all_channels.append(GD1[:,:,np.newaxis].round().astype(np.uint8)) + final_image = np.concatenate(all_channels, axis =-1) + return final_image + + + +class OctreeManager: + def __init__(self,pts=None,max_level=None,octree=None): + import kaolin + if octree is None: + pts_quantized = kaolin.ops.spc.quantize_points(pts.contiguous(), level=max_level) + self.octree = kaolin.ops.spc.unbatched_points_to_octree(pts_quantized, max_level, sorted=False) + else: + self.octree = octree + lengths = torch.tensor([len(self.octree)], dtype=torch.int32).cpu() + self.max_level, self.pyramids, self.exsum = kaolin.ops.spc.scan_octrees(self.octree,lengths) + self.finest_vox_size = 2.0/(2**self.max_level) + self.n_level = self.max_level+1 + self.vox_point_all_levels = kaolin.ops.spc.generate_points(self.octree, self.pyramids, self.exsum) + self.point_hierarchy_dual, self.pyramid_dual = kaolin.ops.spc.unbatched_make_dual(self.vox_point_all_levels, self.pyramids[0]) + self.trinkets, self.pointers_to_parent = kaolin.ops.spc.unbatched_make_trinkets(self.vox_point_all_levels, self.pyramids[0], self.point_hierarchy_dual, self.pyramid_dual) + self.n_vox = len(self.vox_point_all_levels) + self.n_corners = len(self.point_hierarchy_dual) + + for level in range(self.n_level): + vox_pts = self.get_level_quantized_points(level) + corner_pts = self.get_level_corner_quantized_points(level) + logging.info(f'level:{level}, vox_pts:{vox_pts.shape}, corner_pts:{corner_pts.shape}') + + def get_level_corner_quantized_points(self,level): + start = self.pyramid_dual[...,1,level] + num = self.pyramid_dual[...,0,level] + return self.point_hierarchy_dual[start:start+num] + + def get_level_quantized_points(self,level): + start = self.pyramids[...,1,level] + num = self.pyramids[...,0,level] + return self.vox_point_all_levels[start:start+num] + + + def get_center_ids(self,x,level): + '''Get ids with 0 starting from current level's first point + ''' + import kaolin + pidx = kaolin.ops.spc.unbatched_query(self.octree, self.exsum, x.float(), level, with_parents=False) + return pidx + + + def get_vox_size_at_level(self, level): + return 2.0/(2**level) + + + def draw(self,level, method='point'): + import kaolin + logging.info(f"level:{level}") + vox_size = self.get_vox_size_at_level(level) + + if method=='point': + corner_coords = self.get_level_corner_quantized_points(level) + pts = corner_coords*vox_size - 1 + mesh = trimesh.points.PointCloud(pts.data.cpu().numpy().reshape(-1,3)) + return mesh + + + def ray_trace(self,rays_o,rays_d,level,debug=False): + """Octree is in normalized [-1,1] world coordinate frame + 'rays_o': ray origin in normalized world coordinate system + 'rays_d': (N,3) unit length ray direction in normalized world coordinate system + 'octree': spc + @voxel_size: in the scale of [-1,1] space + Return: + ray_depths_in_out: traveling times, NOT the Z value; invalid will be zeros + """ + from mycuda import common + import kaolin + + ray_index, rays_pid, depth_in_out = kaolin.render.spc.unbatched_raytrace(self.octree,self.vox_point_all_levels,self.pyramids[0],self.exsum,rays_o,rays_d,level=level,return_depth=True,with_exit=True) + if ray_index.size()[0] == 0: + pdb.set_trace() + print("[WARNING] batch has 0 intersections!!") + ray_depths_in_out = torch.zeros((rays_o.shape[0],1,2)) + rays_pid = -torch.ones_like(rays_o[:, :1]) + rays_near = torch.zeros_like(rays_o[:, :1]) + rays_far = torch.zeros_like(rays_o[:, :1]) + return rays_near, rays_far, rays_pid, ray_depths_in_out + + intersected_ray_ids,counts = torch.unique_consecutive(ray_index,return_counts=True) + max_intersections = counts.max().item() + start_poss = torch.cat([torch.tensor([0], device=counts.device),torch.cumsum(counts[:-1],dim=0)],dim=0) + + ray_depths_in_out = common.postprocessOctreeRayTracing(ray_index.long().contiguous(),depth_in_out.contiguous(),intersected_ray_ids.long().contiguous(),start_poss.long().contiguous(), max_intersections, rays_o.shape[0]) + + rays_far = ray_depths_in_out[:,:,1].max(dim=-1)[0].reshape(-1,1) + rays_near = ray_depths_in_out[:,0,0].reshape(-1,1) + + return rays_near, rays_far, rays_pid, ray_depths_in_out + + +def make_yaml_dumpable(D): + if isinstance(D, np.ndarray): + return D.tolist() + for d in D: + if isinstance(D[d], dict) or isinstance(D[d], OrderedDict) or isinstance(D[d], defaultdict): + D[d] = dict(D[d]) + D[d] = make_yaml_dumpable(D[d]) + continue + if isinstance(D[d], np.ndarray): + D[d] = D[d].tolist() + continue + if np.issubdtype(type(D[d]), int): + D[d] = int(D[d]) + continue + if np.issubdtype(type(D[d]), float): + D[d] = float(D[d]) + continue + if np.issubdtype(type(D[d]), str): + D[d] = str(D[d]) + continue + if isinstance(D[d], list): + for i in range(len(D[d])): + D[d][i] = make_yaml_dumpable(D[d][i]) + continue + return dict(D) diff --git a/third-party/video_to_data/reconstruction/modules/v2d_foundation_pose/lib/FoundationPose/assets/bop.jpg b/third-party/video_to_data/reconstruction/modules/v2d_foundation_pose/lib/FoundationPose/assets/bop.jpg new file mode 100644 index 0000000000000000000000000000000000000000..4fe26c367e44e5c4965781bee9b2b49a35224715 --- /dev/null +++ b/third-party/video_to_data/reconstruction/modules/v2d_foundation_pose/lib/FoundationPose/assets/bop.jpg @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:f4a652fb63bda0857ad15e4ec9fe4b64c4e347115f98422046b058a9f624e431 +size 296234 diff --git a/third-party/video_to_data/reconstruction/modules/v2d_foundation_pose/lib/FoundationPose/assets/demo.jpg b/third-party/video_to_data/reconstruction/modules/v2d_foundation_pose/lib/FoundationPose/assets/demo.jpg new file mode 100644 index 0000000000000000000000000000000000000000..21338efb8e4badba160430f72eb5c1d096d70726 --- /dev/null +++ b/third-party/video_to_data/reconstruction/modules/v2d_foundation_pose/lib/FoundationPose/assets/demo.jpg @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:113f7570aa8027baf8a7208418c359efbec27ae48fc7946147feaa7eb79575cf +size 57226 diff --git a/third-party/video_to_data/reconstruction/modules/v2d_foundation_pose/lib/FoundationPose/assets/demo_driller.jpg b/third-party/video_to_data/reconstruction/modules/v2d_foundation_pose/lib/FoundationPose/assets/demo_driller.jpg new file mode 100644 index 0000000000000000000000000000000000000000..8d266fccadbe8ee45afe7dfd461ebf65233b0aa1 --- /dev/null +++ b/third-party/video_to_data/reconstruction/modules/v2d_foundation_pose/lib/FoundationPose/assets/demo_driller.jpg @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:2fbd2e92a0b130b0b2d10c3424c32c01daa2d9d022379e1c8c85d84392f6a916 +size 1097680 diff --git a/third-party/video_to_data/reconstruction/modules/v2d_foundation_pose/lib/FoundationPose/assets/intro.jpg b/third-party/video_to_data/reconstruction/modules/v2d_foundation_pose/lib/FoundationPose/assets/intro.jpg new file mode 100644 index 0000000000000000000000000000000000000000..fb49334b6b0e732c1c2ae570211f0271082adef6 --- /dev/null +++ b/third-party/video_to_data/reconstruction/modules/v2d_foundation_pose/lib/FoundationPose/assets/intro.jpg @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:cfa81b32f18b670c67004dd96d08d4e2bdb8159b488f76cff67e7296924676a5 +size 2343023 diff --git a/third-party/video_to_data/reconstruction/modules/v2d_foundation_pose/lib/FoundationPose/build_all.sh b/third-party/video_to_data/reconstruction/modules/v2d_foundation_pose/lib/FoundationPose/build_all.sh new file mode 100644 index 0000000000000000000000000000000000000000..90937574a06a56189cae6adbdc4d45a1875fe498 --- /dev/null +++ b/third-party/video_to_data/reconstruction/modules/v2d_foundation_pose/lib/FoundationPose/build_all.sh @@ -0,0 +1,7 @@ +DIR=$(pwd) + +cd $DIR/mycpp/ && mkdir -p build && cd build && cmake .. -DPYTHON_EXECUTABLE=$(which python) && make -j11 +cd /kaolin && rm -rf build *egg* && pip install -e . +cd $DIR/bundlesdf/mycuda && rm -rf build *egg* && pip install -e . + +cd ${DIR} diff --git a/third-party/video_to_data/reconstruction/modules/v2d_foundation_pose/lib/FoundationPose/build_all_conda.sh b/third-party/video_to_data/reconstruction/modules/v2d_foundation_pose/lib/FoundationPose/build_all_conda.sh new file mode 100644 index 0000000000000000000000000000000000000000..9f88fde15c18d8f99c2ecc477ff6451a205c9e22 --- /dev/null +++ b/third-party/video_to_data/reconstruction/modules/v2d_foundation_pose/lib/FoundationPose/build_all_conda.sh @@ -0,0 +1,14 @@ +PROJ_ROOT=$( cd -- "$( dirname -- "${BASH_SOURCE[0]}" )" &> /dev/null && pwd ) + +# Install mycpp +cd ${PROJ_ROOT}/mycpp/ && \ +rm -rf build && mkdir -p build && cd build && \ +cmake .. && \ +make -j$(nproc) + +# Install mycuda +cd ${PROJ_ROOT}/bundlesdf/mycuda && \ +rm -rf build *egg* *.so && \ +python -m pip install -e . + +cd ${PROJ_ROOT} diff --git a/third-party/video_to_data/reconstruction/modules/v2d_foundation_pose/lib/FoundationPose/bundlesdf/config_linemod.yml b/third-party/video_to_data/reconstruction/modules/v2d_foundation_pose/lib/FoundationPose/bundlesdf/config_linemod.yml new file mode 100644 index 0000000000000000000000000000000000000000..d2cf07f2c54862c97691ec1c65c3f99c45630292 --- /dev/null +++ b/third-party/video_to_data/reconstruction/modules/v2d_foundation_pose/lib/FoundationPose/bundlesdf/config_linemod.yml @@ -0,0 +1,105 @@ +notes: '' +n_step: 1000 +netdepth: 8 +netwidth: 256 +netdepth_fine: 8 +netwidth_fine: 256 +N_rand: 2048 # Batch number of rays +first_frame_ray_in_batch: 0 +lrate: 0.01 +lrate_pose: 0.01 +pose_optimize_start: 0 +decay_rate: 0.1 +chunk: 99999999999 +netchunk: 6553600 +no_batching: 0 +amp: true + +N_samples: 128 #number of coarse samples per ray +N_samples_around_depth: 128 +N_importance: 0 +N_importance_iter: 1 +perturb: 1 +use_viewdirs: 1 +i_embed: 1 #set 1 for hashed embedding, 0 for default positional encoding, 2 for spherical; 3 for octree grid +i_embed_views: 2 #set 1 for hashed embedding, 0 for default positional encoding, 2 for spherical +multires: 8 #log2 of max freq for positional encoding (3D location) +multires_views: 3 #log2 of max freq for positional encoding (2D direction) +feature_grid_dim: 2 +raw_noise_std: 0 +white_bkgd: 0 +gradient_max_norm: 0.1 +gradient_pose_max_norm: 0.1 + +# logging/saving options +i_print: 500 +i_img: 500 +i_weights: 500 +i_mesh: 500 +i_nerf_normals: 500 +i_save_ray: 500 +i_pose: 500 +save_octree_clouds: True + +finest_res: 256 +base_res: 32 +num_levels: 16 +log2_hashmap_size: 22 +datadir: /mnt/9a72c439-d0a7-45e8-8d20-d7a235d02763/github/HashNeRF-pytorch/data/bundlesdf_bundlesdf_e03000196 +n_train_image: 300 +use_octree: 1 +first_frame_weight: 1 +denoise_depth_use_octree_cloud: true +octree_embed_base_voxel_size: 0.02 +octree_smallest_voxel_size: 0.02 # This determines the smallest feature vox size +octree_raytracing_voxel_size: 0.02 +octree_dilate_size: 0.02 # meters +down_scale_ratio: 1 +bounding_box: [[-1,-1,-1], [1,1,1]] +farthest_pose_sampling: 0 # Sampling train images. This replace uniform skip +use_mask: 1 +dilate_mask_size: 0 +rays_valid_depth_only: true +near: 0.1 +far: 2 +rgb_weight: 1 +depth_weight: 0 +trunc: 0.01 #length of the truncation region in meters +trunc_start: 0.01 +sdf_lambda: 5 +neg_trunc_ratio: 1 # -trunc distance ratio compared to +trunc +trunc_decay_type: '' +sdf_loss_type: l2 +fs_weight: 1000 +empty_weight: 1 +fs_rgb_weight: 0 +trunc_weight: 6000 +sparse_loss_weight: 0 +tv_loss_weight: 0 +frame_features: 2 #number of channels of the learnable per-frame features +optimize_poses: 1 #optimize a pose refinement for the initial poses +pose_reg_weight: 0 +point_cloud_loss_weight: 0 +point_cloud_loss_normal_weight: 0 +eikonal_weight: 0 +normal_loss_weight: 0 +feature_reg_weight: 0.1 +deformation_reg_weight: 0 +use_deformation_field: 0 #use a deformation field to account for inaccuracies in intrinsic parameters +max_pix_shift: 0.02 # Pixel shift ratio relative to image size +share_coarse_fine: 1 +mode: sdf +fs_sdf: 1 # Uncertain free space +crop: 0 +mesh_resolution: 0.003 +max_trans: 0.02 # meters +max_rot: 10 # deg + +continual: True + +######### dbscan +dbscan_eps: 0.01 +dbscan_eps_min_samples: 1 + +####### bundlenerf +sync_max_delay: 0 # 0 for strict sync \ No newline at end of file diff --git a/third-party/video_to_data/reconstruction/modules/v2d_foundation_pose/lib/FoundationPose/bundlesdf/config_ycbv.yml b/third-party/video_to_data/reconstruction/modules/v2d_foundation_pose/lib/FoundationPose/bundlesdf/config_ycbv.yml new file mode 100644 index 0000000000000000000000000000000000000000..620c654558cf9c9794306ee81963cfb0bb787eed --- /dev/null +++ b/third-party/video_to_data/reconstruction/modules/v2d_foundation_pose/lib/FoundationPose/bundlesdf/config_ycbv.yml @@ -0,0 +1,105 @@ +notes: '' +n_step: 1000 +netdepth: 8 +netwidth: 256 +netdepth_fine: 8 +netwidth_fine: 256 +N_rand: 2048 # Batch number of rays +first_frame_ray_in_batch: 0 +lrate: 0.01 +lrate_pose: 0.01 +pose_optimize_start: 0 +decay_rate: 0.1 +chunk: 99999999999 +netchunk: 6553600 +no_batching: 0 +amp: true + +N_samples: 128 #number of coarse samples per ray +N_samples_around_depth: 128 +N_importance: 0 +N_importance_iter: 1 +perturb: 1 +use_viewdirs: 1 +i_embed: 1 #set 1 for hashed embedding, 0 for default positional encoding, 2 for spherical; 3 for octree grid +i_embed_views: 2 #set 1 for hashed embedding, 0 for default positional encoding, 2 for spherical +multires: 8 #log2 of max freq for positional encoding (3D location) +multires_views: 3 #log2 of max freq for positional encoding (2D direction) +feature_grid_dim: 2 +raw_noise_std: 0 +white_bkgd: 0 +gradient_max_norm: 0.1 +gradient_pose_max_norm: 0.1 + +# logging/saving options +i_print: 500 +i_img: 500 +i_weights: 500 +i_mesh: 500 +i_nerf_normals: 500 +i_save_ray: 500 +i_pose: 500 +save_octree_clouds: True + +finest_res: 512 +base_res: 32 +num_levels: 16 +log2_hashmap_size: 22 +datadir: /mnt/9a72c439-d0a7-45e8-8d20-d7a235d02763/github/HashNeRF-pytorch/data/bundlesdf_bundlesdf_e03000196 +n_train_image: 300 +use_octree: 1 +first_frame_weight: 1 +denoise_depth_use_octree_cloud: true +octree_embed_base_voxel_size: 0.02 +octree_smallest_voxel_size: 0.02 # This determines the smallest feature vox size +octree_raytracing_voxel_size: 0.02 +octree_dilate_size: 0.02 # meters +down_scale_ratio: 1 +bounding_box: [[-1,-1,-1], [1,1,1]] +farthest_pose_sampling: 0 # Sampling train images. This replace uniform skip +use_mask: 1 +dilate_mask_size: 0 +rays_valid_depth_only: true +near: 0.1 +far: 2 +rgb_weight: 100 +depth_weight: 0 +trunc: 0.01 #length of the truncation region in meters +trunc_start: 0.01 +sdf_lambda: 5 +neg_trunc_ratio: 1 # -trunc distance ratio compared to +trunc +trunc_decay_type: '' +sdf_loss_type: l2 +fs_weight: 100 +empty_weight: 1 +fs_rgb_weight: 0 +trunc_weight: 6000 +sparse_loss_weight: 0 +tv_loss_weight: 0 +frame_features: 2 #number of channels of the learnable per-frame features +optimize_poses: 1 #optimize a pose refinement for the initial poses +pose_reg_weight: 0 +point_cloud_loss_weight: 0 +point_cloud_loss_normal_weight: 0 +eikonal_weight: 0 +normal_loss_weight: 0 +feature_reg_weight: 0.1 +deformation_reg_weight: 0 +use_deformation_field: 0 #use a deformation field to account for inaccuracies in intrinsic parameters +max_pix_shift: 0.02 # Pixel shift ratio relative to image size +share_coarse_fine: 1 +mode: sdf +fs_sdf: 1 # Uncertain free space +crop: 0 +mesh_resolution: 0.003 +max_trans: 0.02 # meters +max_rot: 10 # deg + +continual: True + +######### dbscan +dbscan_eps: 0.01 +dbscan_eps_min_samples: 1 + +####### bundlenerf +sync_max_delay: 0 # 0 for strict sync \ No newline at end of file diff --git a/third-party/video_to_data/reconstruction/modules/v2d_foundation_pose/lib/FoundationPose/bundlesdf/mycuda/__init__.py b/third-party/video_to_data/reconstruction/modules/v2d_foundation_pose/lib/FoundationPose/bundlesdf/mycuda/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/third-party/video_to_data/reconstruction/modules/v2d_foundation_pose/lib/FoundationPose/bundlesdf/mycuda/bindings.cpp b/third-party/video_to_data/reconstruction/modules/v2d_foundation_pose/lib/FoundationPose/bundlesdf/mycuda/bindings.cpp new file mode 100644 index 0000000000000000000000000000000000000000..605ffb44af1ac7a26a1c5a58dfea7e56431b1125 --- /dev/null +++ b/third-party/video_to_data/reconstruction/modules/v2d_foundation_pose/lib/FoundationPose/bundlesdf/mycuda/bindings.cpp @@ -0,0 +1,20 @@ +/* + * Copyright (c) 2023, NVIDIA CORPORATION. All rights reserved. + * + * NVIDIA CORPORATION and its licensors retain all intellectual property + * and proprietary rights in and to this software, related documentation + * and any modifications thereto. Any use, reproduction, disclosure or + * distribution of this software and related documentation without an express + * license agreement from NVIDIA CORPORATION is strictly prohibited. + */ + + +#include +#include "common.h" + +PYBIND11_MODULE(TORCH_EXTENSION_NAME, m) { + m.def("sampleRaysUniformOccupiedVoxels", &sampleRaysUniformOccupiedVoxels); + m.def("postprocessOctreeRayTracing", &postprocessOctreeRayTracing); + m.def("rayColorToTextureImageCUDA", &rayColorToTextureImageCUDA); + +} \ No newline at end of file diff --git a/third-party/video_to_data/reconstruction/modules/v2d_foundation_pose/lib/FoundationPose/bundlesdf/mycuda/common.cu b/third-party/video_to_data/reconstruction/modules/v2d_foundation_pose/lib/FoundationPose/bundlesdf/mycuda/common.cu new file mode 100644 index 0000000000000000000000000000000000000000..97974d2d1766bd01d059499fa3f71e3fb12794c4 --- /dev/null +++ b/third-party/video_to_data/reconstruction/modules/v2d_foundation_pose/lib/FoundationPose/bundlesdf/mycuda/common.cu @@ -0,0 +1,313 @@ +/* + * Copyright (c) 2023, NVIDIA CORPORATION. All rights reserved. + * + * NVIDIA CORPORATION and its licensors retain all intellectual property + * and proprietary rights in and to this software, related documentation + * and any modifications thereto. Any use, reproduction, disclosure or + * distribution of this software and related documentation without an express + * license agreement from NVIDIA CORPORATION is strictly prohibited. + */ + + + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include "common.h" +#include "Eigen/Dense" + + + + + +/** + * @brief + * + * @tparam scalar_t + * @param z_sampled + * @param z_in_out + * @param z_vals + * @return __global__ + */ +template +__global__ void sample_rays_uniform_occupied_voxels_kernel(const torch::PackedTensorAccessor32 z_sampled, const torch::PackedTensorAccessor32 z_in_out, torch::PackedTensorAccessor32 z_vals) +{ + const int i_ray = blockIdx.x * blockDim.x + threadIdx.x; + const int i_sample = blockIdx.y * blockDim.y + threadIdx.y; + if (i_ray>=z_sampled.size(0)) return; + if (i_sample>=z_sampled.size(1)) return; + + int i_box = 0; + float z_remain = z_sampled[i_ray][i_sample]; + auto z_in_out_cur_ray = z_in_out[i_ray]; + const float eps = 1e-4; + const int max_n_box = z_in_out.size(1); + + if (z_in_out_cur_ray[0][0]==0) return; + + while (1) + { + if (i_box>=max_n_box) + { + if (z_remain<=eps) + { + z_vals[i_ray][i_sample] = z_in_out_cur_ray[max_n_box-1][1]; + } + else + { + printf("ERROR sample_rays_uniform_occupied_voxels_kernel: z_remain=%f, i_ray=%d, i_sample=%d, i_box=%d, z_in_out_cur_ray=(%f,%f)\n",z_remain,i_ray,i_sample,i_box,z_in_out_cur_ray[i_box][0],z_in_out_cur_ray[i_box][1]); + for (int i=0;i=1) + { + z_vals[i_ray][i_sample] = z_in_out_cur_ray[i_box-1][1]; + return; + } + else + { + printf("ERROR sample_rays_uniform_occupied_voxels_kernel: z_remain=%f, i_ray=%d, i_sample=%d, i_box=%d, z_in_out_cur_ray=(%f,%f)\n",z_remain,i_ray,i_sample,i_box,z_in_out_cur_ray[i_box][0],z_in_out_cur_ray[i_box][1]); + for (int i=0;i<<<{divCeil(N_rays,threadx),divCeil(N_samples,thready)}, {threadx,thready}>>>(z_sampled.packed_accessor32(),z_in_out.packed_accessor32(),z_vals.packed_accessor32()); + })); + + return z_vals; +} + +template +__global__ void postprocessOctreeRayTracingKernel(const torch::PackedTensorAccessor32 ray_index, const torch::PackedTensorAccessor32 depth_in_out, const torch::PackedTensorAccessor32 unique_intersect_ray_ids, const torch::PackedTensorAccessor32 start_poss, torch::PackedTensorAccessor32 depths_in_out_padded) +{ + const int unique_id_pos = blockIdx.x * blockDim.x + threadIdx.x; + if (unique_id_pos>=unique_intersect_ray_ids.size(0)) return; + const int i_ray = unique_intersect_ray_ids[unique_id_pos]; + + int i_intersect = 0; + auto cur_depths_in_out_padded = depths_in_out_padded[i_ray]; + for (int i=start_poss[unique_id_pos];idepth_in_out[i][1]) continue; + if (abs(depth_in_out[i][1]-depth_in_out[i][0])<1e-4) continue; + + cur_depths_in_out_padded[i_intersect][0] = depth_in_out[i][0]; + cur_depths_in_out_padded[i_intersect][1] = depth_in_out[i][1]; + + i_intersect++; + + } +} + +at::Tensor postprocessOctreeRayTracing(const at::Tensor ray_index, const at::Tensor depth_in_out, const at::Tensor unique_intersect_ray_ids, const at::Tensor start_poss, const int max_intersections, const int N_rays) +{ + CHECK_INPUT(ray_index); + CHECK_INPUT(depth_in_out); + CHECK_INPUT(start_poss); + + const int n_unique_ids = unique_intersect_ray_ids.sizes()[0]; + at::Tensor depths_in_out_padded = at::zeros({N_rays,max_intersections,2}, torch::TensorOptions().dtype(torch::kFloat32).device(torch::kCUDA, 0).requires_grad(false)); + dim3 threads = {256}; + dim3 blocks = {divCeil(n_unique_ids,threads.x)}; + AT_DISPATCH_FLOATING_TYPES(depth_in_out.type(), "postprocessOctreeRayTracingKernel", ([&] + { + postprocessOctreeRayTracingKernel<<>>(ray_index.packed_accessor32(), depth_in_out.packed_accessor32(), unique_intersect_ray_ids.packed_accessor32(), start_poss.packed_accessor32(), depths_in_out_padded.packed_accessor32()); + })); + + return depths_in_out_padded; +} + + +at::Tensor calculateBarycentricCoordinate3D(const at::Tensor &triangle, const at::Tensor &p) +{ + auto vector_A = triangle[1]-triangle[2]; + auto vector_B = triangle[1]-triangle[0]; + auto normal = vector_A.cross(vector_B); + auto areaABC = (normal * at::cross(triangle[1]-triangle[0], triangle[2]-triangle[0])).sum(); + auto areaPBC = (normal * at::cross(triangle[1]-p, triangle[2]-p)).sum(); + auto areaPCA = (normal * at::cross(triangle[2]-p, triangle[0]-p)).sum(); + at::Tensor ws = at::zeros({3}).to(torch::kFloat32); + ws[0] = areaPBC / areaABC; + ws[1] = areaPCA / areaABC; + ws[2] = 1-ws[0]-ws[1]; + return ws; +} + + +__device__ Eigen::Vector3f calculateBarycentricCoordinate3DKernel(const Eigen::Matrix &triangle, const Eigen::Vector3f &p) +{ + Eigen::Vector3f vector_A = triangle.row(1)-triangle.row(2); + Eigen::Vector3f vector_B = triangle.row(1)-triangle.row(0); + Eigen::Vector3f normal = vector_A.cross(vector_B); + float areaABC = (normal.array() * (triangle.row(1)-triangle.row(0)).cross(triangle.row(2)-triangle.row(0)).transpose().array()).sum(); + float areaPBC = (normal.array() * (triangle.row(1).transpose()-p).cross(triangle.row(2).transpose()-p).array()).sum(); + float areaPCA = (normal.array() * (triangle.row(2).transpose()-p).cross(triangle.row(0).transpose()-p).array()).sum(); + Eigen::Vector3f w; + w[0] = areaPBC / areaABC; + w[1] = areaPCA / areaABC; + w[2] = 1-w[0]-w[1]; + return w; + +} + + +__device__ void calculateBarycentricCoordinate2DKernel(const Eigen::Matrix &triangle, const Eigen::Vector2f &p, Eigen::Vector3f &w) +{ + Eigen::Vector2f CA = triangle.row(0)-triangle.row(2); + Eigen::Vector2f AC = -CA; + Eigen::Vector2f CP = p-triangle.row(2).transpose(); + Eigen::Vector2f AB = triangle.row(1)-triangle.row(0); + Eigen::Vector2f AP = p-triangle.row(0).transpose(); + Eigen::Matrix2f numerator, denominator; + numerator << CA, CP; + denominator< +__global__ void rayColorToTextureImageKernel(const torch::PackedTensorAccessor32 F, const torch::PackedTensorAccessor32 V, const torch::PackedTensorAccessor32 hit_locations, const torch::PackedTensorAccessor32 hit_face_ids, const torch::PackedTensorAccessor32 uvs_tex, torch::PackedTensorAccessor32 uvs) +{ + const int i_hit = blockIdx.x*blockDim.x + threadIdx.x; + if (i_hit>=hit_locations.size(0)) return; + + auto face = F[hit_face_ids[i_hit]]; + Eigen::Matrix3f tri_v = Eigen::Matrix3f::Zero(); + for (int r=0;r<3;r++) + { + for (int c=0;c<3;c++) + { + tri_v(r,c) = V[face[r]][c]; + } + } + auto location = hit_locations[i_hit]; + Eigen::Vector3f p(location[0], location[1], location[2]); + auto w = calculateBarycentricCoordinate3DKernel(tri_v, p); + + Eigen::Matrix tri_uvs; + for (int i=0;i<3;i++) + { + for (int j=0;j<2;j++) + { + tri_uvs(i,j) = uvs_tex[face[i]][j]; + } + } + + Eigen::Vector2f cur_uv = tri_uvs.transpose() * w; + uvs[i_hit][0] = cur_uv(0); + uvs[i_hit][1] = cur_uv(1); +} + + + +void rayColorToTextureImageCUDA(const at::Tensor &F, const at::Tensor &V, const at::Tensor &hit_locations, const at::Tensor &hit_face_ids, const at::Tensor &uvs_tex, at::Tensor &uvs) +{ + CHECK_CONTIGUOUS(F); + CHECK_CONTIGUOUS(V); + CHECK_CONTIGUOUS(hit_locations); + CHECK_CONTIGUOUS(hit_face_ids); + CHECK_CONTIGUOUS(uvs_tex); + + dim3 threads = {512}; + dim3 blocks = {divCeil(int(hit_locations.sizes()[0]),threads.x)}; + + AT_DISPATCH_FLOATING_TYPES(V.type(), "rayColorToTextureImageKernel", ([&] + { + rayColorToTextureImageKernel<<>>(F.packed_accessor32(), V.packed_accessor32(), hit_locations.packed_accessor32(), hit_face_ids.packed_accessor32(), uvs_tex.packed_accessor32(), uvs.packed_accessor32()); + })); +} + + + +__device__ bool isLineIntersectLine(Eigen::Vector2f l1p1, Eigen::Vector2f l1p2, Eigen::Vector2f l2p1, Eigen::Vector2f l2p2) +{ + float q = (l1p1(1) - l2p1(1)) * (l2p2(0) - l2p1(0)) - (l1p1(0) - l2p1(0)) * (l2p2(1) - l2p1(1)); + float d = (l1p2(0) - l1p1(0)) * (l2p2(1) - l2p1(1)) - (l1p2(1) - l1p1(1)) * (l2p2(0) - l2p1(0)); + + if ( d == 0 ) + { + return false; + } + + float r = q / d; + + q = (l1p1(1) - l2p1(1)) * (l1p2(0) - l1p1(0)) - (l1p1(0) - l2p1(0)) * (l1p2(1) - l1p1(1)); + float s = q / d; + + if( r < 0 || r > 1 || s < 0 || s > 1 ) + { + return false; + } + + return true; +} + +__device__ bool isLineIntersectSquare(const Eigen::Vector2f &la, const Eigen::Vector2f &lb, const Eigen::Vector2f &p0, const Eigen::Vector2f &p1, const Eigen::Vector2f &p2, const Eigen::Vector2f &p3) +{ + return isLineIntersectLine(la, lb, p0, p1) || isLineIntersectLine(la, lb, p1, p2) || isLineIntersectLine(la, lb, p2, p3) || isLineIntersectLine(la, lb, p3, p0); +} + + +__device__ bool isPixelInsideTriangle(const Eigen::Matrix &triangle, Eigen::Vector2f p, Eigen::Vector3f &w) +{ + calculateBarycentricCoordinate2DKernel(triangle, p, w); + for (int j=0;j<3;j++) + { + if (w(j)<0) return false; + } + return true; +} diff --git a/third-party/video_to_data/reconstruction/modules/v2d_foundation_pose/lib/FoundationPose/bundlesdf/mycuda/common.h b/third-party/video_to_data/reconstruction/modules/v2d_foundation_pose/lib/FoundationPose/bundlesdf/mycuda/common.h new file mode 100644 index 0000000000000000000000000000000000000000..77d98cb166588a80f8bdde52bb9de3588bf69f71 --- /dev/null +++ b/third-party/video_to_data/reconstruction/modules/v2d_foundation_pose/lib/FoundationPose/bundlesdf/mycuda/common.h @@ -0,0 +1,30 @@ +/* + * Copyright (c) 2023, NVIDIA CORPORATION. All rights reserved. + * + * NVIDIA CORPORATION and its licensors retain all intellectual property + * and proprietary rights in and to this software, related documentation + * and any modifications thereto. Any use, reproduction, disclosure or + * distribution of this software and related documentation without an express + * license agreement from NVIDIA CORPORATION is strictly prohibited. + */ + + +#pragma once + +#include +#include + +#define CHECK_CUDA(x) AT_ASSERTM(x.is_cuda(), #x " must be a CUDA tensor") +#define CHECK_CONTIGUOUS(x) AT_ASSERTM(x.is_contiguous(), #x " must be contiguous") +#define CHECK_INPUT(x) CHECK_CUDA(x); CHECK_CONTIGUOUS(x) + + +inline int divCeil(int a, int b) +{ + return (a+b-1)/b; +}; + + +at::Tensor sampleRaysUniformOccupiedVoxels(const at::Tensor z_in_out, const at::Tensor z_sampled, at::Tensor z_vals); +at::Tensor postprocessOctreeRayTracing(const at::Tensor ray_index, const at::Tensor depth_in_out, const at::Tensor unique_intersect_ray_ids, const at::Tensor start_poss, const int max_intersections, const int N_rays); +void rayColorToTextureImageCUDA(const at::Tensor &F, const at::Tensor &V, const at::Tensor &hit_locations, const at::Tensor &hit_face_ids, const at::Tensor &uvs_tex, at::Tensor &uvs); \ No newline at end of file diff --git a/third-party/video_to_data/reconstruction/modules/v2d_foundation_pose/lib/FoundationPose/bundlesdf/mycuda/setup.py b/third-party/video_to_data/reconstruction/modules/v2d_foundation_pose/lib/FoundationPose/bundlesdf/mycuda/setup.py new file mode 100644 index 0000000000000000000000000000000000000000..55fa5967a0ef7d2b6b658f5a1d08b57aa0c54b29 --- /dev/null +++ b/third-party/video_to_data/reconstruction/modules/v2d_foundation_pose/lib/FoundationPose/bundlesdf/mycuda/setup.py @@ -0,0 +1,41 @@ +# Copyright (c) 2023, NVIDIA CORPORATION. All rights reserved. +# +# NVIDIA CORPORATION and its licensors retain all intellectual property +# and proprietary rights in and to this software, related documentation +# and any modifications thereto. Any use, reproduction, disclosure or +# distribution of this software and related documentation without an express +# license agreement from NVIDIA CORPORATION is strictly prohibited. + + +from setuptools import setup +import os,sys +from torch.utils.cpp_extension import BuildExtension, CUDAExtension +from torch.utils.cpp_extension import load + +code_dir = os.path.dirname(os.path.realpath(__file__)) + + +nvcc_flags = ['-Xcompiler', '-O3', '-std=c++17', '-U__CUDA_NO_HALF_OPERATORS__', '-U__CUDA_NO_HALF_CONVERSIONS__', '-U__CUDA_NO_HALF2_OPERATORS__'] +c_flags = ['-O3', '-std=c++17'] + +setup( + name='common', + extra_cflags=c_flags, + extra_cuda_cflags=nvcc_flags, + ext_modules=[ + CUDAExtension('common', [ + 'bindings.cpp', + 'common.cu', + ],extra_compile_args={'gcc': c_flags, 'nvcc': nvcc_flags}), + CUDAExtension('gridencoder', [ + f"{code_dir}/torch_ngp_grid_encoder/gridencoder.cu", + f"{code_dir}/torch_ngp_grid_encoder/bindings.cpp", + ],extra_compile_args={'gcc': c_flags, 'nvcc': nvcc_flags}), + ], + include_dirs=[ + "/usr/local/include/eigen3", + "/usr/include/eigen3", + ], + cmdclass={ + 'build_ext': BuildExtension +}) diff --git a/third-party/video_to_data/reconstruction/modules/v2d_foundation_pose/lib/FoundationPose/bundlesdf/mycuda/torch_ngp_grid_encoder/LICENSE b/third-party/video_to_data/reconstruction/modules/v2d_foundation_pose/lib/FoundationPose/bundlesdf/mycuda/torch_ngp_grid_encoder/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..56f524a263863d139bce3bef0f9c71a2c37a36ad --- /dev/null +++ b/third-party/video_to_data/reconstruction/modules/v2d_foundation_pose/lib/FoundationPose/bundlesdf/mycuda/torch_ngp_grid_encoder/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2022 hawkey + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. \ No newline at end of file diff --git a/third-party/video_to_data/reconstruction/modules/v2d_foundation_pose/lib/FoundationPose/bundlesdf/mycuda/torch_ngp_grid_encoder/bindings.cpp b/third-party/video_to_data/reconstruction/modules/v2d_foundation_pose/lib/FoundationPose/bundlesdf/mycuda/torch_ngp_grid_encoder/bindings.cpp new file mode 100644 index 0000000000000000000000000000000000000000..afa6f64fd7d7d1efc0380e279aad3ae3ca66c36f --- /dev/null +++ b/third-party/video_to_data/reconstruction/modules/v2d_foundation_pose/lib/FoundationPose/bundlesdf/mycuda/torch_ngp_grid_encoder/bindings.cpp @@ -0,0 +1,8 @@ +#include + +#include "gridencoder.h" + +PYBIND11_MODULE(TORCH_EXTENSION_NAME, m) { + m.def("grid_encode_forward", &grid_encode_forward, "grid_encode_forward (CUDA)"); + m.def("grid_encode_backward", &grid_encode_backward, "grid_encode_backward (CUDA)"); +} \ No newline at end of file diff --git a/third-party/video_to_data/reconstruction/modules/v2d_foundation_pose/lib/FoundationPose/bundlesdf/mycuda/torch_ngp_grid_encoder/grid.py b/third-party/video_to_data/reconstruction/modules/v2d_foundation_pose/lib/FoundationPose/bundlesdf/mycuda/torch_ngp_grid_encoder/grid.py new file mode 100644 index 0000000000000000000000000000000000000000..6573ce498c282b9aacaf76254b22d2e1a96bb63d --- /dev/null +++ b/third-party/video_to_data/reconstruction/modules/v2d_foundation_pose/lib/FoundationPose/bundlesdf/mycuda/torch_ngp_grid_encoder/grid.py @@ -0,0 +1,158 @@ +import numpy as np +import os,sys,pdb +code_dir = os.path.dirname(os.path.realpath(__file__)) +sys.path.append(code_dir) +import torch +import torch.nn as nn +from torch.autograd import Function +from torch.autograd.function import once_differentiable +from torch.cuda.amp import custom_bwd, custom_fwd +from setuptools import setup +from torch.utils.cpp_extension import BuildExtension, CUDAExtension +from torch.utils.cpp_extension import load +import os,sys +import gridencoder + + +_gridtype_to_id = { + 'hash': 0, + 'tiled': 1, +} + +class _grid_encode(Function): + @staticmethod + @custom_fwd + def forward(ctx, inputs, embeddings, offsets, per_level_scale, base_resolution, calc_grad_inputs=False, gridtype=0, align_corners=False): + # inputs: [B, D], float in [0, 1] + # embeddings: [sO, C], float + # offsets: [L + 1], int + # RETURN: [B, F], float + + inputs = inputs.contiguous() + + B, D = inputs.shape + L = offsets.shape[0] - 1 + C = embeddings.shape[1] + S = np.log2(per_level_scale) + H = base_resolution + + if torch.is_autocast_enabled() and C % 2 == 0: + embeddings = embeddings.to(torch.half) + + outputs = torch.empty(L, B, C, device=inputs.device, dtype=embeddings.dtype) + + if calc_grad_inputs: + dy_dx = torch.empty(B, L * D * C, device=inputs.device, dtype=embeddings.dtype) + else: + dy_dx = torch.empty(1, device=inputs.device, dtype=embeddings.dtype) # placeholder... TODO: a better way? + + gridencoder.grid_encode_forward(inputs, embeddings, offsets, outputs, B, D, C, L, S, H, calc_grad_inputs, dy_dx, gridtype, align_corners) + + outputs = outputs.permute(1, 0, 2).reshape(B, L * C) + + ctx.save_for_backward(inputs, embeddings, offsets, dy_dx) + ctx.dims = [B, D, C, L, S, H, gridtype] + ctx.calc_grad_inputs = calc_grad_inputs + ctx.align_corners = align_corners + + return outputs + + @staticmethod + @custom_bwd + def backward(ctx, grad): + + inputs, embeddings, offsets, dy_dx = ctx.saved_tensors + B, D, C, L, S, H, gridtype = ctx.dims + calc_grad_inputs = ctx.calc_grad_inputs + align_corners = ctx.align_corners + + # grad: [B, L * C] --> [L, B, C] + grad = grad.view(B, L, C).permute(1, 0, 2).contiguous() + + grad_embeddings = torch.zeros_like(embeddings) + + if calc_grad_inputs: + grad_inputs = torch.zeros_like(inputs, dtype=embeddings.dtype) + else: + grad_inputs = torch.zeros(1, device=inputs.device, dtype=embeddings.dtype) + + gridencoder.grid_encode_backward(grad, inputs, embeddings, offsets, grad_embeddings, B, D, C, L, S, H, calc_grad_inputs, dy_dx, grad_inputs, gridtype, align_corners) + + if calc_grad_inputs: + grad_inputs = grad_inputs.to(inputs.dtype) + return grad_inputs, grad_embeddings, None, None, None, None, None, None + else: + return None, grad_embeddings, None, None, None, None, None, None + + +grid_encode = _grid_encode.apply + + +# https://github.com/ashawkey/torch-ngp/blob/main/gridencoder/grid.py +class GridEncoder(nn.Module): + def __init__(self, input_dim=3, n_levels=16, level_dim=2, base_resolution=16, log2_hashmap_size=19, desired_resolution=None, gridtype='hash', align_corners=False): + super().__init__() + + per_level_scale = np.exp2(np.log2(desired_resolution / base_resolution) / (n_levels - 1)) + + self.input_dim = input_dim # coord dims, 2 or 3 + self.n_levels = n_levels # num levels, each level multiply resolution by 2 + self.level_dim = level_dim # encode channels per level + self.per_level_scale = per_level_scale # multiply resolution by this scale at each level. + self.log2_hashmap_size = log2_hashmap_size + self.base_resolution = base_resolution + self.out_dim = n_levels * level_dim + self.gridtype = gridtype + self.gridtype_id = _gridtype_to_id[gridtype] # "tiled" or "hash" + self.align_corners = align_corners + + # allocate parameters + offsets = [] + offset = 0 + self.max_params = 2 ** log2_hashmap_size + for i in range(n_levels): + resolution = int(np.ceil(base_resolution * per_level_scale ** i)) + params_in_level = min(self.max_params, (resolution if align_corners else resolution + 1) ** input_dim) # limit max number + params_in_level = int(np.ceil(params_in_level / 8) * 8) # make divisible + print(f"level {i}, resolution: {resolution}") + offsets.append(offset) + offset += params_in_level + offsets.append(offset) + offsets = torch.from_numpy(np.array(offsets, dtype=np.int32)) + self.register_buffer('offsets', offsets) + + self.n_params = offsets[-1] * level_dim + + # parameters + self.embeddings = nn.Parameter(torch.empty(offset, level_dim)) + # self.embeddings = nn.Embedding(offset, level_dim, sparse=True) + + self.reset_parameters() + + def reset_parameters(self): + std = 1e-4 + self.embeddings.data.uniform_(-std, std) + # self.embeddings.weight.data.uniform_(-std, std) + + + def __repr__(self): + return f"GridEncoder: input_dim={self.input_dim} n_levels={self.n_levels} level_dim={self.level_dim} resolution={self.base_resolution} -> {int(round(self.base_resolution * self.per_level_scale ** (self.n_levels - 1)))} per_level_scale={self.per_level_scale:.4f} params={tuple(self.embeddings.shape)} gridtype={self.gridtype} align_corners={self.align_corners}" + + + def forward(self, inputs, bound=1): + # inputs: [..., input_dim], normalized real world positions in [-bound, bound] + # return: [..., num_levels * level_dim] + + inputs = (inputs + bound) / (2 * bound) # map to [0, 1] + + #print('inputs', inputs.shape, inputs.dtype, inputs.min().item(), inputs.max().item()) + + prefix_shape = list(inputs.shape[:-1]) + inputs = inputs.view(-1, self.input_dim) + + outputs = grid_encode(inputs, self.embeddings, self.offsets, self.per_level_scale, self.base_resolution, inputs.requires_grad, self.gridtype_id, self.align_corners) + outputs = outputs.view(prefix_shape + [self.out_dim]) + + #print('outputs', outputs.shape, outputs.dtype, outputs.min().item(), outputs.max().item()) + + return outputs \ No newline at end of file diff --git a/third-party/video_to_data/reconstruction/modules/v2d_foundation_pose/lib/FoundationPose/bundlesdf/mycuda/torch_ngp_grid_encoder/gridencoder.cu b/third-party/video_to_data/reconstruction/modules/v2d_foundation_pose/lib/FoundationPose/bundlesdf/mycuda/torch_ngp_grid_encoder/gridencoder.cu new file mode 100644 index 0000000000000000000000000000000000000000..6bb45c7133f2d9a6d577c74137d5c28a6c27f868 --- /dev/null +++ b/third-party/video_to_data/reconstruction/modules/v2d_foundation_pose/lib/FoundationPose/bundlesdf/mycuda/torch_ngp_grid_encoder/gridencoder.cu @@ -0,0 +1,500 @@ +#include +#include +#include + +#include +#include + +#include +#include + +#include +#include + + +#define CHECK_CUDA(x) TORCH_CHECK(x.device().is_cuda(), #x " must be a CUDA tensor") +#define CHECK_CONTIGUOUS(x) TORCH_CHECK(x.is_contiguous(), #x " must be a contiguous tensor") +#define CHECK_IS_INT(x) TORCH_CHECK(x.scalar_type() == at::ScalarType::Int, #x " must be an int tensor") +#define CHECK_IS_FLOATING(x) TORCH_CHECK(x.scalar_type() == at::ScalarType::Float || x.scalar_type() == at::ScalarType::Half || x.scalar_type() == at::ScalarType::Double, #x " must be a floating tensor") + + +// just for compatability of half precision in AT_DISPATCH_FLOATING_TYPES_AND_HALF... +static inline __device__ at::Half atomicAdd(at::Half *address, at::Half val) { + // requires CUDA >= 10 and ARCH >= 70 + // this is very slow compared to float or __half2, and never used. + //return atomicAdd(reinterpret_cast<__half*>(address), val); +} + + +template +static inline __host__ __device__ T div_round_up(T val, T divisor) { + return (val + divisor - 1) / divisor; +} + + +template +__device__ uint32_t fast_hash(const uint32_t pos_grid[D]) { + static_assert(D <= 7, "fast_hash can only hash up to 7 dimensions."); + + // While 1 is technically not a good prime for hashing (or a prime at all), it helps memory coherence + // and is sufficient for our use case of obtaining a uniformly colliding index from high-dimensional + // coordinates. + constexpr uint32_t primes[7] = { 1, 2654435761, 805459861, 3674653429, 2097192037, 1434869437, 2165219737 }; + + uint32_t result = 0; + #pragma unroll + for (uint32_t i = 0; i < D; ++i) { + result ^= pos_grid[i] * primes[i]; + } + + return result; +} + + +template +__device__ uint32_t get_grid_index(const uint32_t gridtype, const bool align_corners, const uint32_t ch, const uint32_t hashmap_size, const uint32_t resolution, const uint32_t pos_grid[D]) { + uint32_t stride = 1; + uint32_t index = 0; + + #pragma unroll + for (uint32_t d = 0; d < D && stride <= hashmap_size; d++) { + index += pos_grid[d] * stride; + stride *= align_corners ? resolution: (resolution + 1); + } + + // NOTE: for NeRF, the hash is in fact not necessary. Check https://github.com/NVlabs/instant-ngp/issues/97. + // gridtype: 0 == hash, 1 == tiled + if (gridtype == 0 && stride > hashmap_size) { + index = fast_hash(pos_grid); + } + + return (index % hashmap_size) * C + ch; +} + + +/** + * @brief + * + * @tparam scalar_t + * @tparam D : point dimension usually 3D + * @tparam C : embedding dim 1/2/4 + * @param inputs + * @param grid + * @param offsets + * @param outputs + * @param B + * @param L + * @param S + * @param H + * @param calc_grad_inputs + * @param dy_dx + * @param gridtype + * @param align_corners + * @return __global__ + */ +template +__global__ void kernel_grid( + const float * __restrict__ inputs, + const scalar_t * __restrict__ grid, + const int * __restrict__ offsets, + scalar_t * __restrict__ outputs, + const uint32_t B, const uint32_t L, const float S, const uint32_t H, + const bool calc_grad_inputs, + scalar_t * __restrict__ dy_dx, + const uint32_t gridtype, + const bool align_corners +) { + const uint32_t b = blockIdx.x * blockDim.x + threadIdx.x; // batch id + + if (b >= B) return; + + const uint32_t level = blockIdx.y; + + // locate + grid += (uint32_t)offsets[level] * C; + inputs += b * D; + outputs += level * B * C + b * C; + + // check input range (should be in [0, 1]) + bool flag_oob = false; + #pragma unroll + for (uint32_t d = 0; d < D; d++) { + if (inputs[d] < 0 || inputs[d] > 1) { + flag_oob = true; + } + } + // if input out of bound, just set output to 0 + if (flag_oob) { + #pragma unroll + for (uint32_t ch = 0; ch < C; ch++) { + outputs[ch] = 0; + } + if (calc_grad_inputs) { + dy_dx += b * D * L * C + level * D * C; // B L D C + #pragma unroll + for (uint32_t d = 0; d < D; d++) { + #pragma unroll + for (uint32_t ch = 0; ch < C; ch++) { + dy_dx[d * C + ch] = 0; + } + } + } + return; + } + + const uint32_t hashmap_size = offsets[level + 1] - offsets[level]; + const float scale = exp2f(level * S) * H - 1.0f; + const uint32_t resolution = (uint32_t)ceil(scale) + 1; + + // calculate coordinate + float pos[D]; + uint32_t pos_grid[D]; + + #pragma unroll + for (uint32_t d = 0; d < D; d++) { + pos[d] = inputs[d] * scale + (align_corners ? 0.0f : 0.5f); + pos_grid[d] = floorf(pos[d]); + pos[d] -= (float)pos_grid[d]; + } + + //printf("[b=%d, l=%d] pos=(%f, %f)+(%d, %d)\n", b, level, pos[0], pos[1], pos_grid[0], pos_grid[1]); + + // interpolate + scalar_t results[C] = {0}; // temp results in register + + #pragma unroll + for (uint32_t idx = 0; idx < (1 << D); idx++) { + float w = 1; + uint32_t pos_grid_local[D]; + + #pragma unroll + for (uint32_t d = 0; d < D; d++) { + if ((idx & (1 << d)) == 0) { + w *= 1 - pos[d]; + pos_grid_local[d] = pos_grid[d]; + } else { + w *= pos[d]; + pos_grid_local[d] = pos_grid[d] + 1; + } + } + + uint32_t index = get_grid_index(gridtype, align_corners, 0, hashmap_size, resolution, pos_grid_local); // Hashing + + // writing to register (fast) + #pragma unroll + for (uint32_t ch = 0; ch < C; ch++) { + results[ch] += w * grid[index + ch]; + } + + //printf("[b=%d, l=%d] int %d, idx %d, w %f, val %f\n", b, level, idx, index, w, grid[index]); + } + + // writing to global memory (slow) + #pragma unroll + for (uint32_t ch = 0; ch < C; ch++) { + outputs[ch] = results[ch]; + } + + // prepare dy_dx for calc_grad_inputs + // differentiable (soft) indexing: https://discuss.pytorch.org/t/differentiable-indexing/17647/9 + if (calc_grad_inputs) { + + dy_dx += b * D * L * C + level * D * C; // B L D C + + #pragma unroll + for (uint32_t gd = 0; gd < D; gd++) { + + scalar_t results_grad[C] = {0}; + + #pragma unroll + for (uint32_t idx = 0; idx < (1 << (D - 1)); idx++) { + float w = scale; + uint32_t pos_grid_local[D]; + + #pragma unroll + for (uint32_t nd = 0; nd < D - 1; nd++) { + const uint32_t d = (nd >= gd) ? (nd + 1) : nd; + + if ((idx & (1 << nd)) == 0) { + w *= 1 - pos[d]; + pos_grid_local[d] = pos_grid[d]; + } else { + w *= pos[d]; + pos_grid_local[d] = pos_grid[d] + 1; + } + } + + pos_grid_local[gd] = pos_grid[gd]; + uint32_t index_left = get_grid_index(gridtype, align_corners, 0, hashmap_size, resolution, pos_grid_local); + pos_grid_local[gd] = pos_grid[gd] + 1; + uint32_t index_right = get_grid_index(gridtype, align_corners, 0, hashmap_size, resolution, pos_grid_local); + + #pragma unroll + for (uint32_t ch = 0; ch < C; ch++) { + results_grad[ch] += w * (grid[index_right + ch] - grid[index_left + ch]); + } + } + + #pragma unroll + for (uint32_t ch = 0; ch < C; ch++) { + dy_dx[gd * C + ch] = results_grad[ch]; + } + } + } +} + + +template +__global__ void kernel_grid_backward( + const scalar_t * __restrict__ grad, + const float * __restrict__ inputs, + const scalar_t * __restrict__ grid, + const int * __restrict__ offsets, + scalar_t * __restrict__ grad_grid, + const uint32_t B, const uint32_t L, const float S, const uint32_t H, + const uint32_t gridtype, + const bool align_corners +) { + const uint32_t b = (blockIdx.x * blockDim.x + threadIdx.x) * N_C / C; + if (b >= B) return; + + const uint32_t level = blockIdx.y; + const uint32_t ch = (blockIdx.x * blockDim.x + threadIdx.x) * N_C - b * C; + + // locate + grad_grid += offsets[level] * C; + inputs += b * D; + grad += level * B * C + b * C + ch; // L, B, C + + const uint32_t hashmap_size = offsets[level + 1] - offsets[level]; + const float scale = exp2f(level * S) * H - 1.0f; + const uint32_t resolution = (uint32_t)ceil(scale) + 1; + + // check input range (should be in [0, 1]) + #pragma unroll + for (uint32_t d = 0; d < D; d++) { + if (inputs[d] < 0 || inputs[d] > 1) { + return; // grad is init as 0, so we simply return. + } + } + + // calculate coordinate + float pos[D]; + uint32_t pos_grid[D]; + + #pragma unroll + for (uint32_t d = 0; d < D; d++) { + pos[d] = inputs[d] * scale + (align_corners ? 0.0f : 0.5f); + pos_grid[d] = floorf(pos[d]); + pos[d] -= (float)pos_grid[d]; + } + + scalar_t grad_cur[N_C] = {0}; // fetch to register + #pragma unroll + for (uint32_t c = 0; c < N_C; c++) { + grad_cur[c] = grad[c]; + } + + // interpolate + #pragma unroll + for (uint32_t idx = 0; idx < (1 << D); idx++) { + float w = 1; + uint32_t pos_grid_local[D]; + + #pragma unroll + for (uint32_t d = 0; d < D; d++) { + if ((idx & (1 << d)) == 0) { + w *= 1 - pos[d]; + pos_grid_local[d] = pos_grid[d]; + } else { + w *= pos[d]; + pos_grid_local[d] = pos_grid[d] + 1; + } + } + + uint32_t index = get_grid_index(gridtype, align_corners, ch, hashmap_size, resolution, pos_grid_local); + + // atomicAdd for __half is slow (especially for large values), so we use __half2 if N_C % 2 == 0 + // TODO: use float which is better than __half, if N_C % 2 != 0 + if (std::is_same::value && N_C % 2 == 0) { + #pragma unroll + for (uint32_t c = 0; c < N_C; c += 2) { + // process two __half at once (by interpreting as a __half2) + __half2 v = {(__half)(w * grad_cur[c]), (__half)(w * grad_cur[c + 1])}; + atomicAdd((__half2*)&grad_grid[index + c], v); + } + // float, or __half when N_C % 2 != 0 (which means C == 1) + } else { + #pragma unroll + for (uint32_t c = 0; c < N_C; c++) { + atomicAdd(&grad_grid[index + c], w * grad_cur[c]); + } + } + } +} + + +template +__global__ void kernel_input_backward( + const scalar_t * __restrict__ grad, + const scalar_t * __restrict__ dy_dx, + scalar_t * __restrict__ grad_inputs, + uint32_t B, uint32_t L +) { + const uint32_t t = threadIdx.x + blockIdx.x * blockDim.x; + if (t >= B * D) return; + + const uint32_t b = t / D; + const uint32_t d = t - b * D; + + dy_dx += b * L * D * C; + + scalar_t result = 0; + + # pragma unroll + for (int l = 0; l < L; l++) { + # pragma unroll + for (int ch = 0; ch < C; ch++) { + result += grad[l * B * C + b * C + ch] * dy_dx[l * D * C + d * C + ch]; + } + } + + grad_inputs[t] = result; +} + + +template +void kernel_grid_wrapper(const float *inputs, const scalar_t *embeddings, const int *offsets, scalar_t *outputs, const uint32_t B, const uint32_t C, const uint32_t L, const float S, const uint32_t H, const bool calc_grad_inputs, scalar_t *dy_dx, const uint32_t gridtype, const bool align_corners) { + static constexpr uint32_t N_THREAD = 512; + const dim3 blocks_hashgrid = { div_round_up(B, N_THREAD), L, 1 }; + switch (C) { + case 1: kernel_grid<<>>(inputs, embeddings, offsets, outputs, B, L, S, H, calc_grad_inputs, dy_dx, gridtype, align_corners); break; + case 2: kernel_grid<<>>(inputs, embeddings, offsets, outputs, B, L, S, H, calc_grad_inputs, dy_dx, gridtype, align_corners); break; + case 4: kernel_grid<<>>(inputs, embeddings, offsets, outputs, B, L, S, H, calc_grad_inputs, dy_dx, gridtype, align_corners); break; + case 8: kernel_grid<<>>(inputs, embeddings, offsets, outputs, B, L, S, H, calc_grad_inputs, dy_dx, gridtype, align_corners); break; + default: throw std::runtime_error{"GridEncoding: C must be 1, 2, 4, or 8."}; + } +} + +// inputs: [B, D], float, in [0, 1] +// embeddings: [sO, C], float +// offsets: [L + 1], uint32_t +// outputs: [L, B, C], float (L first, so only one level of hashmap needs to fit into cache at a time.) +// H: base resolution +// dy_dx: [B, L * D * C] +template +void grid_encode_forward_cuda(const float *inputs, const scalar_t *embeddings, const int *offsets, scalar_t *outputs, const uint32_t B, const uint32_t D, const uint32_t C, const uint32_t L, const float S, const uint32_t H, const bool calc_grad_inputs, scalar_t *dy_dx, const uint32_t gridtype, const bool align_corners) { + switch (D) { + case 1: kernel_grid_wrapper(inputs, embeddings, offsets, outputs, B, C, L, S, H, calc_grad_inputs, dy_dx, gridtype, align_corners); break; + case 2: kernel_grid_wrapper(inputs, embeddings, offsets, outputs, B, C, L, S, H, calc_grad_inputs, dy_dx, gridtype, align_corners); break; + case 3: kernel_grid_wrapper(inputs, embeddings, offsets, outputs, B, C, L, S, H, calc_grad_inputs, dy_dx, gridtype, align_corners); break; + case 4: kernel_grid_wrapper(inputs, embeddings, offsets, outputs, B, C, L, S, H, calc_grad_inputs, dy_dx, gridtype, align_corners); break; + case 5: kernel_grid_wrapper(inputs, embeddings, offsets, outputs, B, C, L, S, H, calc_grad_inputs, dy_dx, gridtype, align_corners); break; + default: throw std::runtime_error{"GridEncoding: D must be 1, 2, 3, 4, or 5."}; + } + +} + +template +void kernel_grid_backward_wrapper(const scalar_t *grad, const float *inputs, const scalar_t *embeddings, const int *offsets, scalar_t *grad_embeddings, const uint32_t B, const uint32_t C, const uint32_t L, const float S, const uint32_t H, const bool calc_grad_inputs, scalar_t *dy_dx, scalar_t *grad_inputs, const uint32_t gridtype, const bool align_corners) { + static constexpr uint32_t N_THREAD = 256; + const uint32_t N_C = std::min(2u, C); // n_features_per_thread + const dim3 blocks_hashgrid = { div_round_up(B * C / N_C, N_THREAD), L, 1 }; + switch (C) { + case 1: + kernel_grid_backward<<>>(grad, inputs, embeddings, offsets, grad_embeddings, B, L, S, H, gridtype, align_corners); + if (calc_grad_inputs) kernel_input_backward<<>>(grad, dy_dx, grad_inputs, B, L); + break; + case 2: + kernel_grid_backward<<>>(grad, inputs, embeddings, offsets, grad_embeddings, B, L, S, H, gridtype, align_corners); + if (calc_grad_inputs) kernel_input_backward<<>>(grad, dy_dx, grad_inputs, B, L); + break; + case 4: + kernel_grid_backward<<>>(grad, inputs, embeddings, offsets, grad_embeddings, B, L, S, H, gridtype, align_corners); + if (calc_grad_inputs) kernel_input_backward<<>>(grad, dy_dx, grad_inputs, B, L); + break; + case 8: + kernel_grid_backward<<>>(grad, inputs, embeddings, offsets, grad_embeddings, B, L, S, H, gridtype, align_corners); + if (calc_grad_inputs) kernel_input_backward<<>>(grad, dy_dx, grad_inputs, B, L); + break; + default: throw std::runtime_error{"GridEncoding: C must be 1, 2, 4, or 8."}; + } +} + + +// grad: [L, B, C], float +// inputs: [B, D], float, in [0, 1] +// embeddings: [sO, C], float +// offsets: [L + 1], uint32_t +// grad_embeddings: [sO, C] +// H: base resolution +template +void grid_encode_backward_cuda(const scalar_t *grad, const float *inputs, const scalar_t *embeddings, const int *offsets, scalar_t *grad_embeddings, const uint32_t B, const uint32_t D, const uint32_t C, const uint32_t L, const float S, const uint32_t H, const bool calc_grad_inputs, scalar_t *dy_dx, scalar_t *grad_inputs, const uint32_t gridtype, const bool align_corners) { + switch (D) { + case 1: kernel_grid_backward_wrapper(grad, inputs, embeddings, offsets, grad_embeddings, B, C, L, S, H, calc_grad_inputs, dy_dx, grad_inputs, gridtype, align_corners); break; + case 2: kernel_grid_backward_wrapper(grad, inputs, embeddings, offsets, grad_embeddings, B, C, L, S, H, calc_grad_inputs, dy_dx, grad_inputs, gridtype, align_corners); break; + case 3: kernel_grid_backward_wrapper(grad, inputs, embeddings, offsets, grad_embeddings, B, C, L, S, H, calc_grad_inputs, dy_dx, grad_inputs, gridtype, align_corners); break; + case 4: kernel_grid_backward_wrapper(grad, inputs, embeddings, offsets, grad_embeddings, B, C, L, S, H, calc_grad_inputs, dy_dx, grad_inputs, gridtype, align_corners); break; + case 5: kernel_grid_backward_wrapper(grad, inputs, embeddings, offsets, grad_embeddings, B, C, L, S, H, calc_grad_inputs, dy_dx, grad_inputs, gridtype, align_corners); break; + default: throw std::runtime_error{"GridEncoding: D must be 1, 2, 3, 4, or 5."}; + } +} + + + +void grid_encode_forward(const at::Tensor inputs, const at::Tensor embeddings, const at::Tensor offsets, at::Tensor outputs, const uint32_t B, const uint32_t D, const uint32_t C, const uint32_t L, const float S, const uint32_t H, const bool calc_grad_inputs, at::Tensor dy_dx, const uint32_t gridtype, const bool align_corners) { + CHECK_CUDA(inputs); + CHECK_CUDA(embeddings); + CHECK_CUDA(offsets); + CHECK_CUDA(outputs); + CHECK_CUDA(dy_dx); + + CHECK_CONTIGUOUS(inputs); + CHECK_CONTIGUOUS(embeddings); + CHECK_CONTIGUOUS(offsets); + CHECK_CONTIGUOUS(outputs); + CHECK_CONTIGUOUS(dy_dx); + + CHECK_IS_FLOATING(inputs); + CHECK_IS_FLOATING(embeddings); + CHECK_IS_INT(offsets); + CHECK_IS_FLOATING(outputs); + CHECK_IS_FLOATING(dy_dx); + + AT_DISPATCH_FLOATING_TYPES_AND_HALF( + embeddings.scalar_type(), "grid_encode_forward", ([&] { + grid_encode_forward_cuda(inputs.data_ptr(), embeddings.data_ptr(), offsets.data_ptr(), outputs.data_ptr(), B, D, C, L, S, H, calc_grad_inputs, dy_dx.data_ptr(), gridtype, align_corners); + })); +} + +void grid_encode_backward(const at::Tensor grad, const at::Tensor inputs, const at::Tensor embeddings, const at::Tensor offsets, at::Tensor grad_embeddings, const uint32_t B, const uint32_t D, const uint32_t C, const uint32_t L, const float S, const uint32_t H, const bool calc_grad_inputs, const at::Tensor dy_dx, at::Tensor grad_inputs, const uint32_t gridtype, const bool align_corners) { + CHECK_CUDA(grad); + CHECK_CUDA(inputs); + CHECK_CUDA(embeddings); + CHECK_CUDA(offsets); + CHECK_CUDA(grad_embeddings); + CHECK_CUDA(dy_dx); + CHECK_CUDA(grad_inputs); + + CHECK_CONTIGUOUS(grad); + CHECK_CONTIGUOUS(inputs); + CHECK_CONTIGUOUS(embeddings); + CHECK_CONTIGUOUS(offsets); + CHECK_CONTIGUOUS(grad_embeddings); + CHECK_CONTIGUOUS(dy_dx); + CHECK_CONTIGUOUS(grad_inputs); + + CHECK_IS_FLOATING(grad); + CHECK_IS_FLOATING(inputs); + CHECK_IS_FLOATING(embeddings); + CHECK_IS_INT(offsets); + CHECK_IS_FLOATING(grad_embeddings); + CHECK_IS_FLOATING(dy_dx); + CHECK_IS_FLOATING(grad_inputs); + + AT_DISPATCH_FLOATING_TYPES_AND_HALF( + grad.scalar_type(), "grid_encode_backward", ([&] { + grid_encode_backward_cuda(grad.data_ptr(), inputs.data_ptr(), embeddings.data_ptr(), offsets.data_ptr(), grad_embeddings.data_ptr(), B, D, C, L, S, H, calc_grad_inputs, dy_dx.data_ptr(), grad_inputs.data_ptr(), gridtype, align_corners); + })); + +} diff --git a/third-party/video_to_data/reconstruction/modules/v2d_foundation_pose/lib/FoundationPose/bundlesdf/mycuda/torch_ngp_grid_encoder/gridencoder.h b/third-party/video_to_data/reconstruction/modules/v2d_foundation_pose/lib/FoundationPose/bundlesdf/mycuda/torch_ngp_grid_encoder/gridencoder.h new file mode 100644 index 0000000000000000000000000000000000000000..b093e78272ee55a309fadfa08db6a2943c247700 --- /dev/null +++ b/third-party/video_to_data/reconstruction/modules/v2d_foundation_pose/lib/FoundationPose/bundlesdf/mycuda/torch_ngp_grid_encoder/gridencoder.h @@ -0,0 +1,15 @@ +#ifndef _HASH_ENCODE_H +#define _HASH_ENCODE_H + +#include +#include + +// inputs: [B, D], float, in [0, 1] +// embeddings: [sO, C], float +// offsets: [L + 1], uint32_t +// outputs: [B, L * C], float +// H: base resolution +void grid_encode_forward(const at::Tensor inputs, const at::Tensor embeddings, const at::Tensor offsets, at::Tensor outputs, const uint32_t B, const uint32_t D, const uint32_t C, const uint32_t L, const float S, const uint32_t H, const bool calc_grad_inputs, at::Tensor dy_dx, const uint32_t gridtype, const bool align_corners); +void grid_encode_backward(const at::Tensor grad, const at::Tensor inputs, const at::Tensor embeddings, const at::Tensor offsets, at::Tensor grad_embeddings, const uint32_t B, const uint32_t D, const uint32_t C, const uint32_t L, const float S, const uint32_t H, const bool calc_grad_inputs, const at::Tensor dy_dx, at::Tensor grad_inputs, const uint32_t gridtype, const bool align_corners); + +#endif \ No newline at end of file diff --git a/third-party/video_to_data/reconstruction/modules/v2d_foundation_pose/lib/FoundationPose/bundlesdf/nerf_helpers.py b/third-party/video_to_data/reconstruction/modules/v2d_foundation_pose/lib/FoundationPose/bundlesdf/nerf_helpers.py new file mode 100644 index 0000000000000000000000000000000000000000..0b8e0f2f4a23c4fb5e1ba5a365502aedbb742cf8 --- /dev/null +++ b/third-party/video_to_data/reconstruction/modules/v2d_foundation_pose/lib/FoundationPose/bundlesdf/nerf_helpers.py @@ -0,0 +1,475 @@ +# Copyright (c) 2023, NVIDIA CORPORATION. All rights reserved. +# +# NVIDIA CORPORATION and its licensors retain all intellectual property +# and proprietary rights in and to this software, related documentation +# and any modifications thereto. Any use, reproduction, disclosure or +# distribution of this software and related documentation without an express +# license agreement from NVIDIA CORPORATION is strictly prohibited. + + +import torch,pdb,os,sys +import torch.nn as nn +import torch.nn.functional as F +import numpy as np +code_dir = os.path.dirname(os.path.realpath(__file__)) +sys.path.append(f'{code_dir}/../') +from Utils import * +from pytorch3d.transforms import so3_log_map,so3_exp_map,se3_exp_map + +img2mse = lambda x, y : torch.mean((x - y) ** 2) +img2mae = lambda x, y: (torch.abs(x - y)).mean() +mse2psnr = lambda x : -10. * torch.log(x) / torch.log(torch.Tensor([10.])) +to8b = lambda x : (255*np.clip(x,0,1)).astype(np.uint8) + + +class FeatureArray(nn.Module): + """ + Per-frame corrective latent code. + """ + + def __init__(self, num_frames, num_channels): + super().__init__() + + self.num_frames = num_frames + self.num_channels = num_channels + + self.data = nn.parameter.Parameter(torch.normal(0,1,size=[num_frames, num_channels]).float(), requires_grad=True) + self.register_parameter('data',self.data) + + + def __call__(self, ids): + return self.data[ids] + + +class PoseArray(nn.Module): + def __init__(self, num_frames,max_trans,max_rot): + super().__init__() + self.num_frames = num_frames + self.max_trans = max_trans + self.max_rot = max_rot + self.data = nn.parameter.Parameter(torch.zeros([num_frames, 6]).float(), requires_grad=True) + self.register_parameter('data',self.data) + + + def get_matrices(self,ids): + if not torch.is_tensor(ids): + ids = torch.tensor(ids).long() + theta = torch.tanh(self.data) + trans = theta[:,:3] * self.max_trans + rot = theta[:,3:6] * self.max_rot/180.0*np.pi + Ts_data = se3_exp_map(torch.cat((trans,rot),dim=-1)).permute(0,2,1) + Ts = torch.eye(4, device=self.data.device).reshape(1,4,4).repeat(len(ids),1,1) + mask = ids!=0 + Ts[mask] = Ts_data[ids[mask]] + return Ts + + + +class SHEncoder(nn.Module): + '''Spherical encoding + ''' + def __init__(self, input_dim=3, degree=4): + + super().__init__() + + self.input_dim = input_dim + self.degree = degree + + assert self.input_dim == 3 + assert self.degree >= 1 and self.degree <= 5 + + self.out_dim = degree ** 2 + + self.C0 = 0.28209479177387814 + self.C1 = 0.4886025119029199 + self.C2 = [ + 1.0925484305920792, + -1.0925484305920792, + 0.31539156525252005, + -1.0925484305920792, + 0.5462742152960396 + ] + self.C3 = [ + -0.5900435899266435, + 2.890611442640554, + -0.4570457994644658, + 0.3731763325901154, + -0.4570457994644658, + 1.445305721320277, + -0.5900435899266435 + ] + self.C4 = [ + 2.5033429417967046, + -1.7701307697799304, + 0.9461746957575601, + -0.6690465435572892, + 0.10578554691520431, + -0.6690465435572892, + 0.47308734787878004, + -1.7701307697799304, + 0.6258357354491761 + ] + + def forward(self, input, **kwargs): + + result = torch.empty((*input.shape[:-1], self.out_dim), dtype=input.dtype, device=input.device) + x, y, z = input.unbind(-1) + + result[..., 0] = self.C0 + if self.degree > 1: + result[..., 1] = -self.C1 * y + result[..., 2] = self.C1 * z + result[..., 3] = -self.C1 * x + if self.degree > 2: + xx, yy, zz = x * x, y * y, z * z + xy, yz, xz = x * y, y * z, x * z + result[..., 4] = self.C2[0] * xy + result[..., 5] = self.C2[1] * yz + result[..., 6] = self.C2[2] * (2.0 * zz - xx - yy) + #result[..., 6] = self.C2[2] * (3.0 * zz - 1) # xx + yy + zz == 1, but this will lead to different backward gradients, interesting... + result[..., 7] = self.C2[3] * xz + result[..., 8] = self.C2[4] * (xx - yy) + if self.degree > 3: + result[..., 9] = self.C3[0] * y * (3 * xx - yy) + result[..., 10] = self.C3[1] * xy * z + result[..., 11] = self.C3[2] * y * (4 * zz - xx - yy) + result[..., 12] = self.C3[3] * z * (2 * zz - 3 * xx - 3 * yy) + result[..., 13] = self.C3[4] * x * (4 * zz - xx - yy) + result[..., 14] = self.C3[5] * z * (xx - yy) + result[..., 15] = self.C3[6] * x * (xx - 3 * yy) + if self.degree > 4: + result[..., 16] = self.C4[0] * xy * (xx - yy) + result[..., 17] = self.C4[1] * yz * (3 * xx - yy) + result[..., 18] = self.C4[2] * xy * (7 * zz - 1) + result[..., 19] = self.C4[3] * yz * (7 * zz - 3) + result[..., 20] = self.C4[4] * (zz * (35 * zz - 30) + 3) + result[..., 21] = self.C4[5] * xz * (7 * zz - 3) + result[..., 22] = self.C4[6] * (xx - yy) * (7 * zz - 1) + result[..., 23] = self.C4[7] * xz * (xx - 3 * yy) + result[..., 24] = self.C4[8] * (xx * (xx - 3 * yy) - yy * (3 * xx - yy)) + + return result + + +class Embedder(nn.Module): + def __init__(self, **kwargs): + super().__init__() + self.kwargs = kwargs + self.create_embedding_fn() + + def create_embedding_fn(self): + embed_fns = [] + d = self.kwargs['input_dims'] + out_dim = 0 + if self.kwargs['include_input']: + embed_fns.append(lambda x : x) + out_dim += d + + max_freq = self.kwargs['max_freq_log2'] + N_freqs = self.kwargs['num_freqs'] + + if self.kwargs['log_sampling']: + freq_bands = 2.**torch.linspace(0., max_freq, steps=N_freqs) + else: + freq_bands = torch.linspace(2.**0., 2.**max_freq, steps=N_freqs) + + for freq in freq_bands: + for p_fn in self.kwargs['periodic_fns']: + embed_fns.append(lambda x, p_fn=p_fn, freq=freq : p_fn(x * freq)) + out_dim += d + + self.embed_fns = embed_fns + self.out_dim = out_dim + + def forward(self, inputs): + return torch.cat([fn(inputs) for fn in self.embed_fns], -1) + + +def get_embedder(multires, cfg, i=0, octree_m=None): + if i == -1: + return nn.Identity(), 3 + elif i==0: + embed_kwargs = { + 'include_input' : True, + 'input_dims' : 3, + 'max_freq_log2' : multires-1, + 'num_freqs' : multires, + 'log_sampling' : True, + 'periodic_fns' : [torch.sin, torch.cos], + } + + embed = Embedder(**embed_kwargs) + out_dim = embed.out_dim + elif i==1: + from mycuda.torch_ngp_grid_encoder.grid import GridEncoder + embed = GridEncoder(input_dim=3, n_levels=cfg['num_levels'], log2_hashmap_size=cfg['log2_hashmap_size'], desired_resolution=cfg['finest_res'], base_resolution=cfg['base_res'], level_dim=cfg['feature_grid_dim']) + print(embed) + out_dim = embed.out_dim + elif i==2: + embed = SHEncoder(degree=cfg['multires_views']) + out_dim = embed.out_dim + return embed, out_dim + + + +def mesh_to_real_world(mesh,pose_offset,translation,sc_factor): + ''' + @pose_offset: optimized delta pose of the first frame. Usually it's identity + ''' + mesh.vertices = mesh.vertices/sc_factor - np.array(translation).reshape(1,3) + mesh.apply_transform(pose_offset) + return mesh + + +def get_optimized_poses_in_real_world(poses_normalized, pose_array, sc_factor, translation): + ''' + @poses_normalized: np array, cam_in_ob (opengl convention), normalized to [-1,1] and centered + @pose_array: PoseArray, delta poses + Return: + cam_in_ob, real-world unit, opencv convention + ''' + original_poses = poses_normalized.copy() + original_poses[:, :3, 3] /= sc_factor # To true world scale + original_poses[:, :3, 3] -= translation + + # Apply pose transformation + tf = pose_array.get_matrices(np.arange(len(poses_normalized))).reshape(-1,4,4).data.cpu().numpy() + optimized_poses = tf@poses_normalized + + optimized_poses = np.array(optimized_poses).astype(np.float32) + optimized_poses[:, :3, 3] /= sc_factor + optimized_poses[:, :3, 3] -= translation + + original_init_ob_in_cam = optimized_poses[0].copy() + offset = np.linalg.inv(original_init_ob_in_cam)@original_poses[0] + for i in range(len(optimized_poses)): + new_ob_in_cam = optimized_poses[i]@offset + optimized_poses[i] = new_ob_in_cam + optimized_poses[i] = optimized_poses[i]@glcam_in_cvcam + + return optimized_poses,offset + +def preprocess_data(rgbs,depths,masks,normal_maps,poses,sc_factor,translation): + ''' + @rgbs: np array (N,H,W,3) + @depths: (N,H,W) + @masks: (N,H,W) + @normal_maps: (N,H,W,3) + @poses: (N,4,4) + ''' + depths[depths<0.001] = BAD_DEPTH + if masks is not None: + rgbs[masks==0] = BAD_COLOR + depths[masks==0] = BAD_DEPTH + if normal_maps is not None: + normal_maps[...,[1,2]] *= -1 # To OpenGL + normal_maps[masks==0] = 0 + masks = masks[...,None] + + rgbs = (rgbs / 255.0).astype(np.float32) + depths *= sc_factor + depths = depths[...,None] + poses[:, :3, 3] += translation + poses[:, :3, 3] *= sc_factor + return rgbs,depths,masks,normal_maps,poses + + +class NeRFSmall(nn.Module): + def __init__(self,num_layers=3,hidden_dim=64,geo_feat_dim=15,num_layers_color=4,hidden_dim_color=64,input_ch=3, input_ch_views=3): + super(NeRFSmall, self).__init__() + + self.input_ch = input_ch + self.input_ch_views = input_ch_views + + # sigma network + self.num_layers = num_layers + self.hidden_dim = hidden_dim + self.geo_feat_dim = geo_feat_dim + + sigma_net = [] + for l in range(num_layers): + if l == 0: + in_dim = self.input_ch + else: + in_dim = hidden_dim + + if l == num_layers - 1: + out_dim = 1 + self.geo_feat_dim # 1 sigma + 15 SH features for color + else: + out_dim = hidden_dim + + sigma_net.append(nn.Linear(in_dim, out_dim, bias=True)) + if l!=num_layers-1: + sigma_net.append(nn.ReLU(inplace=True)) + + self.sigma_net = nn.Sequential(*sigma_net) + torch.nn.init.constant_(self.sigma_net[-1].bias, 0.1) # Encourage last layer predict positive SDF + + # color network + self.num_layers_color = num_layers_color + self.hidden_dim_color = hidden_dim_color + + color_net = [] + for l in range(num_layers_color): + if l == 0: + in_dim = self.input_ch_views + self.geo_feat_dim + else: + in_dim = hidden_dim + + if l == num_layers_color - 1: + out_dim = 3 # 3 rgb + else: + out_dim = hidden_dim + + color_net.append(nn.Linear(in_dim, out_dim, bias=True)) + if l!=num_layers_color-1: + color_net.append(nn.ReLU(inplace=True)) + + self.color_net = nn.Sequential(*color_net) + + def forward_sdf(self,x): + ''' + @x: embedded positions + ''' + h = self.sigma_net(x) + sigma, geo_feat = h[..., 0], h[..., 1:] + return sigma + + + def forward(self, x): + x = x.float() + input_pts, input_views = torch.split(x, [self.input_ch, self.input_ch_views], dim=-1) + + # sigma + h = input_pts + h = self.sigma_net(h) + + sigma, geo_feat = h[..., 0], h[..., 1:] + + # color + h = torch.cat([input_views, geo_feat], dim=-1) + color = self.color_net(h) + + outputs = torch.cat([color, sigma.unsqueeze(dim=-1)], -1) + + return outputs + + +def sample_pdf(bins, weights, N_samples, det=False): + weights = weights + 1e-5 # prevent nans + pdf = weights / torch.sum(weights, -1, keepdim=True) + cdf = torch.cumsum(pdf, -1) + cdf = torch.cat([torch.zeros_like(cdf[...,:1]), cdf], -1) # (batch, len(bins)) + + if det: + u = torch.linspace(0., 1., steps=N_samples) + u = u.expand(list(cdf.shape[:-1]) + [N_samples]) + else: + u = torch.rand(list(cdf.shape[:-1]) + [N_samples]) + + u = u.contiguous() + inds = torch.searchsorted(cdf, u, right=True) + below = torch.max(torch.zeros_like(inds-1), inds-1) + above = torch.min((cdf.shape[-1]-1) * torch.ones_like(inds), inds) + inds_g = torch.stack([below, above], -1) # (batch, N_samples, 2) + + matched_shape = [inds_g.shape[0], inds_g.shape[1], cdf.shape[-1]] + cdf_g = torch.gather(cdf.unsqueeze(1).expand(matched_shape), 2, inds_g) + bins_g = torch.gather(bins.unsqueeze(1).expand(matched_shape), 2, inds_g) + + denom = (cdf_g[...,1]-cdf_g[...,0]) + denom = torch.where(denom<1e-5, torch.ones_like(denom), denom) + t = (u-cdf_g[...,0])/denom + samples = bins_g[...,0] + t * (bins_g[...,1]-bins_g[...,0]) + + return samples + + + +def get_camera_rays_np(H, W, K): + """Get ray origins, directions from a pinhole camera.""" + i, j = np.meshgrid(np.arange(W, dtype=np.float32), + np.arange(H, dtype=np.float32), indexing='xy') + dirs = np.stack([(i - K[0,2])/K[0,0], -(j - K[1,2])/K[1,1], -np.ones_like(i)], axis=-1) + return dirs + + + +def get_masks(z_vals, target_d, truncation, cfg, dir_norm=None): + valid_depth_mask = (target_d>=cfg['near']*cfg['sc_factor']) & (target_d<=cfg['far']*cfg['sc_factor']) + front_mask = (z_vals < target_d - truncation) + back_mask = (z_vals > target_d + truncation*cfg['neg_trunc_ratio']) + + sdf_mask = (1.0 - front_mask.float()) * (1.0 - back_mask.float()) * valid_depth_mask + + num_fs_samples = front_mask.sum() + num_sdf_samples = sdf_mask.sum() + num_samples = num_sdf_samples + num_fs_samples + fs_weight = 0.5 + sdf_weight = 1.0 - fs_weight + return front_mask.bool(), sdf_mask.bool(), fs_weight, sdf_weight + + +def get_sdf_loss(z_vals, target_d, predicted_sdf, truncation, cfg, return_mask=False, sample_weights=None, rays_d=None): + dir_norm = rays_d.norm(dim=-1,keepdim=True) + front_mask, sdf_mask, fs_weight, sdf_weight = get_masks(z_vals, target_d, truncation, cfg, dir_norm=dir_norm) + front_mask = front_mask.bool() + + mask = (target_d>cfg['far']*cfg['sc_factor']) & (predicted_sdf tymax) | (tymin > tmax)] = 0 + tmin[tymin>tmin] = tymin[tymin>tmin] + tmax[tymax tzmax) | (tzmin > tmax)] = 0 + tmin[tzmin>tmin] = tzmin[tzmin>tmin] #(N) + tmax[tzmax=0 + near = (dirs_unit*tmin.reshape(-1,1))[:,2] + far = (dirs_unit*tmax.reshape(-1,1))[:,2] + good_rays = rays[ishit] + near = near[ishit] + far = far[ishit] + near = np.abs(near) + far = np.abs(far) + good_rays = np.concatenate((good_rays,near.reshape(-1,1),far.reshape(-1,1)), axis=-1) #(N,8+2) + + return good_rays + +@torch.no_grad() +def sample_rays_uniform(N_samples,near,far,lindisp=False,perturb=True): + ''' + @near: (N_ray,1) + ''' + N_ray = near.shape[0] + t_vals = torch.linspace(0., 1., steps=N_samples, device=near.device).reshape(1,-1) + if not lindisp: + z_vals = near * (1.-t_vals) + far * (t_vals) + else: + z_vals = 1./(1./near * (1.-t_vals) + 1./far * (t_vals)) #(N_ray,N_sample) + + if perturb > 0.: + mids = .5 * (z_vals[...,1:] + z_vals[...,:-1]) + upper = torch.cat([mids, z_vals[...,-1:]], -1) + lower = torch.cat([z_vals[...,:1], mids], -1) + t_rand = torch.rand(z_vals.shape, device=far.device) + z_vals = lower + (upper - lower) * t_rand + z_vals = torch.clip(z_vals,near,far) + + return z_vals.reshape(N_ray,N_samples) + + +class DataLoader: + def __init__(self,rays,batch_size): + self.rays = rays + self.batch_size = batch_size + self.pos = 0 + self.ids = torch.randperm(len(self.rays)) + + def __next__(self): + if self.pos+self.batch_size0) & (rays[:,self.ray_depth_slice]<=self.cfg['far']*self.cfg['sc_factor']) + rays_dir = rays[mask][:,self.ray_dir_slice] + rays_depth = rays[mask][:,self.ray_depth_slice] + pts3d = rays_dir*rays_depth.reshape(-1,1) + frame_ids = rays[mask][:,self.ray_frame_id_slice].astype(int) + pts3d_w = (self.poses[frame_ids]@to_homo(pts3d)[...,None])[:,:3,0] + logging.info(f"Denoising rays based on octree cloud") + + kdtree = cKDTree(self.build_octree_pts) + dists,indices = kdtree.query(pts3d_w,k=1,workers=-1) + bad_mask = dists>0.02*self.cfg['sc_factor'] + bad_ids = np.arange(len(rays))[mask][bad_mask] + rays[bad_ids,self.ray_depth_slice] = BAD_DEPTH*self.cfg['sc_factor'] + rays[bad_ids, self.ray_type_slice] = 1 + rays = rays[rays[:,self.ray_type_slice]==0] + logging.info(f"bad_mask#={bad_mask.sum()}") + + rays = torch.tensor(rays, dtype=torch.float).cuda() + + self.rays = rays + print("rays",rays.shape) + self.data_loader = DataLoader(rays=self.rays, batch_size=self.cfg['N_rand']) + + + def create_nerf(self,device=torch.device("cuda")): + """Instantiate NeRF's MLP model. + """ + models = {} + embed_fn, input_ch = get_embedder(self.cfg['multires'], self.cfg, i=self.cfg['i_embed'], octree_m=self.octree_m) + embed_fn = embed_fn.to(device) + models['embed_fn'] = embed_fn + + input_ch_views = 0 + embeddirs_fn = None + if self.cfg['use_viewdirs']: + embeddirs_fn, input_ch_views = get_embedder(self.cfg['multires_views'], self.cfg, i=self.cfg['i_embed_views'], octree_m=self.octree_m) + models['embeddirs_fn'] = embeddirs_fn + + output_ch = 4 + skips = [4] + + model = NeRFSmall(num_layers=2,hidden_dim=64,geo_feat_dim=15,num_layers_color=3,hidden_dim_color=64,input_ch=input_ch, input_ch_views=input_ch_views+self.cfg['frame_features']).to(device) + model = model.to(device) + models['model'] = model + + model_fine = None + if self.cfg['N_importance'] > 0: + if not self.cfg['share_coarse_fine']: + model_fine = NeRFSmall(num_layers=2,hidden_dim=64,geo_feat_dim=15,num_layers_color=3,hidden_dim_color=64,input_ch=input_ch, input_ch_views=input_ch_views).to(device) + models['model_fine'] = model_fine + + # Create feature array + num_training_frames = len(self.images) + feature_array = None + if self.cfg['frame_features'] > 0: + feature_array = FeatureArray(num_training_frames, self.cfg['frame_features']).to(device) + models['feature_array'] = feature_array + # Create pose array + pose_array = None + if self.cfg['optimize_poses']: + pose_array = PoseArray(num_training_frames,max_trans=self.cfg['max_trans']*self.cfg['sc_factor'],max_rot=self.cfg['max_rot']).to(device) + models['pose_array'] = pose_array + self.models = models + + + + def make_frame_rays(self,frame_id): + mask = self.masks[frame_id,...,0].copy() + rays = get_camera_rays_np(self.H, self.W, self.K) # [self.H, self.W, 3] We create rays frame-by-frame to save memory + rays = np.concatenate([rays, self.images[frame_id]], -1) # [H, W, 6] + rays = np.concatenate([rays, self.depths[frame_id]], -1) # [H, W, 7] + rays = np.concatenate([rays, self.masks[frame_id]>0], -1) # [H, W, 8] + if self.normal_maps is not None: + rays = np.concatenate([rays, self.normal_maps[frame_id]], -1) # [H, W, 11] + rays = np.concatenate([rays, frame_id*np.ones(self.depths[frame_id].shape)], -1) # [H, W, 12] + ray_types = np.zeros((self.H,self.W,1)) # 0 is good; 1 is invalid depth (uncertain) + invalid_depth = ((self.depths[frame_id,...,0]self.cfg['far']*self.cfg['sc_factor'])) & (mask>0) + ray_types[invalid_depth] = 1 + rays = np.concatenate((rays,ray_types), axis=-1) + self.ray_dir_slice = [0,1,2] + self.ray_rgb_slice = [3,4,5] + self.ray_depth_slice = 6 + self.ray_mask_slice = 7 + if self.normal_maps is not None: + self.ray_normal_slice = [8,9,10] + self.ray_frame_id_slice = 11 + self.ray_type_slice = 12 + else: + self.ray_frame_id_slice = 8 + self.ray_type_slice = 9 + + n = rays.shape[-1] + + ########## Option2: dilate + down_scale_ratio = int(self.cfg['down_scale_ratio']) + if frame_id==0: #!NOTE first frame ob mask is assumed perfect + kernel = np.ones((100, 100), np.uint8) + mask = cv2.dilate(mask.astype(np.uint8), kernel, iterations=1) + if self.occ_masks is not None: + mask[self.occ_masks[frame_id]>0] = 0 + else: + dilate = 60//down_scale_ratio + kernel = np.ones((dilate, dilate), np.uint8) + mask = cv2.dilate(mask.astype(np.uint8), kernel, iterations=1) + if self.occ_masks is not None: + mask[self.occ_masks[frame_id]>0] = 0 + + + if self.cfg['rays_valid_depth_only']: + mask[invalid_depth] = 0 + + vs,us = np.where(mask>0) + cur_rays = rays[vs,us].reshape(-1,n) + cur_rays = cur_rays[cur_rays[:,self.ray_type_slice]==0] + cur_rays = compute_near_far_and_filter_rays(self.poses[frame_id],cur_rays,self.cfg) + if self.normal_maps is not None: + self.ray_near_slice = 13 + self.ray_far_slice = 14 + else: + self.ray_near_slice = 10 + self.ray_far_slice = 11 + + if self.cfg['use_octree']: + rays_o_world = (self.poses[frame_id]@to_homo(np.zeros((len(cur_rays),3))).T).T[:,:3] + rays_o_world = torch.from_numpy(rays_o_world).cuda().float() + rays_unit_d_cam = cur_rays[:,:3]/np.linalg.norm(cur_rays[:,:3],axis=-1).reshape(-1,1) + rays_d_world = (self.poses[frame_id][:3,:3]@rays_unit_d_cam.T).T + rays_d_world = torch.from_numpy(rays_d_world).cuda().float() + + vox_size = self.cfg['octree_raytracing_voxel_size']*self.cfg['sc_factor'] + level = int(np.floor(np.log2(2.0/vox_size))) + near,far,_,ray_depths_in_out = self.octree_m.ray_trace(rays_o_world,rays_d_world,level=level) + near = near.cpu().numpy() + valid = (near>0).reshape(-1) + cur_rays = cur_rays[valid] + + return cur_rays + + + def build_octree(self): + if self.cfg['save_octree_clouds']: + dir = f"{self.cfg['save_dir']}/build_octree_cloud.ply" + pcd = toOpen3dCloud(self.build_octree_pts) + o3d.io.write_point_cloud(dir,pcd) + if self._run is not None: + self._run.add_artifact(dir) + pts = torch.tensor(self.build_octree_pts).cuda().float() # Must be within [-1,1] + octree_smallest_voxel_size = self.cfg['octree_smallest_voxel_size']*self.cfg['sc_factor'] + finest_n_voxels = 2.0/octree_smallest_voxel_size + max_level = int(np.round(np.log2(finest_n_voxels))) + octree_smallest_voxel_size = 2.0/(2**max_level) + + #################### Dilate + dilate_radius = int(np.round(self.cfg['octree_dilate_size']/octree_smallest_voxel_size)) + dilate_radius = max(1, dilate_radius) + logging.info(f"Octree voxel dilate_radius:{dilate_radius}") + shifts = [] + for dx in [-1,0,1]: + for dy in [-1,0,1]: + for dz in [-1,0,1]: + shifts.append([dx,dy,dz]) + shifts = torch.tensor(shifts).cuda().long() # (27,3) + coords = torch.floor((pts+1)/octree_smallest_voxel_size).long() #(N,3) + dilated_coords = coords.detach().clone() + for iter in range(dilate_radius): + dilated_coords = (dilated_coords[None].expand(shifts.shape[0],-1,-1) + shifts[:,None]).reshape(-1,3) + dilated_coords = torch.unique(dilated_coords,dim=0) + pts = (dilated_coords+0.5) * octree_smallest_voxel_size - 1 + pts = torch.clip(pts,-1,1) + + if self.cfg['save_octree_clouds']: + pcd = toOpen3dCloud(pts.data.cpu().numpy()) + dir = f"{self.cfg['save_dir']}/build_octree_cloud_dilated.ply" + o3d.io.write_point_cloud(dir,pcd) + if self._run is not None: + self._run.add_artifact(dir) + #################### + + assert pts.min()>=-1 and pts.max()<=1 + self.octree_m = OctreeManager(pts, max_level) + + if self.cfg['save_octree_clouds']: + dir = f"{self.cfg['save_dir']}/octree_boxes_max_level.ply" + m = self.octree_m.draw(level=max_level,method='point') + m.export(dir) + if self._run is not None: + self._run.add_artifact(dir) + vox_size = self.cfg['octree_raytracing_voxel_size']*self.cfg['sc_factor'] + level = int(np.round(np.log2(2.0/vox_size))) + if self.cfg['save_octree_clouds']: + dir = f"{self.cfg['save_dir']}/octree_boxes_ray_tracing_level.ply" + m = self.octree_m.draw(level=level,method='point') + m.export(dir) + if self._run is not None: + self._run.add_artifact(dir) + + + def create_optimizer(self): + params = [] + for k in self.models: + if self.models[k] is not None and k!='pose_array': + params += list(self.models[k].parameters()) + + param_groups = [{'name':'basic', 'params':params, 'lr':self.cfg['lrate']}] + if self.models['pose_array'] is not None: + param_groups.append({'name':'pose_array', 'params':self.models['pose_array'].parameters(), 'lr':self.cfg['lrate_pose']}) + + self.optimizer = torch.optim.Adam(param_groups, betas=(0.9, 0.999),weight_decay=0,eps=1e-15) + + self.param_groups_init = copy.deepcopy(self.optimizer.param_groups) + + + def save_weights(self,out_file,models): + data = { + 'global_step': self.global_step, + 'model': models['model'].state_dict(), + 'optimizer': self.optimizer.state_dict(), + } + if 'model_fine' in models and models['model_fine'] is not None: + data['model_fine'] = models['model_fine'].state_dict() + if models['embed_fn'] is not None: + data['embed_fn'] = models['embed_fn'].state_dict() + if models['embeddirs_fn'] is not None: + data['embeddirs_fn'] = models['embeddirs_fn'].state_dict() + if self.cfg['optimize_poses']>0: + data['pose_array'] = models['pose_array'].state_dict() + if self.cfg['frame_features'] > 0: + data['feature_array'] = models['feature_array'].state_dict() + if self.octree_m is not None: + data['octree'] = self.octree_m.octree + dir = out_file + torch.save(data,dir) + print('Saved checkpoints at', dir) + if self._run is not None: + self._run.add_artifact(dir) + dir1 = copy.deepcopy(dir) + dir = f'{os.path.dirname(out_file)}/model_latest.pth' + if dir1!=dir: + os.system(f'cp {dir1} {dir}') + if self._run is not None: + self._run.add_artifact(dir) + + + def schedule_lr(self): + for i,param_group in enumerate(self.optimizer.param_groups): + init_lr = self.param_groups_init[i]['lr'] + new_lrate = init_lr * (self.cfg['decay_rate'] ** (float(self.global_step) / self.N_iters)) + param_group['lr'] = new_lrate + + + def render_images(self,img_i,cur_rays=None): + if cur_rays is None: + frame_ids = self.rays[:, self.ray_frame_id_slice].cuda() + cur_rays = self.rays[frame_ids==img_i].cuda() + gt_depth = cur_rays[:,self.ray_depth_slice] + gt_rgb = cur_rays[:,self.ray_rgb_slice].cpu() + ray_type = cur_rays[:,self.ray_type_slice].data.cpu().numpy() + + ori_chunk = self.cfg['chunk'] + self.cfg['chunk'] = copy.deepcopy(self.cfg['N_rand']) + with torch.no_grad(): + rgb, extras = self.render(rays=cur_rays, lindisp=False,perturb=False,raw_noise_std=0, depth=gt_depth) + self.cfg['chunk'] = ori_chunk + + sdf = extras['raw'][...,-1] + z_vals = extras['z_vals'] + signs = sdf[:, 1:] * sdf[:, :-1] + empty_rays = (signs>0).all(dim=-1) + mask = signs<0 + inds = torch.argmax(mask.float(), axis=1) + inds = inds[..., None] + depth = torch.gather(z_vals,dim=1,index=inds) + depth[empty_rays] = self.cfg['far']*self.cfg['sc_factor'] + depth = depth[..., None].data.cpu().numpy() + + rgb = rgb.data.cpu().numpy() + + rgb_full = np.zeros((self.H,self.W,3),dtype=float) + depth_full = np.zeros((self.H,self.W),dtype=float) + ray_mask_full = np.zeros((self.H,self.W,3),dtype=np.uint8) + X = cur_rays[:,self.ray_dir_slice].data.cpu().numpy() + X[:,[1,2]] = -X[:,[1,2]] + projected = (self.K@X.T).T + uvs = projected/projected[:,2].reshape(-1,1) + uvs = uvs.round().astype(int) + uvs_good = uvs[ray_type==0] + ray_mask_full[uvs_good[:,1],uvs_good[:,0]] = [255,0,0] + uvs_uncertain = uvs[ray_type==1] + ray_mask_full[uvs_uncertain[:,1],uvs_uncertain[:,0]] = [0,255,0] + rgb_full[uvs[:,1],uvs[:,0]] = rgb.reshape(-1,3) + depth_full[uvs[:,1],uvs[:,0]] = depth.reshape(-1) + gt_rgb_full = np.zeros((self.H,self.W,3),dtype=float) + gt_rgb_full[uvs[:,1],uvs[:,0]] = gt_rgb.reshape(-1,3).data.cpu().numpy() + gt_depth_full = np.zeros((self.H,self.W),dtype=float) + gt_depth_full[uvs[:,1],uvs[:,0]] = gt_depth.reshape(-1).data.cpu().numpy() + + return rgb_full, depth_full, ray_mask_full, gt_rgb_full, gt_depth_full, extras + + + def get_gradients(self): + if self.models['pose_array'] is not None: + max_pose_grad = torch.abs(self.models['pose_array'].data.grad).max() + max_embed_grad = 0 + for embed in self.models['embed_fn'].embeddings: + max_embed_grad = max(max_embed_grad,torch.abs(embed.weight.grad).max()) + if self.models['feature_array'] is not None: + max_feature_grad = torch.abs(self.models['feature_array'].data.grad).max() + return max_pose_grad, max_embed_grad, max_feature_grad + + + def get_truncation(self): + '''Annearl truncation over training + ''' + if self.cfg['trunc_decay_type']=='linear': + truncation = self.cfg['trunc_start'] - (self.cfg['trunc_start']-self.cfg['trunc']) * float(self.global_step)/self.cfg['n_step'] + elif self.cfg['trunc_decay_type']=='exp': + lamb = np.log(self.cfg['trunc']/self.cfg['trunc_start']) / (self.cfg['n_step']/4) + truncation = self.cfg['trunc_start']*np.exp(self.global_step*lamb) + truncation = max(truncation,self.cfg['trunc']) + else: + truncation = self.cfg['trunc'] + + truncation *= self.cfg['sc_factor'] + return truncation + + + def train_loop(self,batch): + target_s = batch[:, self.ray_rgb_slice] # Color (N,3) + target_d = batch[:, self.ray_depth_slice] # Normalized scale (N) + + target_mask = batch[:,self.ray_mask_slice].bool().reshape(-1) + frame_ids = batch[:,self.ray_frame_id_slice] + + rgb, extras = self.render(rays=batch, depth=target_d,lindisp=False,perturb=True,raw_noise_std=self.cfg['raw_noise_std'], get_normals=False) + + valid_samples = extras['valid_samples'] #(N_ray,N_samples) + z_vals = extras['z_vals'] # [N_rand, N_samples + N_importance] + sdf = extras['raw'][..., -1] + + N_rays,N_samples = sdf.shape[:2] + valid_rays = (valid_samples>0).any(dim=-1).bool().reshape(N_rays) & (batch[:,self.ray_type_slice]==0) + + ray_type = batch[:,self.ray_type_slice].reshape(-1) + ray_weights = torch.ones((N_rays), device=rgb.device, dtype=torch.float32) + ray_weights[(frame_ids==0).view(-1)] = self.cfg['first_frame_weight'] + ray_weights = ray_weights*valid_rays.view(-1) + sample_weights = ray_weights.view(N_rays,1).expand(-1,N_samples) * valid_samples + img_loss = (((rgb-target_s)**2 * ray_weights.view(-1,1))).mean() + rgb_loss = self.cfg['rgb_weight'] * img_loss + loss = rgb_loss + + rgb0_loss = torch.tensor(0) + if 'rgb0' in extras: + img_loss0 = (((extras['rgb0']-target_s)**2 * ray_weights.view(-1,1))).mean() + rgb0_loss = img_loss0*self.cfg['rgb_weight'] + loss += rgb0_loss + + depth_loss = torch.tensor(0) + depth_loss0 = torch.tensor(0) + if self.cfg['depth_weight']>0: + signs = sdf[:, 1:] * sdf[:, :-1] + mask = signs<0 + inds = torch.argmax(mask.float(), axis=1) + inds = inds[..., None] + z_min = torch.gather(z_vals,dim=1,index=inds) + weights = ray_weights * (depth<=self.cfg['far']*self.cfg['sc_factor']) * (mask.any(dim=-1)) + depth_loss = ((z_min*weights-depth.view(-1,1)*weights)**2).mean() * self.cfg['depth_weight'] + loss = loss+depth_loss + + truncation = self.get_truncation() + sample_weights[ray_type==1] = 0 + fs_loss, sdf_loss,empty_loss, front_mask,sdf_mask = get_sdf_loss(z_vals, target_d.reshape(-1,1).expand(-1,N_samples), sdf, truncation, self.cfg,return_mask=True, sample_weights=sample_weights, rays_d=batch[:,self.ray_dir_slice]) + fs_loss = fs_loss*self.cfg['fs_weight'] + empty_loss = empty_loss*self.cfg['empty_weight'] + sdf_loss = sdf_loss*self.cfg['trunc_weight'] + loss = loss + fs_loss + sdf_loss + empty_loss + + fs_rgb_loss = torch.tensor(0) + if self.cfg['fs_rgb_weight']>0: + fs_rgb_loss = ((((torch.sigmoid(extras['raw'][...,:3])-1)*front_mask[...,None])**2) * sample_weights[...,None]).mean() + loss += fs_rgb_loss*self.cfg['fs_rgb_weight'] + + eikonal_loss = torch.tensor(0) + if self.cfg['eikonal_weight']>0: + nerf_normals = extras['normals'] + eikonal_loss = ((torch.norm(nerf_normals[sdf<1], dim=-1)-1)**2).mean() * self.cfg['eikonal_weight'] + loss += eikonal_loss + + point_cloud_loss = torch.tensor(0) + point_cloud_normal_loss = torch.tensor(0) + + + reg_features = torch.tensor(0) + if self.models['feature_array'] is not None: + reg_features = self.cfg['feature_reg_weight'] * (self.models['feature_array'].data**2).mean() + loss += reg_features + + if self.models['pose_array'] is not None: + pose_array = self.models['pose_array'] + pose_reg = self.cfg['pose_reg_weight']*pose_array.data[1:].norm() + loss += pose_reg + + variation_loss = torch.tensor(0) + + self.optimizer.zero_grad() + self.amp_scaler.scale(loss).backward() + + self.amp_scaler.step(self.optimizer) + self.amp_scaler.update() + if self.global_step%10==0 and self.global_step>0: + self.schedule_lr() + + if self.global_step%self.cfg['i_weights']==0 and self.global_step>0: + self.save_weights(out_file=os.path.join(self.cfg['save_dir'], f'model_latest.pth'), models=self.models) + + if self.global_step % self.cfg['i_img'] == 0 and self.global_step>0: + ids = torch.unique(self.rays[:, self.ray_frame_id_slice]).data.cpu().numpy().astype(int).tolist() + ids.sort() + last = ids[-1] + ids = ids[::max(1,len(ids)//5)] + if last not in ids: + ids.append(last) + canvas = [] + for frame_idx in ids: + rgb, depth, ray_mask, gt_rgb, gt_depth, _ = self.render_images(frame_idx) + mask_vis = (rgb*255*0.2 + ray_mask*0.8).astype(np.uint8) + mask_vis = np.clip(mask_vis,0,255) + rgb = np.concatenate((rgb,gt_rgb),axis=1) + far = self.cfg['far']*self.cfg['sc_factor'] + gt_depth = np.clip(gt_depth, self.cfg['near']*self.cfg['sc_factor'], far) + depth_vis = np.concatenate((to8b(depth / far), to8b(gt_depth / far)), axis=1) + depth_vis = np.tile(depth_vis[...,None],(1,1,3)) + row = np.concatenate((to8b(rgb),depth_vis,mask_vis),axis=1) + canvas.append(row) + canvas = np.concatenate(canvas,axis=0).astype(np.uint8) + dir = f"{self.cfg['save_dir']}/image_step_{self.global_step:07d}.png" + imageio.imwrite(dir,canvas) + if self._run is not None: + self._run.add_artifact(dir) + + + if self.global_step%self.cfg['i_print']==0: + msg = f"Iter: {self.global_step}, valid_samples: {valid_samples.sum()}/{torch.numel(valid_samples)}, valid_rays: {valid_rays.sum()}/{torch.numel(valid_rays)}, " + metrics = { + 'loss':loss.item(), + 'rgb_loss':rgb_loss.item(), + 'rgb0_loss':rgb0_loss.item(), + 'fs_rgb_loss': fs_rgb_loss.item(), + 'depth_loss':depth_loss.item(), + 'depth_loss0':depth_loss0.item(), + 'fs_loss':fs_loss.item(), + 'point_cloud_loss': point_cloud_loss.item(), + 'point_cloud_normal_loss':point_cloud_normal_loss.item(), + 'sdf_loss':sdf_loss.item(), + 'eikonal_loss': eikonal_loss.item(), + "variation_loss": variation_loss.item(), + 'truncation(meter)': self.get_truncation()/self.cfg['sc_factor'], + } + if self.models['pose_array'] is not None: + metrics['pose_reg'] = pose_reg.item() + if 'feature_array' in self.models: + metrics['reg_features'] = reg_features.item() + for k in metrics.keys(): + msg += f"{k}: {metrics[k]:.7f}, " + msg += "\n" + logging.info(msg) + + if self._run is not None: + for k in metrics.keys(): + self._run.log_scalar(k,metrics[k],self.global_step) + + if self.global_step % self.cfg['i_mesh'] == 0 and self.global_step > 0: + with torch.no_grad(): + model = self.models['model_fine'] if self.models['model_fine'] is not None else self.models['model'] + mesh = self.extract_mesh(isolevel=0, voxel_size=self.cfg['mesh_resolution']) + self.mesh = copy.deepcopy(mesh) + if mesh is not None: + dir = os.path.join(self.cfg['save_dir'], f'step_{self.global_step:07d}_mesh_normalized_space.obj') + mesh.export(dir) + if self._run is not None: + self._run.add_artifact(dir) + dir = os.path.join(self.cfg['save_dir'], f'step_{self.global_step:07d}_mesh_real_world.obj') + if self.models['pose_array'] is not None: + _,offset = get_optimized_poses_in_real_world(self.poses,self.models['pose_array'],translation=self.cfg['translation'],sc_factor=self.cfg['sc_factor']) + else: + offset = np.eye(4) + mesh = mesh_to_real_world(mesh,offset,translation=self.cfg['translation'],sc_factor=self.cfg['sc_factor']) + mesh.export(dir) + if self._run is not None: + self._run.add_artifact(dir) + + if self.global_step % self.cfg['i_pose'] == 0 and self.global_step > 0: + if self.models['pose_array'] is not None: + optimized_poses,offset = get_optimized_poses_in_real_world(self.poses,self.models['pose_array'],translation=self.cfg['translation'],sc_factor=self.cfg['sc_factor']) + else: + optimized_poses = self.poses + dir = os.path.join(self.cfg['save_dir'], f'step_{self.global_step:07d}_optimized_poses.txt') + np.savetxt(dir,optimized_poses.reshape(-1,4)) + if self._run is not None: + self._run.add_artifact(dir) + + + def train(self): + set_seed(0) + + for iter in range(self.N_iters): + if iter%(self.N_iters//10)==0: + logging.info(f'train progress {iter}/{self.N_iters}') + batch = next(self.data_loader) + self.train_loop(batch.cuda()) + self.global_step += 1 + + + + @torch.no_grad() + def sample_rays_uniform_occupied_voxels(self,rays_d,depths_in_out,lindisp=False,perturb=False, depths=None, N_samples=None): + '''We first connect the discontinuous boxes for each ray and treat it as uniform sample, then we disconnect into correct boxes + @rays_d: (N_ray,3) + @depths_in_out: Padded tensor each has (N_ray,N_intersect,2) tensor, the time travel of each ray + ''' + N_rays = rays_d.shape[0] + N_intersect = depths_in_out.shape[1] + dirs = rays_d/rays_d.norm(dim=-1,keepdim=True) + + ########### Convert the time to Z + z_in_out = depths_in_out.cuda()*torch.abs(dirs[...,2]).reshape(N_rays,1,1).cuda() + + if depths is not None: + depths = depths.reshape(-1,1) + trunc = self.get_truncation() + valid = (depths>=self.cfg['near']*self.cfg['sc_factor']) & (depths<=self.cfg['far']*self.cfg['sc_factor']).expand(-1,N_intersect) + valid = valid & (z_in_out>0).all(dim=-1) #(N_ray, N_intersect) + z_in_out[valid] = torch.clip(z_in_out[valid], + min=torch.zeros_like(z_in_out[valid]), + max=torch.ones_like(z_in_out[valid])*(depths.reshape(-1,1,1).expand(-1,N_intersect,2)[valid]+trunc)) + + + depths_lens = z_in_out[:,:,1]-z_in_out[:,:,0] #(N_ray,N_intersect) + z_vals_continous = sample_rays_uniform(N_samples,torch.zeros((N_rays,1),device=z_in_out.device).reshape(-1,1),depths_lens.sum(dim=-1).reshape(-1,1),lindisp=lindisp,perturb=perturb) #(N_ray,N_sample) + + ############# Option2 mycuda extension + N_samples = z_vals_continous.shape[1] + z_vals = torch.zeros((N_rays,N_samples), dtype=torch.float, device=rays_d.device) + z_vals = common.sampleRaysUniformOccupiedVoxels(z_in_out.contiguous(),z_vals_continous.contiguous(), z_vals) + z_vals = z_vals.float().to(rays_d.device) #(N_ray,N_sample) + + return z_vals,z_vals_continous + + + def render_rays(self,ray_batch,retraw=True,lindisp=False,perturb=False,raw_noise_std=0.,depth=None, get_normals=False, tf=None): + """Volumetric rendering. + Args: + ray_batch: array of shape [batch_size, ...]. All information necessary + for sampling along a ray, including: ray origin, ray direction, min + dist, max dist, and unit-magnitude viewing direction, frame_ids. + model: function. Model for predicting RGB and density at each point + in space. + N_samples: int. Number of different times to sample along each ray. + retraw: bool. If True, include model's raw, unprocessed predictions. + lindisp: bool. If True, sample linearly in inverse depth rather than in depth. + perturb: float, 0 or 1. If non-zero, each ray is sampled at stratified + random points in time. + N_importance: int. Number of additional times to sample along each ray. + These samples are only passed to model_fine. + model_fine: "fine" network with same spec as model. + raw_noise_std: ... + verbose: bool. If True, print more debugging info. + @depth: depth (from depth image) values of the ray (N_ray,1) + @tf: (N_ray,4,4) glcam in ob, normalized space + Returns: + rgb_map: [num_rays, 3]. Estimated RGB color of a ray. Comes from fine model. + disp_map: [num_rays]. Disparity map. 1 / depth. + acc_map: [num_rays]. Accumulated opacity along each ray. Comes from fine model. + raw: [num_rays, num_samples, 4]. Raw predictions from model. + rgb0: See rgb_map. Output for coarse model. + disp0: See disp_map. Output for coarse model. + acc0: See acc_map. Output for coarse model. + z_std: [num_rays]. Standard deviation of distances along ray for each + sample. + """ + N_rays = ray_batch.shape[0] + rays_d = ray_batch[:,self.ray_dir_slice] + rays_o = torch.zeros_like(rays_d) + viewdirs = rays_d/rays_d.norm(dim=-1,keepdim=True) + + frame_ids = ray_batch[:,self.ray_frame_id_slice].long() + + tf = self.c2w_array[frame_ids] + if self.models['pose_array'] is not None: + tf = self.models['pose_array'].get_matrices(frame_ids)@tf + + rays_o_w = transform_pts(rays_o,tf) + viewdirs_w = (tf[:,:3,:3]@viewdirs[:,None].permute(0,2,1))[:,:3,0] + voxel_size = self.cfg['octree_raytracing_voxel_size']*self.cfg['sc_factor'] + level = int(np.floor(np.log2(2.0/voxel_size))) + near,far,_,depths_in_out = self.octree_m.ray_trace(rays_o_w,viewdirs_w,level=level,debug=0) + z_vals,_ = self.sample_rays_uniform_occupied_voxels(rays_d=viewdirs,depths_in_out=depths_in_out,lindisp=lindisp,perturb=perturb, depths=depth, N_samples=self.cfg['N_samples']) + + if self.cfg['N_samples_around_depth']>0 and depth is not None: #!NOTE only fine when depths are all valid + valid_depth_mask = (depth>=self.cfg['near']*self.cfg['sc_factor']) & (depth<=self.cfg['far']*self.cfg['sc_factor']) + valid_depth_mask = valid_depth_mask.reshape(-1) + trunc = self.get_truncation() + near_depth = depth[valid_depth_mask]-trunc + far_depth = depth[valid_depth_mask]+trunc*self.cfg['neg_trunc_ratio'] + z_vals_around_depth = torch.zeros((N_rays,self.cfg['N_samples_around_depth']), device=ray_batch.device).float() + # if torch.sum(inside_mask)>0: + z_vals_around_depth[valid_depth_mask] = sample_rays_uniform(self.cfg['N_samples_around_depth'],near_depth.reshape(-1,1),far_depth.reshape(-1,1),lindisp=lindisp,perturb=perturb) + invalid_depth_mask = valid_depth_mask==0 + + if invalid_depth_mask.any() and self.cfg['use_octree']: + z_vals_invalid,_ = self.sample_rays_uniform_occupied_voxels(rays_d=viewdirs[invalid_depth_mask],depths_in_out=depths_in_out[invalid_depth_mask],lindisp=lindisp,perturb=perturb, depths=None, N_samples=self.cfg['N_samples_around_depth']) + z_vals_around_depth[invalid_depth_mask] = z_vals_invalid + else: + z_vals_around_depth[invalid_depth_mask] = sample_rays_uniform(self.cfg['N_samples_around_depth'],near[invalid_depth_mask].reshape(-1,1),far[invalid_depth_mask].reshape(-1,1),lindisp=lindisp,perturb=perturb) + + z_vals = torch.cat((z_vals,z_vals_around_depth), dim=-1) + valid_samples = torch.ones(z_vals.shape, dtype=torch.bool, device=ray_batch.device) # During pose update if ray out of box, it becomes invalid + + pts = rays_o[...,None,:] + rays_d[...,None,:] * z_vals[...,:,None] # [N_rays, N_samples, 3] + + deformation = None + raw,normals,valid_samples = self.run_network(pts, viewdirs, frame_ids, tf=tf, valid_samples=valid_samples, get_normals=get_normals) # [N_rays, N_samples, 4] + + rgb_map, weights = self.raw2outputs(raw, z_vals, rays_d, raw_noise_std=raw_noise_std, valid_samples=valid_samples, depth=depth) + + if self.cfg['N_importance'] > 0: + rgb_map_0 = rgb_map + + for iter in range(self.cfg['N_importance_iter']): + z_vals_mid = .5 * (z_vals[...,1:] + z_vals[...,:-1]) + z_samples = sample_pdf(z_vals_mid, weights[...,1:-1], self.cfg['N_importance'], det=(perturb==0.)) + z_samples = z_samples.detach() + valid_samples_importance = torch.ones(z_samples.shape, dtype=torch.bool).to(z_vals.device) + valid_samples_importance[torch.all(valid_samples==0, dim=-1).reshape(-1)] = 0 + + if self.models['model_fine'] is not None and self.models['model_fine']!=self.models['model']: + z_vals, _ = torch.sort(torch.cat([z_vals, z_samples], -1), -1) + pts = rays_o[...,None,:] + rays_d[...,None,:] * z_vals[...,:,None] # [N_rays, N_samples + self.cfg['N_importance'], 3] + raw, normals,valid_samples = self.run_network(pts, viewdirs, frame_ids, tf=tf, valid_samples=valid_samples, get_normals=False) + else: + pts = rays_o[..., None, :] + rays_d[..., None, :] * z_samples[..., :, None] # [N_rays, N_samples + self.cfg['N_importance'], 3] + raw_fine,valid_samples_importance = self.run_network(pts, viewdirs, frame_ids, tf=tf, valid_samples=valid_samples_importance, get_normals=False) + z_vals = torch.cat([z_vals, z_samples], -1) #(N_ray, N_sample) + indices = torch.argsort(z_vals, dim=-1) + z_vals = torch.gather(z_vals,dim=1,index=indices) + raw = torch.gather(torch.cat([raw, raw_fine], dim=1), dim=1, index=indices[...,None].expand(-1,-1,raw.shape[-1])) + valid_samples = torch.cat((valid_samples,valid_samples_importance), dim=-1) + + rgb_map, weights = self.raw2outputs(raw, z_vals, rays_d, raw_noise_std=raw_noise_std,valid_samples=valid_samples) + + ret = {'rgb_map' : rgb_map, 'valid_samples':valid_samples, 'weights':weights, 'z_vals':z_vals} + + if retraw: + ret['raw'] = raw + + if normals is not None: + ret['normals'] = normals + + if deformation is not None: + ret['deformation'] = deformation + + if self.cfg['N_importance'] > 0: + ret['rgb0'] = rgb_map_0 + + return ret + + + def raw2outputs(self, raw, z_vals, rays_d, raw_noise_std=0, valid_samples=None, depth=None): + """Transforms model's predictions to semantically meaningful values. + Args: + raw: [num_rays, num_samples along ray, 4]. Prediction from model. + z_vals: [num_rays, num_samples along ray]. Integration time. + rays_d: [num_rays, 3]. Direction of each ray. + Returns: + rgb_map: [num_rays, 3]. Estimated RGB color of a ray. + disp_map: [num_rays]. Disparity map. Inverse of depth map. + acc_map: [num_rays]. Sum of weights along each ray. + weights: [num_rays, num_samples]. Weights assigned to each sampled color. + depth_map: [num_rays]. Estimated distance to object. + """ + truncation = self.get_truncation() + if depth is not None: + depth = depth.view(-1,1) + + if valid_samples is None: + valid_samples = torch.ones(z_vals.shape, dtype=torch.bool).to(z_vals.device) + + def sdf2weights(sdf): + sdf_from_depth = (depth.view(-1,1)-z_vals)/truncation + weights = torch.sigmoid(sdf_from_depth*self.cfg['sdf_lambda']) * torch.sigmoid(-sdf_from_depth*self.cfg['sdf_lambda']) # This not work well + + invalid = (depth>self.cfg['far']*self.cfg['sc_factor']).reshape(-1) + mask = (z_vals-depth<=truncation*self.cfg['neg_trunc_ratio']) & (z_vals-depth>=-truncation) + weights[~invalid] = weights[~invalid] * mask[~invalid] + weights[invalid] = 0 + + return weights / (weights.sum(dim=-1,keepdim=True) + 1e-10) + + rgb = torch.sigmoid(raw[...,:3]) # [N_rays, N_samples, 3] + weights = sdf2weights(raw[..., 3]) + + weights[valid_samples==0] = 0 + rgb_map = torch.sum(weights[...,None] * rgb, -2) # [N_rays, 3] + + return rgb_map, weights + + + def render(self, rays, depth=None,lindisp=False,perturb=False,raw_noise_std=0.0, get_normals=False): + """Render rays + Args: + H: int. Height of image in pixels. + W: int. Width of image in pixels. + K: float. Focal length of pinhole camera. + chunk: int. Maximum number of rays to process simultaneously. Used to + control maximum memory usage. Does not affect final results. + rays: array of shape [batch_size, 6]. Ray origin and direction for + each example in batch. + ndc: bool. If True, represent ray origin, direction in NDC coordinates. Only true for llff data + near: float or array of shape [batch_size]. Nearest distance for a ray. + far: float or array of shape [batch_size]. Farthest distance for a ray. + @depth: depth values (N_ray,1) + Returns: + rgb_map: [batch_size, 3]. Predicted RGB values for rays. + disp_map: [batch_size]. Disparity map. Inverse of depth. + acc_map: [batch_size]. Accumulated opacity (alpha) along a ray. + extras: dict with everything. + """ + all_ret = self.batchify_rays(rays,depth=depth,lindisp=lindisp,perturb=perturb,raw_noise_std=raw_noise_std, get_normals=get_normals) + + k_extract = ['rgb_map'] + ret_list = [all_ret[k] for k in k_extract] + ret_dict = {k : all_ret[k] for k in all_ret if k not in k_extract} + return ret_list + [ret_dict] + + + + def batchify_rays(self,rays_flat, depth=None,lindisp=False,perturb=False,raw_noise_std=0.0, get_normals=False): + """Render rays in smaller minibatches to avoid OOM. + """ + all_ret = {} + chunk = self.cfg['chunk'] + for i in range(0, rays_flat.shape[0], chunk): + if depth is not None: + cur_depth = depth[i:i+chunk] + else: + cur_depth = None + ret = self.render_rays(rays_flat[i:i+chunk],depth=cur_depth,lindisp=lindisp,perturb=perturb,raw_noise_std=raw_noise_std, get_normals=get_normals) + for k in ret: + if ret[k] is None: + continue + if k not in all_ret: + all_ret[k] = [] + all_ret[k].append(ret[k]) + + all_ret = {k : torch.cat(all_ret[k], 0) for k in all_ret} + return all_ret + + + def run_network(self, inputs, viewdirs, frame_ids=None, tf=None, latent_code=None, valid_samples=None, get_normals=False): + """Prepares inputs and applies network 'fn'. + @inputs: (N_ray,N_sample,3) sampled points on rays in GL camera's frame + @viewdirs: (N_ray,3) unit length vector in camera frame, z-axis backward + @frame_ids: (N_ray) + @tf: (N_ray,4,4) + @latent_code: (N_ray, D) + """ + N_ray,N_sample = inputs.shape[:2] + + if valid_samples is None: + valid_samples = torch.ones((N_ray,N_sample), dtype=torch.bool, device=inputs.device) + + inputs_flat = torch.reshape(inputs, [-1, inputs.shape[-1]]) + + tf_flat = tf[:,None].expand(-1,N_sample,-1,-1).reshape(-1,4,4) + inputs_flat = transform_pts(inputs_flat, tf_flat) + + valid_samples = valid_samples.bool() & (torch.abs(inputs_flat)<=1).all(dim=-1).view(N_ray,N_sample).bool() + + embedded = torch.zeros((inputs_flat.shape[0],self.models['embed_fn'].out_dim), device=inputs_flat.device) + if valid_samples is None: + valid_samples = torch.ones((N_ray,N_sample), dtype=torch.bool, device=inputs_flat.device) + + if get_normals: + if inputs_flat.requires_grad==False: + inputs_flat.requires_grad = True + + with torch.cuda.amp.autocast(enabled=self.cfg['amp']): + if self.cfg['i_embed'] in [3]: + embedded[valid_samples.reshape(-1)], valid_samples_embed = self.models['embed_fn'](inputs_flat[valid_samples.reshape(-1)]) + valid_samples = valid_samples.reshape(-1) + prev_valid_ids = valid_samples.nonzero().reshape(-1) + bad_ids = prev_valid_ids[valid_samples_embed==0] + new_valid_ids = torch.ones((N_ray*N_sample),device=inputs.device).bool() + new_valid_ids[bad_ids] = 0 + valid_samples = valid_samples & new_valid_ids + valid_samples = valid_samples.reshape(N_ray,N_sample).bool() + else: + embedded[valid_samples.reshape(-1)] = self.models['embed_fn'](inputs_flat[valid_samples.reshape(-1)]).to(embedded.dtype) + embedded = embedded.float() + + # Add latent code + if self.models['feature_array'] is not None: + if latent_code is None: + frame_features = self.models['feature_array'](frame_ids) + D = frame_features.shape[-1] + frame_features = frame_features[:,None].expand(-1,N_sample,-1).reshape(-1,D) + else: + D = latent_code.shape[-1] + frame_features = latent_code[:,None].expand(N_ray,N_sample,latent_code.shape[-1]).reshape(-1,D) + embedded = torch.cat([embedded, frame_features], -1) + + # Add view directions + if self.models['embeddirs_fn'] is not None: + input_dirs = (tf[..., :3, :3]@viewdirs[...,None])[...,0] #(N_ray,3) + embedded_dirs = self.models['embeddirs_fn'](input_dirs) + tmp = embedded_dirs.shape[1:] + embedded_dirs_flat = embedded_dirs[:,None].expand(-1,N_sample,*tmp).reshape(-1,*tmp) + embedded = torch.cat([embedded, embedded_dirs_flat], -1) + + outputs_flat = [] + with torch.cuda.amp.autocast(enabled=self.cfg['amp']): + chunk = self.cfg['netchunk'] + for i in range(0,embedded.shape[0],chunk): + out = self.models['model'](embedded[i:i+chunk]) + outputs_flat.append(out) + outputs_flat = torch.cat(outputs_flat, dim=0).float() + outputs = torch.reshape(outputs_flat, list(inputs.shape[:-1]) + [outputs_flat.shape[-1]]).float() + + normals = None + if get_normals: + sdf = outputs[...,-1] + d_output = torch.zeros(sdf.shape, device=sdf.device) + normals = torch.autograd.grad(outputs=sdf,inputs=inputs_flat,grad_outputs=d_output,create_graph=False,retain_graph=True,only_inputs=True,allow_unused=True)[0] + normals = normals.reshape(N_ray,N_sample,3) + + return outputs,normals,valid_samples + + + def run_network_density(self, inputs, get_normals=False): + """Directly query the network w/o pose transformations or deformations (inputs are already in normalized [-1,1]); Particularly used for mesh extraction + @inputs: (N,3) sampled points on rays in GL camera's frame + """ + inputs_flat = torch.reshape(inputs, [-1, inputs.shape[-1]]) + + inputs_flat = torch.clip(inputs_flat,-1,1) + valid_samples = torch.ones((len(inputs_flat)),device=inputs.device).bool() + + if not inputs_flat.requires_grad: + inputs_flat.requires_grad = True + + with torch.cuda.amp.autocast(enabled=self.cfg['amp']): + if self.cfg['i_embed'] in [3]: + embedded, valid_samples_embed = self.models['embed_fn'](inputs_flat) + valid_samples = valid_samples.reshape(-1) + prev_valid_ids = valid_samples.nonzero().reshape(-1) + bad_ids = prev_valid_ids[valid_samples_embed==0] + new_valid_ids = torch.ones((len(inputs_flat)),device=inputs.device).bool() + new_valid_ids[bad_ids] = 0 + valid_samples = valid_samples & new_valid_ids + else: + embedded = self.models['embed_fn'](inputs_flat) + embedded = embedded.float() + input_ch = embedded.shape[-1] + + outputs_flat = [] + with torch.cuda.amp.autocast(enabled=self.cfg['amp']): + chunk = self.cfg['netchunk'] + for i in range(0,embedded.shape[0],chunk): + alpha = self.models['model'].forward_sdf(embedded[i:i+chunk]) #(N,1) + outputs_flat.append(alpha.reshape(-1,1)) + outputs_flat = torch.cat(outputs_flat,dim=0).float() + outputs = torch.reshape(outputs_flat, list(inputs.shape[:-1]) + [outputs_flat.shape[-1]]) + + if get_normals: + d_output = torch.ones_like(outputs, requires_grad=False, device=outputs.device) + normal = torch.autograd.grad(outputs=outputs,inputs=inputs_flat,grad_outputs=d_output,create_graph=False,retain_graph=True,only_inputs=True,allow_unused=True)[0] + outputs = torch.cat((outputs, normal), dim=-1) + + return outputs,valid_samples + + + @torch.no_grad() + def extract_mesh(self, level=None, voxel_size=0.003, isolevel=0.0, return_sigma=False): + voxel_size *= self.cfg['sc_factor'] # in "network space" + + bounds = np.array(self.cfg['bounding_box']).reshape(2,3) + x_min, x_max = bounds[0,0], bounds[1,0] + y_min, y_max = bounds[0,1], bounds[1,1] + z_min, z_max = bounds[0,2], bounds[1,2] + tx = np.arange(x_min+0.5*voxel_size, x_max, voxel_size) + ty = np.arange(y_min+0.5*voxel_size, y_max, voxel_size) + tz = np.arange(z_min+0.5*voxel_size, z_max, voxel_size) + N = len(tx) + query_pts = torch.tensor(np.stack(np.meshgrid(tx, ty, tz, indexing='ij'), -1).astype(np.float32).reshape(-1,3)).float().cuda() + + if self.octree_m is not None: + vox_size = self.cfg['octree_raytracing_voxel_size']*self.cfg['sc_factor'] + level = int(np.floor(np.log2(2.0/vox_size))) + center_ids = self.octree_m.get_center_ids(query_pts, level) + valid = center_ids>=0 + else: + valid = torch.ones(len(query_pts), dtype=bool).cuda() + + logging.info(f'query_pts:{query_pts.shape}, valid:{valid.sum()}') + flat = query_pts[valid] + + sigma = [] + chunk = self.cfg['netchunk'] + for i in range(0,flat.shape[0],chunk): + inputs = flat[i:i+chunk] + with torch.no_grad(): + outputs,valid_samples = self.run_network_density(inputs=inputs) + sigma.append(outputs) + sigma = torch.cat(sigma, dim=0) + sigma_ = torch.ones((N**3)).float().cuda() + sigma_[valid] = sigma.reshape(-1) + sigma = sigma_.reshape(N,N,N).data.cpu().numpy() + + logging.info('Running Marching Cubes') + from skimage import measure + try: + vertices, triangles, normals, values = measure.marching_cubes(sigma, isolevel) + except Exception as e: + logging.info(f"ERROR Marching Cubes {e}") + return None + + logging.info(f'done V:{vertices.shape}, F:{triangles.shape}') + + voxel_size_ndc = np.array([tx[-1] - tx[0], ty[-1] - ty[0], tz[-1] - tz[0]]) / np.array([[tx.shape[0] - 1, ty.shape[0] - 1, tz.shape[0] - 1]]) + offset = np.array([tx[0], ty[0], tz[0]]) + vertices[:, :3] = voxel_size_ndc.reshape(1,3) * vertices[:, :3] + offset.reshape(1,3) + + mesh = trimesh.Trimesh(vertices, triangles, process=False) + + if return_sigma: + return mesh,sigma,query_pts + + return mesh + + + def mesh_texture_from_train_images(self, mesh, rgbs_raw, tex_res=1024): + ''' + @rgbs_raw: raw complete image that was trained on, no black holes + @mesh: in normalized space + ''' + assert len(self.images)==len(rgbs_raw) + + frame_ids = torch.arange(len(self.images)).long().cuda() + tf = self.c2w_array[frame_ids] + if self.models['pose_array'] is not None: + tf = self.models['pose_array'].get_matrices(frame_ids)@tf + tf = tf.data.cpu().numpy() + from offscreen_renderer import ModelRendererOffscreen + + tex_image = torch.zeros((tex_res,tex_res,3)).cuda().float() + weight_tex_image = torch.zeros(tex_image.shape[:-1]).cuda().float() + mesh.merge_vertices() + mesh.remove_duplicate_faces() + mesh = mesh.unwrap() + H,W = tex_image.shape[:2] + uvs_tex = (mesh.visual.uv*np.array([W-1,H-1]).reshape(1,2)) #(n_V,2) + + renderer = ModelRendererOffscreen(cam_K=self.K, H=self.H, W=self.W, zfar=self.cfg['far']*self.cfg['sc_factor']) + + vertices_cuda = torch.from_numpy(mesh.vertices).float().cuda() + faces_cuda = torch.from_numpy(mesh.faces).long().cuda() + face_vertices = torch.zeros((len(faces_cuda),3,3)) + for i in range(3): + face_vertices[:,i] = vertices_cuda[faces_cuda[:,i]] + + all_tri_list= {key: [] for key in range(mesh.triangles.shape[0])} + for i in range(len(rgbs_raw)): + cvcam_in_ob = tf[i]@np.linalg.inv(glcam_in_cvcam) + _, render_depth = renderer.render(mesh=mesh, ob_in_cvcam=np.linalg.inv(cvcam_in_ob)) + xyz_map = depth2xyzmap(render_depth, self.K) + mask = self.masks[i].reshape(self.H,self.W).astype(bool) + valid = (render_depth.reshape(self.H,self.W)>=0.1*self.cfg['sc_factor']) & (mask) + pts = xyz_map[valid].reshape(-1,3) + pts = transform_pts(pts, cvcam_in_ob) + ray_colors = rgbs_raw[i][valid].reshape(-1,3) + locations, distance, index_tri = trimesh.proximity.closest_point(mesh, pts) + normals = mesh.face_normals[index_tri] + for ind_tri, each_tri in enumerate(index_tri): + rays_o = np.zeros(3) + pts = transform_pts(rays_o, cvcam_in_ob) #transform to world space + rays_d = locations[ind_tri]-pts + rays_d /= np.linalg.norm(rays_d) + dot_product = np.dot(-rays_d, normals[ind_tri]) + angle_radians = np.arccos(dot_product) + angle_degrees = np.degrees(angle_radians) + all_tri_list[each_tri].extend([[i,angle_degrees]]) + + _CHOOSE_TOP_N = 4 + all_triangles_dict={} + for k,v in all_tri_list.items(): + if(v): + v.sort(key=lambda x: x[1]) + tep = [i[0] for i in v[:_CHOOSE_TOP_N]] + all_triangles_dict[k]=set(list(tep)) + + + all_tri_visited= {key: 0 for key in range(mesh.triangles.shape[0])} + + logging.info(f"Texture: Texture map computation") + for i in range(len(rgbs_raw)): + print(f'project train_images {i}/{len(rgbs_raw)}') + + cvcam_in_ob = tf[i]@np.linalg.inv(glcam_in_cvcam) + _, render_depth = renderer.render(mesh=mesh, ob_in_cvcam=np.linalg.inv(cvcam_in_ob)) + xyz_map = depth2xyzmap(render_depth, self.K) + mask = self.masks[i].reshape(self.H,self.W).astype(bool) + valid = (render_depth.reshape(self.H,self.W)>=0.1*self.cfg['sc_factor']) & (mask) + pts = xyz_map[valid].reshape(-1,3) + pts = transform_pts(pts, cvcam_in_ob) + ray_colors = rgbs_raw[i][valid].reshape(-1,3) + locations, distance, index_tri = trimesh.proximity.closest_point(mesh, pts) + normals = mesh.face_normals[index_tri] + rays_o = np.zeros((len(normals),3)) + rays_o = transform_pts(rays_o,cvcam_in_ob) + rays_d = locations-rays_o + rays_d /= np.linalg.norm(rays_d,axis=-1).reshape(-1,1) + dots = (normals*(-rays_d)).sum(axis=-1) + ray_weights = np.ones((len(rays_o))) + bool_weights=torch.zeros(len(locations), dtype=torch.bool, device='cuda') + count = 0 + for jj, trtind__ in enumerate(index_tri): + if(i in all_triangles_dict[trtind__] ): + bool_weights[jj]=1 + all_tri_visited[trtind__]=1 + count +=1 + + uvs = torch.zeros((len(locations),2)).cuda().float() + common.rayColorToTextureImageCUDA(torch.from_numpy(mesh.faces).cuda().long(), torch.from_numpy(mesh.vertices).cuda().float(), torch.from_numpy(locations).cuda().float(), torch.from_numpy(index_tri).cuda().long(), torch.from_numpy(uvs_tex).cuda().float(), uvs) + uvs = torch.round(uvs).long() + uvs_flat = uvs[:,1]*(W-1) + uvs[:,0] + uvs_flat_unique, inverse_ids, cnts = torch.unique(uvs_flat, return_counts=True, return_inverse=True) + perm = torch.arange(inverse_ids.size(0)).cuda() + inverse_ids, perm = inverse_ids.flip([0]), perm.flip([0]) + unique_ids = inverse_ids.new_empty(uvs_flat_unique.size(0)).scatter_(0, inverse_ids, perm) + uvs_unique = torch.stack((uvs_flat_unique%(W-1), uvs_flat_unique//(W-1)), dim=-1).reshape(-1,2) + cur_weights= bool_weights[unique_ids].cuda().float() + tex_image[uvs_unique[:,1],uvs_unique[:,0]] += torch.from_numpy(ray_colors).cuda().float()[unique_ids]*cur_weights.reshape(-1,1) + weight_tex_image[uvs_unique[:,1], uvs_unique[:,0]] += cur_weights + + tex_image = tex_image/weight_tex_image[...,None] + tex_image = tex_image.data.cpu().numpy() + tex_image = np.clip(tex_image,0,255).astype(np.uint8) + tex_image = tex_image[::-1].copy() + new_texture = texture_map_interpolation(tex_image) + + mesh.visual = trimesh.visual.texture.TextureVisuals(uv=mesh.visual.uv,image=Image.fromarray(new_texture)) + return mesh diff --git a/third-party/video_to_data/reconstruction/modules/v2d_foundation_pose/lib/FoundationPose/bundlesdf/run_nerf.py b/third-party/video_to_data/reconstruction/modules/v2d_foundation_pose/lib/FoundationPose/bundlesdf/run_nerf.py new file mode 100644 index 0000000000000000000000000000000000000000..5cfea7d318f9cbe5e44b43fce2235b0cfd69e3d5 --- /dev/null +++ b/third-party/video_to_data/reconstruction/modules/v2d_foundation_pose/lib/FoundationPose/bundlesdf/run_nerf.py @@ -0,0 +1,115 @@ +# Copyright (c) 2023, NVIDIA CORPORATION. All rights reserved. +# +# NVIDIA CORPORATION and its licensors retain all intellectual property +# and proprietary rights in and to this software, related documentation +# and any modifications thereto. Any use, reproduction, disclosure or +# distribution of this software and related documentation without an express +# license agreement from NVIDIA CORPORATION is strictly prohibited. + + +from nerf_runner import * +code_dir = os.path.dirname(os.path.realpath(__file__)) +sys.path.append(f'{code_dir}/../') +from datareader import * +from bundlesdf.tool import * +import yaml,argparse + + +def run_neural_object_field(cfg, K, rgbs, depths, masks, cam_in_obs, debug=0, save_dir='/home/bowen/debug/foundationpose_bundlesdf'): + rgbs = np.asarray(rgbs) + depths = np.asarray(depths) + masks = np.asarray(masks) + cam_in_obs = np.asarray(cam_in_obs) + glcam_in_obs = cam_in_obs@glcam_in_cvcam + + cfg['save_dir'] = save_dir + os.makedirs(save_dir, exist_ok=True) + + for i,rgb in enumerate(rgbs): + imageio.imwrite(f'{save_dir}/rgb_{i:07d}.png', rgb) + + sc_factor,translation,pcd_real_scale, pcd_normalized = compute_scene_bounds(None,glcam_in_obs, K, use_mask=True,base_dir=save_dir,rgbs=rgbs,depths=depths,masks=masks, eps=cfg['dbscan_eps'], min_samples=cfg['dbscan_eps_min_samples']) + cfg['sc_factor'] = sc_factor + cfg['translation'] = translation + + o3d.io.write_point_cloud(f'{save_dir}/pcd_normalized.ply', pcd_normalized) + + rgbs_, depths_, masks_, normal_maps,poses = preprocess_data(rgbs, depths, masks,normal_maps=None,poses=glcam_in_obs,sc_factor=cfg['sc_factor'],translation=cfg['translation']) + + nerf = NerfRunner(cfg, rgbs_, depths_, masks_, normal_maps=None, poses=poses, K=K, occ_masks=None, build_octree_pcd=pcd_normalized) + nerf.train() + + mesh = nerf.extract_mesh(isolevel=0,voxel_size=cfg['mesh_resolution']) + mesh = nerf.mesh_texture_from_train_images(mesh, rgbs_raw=rgbs, tex_res=1028) + optimized_cvcam_in_obs,offset = get_optimized_poses_in_real_world(poses,nerf.models['pose_array'],cfg['sc_factor'],cfg['translation']) + mesh = mesh_to_real_world(mesh, pose_offset=offset, translation=nerf.cfg['translation'], sc_factor=nerf.cfg['sc_factor']) + return mesh + + +def run_one_ob(base_dir, cfg, use_refined_mask=False): + save_dir = f'{base_dir}/nerf' + os.system(f'rm -rf {save_dir} && mkdir -p {save_dir}') + with open(f'{base_dir}/select_frames.yml','r') as ff: + info = yaml.safe_load(ff) + rgbs = [] + depths = [] + masks = [] + cam_in_obs = [] + color_files = sorted(glob.glob(f'{base_dir}/rgb/*.png')) + K = np.loadtxt(f'{base_dir}/K.txt') + for i,color_file in enumerate(color_files): + rgb = imageio.imread(color_file) + depth = cv2.imread(color_file.replace('rgb','depth_enhanced'), -1)/1e3 + if use_refined_mask: + mask = cv2.imread(color_file.replace('rgb','mask_refined'), -1) + else: + mask = cv2.imread(color_file.replace('rgb','mask'), -1) + cam_in_ob = np.loadtxt(color_file.replace('rgb','cam_in_ob').replace('.png','.txt')).reshape(4,4) + rgbs.append(rgb) + depths.append(depth) + masks.append(mask) + cam_in_obs.append(cam_in_ob) + + mesh = run_neural_object_field(cfg, K, rgbs, depths, masks, cam_in_obs, save_dir=save_dir, debug=0) + return mesh + + +def run_ycbv(): + ob_ids = np.arange(1,22) + code_dir = os.path.dirname(os.path.realpath(__file__)) + with open(f'{code_dir}/config_ycbv.yml','r') as ff: + cfg = yaml.safe_load(ff) + + for ob_id in ob_ids: + base_dir = f'{args.ref_view_dir}/ob_{ob_id:07d}' + mesh = run_one_ob(base_dir=base_dir, cfg=cfg) + out_file = f'{base_dir}/model/model.obj' + os.makedirs(os.path.dirname(out_file), exist_ok=True) + mesh.export(out_file) + + +def run_linemod(): + ob_ids = np.setdiff1d(np.arange(1,16), np.array([7,3])).tolist() + code_dir = os.path.dirname(os.path.realpath(__file__)) + with open(f'{code_dir}/config_linemod.yml','r') as ff: + cfg = yaml.safe_load(ff) + for ob_id in ob_ids: + base_dir = f'{args.ref_view_dir}/ob_{ob_id:07d}' + mesh = run_one_ob(base_dir=base_dir, cfg=cfg, use_refined_mask=True) + out_file = f'{base_dir}/model/model.obj' + os.makedirs(os.path.dirname(out_file), exist_ok=True) + mesh.export(out_file) + logging.info(f"saved to {out_file}") + + +if __name__=="__main__": + parser = argparse.ArgumentParser() + code_dir = os.path.dirname(os.path.realpath(__file__)) + parser.add_argument('--ref_view_dir', type=str, default=f'/mnt/9a72c439-d0a7-45e8-8d20-d7a235d02763/DATASET/YCB_Video/bowen_addon/ref_views_16') + parser.add_argument('--dataset', type=str, default=f'ycbv', help='one of [ycbv/linemod]') + args = parser.parse_args() + + if args.dataset=='ycbv': + run_ycbv() + else: + run_linemod() diff --git a/third-party/video_to_data/reconstruction/modules/v2d_foundation_pose/lib/FoundationPose/bundlesdf/tool.py b/third-party/video_to_data/reconstruction/modules/v2d_foundation_pose/lib/FoundationPose/bundlesdf/tool.py new file mode 100644 index 0000000000000000000000000000000000000000..d52bb9d57a175edf54ed46647d37921107fb2953 --- /dev/null +++ b/third-party/video_to_data/reconstruction/modules/v2d_foundation_pose/lib/FoundationPose/bundlesdf/tool.py @@ -0,0 +1,132 @@ +# Copyright (c) 2023, NVIDIA CORPORATION. All rights reserved. +# +# NVIDIA CORPORATION and its licensors retain all intellectual property +# and proprietary rights in and to this software, related documentation +# and any modifications thereto. Any use, reproduction, disclosure or +# distribution of this software and related documentation without an express +# license agreement from NVIDIA CORPORATION is strictly prohibited. + + +import joblib,json,gzip,pickle +from sklearn.cluster import DBSCAN +import shutil,re,imageio,pdb,os,sys +from Utils import * +import pandas as pd + + +def find_biggest_cluster(pts, eps=0.06, min_samples=1): + dbscan = DBSCAN(eps=eps,min_samples=min_samples,n_jobs=-1) + dbscan.fit(pts) + ids, cnts = np.unique(dbscan.labels_, return_counts=True) + best_id = ids[cnts.argsort()[-1]] + keep_mask = dbscan.labels_==best_id + pts_cluster = pts[keep_mask] + return pts_cluster, keep_mask + + +def compute_translation_scales(pts,max_dim=2,cluster=True, eps=0.06, min_samples=1): + if cluster: + pts, keep_mask = find_biggest_cluster(pts, eps, min_samples) + else: + keep_mask = np.ones((len(pts)), dtype=bool) + max_xyz = pts.max(axis=0) + min_xyz = pts.min(axis=0) + center = (max_xyz+min_xyz)/2 + sc_factor = max_dim/(max_xyz-min_xyz).max() #Normalize to [-1,1] + sc_factor *= 0.9 + translation_cvcam = -center + return translation_cvcam, sc_factor, keep_mask + + +def compute_scene_bounds_worker(color_file,K,glcam_in_world,use_mask,rgb=None,depth=None,mask=None): + if rgb is None: + depth_file = color_file.replace('images','depth_filtered') + mask_file = color_file.replace('images','masks') + rgb = np.array(Image.open(color_file))[...,:3] + depth = cv2.imread(depth_file,-1)/1e3 + xyz_map = depth2xyzmap(depth,K) + valid = depth>=0.1 + if use_mask: + if mask is None: + mask = cv2.imread(mask_file,-1) + valid = valid & (mask>0) + pts = xyz_map[valid].reshape(-1,3) + if len(pts)==0: + return None + colors = rgb[valid].reshape(-1,3) + pcd = toOpen3dCloud(pts,colors) + pcd = pcd.voxel_down_sample(0.01) + pcd, ind = pcd.remove_statistical_outlier(nb_neighbors=30,std_ratio=2.0) + cam_in_world = glcam_in_world@glcam_in_cvcam + pcd.transform(cam_in_world) + return np.asarray(pcd.points).copy(), np.asarray(pcd.colors).copy() + + +def compute_scene_bounds(color_files,glcam_in_worlds,K,use_mask=True,base_dir=None,rgbs=None,depths=None,masks=None,cluster=True, translation_cvcam=None, sc_factor=None, eps=0.06, min_samples=1): + assert color_files is None or rgbs is None + + if base_dir is None: + base_dir = os.path.dirname(color_files[0])+'/../' + + args = [] + if rgbs is not None: + for i in range(len(rgbs)): + args.append((None,K,glcam_in_worlds[i],use_mask,rgbs[i],depths[i],masks[i])) + else: + for i in range(len(color_files)): + args.append((color_files[i],K,glcam_in_worlds[i],use_mask)) + + logging.info(f"compute_scene_bounds_worker start") + ret = joblib.Parallel(n_jobs=10, prefer="threads")(joblib.delayed(compute_scene_bounds_worker)(*arg) for arg in args) + logging.info(f"compute_scene_bounds_worker done") + + pcd_all = None + for r in ret: + if r is None: + continue + if pcd_all is None: + pcd_all = toOpen3dCloud(r[0],r[1]) + else: + pcd_all += toOpen3dCloud(r[0],r[1]) + pcd = pcd_all.voxel_down_sample(eps/5) + + logging.info(f"merge pcd") + + o3d.io.write_point_cloud(f'{base_dir}/naive_fusion.ply',pcd) + pts = np.asarray(pcd.points).copy() + + def make_tf(translation_cvcam, sc_factor): + tf = np.eye(4) + tf[:3,3] = translation_cvcam + tf1 = np.eye(4) + tf1[:3,:3] *= sc_factor + tf = tf1@tf + return tf + + if translation_cvcam is None: + translation_cvcam, sc_factor, keep_mask = compute_translation_scales(pts, cluster=cluster, eps=eps, min_samples=min_samples) + tf = make_tf(translation_cvcam, sc_factor) + else: + tf = make_tf(translation_cvcam, sc_factor) + tmp = copy.deepcopy(pcd) + tmp.transform(tf) + tmp_pts = np.asarray(tmp.points) + keep_mask = (np.abs(tmp_pts)<1).all(axis=-1) + + logging.info(f"compute_translation_scales done") + + pcd = toOpen3dCloud(pts[keep_mask],np.asarray(pcd.colors)[keep_mask]) + o3d.io.write_point_cloud(f"{base_dir}/naive_fusion_biggest_cluster.ply",pcd) + pcd_real_scale = copy.deepcopy(pcd) + print(f'translation_cvcam={translation_cvcam}, sc_factor={sc_factor}') + with open(f'{base_dir}/normalization.yml','w') as ff: + tmp = { + 'translation_cvcam':translation_cvcam.tolist(), + 'sc_factor':float(sc_factor), + } + yaml.dump(tmp,ff) + + pcd.transform(tf) + return sc_factor, translation_cvcam, pcd_real_scale, pcd + + diff --git a/third-party/video_to_data/reconstruction/modules/v2d_foundation_pose/lib/FoundationPose/datareader.py b/third-party/video_to_data/reconstruction/modules/v2d_foundation_pose/lib/FoundationPose/datareader.py new file mode 100644 index 0000000000000000000000000000000000000000..b7a66068170070de99399eb7783fbbbe910c650b --- /dev/null +++ b/third-party/video_to_data/reconstruction/modules/v2d_foundation_pose/lib/FoundationPose/datareader.py @@ -0,0 +1,613 @@ +# Copyright (c) 2023, NVIDIA CORPORATION. All rights reserved. +# +# NVIDIA CORPORATION and its licensors retain all intellectual property +# and proprietary rights in and to this software, related documentation +# and any modifications thereto. Any use, reproduction, disclosure or +# distribution of this software and related documentation without an express +# license agreement from NVIDIA CORPORATION is strictly prohibited. + + +from Utils import * +import json,os,sys + + +BOP_LIST = ['lmo','tless','ycbv','hb','tudl','icbin','itodd'] +BOP_DIR = os.getenv('BOP_DIR') + +def get_bop_reader(video_dir, zfar=np.inf): + if 'ycbv' in video_dir or 'YCB' in video_dir: + return YcbVideoReader(video_dir, zfar=zfar) + if 'lmo' in video_dir or 'LINEMOD-O' in video_dir: + return LinemodOcclusionReader(video_dir, zfar=zfar) + if 'tless' in video_dir or 'TLESS' in video_dir: + return TlessReader(video_dir, zfar=zfar) + if 'hb' in video_dir: + return HomebrewedReader(video_dir, zfar=zfar) + if 'tudl' in video_dir: + return TudlReader(video_dir, zfar=zfar) + if 'icbin' in video_dir: + return IcbinReader(video_dir, zfar=zfar) + if 'itodd' in video_dir: + return ItoddReader(video_dir, zfar=zfar) + else: + raise RuntimeError + + +def get_bop_video_dirs(dataset): + if dataset=='ycbv': + video_dirs = sorted(glob.glob(f'{BOP_DIR}/ycbv/test/*')) + elif dataset=='lmo': + video_dirs = sorted(glob.glob(f'{BOP_DIR}/lmo/lmo_test_bop19/test/*')) + elif dataset=='tless': + video_dirs = sorted(glob.glob(f'{BOP_DIR}/tless/tless_test_primesense_bop19/test_primesense/*')) + elif dataset=='hb': + video_dirs = sorted(glob.glob(f'{BOP_DIR}/hb/hb_test_primesense_bop19/test_primesense/*')) + elif dataset=='tudl': + video_dirs = sorted(glob.glob(f'{BOP_DIR}/tudl/tudl_test_bop19/test/*')) + elif dataset=='icbin': + video_dirs = sorted(glob.glob(f'{BOP_DIR}/icbin/icbin_test_bop19/test/*')) + elif dataset=='itodd': + video_dirs = sorted(glob.glob(f'{BOP_DIR}/itodd/itodd_test_bop19/test/*')) + else: + raise RuntimeError + return video_dirs + + + +class YcbineoatReader: + def __init__(self,video_dir, downscale=1, shorter_side=None, zfar=np.inf): + self.video_dir = video_dir + self.downscale = downscale + self.zfar = zfar + self.color_files = sorted(glob.glob(f"{self.video_dir}/rgb/*.png")) + self.K = np.loadtxt(f'{video_dir}/cam_K.txt').reshape(3,3) + self.id_strs = [] + for color_file in self.color_files: + id_str = os.path.basename(color_file).replace('.png','') + self.id_strs.append(id_str) + self.H,self.W = cv2.imread(self.color_files[0]).shape[:2] + + if shorter_side is not None: + self.downscale = shorter_side/min(self.H, self.W) + + self.H = int(self.H*self.downscale) + self.W = int(self.W*self.downscale) + self.K[:2] *= self.downscale + + self.gt_pose_files = sorted(glob.glob(f'{self.video_dir}/annotated_poses/*')) + + self.videoname_to_object = { + 'bleach0': "021_bleach_cleanser", + 'bleach_hard_00_03_chaitanya': "021_bleach_cleanser", + 'cracker_box_reorient': '003_cracker_box', + 'cracker_box_yalehand0': '003_cracker_box', + 'mustard0': '006_mustard_bottle', + 'mustard_easy_00_02': '006_mustard_bottle', + 'sugar_box1': '004_sugar_box', + 'sugar_box_yalehand0': '004_sugar_box', + 'tomato_soup_can_yalehand0': '005_tomato_soup_can', + } + + + def get_video_name(self): + return self.video_dir.split('/')[-1] + + def __len__(self): + return len(self.color_files) + + def get_gt_pose(self,i): + try: + pose = np.loadtxt(self.gt_pose_files[i]).reshape(4,4) + return pose + except: + logging.info("GT pose not found, return None") + return None + + + def get_color(self,i): + color = imageio.imread(self.color_files[i])[...,:3] + color = cv2.resize(color, (self.W,self.H), interpolation=cv2.INTER_NEAREST) + return color + + def get_mask(self,i): + mask = cv2.imread(self.color_files[i].replace('rgb','masks'),-1) + if len(mask.shape)==3: + for c in range(3): + if mask[...,c].sum()>0: + mask = mask[...,c] + break + mask = cv2.resize(mask, (self.W,self.H), interpolation=cv2.INTER_NEAREST).astype(bool).astype(np.uint8) + return mask + + def get_depth(self,i): + depth = cv2.imread(self.color_files[i].replace('rgb','depth'),-1)/1e3 + depth = cv2.resize(depth, (self.W,self.H), interpolation=cv2.INTER_NEAREST) + depth[(depth<0.001) | (depth>=self.zfar)] = 0 + return depth + + + def get_xyz_map(self,i): + depth = self.get_depth(i) + xyz_map = depth2xyzmap(depth, self.K) + return xyz_map + + def get_occ_mask(self,i): + hand_mask_file = self.color_files[i].replace('rgb','masks_hand') + occ_mask = np.zeros((self.H,self.W), dtype=bool) + if os.path.exists(hand_mask_file): + occ_mask = occ_mask | (cv2.imread(hand_mask_file,-1)>0) + + right_hand_mask_file = self.color_files[i].replace('rgb','masks_hand_right') + if os.path.exists(right_hand_mask_file): + occ_mask = occ_mask | (cv2.imread(right_hand_mask_file,-1)>0) + + occ_mask = cv2.resize(occ_mask, (self.W,self.H), interpolation=cv2.INTER_NEAREST) + + return occ_mask.astype(np.uint8) + + def get_gt_mesh(self): + ob_name = self.videoname_to_object[self.get_video_name()] + YCB_VIDEO_DIR = os.getenv('YCB_VIDEO_DIR') + mesh = trimesh.load(f'{YCB_VIDEO_DIR}/models/{ob_name}/textured_simple.obj') + return mesh + + +class BopBaseReader: + def __init__(self, base_dir, zfar=np.inf, resize=1): + self.base_dir = base_dir + self.resize = resize + self.dataset_name = None + self.color_files = sorted(glob.glob(f"{self.base_dir}/rgb/*")) + if len(self.color_files)==0: + self.color_files = sorted(glob.glob(f"{self.base_dir}/gray/*")) + self.zfar = zfar + + self.K_table = {} + with open(f'{self.base_dir}/scene_camera.json','r') as ff: + info = json.load(ff) + for k in info: + self.K_table[f'{int(k):06d}'] = np.array(info[k]['cam_K']).reshape(3,3) + self.bop_depth_scale = info[k]['depth_scale'] + + if os.path.exists(f'{self.base_dir}/scene_gt.json'): + with open(f'{self.base_dir}/scene_gt.json','r') as ff: + self.scene_gt = json.load(ff) + self.scene_gt = copy.deepcopy(self.scene_gt) # Release file handle to be pickle-able by joblib + assert len(self.scene_gt)==len(self.color_files) + else: + self.scene_gt = None + + self.make_id_strs() + + + def make_scene_ob_ids_dict(self): + with open(f'{BOP_DIR}/{self.dataset_name}/test_targets_bop19.json','r') as ff: + self.scene_ob_ids_dict = {} + data = json.load(ff) + for d in data: + if d['scene_id']==self.get_video_id(): + id_str = f"{d['im_id']:06d}" + if id_str not in self.scene_ob_ids_dict: + self.scene_ob_ids_dict[id_str] = [] + self.scene_ob_ids_dict[id_str] += [d['obj_id']]*d['inst_count'] + + + def get_K(self, i_frame): + K = self.K_table[self.id_strs[i_frame]] + if self.resize!=1: + K[:2,:2] *= self.resize + return K + + + def get_video_dir(self): + video_id = int(self.base_dir.rstrip('/').split('/')[-1]) + return video_id + + def make_id_strs(self): + self.id_strs = [] + for i in range(len(self.color_files)): + name = os.path.basename(self.color_files[i]).split('.')[0] + self.id_strs.append(name) + + + def get_instance_ids_in_image(self, i_frame:int): + ob_ids = [] + if self.scene_gt is not None: + name = int(os.path.basename(self.color_files[i_frame]).split('.')[0]) + for k in self.scene_gt[str(name)]: + ob_ids.append(k['obj_id']) + elif self.scene_ob_ids_dict is not None: + return np.array(self.scene_ob_ids_dict[self.id_strs[i_frame]]) + else: + mask_dir = os.path.dirname(self.color_files[0]).replace('rgb','mask_visib') + id_str = self.id_strs[i_frame] + mask_files = sorted(glob.glob(f'{mask_dir}/{id_str}_*.png')) + ob_ids = [] + for mask_file in mask_files: + ob_id = int(os.path.basename(mask_file).split('.')[0].split('_')[1]) + ob_ids.append(ob_id) + ob_ids = np.asarray(ob_ids) + return ob_ids + + + def get_gt_mesh_file(self, ob_id): + raise RuntimeError("You should override this") + + + def get_color(self,i): + color = imageio.imread(self.color_files[i]) + if len(color.shape)==2: + color = np.tile(color[...,None], (1,1,3)) # Gray to RGB + if self.resize!=1: + color = cv2.resize(color, fx=self.resize, fy=self.resize, dsize=None) + return color + + + def get_depth(self,i, filled=False): + if filled: + depth_file = self.color_files[i].replace('rgb','depth_filled') + depth_file = f'{os.path.dirname(depth_file)}/0{os.path.basename(depth_file)}' + depth = cv2.imread(depth_file,-1)/1e3 + else: + depth_file = self.color_files[i].replace('rgb','depth').replace('gray','depth') + depth = cv2.imread(depth_file,-1)*1e-3*self.bop_depth_scale + if self.resize!=1: + depth = cv2.resize(depth, fx=self.resize, fy=self.resize, dsize=None, interpolation=cv2.INTER_NEAREST) + depth[depth<0.001] = 0 + depth[depth>self.zfar] = 0 + return depth + + def get_xyz_map(self,i): + depth = self.get_depth(i) + xyz_map = depth2xyzmap(depth, self.get_K(i)) + return xyz_map + + + def get_mask(self, i_frame:int, ob_id:int, type='mask_visib'): + ''' + @type: mask_visib (only visible part) / mask (projected mask from whole model) + ''' + pos = 0 + name = int(os.path.basename(self.color_files[i_frame]).split('.')[0]) + if self.scene_gt is not None: + for k in self.scene_gt[str(name)]: + if k['obj_id']==ob_id: + break + pos += 1 + mask_file = f'{self.base_dir}/{type}/{name:06d}_{pos:06d}.png' + if not os.path.exists(mask_file): + logging.info(f'{mask_file} not found') + return None + else: + # mask_dir = os.path.dirname(self.color_files[0]).replace('rgb',type) + # mask_file = f'{mask_dir}/{self.id_strs[i_frame]}_{ob_id:06d}.png' + raise RuntimeError + mask = cv2.imread(mask_file, -1) + if self.resize!=1: + mask = cv2.resize(mask, fx=self.resize, fy=self.resize, dsize=None, interpolation=cv2.INTER_NEAREST) + return mask>0 + + + def get_gt_mesh(self, ob_id:int): + mesh_file = self.get_gt_mesh_file(ob_id) + mesh = trimesh.load(mesh_file) + mesh.vertices *= 1e-3 + return mesh + + + def get_model_diameter(self, ob_id): + dir = os.path.dirname(self.get_gt_mesh_file(self.ob_ids[0])) + info_file = f'{dir}/models_info.json' + with open(info_file,'r') as ff: + info = json.load(ff) + return info[str(ob_id)]['diameter']/1e3 + + + + def get_gt_poses(self, i_frame, ob_id): + gt_poses = [] + name = int(self.id_strs[i_frame]) + for i_k, k in enumerate(self.scene_gt[str(name)]): + if k['obj_id']==ob_id: + cur = np.eye(4) + cur[:3,:3] = np.array(k['cam_R_m2c']).reshape(3,3) + cur[:3,3] = np.array(k['cam_t_m2c'])/1e3 + gt_poses.append(cur) + return np.asarray(gt_poses).reshape(-1,4,4) + + + def get_gt_pose(self, i_frame:int, ob_id, mask=None, use_my_correction=False): + ob_in_cam = np.eye(4) + best_iou = -np.inf + best_gt_mask = None + name = int(self.id_strs[i_frame]) + for i_k, k in enumerate(self.scene_gt[str(name)]): + if k['obj_id']==ob_id: + cur = np.eye(4) + cur[:3,:3] = np.array(k['cam_R_m2c']).reshape(3,3) + cur[:3,3] = np.array(k['cam_t_m2c'])/1e3 + if mask is not None: # When multi-instance exists, use mask to determine which one + gt_mask = cv2.imread(f'{self.base_dir}/mask_visib/{self.id_strs[i_frame]}_{i_k:06d}.png', -1).astype(bool) + intersect = (gt_mask*mask).astype(bool) + union = (gt_mask+mask).astype(bool) + iou = float(intersect.sum())/union.sum() + if iou>best_iou: + best_iou = iou + best_gt_mask = gt_mask + ob_in_cam = cur + else: + ob_in_cam = cur + break + + + if use_my_correction: + if 'ycb' in self.base_dir.lower() and 'train_real' in self.color_files[i_frame]: + video_id = self.get_video_id() + if ob_id==1: + if video_id in [12,13,14,17,24]: + ob_in_cam = ob_in_cam@self.symmetry_tfs[ob_id][1] + return ob_in_cam + + + def load_symmetry_tfs(self): + dir = os.path.dirname(self.get_gt_mesh_file(self.ob_ids[0])) + info_file = f'{dir}/models_info.json' + with open(info_file,'r') as ff: + info = json.load(ff) + self.symmetry_tfs = {} + self.symmetry_info_table = {} + for ob_id in self.ob_ids: + self.symmetry_info_table[ob_id] = info[str(ob_id)] + self.symmetry_tfs[ob_id] = symmetry_tfs_from_info(info[str(ob_id)], rot_angle_discrete=5) + self.geometry_symmetry_info_table = copy.deepcopy(self.symmetry_info_table) + + + def get_video_id(self): + return int(self.base_dir.split('/')[-1]) + + +class LinemodOcclusionReader(BopBaseReader): + def __init__(self,base_dir='/mnt/9a72c439-d0a7-45e8-8d20-d7a235d02763/DATASET/LINEMOD-O/lmo_test_all/test/000002', zfar=np.inf): + super().__init__(base_dir, zfar=zfar) + self.dataset_name = 'lmo' + self.K = list(self.K_table.values())[0] + self.ob_ids = [1,5,6,8,9,10,11,12] + self.ob_id_to_names = { + 1: 'ape', + 2: 'benchvise', + 3: 'bowl', + 4: 'camera', + 5: 'water_pour', + 6: 'cat', + 7: 'cup', + 8: 'driller', + 9: 'duck', + 10: 'eggbox', + 11: 'glue', + 12: 'holepuncher', + 13: 'iron', + 14: 'lamp', + 15: 'phone', + } + self.load_symmetry_tfs() + + def get_gt_mesh_file(self, ob_id): + mesh_dir = f'{BOP_DIR}/{self.dataset_name}/models/obj_{ob_id:06d}.ply' + return mesh_dir + + + +class LinemodReader(LinemodOcclusionReader): + def __init__(self, base_dir='/mnt/9a72c439-d0a7-45e8-8d20-d7a235d02763/DATASET/LINEMOD/lm_test_all/test/000001', zfar=np.inf, split=None): + super().__init__(base_dir, zfar=zfar) + self.dataset_name = 'lm' + if split is not None: # train/test + with open(f'/mnt/9a72c439-d0a7-45e8-8d20-d7a235d02763/DATASET/LINEMOD/Linemod_preprocessed/data/{self.get_video_id():02d}/{split}.txt','r') as ff: + lines = ff.read().splitlines() + self.color_files = [] + for line in lines: + id = int(line) + self.color_files.append(f'{self.base_dir}/rgb/{id:06d}.png') + self.make_id_strs() + + self.ob_ids = np.setdiff1d(np.arange(1,16), np.array([7,3])).tolist() # Exclude bowl and mug + self.load_symmetry_tfs() + + + def get_gt_mesh_file(self, ob_id): + root = self.base_dir + while 1: + if os.path.exists(f'{root}/lm_models'): + mesh_dir = f'{root}/lm_models/models/obj_{ob_id:06d}.ply' + break + else: + root = os.path.abspath(f'{root}/../') + return mesh_dir + + + def get_reconstructed_mesh(self, ob_id, ref_view_dir): + mesh = trimesh.load(os.path.abspath(f'{ref_view_dir}/ob_{ob_id:07d}/model/model.obj')) + return mesh + + +class YcbVideoReader(BopBaseReader): + def __init__(self, base_dir, zfar=np.inf): + super().__init__(base_dir, zfar=zfar) + self.dataset_name = 'ycbv' + self.K = list(self.K_table.values())[0] + + self.make_id_strs() + + self.ob_ids = np.arange(1,22).astype(int).tolist() + YCB_VIDEO_DIR = os.getenv('YCB_VIDEO_DIR') + names = sorted(os.listdir(f'{YCB_VIDEO_DIR}/models/')) + self.ob_id_to_names = {} + self.name_to_ob_id = {} + for i,ob_id in enumerate(self.ob_ids): + self.ob_id_to_names[ob_id] = names[i] + self.name_to_ob_id[names[i]] = ob_id + + if 'BOP' not in self.base_dir: + with open(f'{self.base_dir}/../../keyframe.txt','r') as ff: + self.keyframe_lines = ff.read().splitlines() + + self.load_symmetry_tfs() + for ob_id in self.ob_ids: + if ob_id in [1,4,6,18]: # Cylinder + self.geometry_symmetry_info_table[ob_id] = { + 'symmetries_continuous': [ + {'axis':[0,0,1], 'offset':[0,0,0]}, + ], + 'symmetries_discrete': euler_matrix(0, np.pi, 0).reshape(1,4,4).tolist(), + } + elif ob_id in [13]: + self.geometry_symmetry_info_table[ob_id] = { + 'symmetries_continuous': [ + {'axis':[0,0,1], 'offset':[0,0,0]}, + ], + } + elif ob_id in [2,3,9,21]: # Rectangle box + tfs = [] + for rz in [0, np.pi]: + for rx in [0,np.pi]: + for ry in [0,np.pi]: + tfs.append(euler_matrix(rx, ry, rz)) + self.geometry_symmetry_info_table[ob_id] = { + 'symmetries_discrete': np.asarray(tfs).reshape(-1,4,4).tolist(), + } + else: + pass + + def get_gt_mesh_file(self, ob_id): + if 'BOP' in self.base_dir: + mesh_file = os.path.abspath(f'{self.base_dir}/../../ycbv_models/models/obj_{ob_id:06d}.ply') + else: + mesh_file = f'{self.base_dir}/../../ycbv_models/models/obj_{ob_id:06d}.ply' + return mesh_file + + + def get_gt_mesh(self, ob_id:int, get_posecnn_version=False): + if get_posecnn_version: + YCB_VIDEO_DIR = os.getenv('YCB_VIDEO_DIR') + mesh = trimesh.load(f'{YCB_VIDEO_DIR}/models/{self.ob_id_to_names[ob_id]}/textured_simple.obj') + return mesh + mesh_file = self.get_gt_mesh_file(ob_id) + mesh = trimesh.load(mesh_file, process=False) + mesh.vertices *= 1e-3 + tex_file = mesh_file.replace('.ply','.png') + if os.path.exists(tex_file): + from PIL import Image + im = Image.open(tex_file) + uv = mesh.visual.uv + material = trimesh.visual.texture.SimpleMaterial(image=im) + color_visuals = trimesh.visual.TextureVisuals(uv=uv, image=im, material=material) + mesh.visual = color_visuals + return mesh + + + def get_reconstructed_mesh(self, ob_id, ref_view_dir): + mesh = trimesh.load(os.path.abspath(f'{ref_view_dir}/ob_{ob_id:07d}/model/model.obj')) + return mesh + + + def get_transform_reconstructed_to_gt_model(self, ob_id): + out = np.eye(4) + return out + + + def get_visible_cloud(self, ob_id): + file = os.path.abspath(f'{self.base_dir}/../../models/{self.ob_id_to_names[ob_id]}/visible_cloud.ply') + pcd = o3d.io.read_point_cloud(file) + return pcd + + + def is_keyframe(self, i): + color_file = self.color_files[i] + video_id = self.get_video_id() + frame_id = int(os.path.basename(color_file).split('.')[0]) + key = f'{video_id:04d}/{frame_id:06d}' + return (key in self.keyframe_lines) + + + +class TlessReader(BopBaseReader): + def __init__(self, base_dir, zfar=np.inf): + super().__init__(base_dir, zfar=zfar) + self.dataset_name = 'tless' + + self.ob_ids = np.arange(1,31).astype(int).tolist() + self.load_symmetry_tfs() + + + def get_gt_mesh_file(self, ob_id): + mesh_file = f'{self.base_dir}/../../../models_cad/obj_{ob_id:06d}.ply' + return mesh_file + + + def get_gt_mesh(self, ob_id): + mesh = trimesh.load(self.get_gt_mesh_file(ob_id)) + mesh.vertices *= 1e-3 + mesh = trimesh_add_pure_colored_texture(mesh, color=np.ones((3))*200) + return mesh + + +class HomebrewedReader(BopBaseReader): + def __init__(self, base_dir, zfar=np.inf): + super().__init__(base_dir, zfar=zfar) + self.dataset_name = 'hb' + self.ob_ids = np.arange(1,34).astype(int).tolist() + self.load_symmetry_tfs() + self.make_scene_ob_ids_dict() + + + def get_gt_mesh_file(self, ob_id): + mesh_file = f'{self.base_dir}/../../../hb_models/models/obj_{ob_id:06d}.ply' + return mesh_file + + + def get_gt_pose(self, i_frame:int, ob_id, use_my_correction=False): + logging.info("WARN HomeBrewed doesn't have GT pose") + return np.eye(4) + + + +class ItoddReader(BopBaseReader): + def __init__(self, base_dir, zfar=np.inf): + super().__init__(base_dir, zfar=zfar) + self.dataset_name = 'itodd' + self.make_id_strs() + + self.ob_ids = np.arange(1,29).astype(int).tolist() + self.load_symmetry_tfs() + self.make_scene_ob_ids_dict() + + + def get_gt_mesh_file(self, ob_id): + mesh_file = f'{self.base_dir}/../../../itodd_models/models/obj_{ob_id:06d}.ply' + return mesh_file + + +class IcbinReader(BopBaseReader): + def __init__(self, base_dir, zfar=np.inf): + super().__init__(base_dir, zfar=zfar) + self.dataset_name = 'icbin' + self.ob_ids = np.arange(1,3).astype(int).tolist() + self.load_symmetry_tfs() + + def get_gt_mesh_file(self, ob_id): + mesh_file = f'{self.base_dir}/../../../icbin_models/models/obj_{ob_id:06d}.ply' + return mesh_file + + +class TudlReader(BopBaseReader): + def __init__(self, base_dir, zfar=np.inf): + super().__init__(base_dir, zfar=zfar) + self.dataset_name = 'tudl' + self.ob_ids = np.arange(1,4).astype(int).tolist() + self.load_symmetry_tfs() + + def get_gt_mesh_file(self, ob_id): + mesh_file = f'{self.base_dir}/../../../tudl_models/models/obj_{ob_id:06d}.ply' + return mesh_file + + diff --git a/third-party/video_to_data/reconstruction/modules/v2d_foundation_pose/lib/FoundationPose/docker/dockerfile b/third-party/video_to_data/reconstruction/modules/v2d_foundation_pose/lib/FoundationPose/docker/dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..fc235a80f6f8e9e31e38aa1a29877747a400dfdb --- /dev/null +++ b/third-party/video_to_data/reconstruction/modules/v2d_foundation_pose/lib/FoundationPose/docker/dockerfile @@ -0,0 +1,60 @@ +FROM nvidia/cudagl:11.3.0-devel-ubuntu20.04 + +ENV TZ=US/Pacific +RUN ln -snf /usr/share/zoneinfo/$TZ /etc/localtime && echo $TZ > /etc/timezone + +RUN apt-get update --fix-missing && \ + apt-get install -y libgtk2.0-dev && \ + apt-get install -y wget bzip2 ca-certificates curl git vim tmux g++ gcc build-essential cmake checkinstall gfortran libjpeg8-dev libtiff5-dev pkg-config yasm libavcodec-dev libavformat-dev libswscale-dev libdc1394-22-dev libxine2-dev libv4l-dev qt5-default libgtk2.0-dev libtbb-dev libatlas-base-dev libfaac-dev libmp3lame-dev libtheora-dev libvorbis-dev libxvidcore-dev libopencore-amrnb-dev libopencore-amrwb-dev x264 v4l-utils libprotobuf-dev protobuf-compiler libgoogle-glog-dev libgflags-dev libgphoto2-dev libhdf5-dev doxygen libflann-dev libboost-all-dev proj-data libproj-dev libyaml-cpp-dev cmake-curses-gui libzmq3-dev freeglut3-dev + + +RUN cd / && git clone https://github.com/pybind/pybind11 &&\ + cd pybind11 && git checkout v2.10.0 &&\ + mkdir build && cd build && cmake .. -DCMAKE_BUILD_TYPE=Release -DPYBIND11_INSTALL=ON -DPYBIND11_TEST=OFF &&\ + make -j6 && make install + + +RUN cd / && wget https://gitlab.com/libeigen/eigen/-/archive/3.4.0/eigen-3.4.0.tar.gz &&\ + tar xvzf ./eigen-3.4.0.tar.gz &&\ + cd eigen-3.4.0 &&\ + mkdir build &&\ + cd build &&\ + cmake .. &&\ + make install + +SHELL ["/bin/bash", "--login", "-c"] + +RUN cd / && wget --quiet https://repo.anaconda.com/miniconda/Miniconda3-latest-Linux-x86_64.sh -O /miniconda.sh && \ + /bin/bash /miniconda.sh -b -p /opt/conda &&\ + ln -s /opt/conda/etc/profile.d/conda.sh /etc/profile.d/conda.sh &&\ + echo ". /opt/conda/etc/profile.d/conda.sh" >> ~/.bashrc &&\ + /bin/bash -c "source ~/.bashrc" && \ + /opt/conda/bin/conda update -n base -c defaults conda -y &&\ + /opt/conda/bin/conda create -n my python=3.8 + + +ENV PATH $PATH:/opt/conda/envs/my/bin + +RUN conda init bash &&\ + echo "conda activate my" >> ~/.bashrc &&\ + conda activate my &&\ + pip install torch==2.0.0+cu118 torchvision==0.15.1+cu118 torchaudio==2.0.1 --index-url https://download.pytorch.org/whl/cu118 &&\ + pip install "git+https://github.com/facebookresearch/pytorch3d.git@stable" &&\ + pip install scipy joblib scikit-learn ruamel.yaml trimesh pyyaml opencv-python imageio open3d transformations warp-lang einops kornia pyrender + +RUN cd / && git clone --recursive https://github.com/NVIDIAGameWorks/kaolin +RUN conda activate my && cd /kaolin &&\ + FORCE_CUDA=1 python setup.py develop + +RUN cd / && git clone https://github.com/NVlabs/nvdiffrast &&\ + conda activate my && cd /nvdiffrast && pip install . + +ENV OPENCV_IO_ENABLE_OPENEXR=1 + +RUN conda activate my &&\ + pip install scikit-image meshcat webdataset omegaconf pypng roma seaborn opencv-contrib-python openpyxl wandb imgaug Ninja xlsxwriter timm albumentations xatlas rtree nodejs jupyterlab objaverse g4f ultralytics==8.0.120 pycocotools videoio numba &&\ + conda install -y -c anaconda h5py + + +ENV SHELL=/bin/bash +RUN ln -sf /bin/bash /bin/sh diff --git a/third-party/video_to_data/reconstruction/modules/v2d_foundation_pose/lib/FoundationPose/docker/run_container.sh b/third-party/video_to_data/reconstruction/modules/v2d_foundation_pose/lib/FoundationPose/docker/run_container.sh new file mode 100644 index 0000000000000000000000000000000000000000..85035714e53650c4c09cf67c01d94d08e62d78e3 --- /dev/null +++ b/third-party/video_to_data/reconstruction/modules/v2d_foundation_pose/lib/FoundationPose/docker/run_container.sh @@ -0,0 +1,3 @@ +docker rm -f foundationpose +DIR=$(pwd)/../ +xhost + && docker run --gpus all --env NVIDIA_DISABLE_REQUIRE=1 -it --network=host --name foundationpose --cap-add=SYS_PTRACE --security-opt seccomp=unconfined -v $DIR:$DIR -v /home:/home -v /mnt:/mnt -v /tmp/.X11-unix:/tmp/.X11-unix -v /tmp:/tmp --ipc=host -e DISPLAY=${DISPLAY} -e GIT_INDEX_FILE foundationpose:latest bash -c "cd $DIR && bash" diff --git a/third-party/video_to_data/reconstruction/modules/v2d_foundation_pose/lib/FoundationPose/estimater.py b/third-party/video_to_data/reconstruction/modules/v2d_foundation_pose/lib/FoundationPose/estimater.py new file mode 100644 index 0000000000000000000000000000000000000000..215a948193336a3c1e749e82b8a607d08c59f562 --- /dev/null +++ b/third-party/video_to_data/reconstruction/modules/v2d_foundation_pose/lib/FoundationPose/estimater.py @@ -0,0 +1,275 @@ +# Copyright (c) 2023, NVIDIA CORPORATION. All rights reserved. +# +# NVIDIA CORPORATION and its licensors retain all intellectual property +# and proprietary rights in and to this software, related documentation +# and any modifications thereto. Any use, reproduction, disclosure or +# distribution of this software and related documentation without an express +# license agreement from NVIDIA CORPORATION is strictly prohibited. + + +from Utils import * +from datareader import * +import itertools +from learning.training.predict_score import * +from learning.training.predict_pose_refine import * +import yaml + + +class FoundationPose: + def __init__(self, model_pts, model_normals, symmetry_tfs=None, mesh=None, scorer:ScorePredictor=None, refiner:PoseRefinePredictor=None, glctx=None, debug=0, debug_dir='/home/bowen/debug/novel_pose_debug/'): + self.gt_pose = None + self.ignore_normal_flip = True + self.debug = debug + self.debug_dir = debug_dir + os.makedirs(debug_dir, exist_ok=True) + + self.reset_object(model_pts, model_normals, symmetry_tfs=symmetry_tfs, mesh=mesh) + self.make_rotation_grid(min_n_views=40, inplane_step=60) + + self.glctx = glctx + + if scorer is not None: + self.scorer = scorer + else: + self.scorer = ScorePredictor() + + if refiner is not None: + self.refiner = refiner + else: + self.refiner = PoseRefinePredictor() + + self.pose_last = None # Used for tracking; per the centered mesh + + + def reset_object(self, model_pts, model_normals, symmetry_tfs=None, mesh=None): + max_xyz = mesh.vertices.max(axis=0) + min_xyz = mesh.vertices.min(axis=0) + self.model_center = (min_xyz+max_xyz)/2 + if mesh is not None: + self.mesh_ori = mesh.copy() + mesh = mesh.copy() + mesh.vertices = mesh.vertices - self.model_center.reshape(1,3) + + model_pts = mesh.vertices + self.diameter = compute_mesh_diameter(model_pts=mesh.vertices, n_sample=10000) + self.vox_size = max(self.diameter/20.0, 0.003) + logging.info(f'self.diameter:{self.diameter}, vox_size:{self.vox_size}') + self.dist_bin = self.vox_size/2 + self.angle_bin = 20 # Deg + pcd = toOpen3dCloud(model_pts, normals=model_normals) + pcd = pcd.voxel_down_sample(self.vox_size) + self.max_xyz = np.asarray(pcd.points).max(axis=0) + self.min_xyz = np.asarray(pcd.points).min(axis=0) + self.pts = torch.tensor(np.asarray(pcd.points), dtype=torch.float32, device='cuda') + self.normals = F.normalize(torch.tensor(np.asarray(pcd.normals), dtype=torch.float32, device='cuda'), dim=-1) + logging.info(f'self.pts:{self.pts.shape}') + self.mesh_path = None + self.mesh = mesh + if self.mesh is not None: + self.mesh_path = f'/tmp/{uuid.uuid4()}.obj' + self.mesh.export(self.mesh_path) + self.mesh_tensors = make_mesh_tensors(self.mesh) + + if symmetry_tfs is None: + self.symmetry_tfs = torch.eye(4).float().cuda()[None] + else: + self.symmetry_tfs = torch.as_tensor(symmetry_tfs, device='cuda', dtype=torch.float) + + logging.info("reset done") + + + + def get_tf_to_centered_mesh(self): + tf_to_center = torch.eye(4, dtype=torch.float, device='cuda') + tf_to_center[:3,3] = -torch.as_tensor(self.model_center, device='cuda', dtype=torch.float) + return tf_to_center + + + def to_device(self, s='cuda:0'): + for k in self.__dict__: + self.__dict__[k] = self.__dict__[k] + if torch.is_tensor(self.__dict__[k]) or isinstance(self.__dict__[k], nn.Module): + logging.info(f"Moving {k} to device {s}") + self.__dict__[k] = self.__dict__[k].to(s) + for k in self.mesh_tensors: + logging.info(f"Moving {k} to device {s}") + self.mesh_tensors[k] = self.mesh_tensors[k].to(s) + if self.refiner is not None: + self.refiner.model.to(s) + if self.scorer is not None: + self.scorer.model.to(s) + if self.glctx is not None: + self.glctx = dr.RasterizeCudaContext(s) + + + + def make_rotation_grid(self, min_n_views=40, inplane_step=60): + cam_in_obs = sample_views_icosphere(n_views=min_n_views) + logging.info(f'cam_in_obs:{cam_in_obs.shape}') + rot_grid = [] + for i in range(len(cam_in_obs)): + for inplane_rot in np.deg2rad(np.arange(0, 360, inplane_step)): + cam_in_ob = cam_in_obs[i] + R_inplane = euler_matrix(0,0,inplane_rot) + cam_in_ob = cam_in_ob@R_inplane + ob_in_cam = np.linalg.inv(cam_in_ob) + rot_grid.append(ob_in_cam) + + rot_grid = np.asarray(rot_grid) + logging.info(f"rot_grid:{rot_grid.shape}") + + # Ensure proper data type and memory layout for C++ module + rot_grid = np.ascontiguousarray(rot_grid, dtype=np.float32) + symmetry_tfs = np.ascontiguousarray(self.symmetry_tfs.data.cpu().numpy(), dtype=np.float32) + + rot_grid = mycpp.cluster_poses(30, 99999, rot_grid, symmetry_tfs) + rot_grid = np.asarray(rot_grid) + logging.info(f"after cluster, rot_grid:{rot_grid.shape}") + self.rot_grid = torch.as_tensor(rot_grid, device='cuda', dtype=torch.float) + logging.info(f"self.rot_grid: {self.rot_grid.shape}") + + + def generate_random_pose_hypo(self, K, rgb, depth, mask, scene_pts=None): + ''' + @scene_pts: torch tensor (N,3) + ''' + ob_in_cams = self.rot_grid.clone() + center = self.guess_translation(depth=depth, mask=mask, K=K) + ob_in_cams[:,:3,3] = torch.tensor(center, device='cuda', dtype=torch.float).reshape(1,3) + return ob_in_cams + + + def guess_translation(self, depth, mask, K): + vs,us = np.where(mask>0) + if len(us)==0: + logging.info(f'mask is all zero') + return np.zeros((3)) + uc = (us.min()+us.max())/2.0 + vc = (vs.min()+vs.max())/2.0 + valid = mask.astype(bool) & (depth>=0.001) + if not valid.any(): + logging.info(f"valid is empty") + return np.zeros((3)) + + zc = np.median(depth[valid]) + center = (np.linalg.inv(K)@np.asarray([uc,vc,1]).reshape(3,1))*zc + + if self.debug>=2: + pcd = toOpen3dCloud(center.reshape(1,3)) + o3d.io.write_point_cloud(f'{self.debug_dir}/init_center.ply', pcd) + + return center.reshape(3) + + + def register(self, K, rgb, depth, ob_mask, ob_id=None, glctx=None, iteration=5): + '''Copmute pose from given pts to self.pcd + @pts: (N,3) np array, downsampled scene points + ''' + set_seed(0) + logging.info('Welcome') + + if self.glctx is None: + if glctx is None: + self.glctx = dr.RasterizeCudaContext() + # self.glctx = dr.RasterizeGLContext() + else: + self.glctx = glctx + + depth = erode_depth(depth, radius=2, device='cuda') + depth = bilateral_filter_depth(depth, radius=2, device='cuda') + + if self.debug>=2: + xyz_map = depth2xyzmap(depth, K) + valid = xyz_map[...,2]>=0.001 + pcd = toOpen3dCloud(xyz_map[valid], rgb[valid]) + o3d.io.write_point_cloud(f'{self.debug_dir}/scene_raw.ply',pcd) + cv2.imwrite(f'{self.debug_dir}/ob_mask.png', (ob_mask*255.0).clip(0,255)) + + normal_map = None + valid = (depth>=0.001) & (ob_mask>0) + if valid.sum()<4: + logging.info(f'valid too small, return') + pose = np.eye(4) + pose[:3,3] = self.guess_translation(depth=depth, mask=ob_mask, K=K) + return pose + + if self.debug>=2: + imageio.imwrite(f'{self.debug_dir}/color.png', rgb) + cv2.imwrite(f'{self.debug_dir}/depth.png', (depth*1000).astype(np.uint16)) + valid = xyz_map[...,2]>=0.001 + pcd = toOpen3dCloud(xyz_map[valid], rgb[valid]) + o3d.io.write_point_cloud(f'{self.debug_dir}/scene_complete.ply',pcd) + + self.H, self.W = depth.shape[:2] + self.K = K + self.ob_id = ob_id + self.ob_mask = ob_mask + + poses = self.generate_random_pose_hypo(K=K, rgb=rgb, depth=depth, mask=ob_mask, scene_pts=None) + poses = poses.data.cpu().numpy() + logging.info(f'poses:{poses.shape}') + center = self.guess_translation(depth=depth, mask=ob_mask, K=K) + + poses = torch.as_tensor(poses, device='cuda', dtype=torch.float) + poses[:,:3,3] = torch.as_tensor(center.reshape(1,3), device='cuda') + + add_errs = self.compute_add_err_to_gt_pose(poses) + logging.info(f"after viewpoint, add_errs min:{add_errs.min()}") + + xyz_map = depth2xyzmap(depth, K) + poses, vis = self.refiner.predict(mesh=self.mesh, mesh_tensors=self.mesh_tensors, rgb=rgb, depth=depth, K=K, ob_in_cams=poses.data.cpu().numpy(), normal_map=normal_map, xyz_map=xyz_map, glctx=self.glctx, mesh_diameter=self.diameter, iteration=iteration, get_vis=self.debug>=2) + if vis is not None: + imageio.imwrite(f'{self.debug_dir}/vis_refiner.png', vis) + + scores, vis = self.scorer.predict(mesh=self.mesh, rgb=rgb, depth=depth, K=K, ob_in_cams=poses.data.cpu().numpy(), normal_map=normal_map, mesh_tensors=self.mesh_tensors, glctx=self.glctx, mesh_diameter=self.diameter, get_vis=self.debug>=2) + if vis is not None: + imageio.imwrite(f'{self.debug_dir}/vis_score.png', vis) + + add_errs = self.compute_add_err_to_gt_pose(poses) + logging.info(f"final, add_errs min:{add_errs.min()}") + + ids = torch.as_tensor(scores).argsort(descending=True) + logging.info(f'sort ids:{ids}') + scores = scores[ids] + poses = poses[ids] + + logging.info(f'sorted scores:{scores}') + + best_pose = poses[0]@self.get_tf_to_centered_mesh() + self.pose_last = poses[0] + self.best_id = ids[0] + + self.poses = poses + self.scores = scores + + return best_pose.data.cpu().numpy() + + + def compute_add_err_to_gt_pose(self, poses): + ''' + @poses: wrt. the centered mesh + ''' + return -torch.ones(len(poses), device='cuda', dtype=torch.float) + + + def track_one(self, rgb, depth, K, iteration, extra={}): + if self.pose_last is None: + logging.info("Please init pose by register first") + raise RuntimeError + logging.info("Welcome") + + depth = torch.as_tensor(depth, device='cuda', dtype=torch.float) + depth = erode_depth(depth, radius=2, device='cuda') + depth = bilateral_filter_depth(depth, radius=2, device='cuda') + logging.info("depth processing done") + + xyz_map = depth2xyzmap_batch(depth[None], torch.as_tensor(K, dtype=torch.float, device='cuda')[None], zfar=np.inf)[0] + + pose, vis = self.refiner.predict(mesh=self.mesh, mesh_tensors=self.mesh_tensors, rgb=rgb, depth=depth, K=K, ob_in_cams=self.pose_last.reshape(1,4,4).data.cpu().numpy(), normal_map=None, xyz_map=xyz_map, mesh_diameter=self.diameter, glctx=self.glctx, iteration=iteration, get_vis=self.debug>=2) + logging.info("pose done") + if self.debug>=2: + extra['vis'] = vis + self.pose_last = pose + return (pose@self.get_tf_to_centered_mesh()).data.cpu().numpy().reshape(4,4) + + diff --git a/third-party/video_to_data/reconstruction/modules/v2d_foundation_pose/lib/FoundationPose/learning/datasets/h5_dataset.py b/third-party/video_to_data/reconstruction/modules/v2d_foundation_pose/lib/FoundationPose/learning/datasets/h5_dataset.py new file mode 100644 index 0000000000000000000000000000000000000000..3bb51a5919e199bcc205564f1d075c535e1d5566 --- /dev/null +++ b/third-party/video_to_data/reconstruction/modules/v2d_foundation_pose/lib/FoundationPose/learning/datasets/h5_dataset.py @@ -0,0 +1,220 @@ +# Copyright (c) 2023, NVIDIA CORPORATION. All rights reserved. +# +# NVIDIA CORPORATION and its licensors retain all intellectual property +# and proprietary rights in and to this software, related documentation +# and any modifications thereto. Any use, reproduction, disclosure or +# distribution of this software and related documentation without an express +# license agreement from NVIDIA CORPORATION is strictly prohibited. + + + +import os,sys,h5py,bisect,io,json +code_dir = os.path.dirname(os.path.realpath(__file__)) +sys.path.append(f'{code_dir}/../../../../') +from Utils import * +from learning.datasets.pose_dataset import * + + + + +class PairH5Dataset(torch.utils.data.Dataset): + def __init__(self, cfg, h5_file, mode='train', max_num_key=None, cache_data=None): + self.cfg = cfg + self.h5_file = h5_file + self.mode = mode + + logging.info(f"self.h5_file:{self.h5_file}") + self.n_perturb = None + self.H_ori = None + self.W_ori = None + self.cache_data = cache_data + + if self.mode=='test': + pass + else: + self.object_keys = [] + key_file = h5_file.replace('.h5','_keys.pkl') + if os.path.exists(key_file): + with open(key_file, 'rb') as ff: + self.object_keys = pickle.load(ff) + logging.info(f'object_keys loaded#:{len(self.object_keys)} from {key_file}') + if max_num_key is not None: + self.object_keys = self.object_keys[:max_num_key] + else: + with h5py.File(h5_file, 'r', libver='latest') as hf: + for k in hf: + self.object_keys.append(k) + if max_num_key is not None and len(self.object_keys)>=max_num_key: + logging.info("break due to max_num_key") + break + + logging.info(f'self.object_keys#:{len(self.object_keys)}, max_num_key:{max_num_key}') + + with h5py.File(h5_file, 'r', libver='latest') as hf: + group = hf[self.object_keys[0]] + cnt = 0 + for k_perturb in group: + if 'i_perturb' in k_perturb: + cnt += 1 + if 'crop_ratio' in group[k_perturb]: + self.cfg['crop_ratio'] = float(group[k_perturb]['crop_ratio'][()]) + if self.H_ori is None: + if 'H_ori' in group[k_perturb]: + self.H_ori = int(group[k_perturb]['H_ori'][()]) + self.W_ori = int(group[k_perturb]['W_ori'][()]) + else: + self.H_ori = 540 + self.W_ori = 720 + self.n_perturb = cnt + logging.info(f'self.n_perturb:{self.n_perturb}') + + + def __len__(self): + if self.mode=='test': + return 1 + return len(self.object_keys) + + + + def transform_depth_to_xyzmap(self, batch:BatchPoseData, H_ori, W_ori, bound=1): + bs = len(batch.rgbAs) + H,W = batch.rgbAs.shape[-2:] + mesh_radius = batch.mesh_diameters.cuda()/2 + tf_to_crops = batch.tf_to_crops.cuda() + crop_to_oris = batch.tf_to_crops.inverse().cuda() #(B,3,3) + batch.poseA = batch.poseA.cuda() + batch.Ks = batch.Ks.cuda() + + if batch.xyz_mapAs is None: + depthAs_ori = kornia.geometry.transform.warp_perspective(batch.depthAs.cuda().expand(bs,-1,-1,-1), crop_to_oris, dsize=(H_ori, W_ori), mode='nearest', align_corners=False) + batch.xyz_mapAs = depth2xyzmap_batch(depthAs_ori[:,0], batch.Ks, zfar=np.inf).permute(0,3,1,2) #(B,3,H,W) + batch.xyz_mapAs = kornia.geometry.transform.warp_perspective(batch.xyz_mapAs, tf_to_crops, dsize=(H,W), mode='nearest', align_corners=False) + batch.xyz_mapAs = batch.xyz_mapAs.cuda() + if self.cfg['normalize_xyz']: + invalid = batch.xyz_mapAs[:,2:3]<0.001 + batch.xyz_mapAs = batch.xyz_mapAs-batch.poseA[:,:3,3].reshape(bs,3,1,1) + if self.cfg['normalize_xyz']: + batch.xyz_mapAs *= 1/mesh_radius.reshape(bs,1,1,1) + invalid = invalid.expand(bs,3,-1,-1) | (torch.abs(batch.xyz_mapAs)>=2) + batch.xyz_mapAs[invalid.expand(bs,3,-1,-1)] = 0 + + if batch.xyz_mapBs is None: + depthBs_ori = kornia.geometry.transform.warp_perspective(batch.depthBs.cuda().expand(bs,-1,-1,-1), crop_to_oris, dsize=(H_ori, W_ori), mode='nearest', align_corners=False) + batch.xyz_mapBs = depth2xyzmap_batch(depthBs_ori[:,0], batch.Ks, zfar=np.inf).permute(0,3,1,2) #(B,3,H,W) + batch.xyz_mapBs = kornia.geometry.transform.warp_perspective(batch.xyz_mapBs, tf_to_crops, dsize=(H,W), mode='nearest', align_corners=False) + batch.xyz_mapBs = batch.xyz_mapBs.cuda() + if self.cfg['normalize_xyz']: + invalid = batch.xyz_mapBs[:,2:3]<0.001 + batch.xyz_mapBs = batch.xyz_mapBs-batch.poseA[:,:3,3].reshape(bs,3,1,1) + if self.cfg['normalize_xyz']: + batch.xyz_mapBs *= 1/mesh_radius.reshape(bs,1,1,1) + invalid = invalid.expand(bs,3,-1,-1) | (torch.abs(batch.xyz_mapBs)>=2) + batch.xyz_mapBs[invalid.expand(bs,3,-1,-1)] = 0 + + return batch + + + + def transform_batch(self, batch:BatchPoseData, H_ori, W_ori, bound=1): + '''Transform the batch before feeding to the network + !NOTE the H_ori, W_ori could be different at test time from the training data, and needs to be set + ''' + bs = len(batch.rgbAs) + batch.rgbAs = batch.rgbAs.cuda().float()/255.0 + batch.rgbBs = batch.rgbBs.cuda().float()/255.0 + + batch = self.transform_depth_to_xyzmap(batch, H_ori, W_ori, bound=bound) + return batch + + + + +class TripletH5Dataset(PairH5Dataset): + def __init__(self, cfg, h5_file, mode, max_num_key=None, cache_data=None): + super().__init__(cfg, h5_file, mode, max_num_key, cache_data=cache_data) + + + def transform_depth_to_xyzmap(self, batch:BatchPoseData, H_ori, W_ori, bound=1): + bs = len(batch.rgbAs) + H,W = batch.rgbAs.shape[-2:] + mesh_radius = batch.mesh_diameters.cuda()/2 + tf_to_crops = batch.tf_to_crops.cuda() + crop_to_oris = batch.tf_to_crops.inverse().cuda() #(B,3,3) + batch.poseA = batch.poseA.cuda() + batch.Ks = batch.Ks.cuda() + + if batch.xyz_mapAs is None: + depthAs_ori = kornia.geometry.transform.warp_perspective(batch.depthAs.cuda().expand(bs,-1,-1,-1), crop_to_oris, dsize=(H_ori, W_ori), mode='nearest', align_corners=False) + batch.xyz_mapAs = depth2xyzmap_batch(depthAs_ori[:,0], batch.Ks, zfar=np.inf).permute(0,3,1,2) #(B,3,H,W) + batch.xyz_mapAs = kornia.geometry.transform.warp_perspective(batch.xyz_mapAs, tf_to_crops, dsize=(H,W), mode='nearest', align_corners=False) + batch.xyz_mapAs = batch.xyz_mapAs.cuda() + invalid = batch.xyz_mapAs[:,2:3]<0.1 + batch.xyz_mapAs = (batch.xyz_mapAs-batch.poseA[:,:3,3].reshape(bs,3,1,1)) + if self.cfg['normalize_xyz']: + batch.xyz_mapAs *= 1/mesh_radius.reshape(bs,1,1,1) + invalid = invalid.expand(bs,3,-1,-1) | (torch.abs(batch.xyz_mapAs)>=2) + batch.xyz_mapAs[invalid.expand(bs,3,-1,-1)] = 0 + + if batch.xyz_mapBs is None: + depthBs_ori = kornia.geometry.transform.warp_perspective(batch.depthBs.cuda().expand(bs,-1,-1,-1), crop_to_oris, dsize=(H_ori, W_ori), mode='nearest', align_corners=False) + batch.xyz_mapBs = depth2xyzmap_batch(depthBs_ori[:,0], batch.Ks, zfar=np.inf).permute(0,3,1,2) #(B,3,H,W) + batch.xyz_mapBs = kornia.geometry.transform.warp_perspective(batch.xyz_mapBs, tf_to_crops, dsize=(H,W), mode='nearest', align_corners=False) + batch.xyz_mapBs = batch.xyz_mapBs.cuda() + invalid = batch.xyz_mapBs[:,2:3]<0.1 + batch.xyz_mapBs = (batch.xyz_mapBs-batch.poseA[:,:3,3].reshape(bs,3,1,1)) + if self.cfg['normalize_xyz']: + batch.xyz_mapBs *= 1/mesh_radius.reshape(bs,1,1,1) + invalid = invalid.expand(bs,3,-1,-1) | (torch.abs(batch.xyz_mapBs)>=2) + batch.xyz_mapBs[invalid.expand(bs,3,-1,-1)] = 0 + + return batch + + + def transform_batch(self, batch:BatchPoseData, H_ori, W_ori, bound=1): + bs = len(batch.rgbAs) + batch.rgbAs = batch.rgbAs.cuda().float()/255.0 + batch.rgbBs = batch.rgbBs.cuda().float()/255.0 + + batch = self.transform_depth_to_xyzmap(batch, H_ori, W_ori, bound=bound) + return batch + + + +class ScoreMultiPairH5Dataset(TripletH5Dataset): + def __init__(self, cfg, h5_file, mode, max_num_key=None, cache_data=None): + super().__init__(cfg, h5_file, mode, max_num_key, cache_data=cache_data) + if mode in ['train', 'val']: + self.cfg['train_num_pair'] = self.n_perturb + + +class PoseRefinePairH5Dataset(PairH5Dataset): + def __init__(self, cfg, h5_file, mode='train', max_num_key=None, cache_data=None): + super().__init__(cfg=cfg, h5_file=h5_file, mode=mode, max_num_key=max_num_key, cache_data=cache_data) + + if mode!='test': + with h5py.File(h5_file, 'r', libver='latest') as hf: + group = hf[self.object_keys[0]] + for key_perturb in group: + depthA = imageio.imread(group[key_perturb]['depthA'][()]) + depthB = imageio.imread(group[key_perturb]['depthB'][()]) + self.cfg['n_view'] = min(self.cfg['n_view'], depthA.shape[1]//depthB.shape[1]) + logging.info(f'n_view:{self.cfg["n_view"]}') + self.trans_normalizer = group[key_perturb]['trans_normalizer'][()] + if isinstance(self.trans_normalizer, np.ndarray): + self.trans_normalizer = self.trans_normalizer.tolist() + self.rot_normalizer = group[key_perturb]['rot_normalizer'][()]/180.0*np.pi + logging.info(f'self.trans_normalizer:{self.trans_normalizer}, self.rot_normalizer:{self.rot_normalizer}') + break + + + def transform_batch(self, batch:BatchPoseData, H_ori, W_ori, bound=1): + '''Transform the batch before feeding to the network + !NOTE the H_ori, W_ori could be different at test time from the training data, and needs to be set + ''' + bs = len(batch.rgbAs) + batch.rgbAs = batch.rgbAs.cuda().float()/255.0 + batch.rgbBs = batch.rgbBs.cuda().float()/255.0 + + batch = self.transform_depth_to_xyzmap(batch, H_ori, W_ori, bound=bound) + return batch + diff --git a/third-party/video_to_data/reconstruction/modules/v2d_foundation_pose/lib/FoundationPose/learning/datasets/pose_dataset.py b/third-party/video_to_data/reconstruction/modules/v2d_foundation_pose/lib/FoundationPose/learning/datasets/pose_dataset.py new file mode 100644 index 0000000000000000000000000000000000000000..8e76ee4645731128daad385879b738ff58eee9fc --- /dev/null +++ b/third-party/video_to_data/reconstruction/modules/v2d_foundation_pose/lib/FoundationPose/learning/datasets/pose_dataset.py @@ -0,0 +1,135 @@ +# Copyright (c) 2023, NVIDIA CORPORATION. All rights reserved. +# +# NVIDIA CORPORATION and its licensors retain all intellectual property +# and proprietary rights in and to this software, related documentation +# and any modifications thereto. Any use, reproduction, disclosure or +# distribution of this software and related documentation without an express +# license agreement from NVIDIA CORPORATION is strictly prohibited. + + +import os,sys +from dataclasses import dataclass +from typing import Iterator, List, Optional, Set, Union +import numpy as np +import torch +code_dir = os.path.dirname(os.path.realpath(__file__)) +sys.path.append(f'{code_dir}/../../../../') +from Utils import * + + +@dataclass +class PoseData: + """ + rgb: (h, w, 3) uint8 + depth: (bsz, h, w) float32 + bbox: (4, ) int + K: (3, 3) float32 + """ + rgb: np.ndarray = None + bbox: np.ndarray = None + K: np.ndarray = None + depth: Optional[np.ndarray] = None + object_data = None + mesh_diameter: float = None + rgbA: np.ndarray = None + rgbB: np.ndarray = None + depthA: np.ndarray = None + depthB: np.ndarray = None + maskA = None + maskB = None + poseA: np.ndarray = None #(4,4) + target: float = None + + def __init__(self, rgbA=None, rgbB=None, depthA=None, depthB=None, maskA=None, maskB=None, normalA=None, normalB=None, xyz_mapA=None, xyz_mapB=None, poseA=None, poseB=None, K=None, target=None, mesh_diameter=None, tf_to_crop=None, crop_mask=None, model_pts=None, label=None, model_scale=None): + self.rgbA = rgbA #(H,W,3) or (H,W*n_view,3) when multiview + self.rgbB = rgbB + self.depthA = depthA + self.depthB = depthB + self.poseA = poseA + self.poseB = poseB + self.maskA = maskA + self.maskB = maskB + self.crop_mask = crop_mask + self.normalA = normalA + self.normalB = normalB + self.xyz_mapA = xyz_mapA + self.xyz_mapB = xyz_mapB + self.target = target + self.K = K + self.mesh_diameter = mesh_diameter + self.tf_to_crop = tf_to_crop + self.model_pts = model_pts + self.label = label + self.model_scale = model_scale + + +@dataclass +class BatchPoseData: + """ + rgbs: (bsz, 3, h, w) torch tensor uint8 + depths: (bsz, h, w) float32 + bboxes: (bsz, 4) int + K: (bsz, 3, 3) float32 + """ + + rgbs: torch.Tensor = None + object_datas = None + bboxes: torch.Tensor = None + K: torch.Tensor = None + depths: Optional[torch.Tensor] = None + rgbAs = None + rgbBs = None + depthAs = None + depthBs = None + normalAs = None + normalBs = None + poseA = None #(B,4,4) + poseB = None + targets = None # Score targets, torch tensor (B) + + def __init__(self, rgbAs=None, rgbBs=None, depthAs=None, depthBs=None, normalAs=None, normalBs=None, maskAs=None, maskBs=None, poseA=None, poseB=None, xyz_mapAs=None, xyz_mapBs=None, tf_to_crops=None, Ks=None, crop_masks=None, model_pts=None, mesh_diameters=None, labels=None): + self.rgbAs = rgbAs + self.rgbBs = rgbBs + self.depthAs = depthAs + self.depthBs = depthBs + self.normalAs = normalAs + self.normalBs = normalBs + self.poseA = poseA + self.poseB = poseB + self.maskAs = maskAs + self.maskBs = maskBs + self.xyz_mapAs = xyz_mapAs + self.xyz_mapBs = xyz_mapBs + self.tf_to_crops = tf_to_crops + self.crop_masks = crop_masks + self.Ks = Ks + self.model_pts = model_pts + self.mesh_diameters = mesh_diameters + self.labels = labels + + + def pin_memory(self) -> "BatchPoseData": + for k in self.__dict__: + if self.__dict__[k] is not None: + try: + self.__dict__[k] = self.__dict__[k].pin_memory() + except Exception as e: + pass + return self + + def cuda(self): + for k in self.__dict__: + if self.__dict__[k] is not None: + try: + self.__dict__[k] = self.__dict__[k].cuda() + except: + pass + return self + + def select_by_indices(self, ids): + out = BatchPoseData() + for k in self.__dict__: + if self.__dict__[k] is not None: + out.__dict__[k] = self.__dict__[k][ids.to(self.__dict__[k].device)] + return out + diff --git a/third-party/video_to_data/reconstruction/modules/v2d_foundation_pose/lib/FoundationPose/learning/models/network_modules.py b/third-party/video_to_data/reconstruction/modules/v2d_foundation_pose/lib/FoundationPose/learning/models/network_modules.py new file mode 100644 index 0000000000000000000000000000000000000000..a0e4246628fcf60ab7b1cc44bca789892ac59bc6 --- /dev/null +++ b/third-party/video_to_data/reconstruction/modules/v2d_foundation_pose/lib/FoundationPose/learning/models/network_modules.py @@ -0,0 +1,138 @@ +# Copyright (c) 2023, NVIDIA CORPORATION. All rights reserved. +# +# NVIDIA CORPORATION and its licensors retain all intellectual property +# and proprietary rights in and to this software, related documentation +# and any modifications thereto. Any use, reproduction, disclosure or +# distribution of this software and related documentation without an express +# license agreement from NVIDIA CORPORATION is strictly prohibited. + + +import os,sys,copy,math,tqdm +import numpy as np +dir_path = os.path.dirname(os.path.realpath(__file__)) +sys.path.append(dir_path) +import torch.nn.functional as F +import torch +import torch.nn as nn +import time +import cv2 +sys.path.append(f'{dir_path}/../../../../') +from Utils import * + + + +class ConvBN(nn.Module): + def __init__(self, C_in, C_out, kernel_size=3, stride=1, groups=1, bias=True,dilation=1,): + super().__init__() + padding = (kernel_size - 1) // 2 + self.net = nn.Sequential( + nn.Conv2d(C_in, C_out, kernel_size, stride, padding, groups=groups, bias=bias,dilation=dilation), + nn.BatchNorm2d(C_out), + ) + + def forward(self, x): + return self.net(x) + + +class ConvBNReLU(nn.Module): + def __init__(self, C_in, C_out, kernel_size=3, stride=1, groups=1, bias=True,dilation=1, norm_layer=nn.BatchNorm2d): + super().__init__() + padding = (kernel_size - 1) // 2 + layers = [ + nn.Conv2d(C_in, C_out, kernel_size, stride, padding, groups=groups, bias=bias,dilation=dilation), + ] + if norm_layer is not None: + layers.append(norm_layer(C_out)) + layers.append(nn.ReLU(inplace=True)) + self.net = nn.Sequential(*layers) + + def forward(self, x): + return self.net(x) + + +class ConvPadding(nn.Module): + def __init__(self,C_in, C_out, kernel_size=3, stride=1, groups=1, bias=True,dilation=1): + super(ConvPadding, self).__init__() + padding = (kernel_size - 1) // 2 + self.conv = nn.Conv2d(C_in, C_out, kernel_size, stride, padding, groups=groups, bias=bias,dilation=dilation) + + def forward(self,x): + return self.conv(x) + + +def conv3x3(in_planes, out_planes, stride=1, groups=1, dilation=1, bias=False): + """3x3 convolution with padding""" + return nn.Conv2d(in_planes, out_planes, kernel_size=3, stride=stride, + padding=dilation, groups=groups, bias=bias, dilation=dilation) + + +def conv1x1(in_planes, out_planes, stride=1, bias=False): + """1x1 convolution""" + return nn.Conv2d(in_planes, out_planes, kernel_size=1, stride=stride, bias=bias) + +class ResnetBasicBlock(nn.Module): + __constants__ = ['downsample'] + + def __init__(self, inplanes, planes, stride=1, downsample=None, groups=1, base_width=64, dilation=1, norm_layer=nn.BatchNorm2d, bias=False): + super().__init__() + self.norm_layer = norm_layer + if groups != 1 or base_width != 64: + raise ValueError('BasicBlock only supports groups=1 and base_width=64') + if dilation > 1: + raise NotImplementedError("Dilation > 1 not supported in BasicBlock") + # Both self.conv1 and self.downsample layers downsample the input when stride != 1 + self.conv1 = conv3x3(inplanes, planes, stride,bias=bias) + if self.norm_layer is not None: + self.bn1 = norm_layer(planes) + self.relu = nn.ReLU(inplace=True) + self.conv2 = conv3x3(planes, planes,bias=bias) + if self.norm_layer is not None: + self.bn2 = norm_layer(planes) + self.downsample = downsample + self.stride = stride + + def forward(self, x): + identity = x + + out = self.conv1(x) + if self.norm_layer is not None: + out = self.bn1(out) + out = self.relu(out) + + out = self.conv2(out) + if self.norm_layer is not None: + out = self.bn2(out) + + if self.downsample is not None: + identity = self.downsample(x) + out += identity + out = self.relu(out) + + return out + + + +class PositionalEmbedding(nn.Module): + def __init__(self, d_model, max_len=512): + super().__init__() + + # Compute the positional encodings once in log space. + pe = torch.zeros(max_len, d_model).float() + pe.require_grad = False + + position = torch.arange(0, max_len).float().unsqueeze(1) #(N,1) + div_term = (torch.arange(0, d_model, 2).float() * -(math.log(10000.0) / d_model)).exp()[None] + + pe[:, 0::2] = torch.sin(position * div_term) #(N, d_model/2) + pe[:, 1::2] = torch.cos(position * div_term) + + pe = pe.unsqueeze(0) + self.register_buffer('pe', pe) #(1, max_len, D) + + + def forward(self, x): + ''' + @x: (B,N,D) + ''' + return x + self.pe[:, :x.size(1)] + diff --git a/third-party/video_to_data/reconstruction/modules/v2d_foundation_pose/lib/FoundationPose/learning/models/refine_network.py b/third-party/video_to_data/reconstruction/modules/v2d_foundation_pose/lib/FoundationPose/learning/models/refine_network.py new file mode 100644 index 0000000000000000000000000000000000000000..c2e399efc309f36129ad0365c940de71df443f60 --- /dev/null +++ b/third-party/video_to_data/reconstruction/modules/v2d_foundation_pose/lib/FoundationPose/learning/models/refine_network.py @@ -0,0 +1,93 @@ +# Copyright (c) 2023, NVIDIA CORPORATION. All rights reserved. +# +# NVIDIA CORPORATION and its licensors retain all intellectual property +# and proprietary rights in and to this software, related documentation +# and any modifications thereto. Any use, reproduction, disclosure or +# distribution of this software and related documentation without an express +# license agreement from NVIDIA CORPORATION is strictly prohibited. + + +import os,sys +import numpy as np +code_dir = os.path.dirname(os.path.realpath(__file__)) +sys.path.append(code_dir) +sys.path.append(f'{code_dir}/../../../../') +from Utils import * +import torch.nn.functional as F +import torch +import torch.nn as nn +import cv2 +from functools import partial +from network_modules import * +from Utils import * + + + +class RefineNet(nn.Module): + def __init__(self, cfg=None, c_in=4, n_view=1): + super().__init__() + self.cfg = cfg + if self.cfg.use_BN: + norm_layer = nn.BatchNorm2d + norm_layer1d = nn.BatchNorm1d + else: + norm_layer = None + norm_layer1d = None + + self.encodeA = nn.Sequential( + ConvBNReLU(C_in=c_in,C_out=64,kernel_size=7,stride=2, norm_layer=norm_layer), + ConvBNReLU(C_in=64,C_out=128,kernel_size=3,stride=2, norm_layer=norm_layer), + ResnetBasicBlock(128,128,bias=True, norm_layer=norm_layer), + ResnetBasicBlock(128,128,bias=True, norm_layer=norm_layer), + ) + + self.encodeAB = nn.Sequential( + ResnetBasicBlock(256,256,bias=True, norm_layer=norm_layer), + ResnetBasicBlock(256,256,bias=True, norm_layer=norm_layer), + ConvBNReLU(256,512,kernel_size=3,stride=2, norm_layer=norm_layer), + ResnetBasicBlock(512,512,bias=True, norm_layer=norm_layer), + ResnetBasicBlock(512,512,bias=True, norm_layer=norm_layer), + ) + + embed_dim = 512 + num_heads = 4 + self.pos_embed = PositionalEmbedding(d_model=embed_dim, max_len=400) + + self.trans_head = nn.Sequential( + nn.TransformerEncoderLayer(d_model=embed_dim, nhead=num_heads, dim_feedforward=512, batch_first=True), + nn.Linear(512, 3), + ) + + if self.cfg['rot_rep']=='axis_angle': + rot_out_dim = 3 + elif self.cfg['rot_rep']=='6d': + rot_out_dim = 6 + else: + raise RuntimeError + self.rot_head = nn.Sequential( + nn.TransformerEncoderLayer(d_model=embed_dim, nhead=num_heads, dim_feedforward=512, batch_first=True), + nn.Linear(512, rot_out_dim), + ) + + + def forward(self, A, B): + """ + @A: (B,C,H,W) + """ + bs = len(A) + output = {} + + x = torch.cat([A,B], dim=0) + x = self.encodeA(x) + a = x[:bs] + b = x[bs:] + + ab = torch.cat((a,b),1).contiguous() + ab = self.encodeAB(ab) #(B,C,H,W) + + ab = self.pos_embed(ab.reshape(bs, ab.shape[1], -1).permute(0,2,1)) + + output['trans'] = self.trans_head(ab).mean(dim=1) + output['rot'] = self.rot_head(ab).mean(dim=1) + + return output diff --git a/third-party/video_to_data/reconstruction/modules/v2d_foundation_pose/lib/FoundationPose/learning/models/score_network.py b/third-party/video_to_data/reconstruction/modules/v2d_foundation_pose/lib/FoundationPose/learning/models/score_network.py new file mode 100644 index 0000000000000000000000000000000000000000..fbf362ec0f9d95d4ecbd00ef0d64c6d5d903f9e7 --- /dev/null +++ b/third-party/video_to_data/reconstruction/modules/v2d_foundation_pose/lib/FoundationPose/learning/models/score_network.py @@ -0,0 +1,90 @@ +# Copyright (c) 2023, NVIDIA CORPORATION. All rights reserved. +# +# NVIDIA CORPORATION and its licensors retain all intellectual property +# and proprietary rights in and to this software, related documentation +# and any modifications thereto. Any use, reproduction, disclosure or +# distribution of this software and related documentation without an express +# license agreement from NVIDIA CORPORATION is strictly prohibited. + + +import os,sys +import numpy as np +code_dir = os.path.dirname(os.path.realpath(__file__)) +sys.path.append(code_dir) +sys.path.append(f'{code_dir}/../../../../') +from Utils import * +from functools import partial +import torch.nn.functional as F +import torch +import torch.nn as nn +import cv2 +from network_modules import * +from Utils import * + + + + +class ScoreNetMultiPair(nn.Module): + def __init__(self, cfg=None, c_in=4): + super().__init__() + self.cfg = cfg + if self.cfg.use_BN: + norm_layer = nn.BatchNorm2d + else: + norm_layer = None + + self.encoderA = nn.Sequential( + ConvBNReLU(C_in=c_in,C_out=64,kernel_size=7,stride=2, norm_layer=norm_layer), + ConvBNReLU(C_in=64,C_out=128,kernel_size=3,stride=2, norm_layer=norm_layer), + ResnetBasicBlock(128,128,bias=True, norm_layer=norm_layer), + ResnetBasicBlock(128,128,bias=True, norm_layer=norm_layer), + ) + + self.encoderAB = nn.Sequential( + ResnetBasicBlock(256,256,bias=True, norm_layer=norm_layer), + ResnetBasicBlock(256,256,bias=True, norm_layer=norm_layer), + ConvBNReLU(256,512,kernel_size=3,stride=2, norm_layer=norm_layer), + ResnetBasicBlock(512,512,bias=True, norm_layer=norm_layer), + ResnetBasicBlock(512,512,bias=True, norm_layer=norm_layer), + ) + + embed_dim = 512 + num_heads = 4 + self.att = nn.MultiheadAttention(embed_dim=embed_dim, num_heads=num_heads, bias=True, batch_first=True) + self.att_cross = nn.MultiheadAttention(embed_dim=embed_dim, num_heads=num_heads, bias=True, batch_first=True) + + self.pos_embed = PositionalEmbedding(d_model=embed_dim, max_len=400) + self.linear = nn.Linear(embed_dim, 1) + + + def extract_feat(self, A, B): + """ + @A: (B*L,C,H,W) L is num of pairs + """ + bs = A.shape[0] # B*L + + x = torch.cat([A,B], dim=0) + x = self.encoderA(x) + a = x[:bs] + b = x[bs:] + ab = torch.cat((a,b), dim=1) + ab = self.encoderAB(ab) + ab = self.pos_embed(ab.reshape(bs, ab.shape[1], -1).permute(0,2,1)) + ab, _ = self.att(ab, ab, ab) + return ab.mean(dim=1).reshape(bs,-1) + + + def forward(self, A, B, L): + """ + @A: (B*L,C,H,W) L is num of pairs + @L: num of pairs + """ + output = {} + bs = A.shape[0]//L + feats = self.extract_feat(A, B) #(B*L, C) + x = feats.reshape(bs,L,-1) + x, _ = self.att_cross(x, x, x) + + output['score_logit'] = self.linear(x).reshape(bs,L) # (B,L) + + return output diff --git a/third-party/video_to_data/reconstruction/modules/v2d_foundation_pose/lib/FoundationPose/learning/training/predict_pose_refine.py b/third-party/video_to_data/reconstruction/modules/v2d_foundation_pose/lib/FoundationPose/learning/training/predict_pose_refine.py new file mode 100644 index 0000000000000000000000000000000000000000..c0091824b870d68078214b06b58cd1edcc1cff94 --- /dev/null +++ b/third-party/video_to_data/reconstruction/modules/v2d_foundation_pose/lib/FoundationPose/learning/training/predict_pose_refine.py @@ -0,0 +1,297 @@ +# Copyright (c) 2023, NVIDIA CORPORATION. All rights reserved. +# +# NVIDIA CORPORATION and its licensors retain all intellectual property +# and proprietary rights in and to this software, related documentation +# and any modifications thereto. Any use, reproduction, disclosure or +# distribution of this software and related documentation without an express +# license agreement from NVIDIA CORPORATION is strictly prohibited. + + +import functools +import os,sys,kornia +import time +code_dir = os.path.dirname(os.path.realpath(__file__)) +sys.path.append(f'{code_dir}/../../') +import numpy as np +import torch +from omegaconf import OmegaConf +from learning.models.refine_network import RefineNet +from learning.datasets.h5_dataset import * +from Utils import * +from datareader import * + + + +@torch.inference_mode() +def make_crop_data_batch(render_size, ob_in_cams, mesh, rgb, depth, K, crop_ratio, xyz_map, normal_map=None, mesh_diameter=None, cfg=None, glctx=None, mesh_tensors=None, dataset:PoseRefinePairH5Dataset=None): + logging.info("Welcome make_crop_data_batch") + H,W = depth.shape[:2] + args = [] + method = 'box_3d' + tf_to_crops = compute_crop_window_tf_batch(pts=mesh.vertices, H=H, W=W, poses=ob_in_cams, K=K, crop_ratio=crop_ratio, out_size=(render_size[1], render_size[0]), method=method, mesh_diameter=mesh_diameter) + + logging.info("make tf_to_crops done") + + B = len(ob_in_cams) + poseA = torch.as_tensor(ob_in_cams, dtype=torch.float, device='cuda') + + bs = 512 + rgb_rs = [] + depth_rs = [] + normal_rs = [] + xyz_map_rs = [] + + bbox2d_crop = torch.as_tensor(np.array([0, 0, cfg['input_resize'][0]-1, cfg['input_resize'][1]-1]).reshape(2,2), device='cuda', dtype=torch.float) + bbox2d_ori = transform_pts(bbox2d_crop, tf_to_crops.inverse()).reshape(-1,4) + + for b in range(0,len(poseA),bs): + extra = {} + rgb_r, depth_r, normal_r = nvdiffrast_render(K=K, H=H, W=W, ob_in_cams=poseA[b:b+bs], context='cuda', get_normal=cfg['use_normal'], glctx=glctx, mesh_tensors=mesh_tensors, output_size=cfg['input_resize'], bbox2d=bbox2d_ori[b:b+bs], use_light=True, extra=extra) + rgb_rs.append(rgb_r) + depth_rs.append(depth_r[...,None]) + normal_rs.append(normal_r) + xyz_map_rs.append(extra['xyz_map']) + rgb_rs = torch.cat(rgb_rs, dim=0).permute(0,3,1,2) * 255 + depth_rs = torch.cat(depth_rs, dim=0).permute(0,3,1,2) #(B,1,H,W) + xyz_map_rs = torch.cat(xyz_map_rs, dim=0).permute(0,3,1,2) #(B,3,H,W) + Ks = torch.as_tensor(K, device='cuda', dtype=torch.float).reshape(1,3,3) + if cfg['use_normal']: + normal_rs = torch.cat(normal_rs, dim=0).permute(0,3,1,2) #(B,3,H,W) + + logging.info("render done") + + rgbBs = kornia.geometry.transform.warp_perspective(torch.as_tensor(rgb, dtype=torch.float, device='cuda').permute(2,0,1)[None].expand(B,-1,-1,-1), tf_to_crops, dsize=render_size, mode='bilinear', align_corners=False) + if rgb_rs.shape[-2:]!=cfg['input_resize']: + rgbAs = kornia.geometry.transform.warp_perspective(rgb_rs, tf_to_crops, dsize=render_size, mode='bilinear', align_corners=False) + else: + rgbAs = rgb_rs + if xyz_map_rs.shape[-2:]!=cfg['input_resize']: + xyz_mapAs = kornia.geometry.transform.warp_perspective(xyz_map_rs, tf_to_crops, dsize=render_size, mode='nearest', align_corners=False) + else: + xyz_mapAs = xyz_map_rs + xyz_mapBs = kornia.geometry.transform.warp_perspective(torch.as_tensor(xyz_map, device='cuda', dtype=torch.float).permute(2,0,1)[None].expand(B,-1,-1,-1), tf_to_crops, dsize=render_size, mode='nearest', align_corners=False) #(B,3,H,W) + + if cfg['use_normal']: + normalAs = kornia.geometry.transform.warp_perspective(normal_rs, tf_to_crops, dsize=render_size, mode='nearest', align_corners=False) + normalBs = kornia.geometry.transform.warp_perspective(torch.as_tensor(normal_map, dtype=torch.float, device='cuda').permute(2,0,1)[None].expand(B,-1,-1,-1), tf_to_crops, dsize=render_size, mode='nearest', align_corners=False) + else: + normalAs = None + normalBs = None + + logging.info("warp done") + + mesh_diameters = torch.ones((len(rgbAs)), dtype=torch.float, device='cuda')*mesh_diameter + pose_data = BatchPoseData(rgbAs=rgbAs, rgbBs=rgbBs, depthAs=None, depthBs=None, normalAs=normalAs, normalBs=normalBs, poseA=poseA, poseB=None, xyz_mapAs=xyz_mapAs, xyz_mapBs=xyz_mapBs, tf_to_crops=tf_to_crops, Ks=Ks, mesh_diameters=mesh_diameters) + pose_data = dataset.transform_batch(batch=pose_data, H_ori=H, W_ori=W, bound=1) + + logging.info("pose batch data done") + + return pose_data + + + +class PoseRefinePredictor: + def __init__(self,): + logging.info("welcome") + self.amp = True + self.run_name = "2023-10-28-18-33-37" + model_name = 'model_best.pth' + code_dir = os.path.dirname(os.path.realpath(__file__)) + weights_base_dir = os.environ.get("FOUNDATIONPOSE_WEIGHTS_DIR", f'{code_dir}/../../weights') + ckpt_dir = f'{weights_base_dir}/{self.run_name}/{model_name}' + + self.cfg = OmegaConf.load(f'{weights_base_dir}/{self.run_name}/config.yml') + + self.cfg['ckpt_dir'] = ckpt_dir + self.cfg['enable_amp'] = True + + ########## Defaults, to be backward compatible + if 'use_normal' not in self.cfg: + self.cfg['use_normal'] = False + if 'use_mask' not in self.cfg: + self.cfg['use_mask'] = False + if 'use_BN' not in self.cfg: + self.cfg['use_BN'] = False + if 'c_in' not in self.cfg: + self.cfg['c_in'] = 4 + if 'crop_ratio' not in self.cfg or self.cfg['crop_ratio'] is None: + self.cfg['crop_ratio'] = 1.2 + if 'n_view' not in self.cfg: + self.cfg['n_view'] = 1 + if 'trans_rep' not in self.cfg: + self.cfg['trans_rep'] = 'tracknet' + if 'rot_rep' not in self.cfg: + self.cfg['rot_rep'] = 'axis_angle' + if 'zfar' not in self.cfg: + self.cfg['zfar'] = 3 + if 'normalize_xyz' not in self.cfg: + self.cfg['normalize_xyz'] = False + if isinstance(self.cfg['zfar'], str) and 'inf' in self.cfg['zfar'].lower(): + self.cfg['zfar'] = np.inf + if 'normal_uint8' not in self.cfg: + self.cfg['normal_uint8'] = False + logging.info(f"self.cfg: \n {OmegaConf.to_yaml(self.cfg)}") + + self.dataset = PoseRefinePairH5Dataset(cfg=self.cfg, h5_file='', mode='test') + self.model = RefineNet(cfg=self.cfg, c_in=self.cfg['c_in']).cuda() + + logging.info(f"Using pretrained model from {ckpt_dir}") + ckpt = torch.load(ckpt_dir) + if 'model' in ckpt: + ckpt = ckpt['model'] + self.model.load_state_dict(ckpt) + + self.model.cuda().eval() + logging.info("init done") + self.last_trans_update = None + self.last_rot_update = None + + + @torch.inference_mode() + def predict(self, rgb, depth, K, ob_in_cams, xyz_map, normal_map=None, get_vis=False, mesh=None, mesh_tensors=None, glctx=None, mesh_diameter=None, iteration=5): + ''' + @rgb: np array (H,W,3) + @ob_in_cams: np array (N,4,4) + ''' + torch.set_default_tensor_type('torch.cuda.FloatTensor') + logging.info(f'ob_in_cams:{ob_in_cams.shape}') + tf_to_center = np.eye(4) + ob_centered_in_cams = ob_in_cams + mesh_centered = mesh + + logging.info(f'self.cfg.use_normal:{self.cfg.use_normal}') + if not self.cfg.use_normal: + normal_map = None + + crop_ratio = self.cfg['crop_ratio'] + logging.info(f"trans_normalizer:{self.cfg['trans_normalizer']}, rot_normalizer:{self.cfg['rot_normalizer']}") + bs = 1024 + + B_in_cams = torch.as_tensor(ob_centered_in_cams, device='cuda', dtype=torch.float) + + + if mesh_tensors is None: + mesh_tensors = make_mesh_tensors(mesh_centered) + + rgb_tensor = torch.as_tensor(rgb, device='cuda', dtype=torch.float) + depth_tensor = torch.as_tensor(depth, device='cuda', dtype=torch.float) + xyz_map_tensor = torch.as_tensor(xyz_map, device='cuda', dtype=torch.float) + trans_normalizer = self.cfg['trans_normalizer'] + if not isinstance(trans_normalizer, float): + trans_normalizer = torch.as_tensor(list(trans_normalizer), device='cuda', dtype=torch.float).reshape(1,3) + + for _ in range(iteration): + logging.info("making cropped data") + pose_data = make_crop_data_batch(self.cfg.input_resize, B_in_cams, mesh_centered, rgb_tensor, depth_tensor, K, crop_ratio=crop_ratio, normal_map=normal_map, xyz_map=xyz_map_tensor, cfg=self.cfg, glctx=glctx, mesh_tensors=mesh_tensors, dataset=self.dataset, mesh_diameter=mesh_diameter) + B_in_cams = [] + for b in range(0, pose_data.rgbAs.shape[0], bs): + A = torch.cat([pose_data.rgbAs[b:b+bs].cuda(), pose_data.xyz_mapAs[b:b+bs].cuda()], dim=1).float() + B = torch.cat([pose_data.rgbBs[b:b+bs].cuda(), pose_data.xyz_mapBs[b:b+bs].cuda()], dim=1).float() + logging.info("forward start") + with torch.cuda.amp.autocast(enabled=self.amp): + output = self.model(A,B) + for k in output: + output[k] = output[k].float() + logging.info("forward done") + if self.cfg['trans_rep']=='tracknet': + if not self.cfg['normalize_xyz']: + trans_delta = torch.tanh(output["trans"])*trans_normalizer + else: + trans_delta = output["trans"] + + elif self.cfg['trans_rep']=='deepim': + def project_and_transform_to_crop(centers): + uvs = (pose_data.Ks[b:b+bs]@centers.reshape(-1,3,1)).reshape(-1,3) + uvs = uvs/uvs[:,2:3] + uvs = (pose_data.tf_to_crops[b:b+bs]@uvs.reshape(-1,3,1)).reshape(-1,3) + return uvs[:,:2] + + rot_delta = output["rot"] + z_pred = output['trans'][:,2]*pose_data.poseA[b:b+bs][...,2,3] + uvA_crop = project_and_transform_to_crop(pose_data.poseA[b:b+bs][...,:3,3]) + uv_pred_crop = uvA_crop + output['trans'][:,:2]*self.cfg['input_resize'][0] + uv_pred = transform_pts(uv_pred_crop, pose_data.tf_to_crops[b:b+bs].inverse().cuda()) + center_pred = torch.cat([uv_pred, torch.ones((len(rot_delta),1), dtype=torch.float, device='cuda')], dim=-1) + center_pred = (pose_data.Ks[b:b+bs].inverse().cuda()@center_pred.reshape(len(rot_delta),3,1)).reshape(len(rot_delta),3) * z_pred.reshape(len(rot_delta),1) + trans_delta = center_pred-pose_data.poseA[b:b+bs][...,:3,3] + + else: + trans_delta = output["trans"] + + if self.cfg['rot_rep']=='axis_angle': + rot_mat_delta = torch.tanh(output["rot"])*self.cfg['rot_normalizer'] + rot_mat_delta = so3_exp_map(rot_mat_delta).permute(0,2,1) + elif self.cfg['rot_rep']=='6d': + rot_mat_delta = rotation_6d_to_matrix(output['rot']).permute(0,2,1) + else: + raise RuntimeError + + if self.cfg['normalize_xyz']: + trans_delta *= (mesh_diameter/2) + + B_in_cam = egocentric_delta_pose_to_pose(pose_data.poseA[b:b+bs], trans_delta=trans_delta, rot_mat_delta=rot_mat_delta) + B_in_cams.append(B_in_cam) + + B_in_cams = torch.cat(B_in_cams, dim=0).reshape(len(ob_in_cams),4,4) + + B_in_cams_out = B_in_cams@torch.tensor(tf_to_center[None], device='cuda', dtype=torch.float) + torch.cuda.empty_cache() + self.last_trans_update = trans_delta + self.last_rot_update = rot_mat_delta + + if get_vis: + logging.info("get_vis...") + canvas = [] + padding = 2 + pose_data = make_crop_data_batch(self.cfg.input_resize, torch.as_tensor(ob_centered_in_cams), mesh_centered, rgb, depth, K, crop_ratio=crop_ratio, normal_map=normal_map, xyz_map=xyz_map_tensor, cfg=self.cfg, glctx=glctx, mesh_tensors=mesh_tensors, dataset=self.dataset, mesh_diameter=mesh_diameter) + for id in range(0, len(B_in_cams)): + rgbA_vis = (pose_data.rgbAs[id]*255).permute(1,2,0).data.cpu().numpy() + rgbB_vis = (pose_data.rgbBs[id]*255).permute(1,2,0).data.cpu().numpy() + row = [rgbA_vis, rgbB_vis] + H,W = rgbA_vis.shape[:2] + if pose_data.depthAs is not None: + depthA = pose_data.depthAs[id].data.cpu().numpy().reshape(H,W) + depthB = pose_data.depthBs[id].data.cpu().numpy().reshape(H,W) + elif pose_data.xyz_mapAs is not None: + depthA = pose_data.xyz_mapAs[id][2].data.cpu().numpy().reshape(H,W) + depthB = pose_data.xyz_mapBs[id][2].data.cpu().numpy().reshape(H,W) + zmin = min(depthA.min(), depthB.min()) + zmax = max(depthA.max(), depthB.max()) + depthA_vis = depth_to_vis(depthA, zmin=zmin, zmax=zmax, inverse=False) + depthB_vis = depth_to_vis(depthB, zmin=zmin, zmax=zmax, inverse=False) + row += [depthA_vis, depthB_vis] + if pose_data.normalAs is not None: + pass + row = make_grid_image(row, nrow=len(row), padding=padding, pad_value=255) + row = cv_draw_text(row, text=f'id:{id}', uv_top_left=(10,10), color=(0,255,0), fontScale=0.5) + canvas.append(row) + canvas = make_grid_image(canvas, nrow=1, padding=padding, pad_value=255) + + pose_data = make_crop_data_batch(self.cfg.input_resize, B_in_cams, mesh_centered, rgb, depth, K, crop_ratio=crop_ratio, normal_map=normal_map, xyz_map=xyz_map_tensor, cfg=self.cfg, glctx=glctx, mesh_tensors=mesh_tensors, dataset=self.dataset, mesh_diameter=mesh_diameter) + canvas_refined = [] + for id in range(0, len(B_in_cams)): + rgbA_vis = (pose_data.rgbAs[id]*255).permute(1,2,0).data.cpu().numpy() + rgbB_vis = (pose_data.rgbBs[id]*255).permute(1,2,0).data.cpu().numpy() + row = [rgbA_vis, rgbB_vis] + H,W = rgbA_vis.shape[:2] + if pose_data.depthAs is not None: + depthA = pose_data.depthAs[id].data.cpu().numpy().reshape(H,W) + depthB = pose_data.depthBs[id].data.cpu().numpy().reshape(H,W) + elif pose_data.xyz_mapAs is not None: + depthA = pose_data.xyz_mapAs[id][2].data.cpu().numpy().reshape(H,W) + depthB = pose_data.xyz_mapBs[id][2].data.cpu().numpy().reshape(H,W) + zmin = min(depthA.min(), depthB.min()) + zmax = max(depthA.max(), depthB.max()) + depthA_vis = depth_to_vis(depthA, zmin=zmin, zmax=zmax, inverse=False) + depthB_vis = depth_to_vis(depthB, zmin=zmin, zmax=zmax, inverse=False) + row += [depthA_vis, depthB_vis] + row = make_grid_image(row, nrow=len(row), padding=padding, pad_value=255) + canvas_refined.append(row) + + canvas_refined = make_grid_image(canvas_refined, nrow=1, padding=padding, pad_value=255) + canvas = make_grid_image([canvas, canvas_refined], nrow=2, padding=padding, pad_value=255) + torch.cuda.empty_cache() + return B_in_cams_out, canvas + + return B_in_cams_out, None + diff --git a/third-party/video_to_data/reconstruction/modules/v2d_foundation_pose/lib/FoundationPose/learning/training/predict_score.py b/third-party/video_to_data/reconstruction/modules/v2d_foundation_pose/lib/FoundationPose/learning/training/predict_score.py new file mode 100644 index 0000000000000000000000000000000000000000..b9e51ec83bd8d3563798a9ebc66c5effc5dcdc7e --- /dev/null +++ b/third-party/video_to_data/reconstruction/modules/v2d_foundation_pose/lib/FoundationPose/learning/training/predict_score.py @@ -0,0 +1,228 @@ +# Copyright (c) 2023, NVIDIA CORPORATION. All rights reserved. +# +# NVIDIA CORPORATION and its licensors retain all intellectual property +# and proprietary rights in and to this software, related documentation +# and any modifications thereto. Any use, reproduction, disclosure or +# distribution of this software and related documentation without an express +# license agreement from NVIDIA CORPORATION is strictly prohibited. + + +import functools +import os,sys,kornia +import time +import numpy as np +import torch +import torch.distributed as dist +from omegaconf import OmegaConf +from tqdm import tqdm +code_dir = os.path.dirname(os.path.realpath(__file__)) +sys.path.append(f'{code_dir}/../../../') +from learning.datasets.h5_dataset import * +from learning.models.score_network import * +from learning.datasets.pose_dataset import * +from Utils import * +from datareader import * + + +def vis_batch_data_scores(pose_data, ids, scores, pad_margin=5): + assert len(scores)==len(ids) + canvas = [] + for id in ids: + rgbA_vis = (pose_data.rgbAs[id]*255).permute(1,2,0).data.cpu().numpy() + rgbB_vis = (pose_data.rgbBs[id]*255).permute(1,2,0).data.cpu().numpy() + H,W = rgbA_vis.shape[:2] + zmin = pose_data.depthAs[id].data.cpu().numpy().reshape(H,W).min() + zmax = pose_data.depthAs[id].data.cpu().numpy().reshape(H,W).max() + depthA_vis = depth_to_vis(pose_data.depthAs[id].data.cpu().numpy().reshape(H,W), zmin=zmin, zmax=zmax, inverse=False) + depthB_vis = depth_to_vis(pose_data.depthBs[id].data.cpu().numpy().reshape(H,W), zmin=zmin, zmax=zmax, inverse=False) + if pose_data.normalAs is not None: + pass + pad = np.ones((rgbA_vis.shape[0],pad_margin,3))*255 + if pose_data.normalAs is not None: + pass + else: + row = np.concatenate([rgbA_vis, pad, depthA_vis, pad, rgbB_vis, pad, depthB_vis], axis=1) + s = 100/row.shape[0] + row = cv2.resize(row, fx=s, fy=s, dsize=None) + row = cv_draw_text(row, text=f'id:{id}, score:{scores[id]:.3f}', uv_top_left=(10,10), color=(0,255,0), fontScale=0.5) + canvas.append(row) + pad = np.ones((pad_margin, row.shape[1], 3))*255 + canvas.append(pad) + canvas = np.concatenate(canvas, axis=0).astype(np.uint8) + return canvas + + + +@torch.no_grad() +def make_crop_data_batch(render_size, ob_in_cams, mesh, rgb, depth, K, crop_ratio, normal_map=None, mesh_diameter=None, glctx=None, mesh_tensors=None, dataset:TripletH5Dataset=None, cfg=None): + logging.info("Welcome make_crop_data_batch") + H,W = depth.shape[:2] + + args = [] + method = 'box_3d' + tf_to_crops = compute_crop_window_tf_batch(pts=mesh.vertices, H=H, W=W, poses=ob_in_cams, K=K, crop_ratio=crop_ratio, out_size=(render_size[1], render_size[0]), method=method, mesh_diameter=mesh_diameter) + logging.info("make tf_to_crops done") + + B = len(ob_in_cams) + poseAs = torch.as_tensor(ob_in_cams, dtype=torch.float, device='cuda') + + bs = 512 + rgb_rs = [] + depth_rs = [] + xyz_map_rs = [] + + bbox2d_crop = torch.as_tensor(np.array([0, 0, cfg['input_resize'][0]-1, cfg['input_resize'][1]-1]).reshape(2,2), device='cuda', dtype=torch.float) + bbox2d_ori = transform_pts(bbox2d_crop, tf_to_crops.inverse()[:,None]).reshape(-1,4) + + for b in range(0,len(ob_in_cams),bs): + extra = {} + rgb_r, depth_r, normal_r = nvdiffrast_render(K=K, H=H, W=W, ob_in_cams=poseAs[b:b+bs], context='cuda', get_normal=cfg['use_normal'], glctx=glctx, mesh_tensors=mesh_tensors, output_size=cfg['input_resize'], bbox2d=bbox2d_ori[b:b+bs], use_light=True, extra=extra) + rgb_rs.append(rgb_r) + depth_rs.append(depth_r[...,None]) + xyz_map_rs.append(extra['xyz_map']) + + rgb_rs = torch.cat(rgb_rs, dim=0).permute(0,3,1,2) * 255 + depth_rs = torch.cat(depth_rs, dim=0).permute(0,3,1,2) + xyz_map_rs = torch.cat(xyz_map_rs, dim=0).permute(0,3,1,2) #(B,3,H,W) + logging.info("render done") + + rgbBs = kornia.geometry.transform.warp_perspective(torch.as_tensor(rgb, dtype=torch.float, device='cuda').permute(2,0,1)[None].expand(B,-1,-1,-1), tf_to_crops, dsize=render_size, mode='bilinear', align_corners=False) + depthBs = kornia.geometry.transform.warp_perspective(torch.as_tensor(depth, dtype=torch.float, device='cuda')[None,None].expand(B,-1,-1,-1), tf_to_crops, dsize=render_size, mode='nearest', align_corners=False) + if rgb_rs.shape[-2:]!=cfg['input_resize']: + rgbAs = kornia.geometry.transform.warp_perspective(rgb_rs, tf_to_crops, dsize=render_size, mode='bilinear', align_corners=False) + depthAs = kornia.geometry.transform.warp_perspective(depth_rs, tf_to_crops, dsize=render_size, mode='nearest', align_corners=False) + else: + rgbAs = rgb_rs + depthAs = depth_rs + + if xyz_map_rs.shape[-2:]!=cfg['input_resize']: + xyz_mapAs = kornia.geometry.transform.warp_perspective(xyz_map_rs, tf_to_crops, dsize=render_size, mode='nearest', align_corners=False) + else: + xyz_mapAs = xyz_map_rs + + normalAs = None + normalBs = None + + Ks = torch.as_tensor(K, dtype=torch.float).reshape(1,3,3).expand(len(rgbAs),3,3) + mesh_diameters = torch.ones((len(rgbAs)), dtype=torch.float, device='cuda')*mesh_diameter + + pose_data = BatchPoseData(rgbAs=rgbAs, rgbBs=rgbBs, depthAs=depthAs, depthBs=depthBs, normalAs=normalAs, normalBs=normalBs, poseA=poseAs, xyz_mapAs=xyz_mapAs, tf_to_crops=tf_to_crops, Ks=Ks, mesh_diameters=mesh_diameters) + pose_data = dataset.transform_batch(pose_data, H_ori=H, W_ori=W, bound=1) + + logging.info("pose batch data done") + + return pose_data + + +class ScorePredictor: + def __init__(self, amp=True): + self.amp = amp + self.run_name = "2024-01-11-20-02-45" + + model_name = 'model_best.pth' + code_dir = os.path.dirname(os.path.realpath(__file__)) + weights_base_dir = os.environ.get("FOUNDATIONPOSE_WEIGHTS_DIR", f'{code_dir}/../../weights') + ckpt_dir = f'{weights_base_dir}/{self.run_name}/{model_name}' + + self.cfg = OmegaConf.load(f'{weights_base_dir}/{self.run_name}/config.yml') + + self.cfg['ckpt_dir'] = ckpt_dir + self.cfg['enable_amp'] = True + + ########## Defaults, to be backward compatible + if 'use_normal' not in self.cfg: + self.cfg['use_normal'] = False + if 'use_BN' not in self.cfg: + self.cfg['use_BN'] = False + if 'zfar' not in self.cfg: + self.cfg['zfar'] = np.inf + if 'c_in' not in self.cfg: + self.cfg['c_in'] = 4 + if 'normalize_xyz' not in self.cfg: + self.cfg['normalize_xyz'] = False + if 'crop_ratio' not in self.cfg or self.cfg['crop_ratio'] is None: + self.cfg['crop_ratio'] = 1.2 + + logging.info(f"self.cfg: \n {OmegaConf.to_yaml(self.cfg)}") + + self.dataset = ScoreMultiPairH5Dataset(cfg=self.cfg, mode='test', h5_file=None, max_num_key=1) + self.model = ScoreNetMultiPair(cfg=self.cfg, c_in=self.cfg['c_in']).cuda() + + logging.info(f"Using pretrained model from {ckpt_dir}") + ckpt = torch.load(ckpt_dir) + if 'model' in ckpt: + ckpt = ckpt['model'] + self.model.load_state_dict(ckpt) + + self.model.cuda().eval() + logging.info("init done") + + + @torch.inference_mode() + def predict(self, rgb, depth, K, ob_in_cams, normal_map=None, get_vis=False, mesh=None, mesh_tensors=None, glctx=None, mesh_diameter=None): + ''' + @rgb: np array (H,W,3) + ''' + logging.info(f"ob_in_cams:{ob_in_cams.shape}") + ob_in_cams = torch.as_tensor(ob_in_cams, dtype=torch.float, device='cuda') + + logging.info(f'self.cfg.use_normal:{self.cfg.use_normal}') + if not self.cfg.use_normal: + normal_map = None + + logging.info("making cropped data") + + if mesh_tensors is None: + mesh_tensors = make_mesh_tensors(mesh) + + rgb = torch.as_tensor(rgb, device='cuda', dtype=torch.float) + depth = torch.as_tensor(depth, device='cuda', dtype=torch.float) + + pose_data = make_crop_data_batch(self.cfg.input_resize, ob_in_cams, mesh, rgb, depth, K, crop_ratio=self.cfg['crop_ratio'], glctx=glctx, mesh_tensors=mesh_tensors, dataset=self.dataset, cfg=self.cfg, mesh_diameter=mesh_diameter) + + def find_best_among_pairs(pose_data:BatchPoseData): + logging.info(f'pose_data.rgbAs.shape[0]: {pose_data.rgbAs.shape[0]}') + ids = [] + scores = [] + bs = pose_data.rgbAs.shape[0] + for b in range(0, pose_data.rgbAs.shape[0], bs): + A = torch.cat([pose_data.rgbAs[b:b+bs].cuda(), pose_data.xyz_mapAs[b:b+bs].cuda()], dim=1).float() + B = torch.cat([pose_data.rgbBs[b:b+bs].cuda(), pose_data.xyz_mapBs[b:b+bs].cuda()], dim=1).float() + if pose_data.normalAs is not None: + A = torch.cat([A, pose_data.normalAs.cuda().float()], dim=1) + B = torch.cat([B, pose_data.normalBs.cuda().float()], dim=1) + with torch.cuda.amp.autocast(enabled=self.amp): + output = self.model(A, B, L=len(A)) + scores_cur = output["score_logit"].float().reshape(-1) + ids.append(scores_cur.argmax()+b) + scores.append(scores_cur) + ids = torch.stack(ids, dim=0).reshape(-1) + scores = torch.cat(scores, dim=0).reshape(-1) + return ids, scores + + pose_data_iter = pose_data + global_ids = torch.arange(len(ob_in_cams), device='cuda', dtype=torch.long) + scores_global = torch.zeros((len(ob_in_cams)), dtype=torch.float, device='cuda') + + while 1: + ids, scores = find_best_among_pairs(pose_data_iter) + if len(ids)==1: + scores_global[global_ids] = scores + 100 + break + global_ids = global_ids[ids] + pose_data_iter = pose_data.select_by_indices(global_ids) + + scores = scores_global + + logging.info(f'forward done') + torch.cuda.empty_cache() + + if get_vis: + logging.info("get_vis...") + canvas = [] + ids = scores.argsort(descending=True) + canvas = vis_batch_data_scores(pose_data, ids=ids, scores=scores) + return scores, canvas + + return scores, None + diff --git a/third-party/video_to_data/reconstruction/modules/v2d_foundation_pose/lib/FoundationPose/learning/training/training_config.py b/third-party/video_to_data/reconstruction/modules/v2d_foundation_pose/lib/FoundationPose/learning/training/training_config.py new file mode 100644 index 0000000000000000000000000000000000000000..9d689c65da3fd03e9a32b5df332fcdd70af9c67d --- /dev/null +++ b/third-party/video_to_data/reconstruction/modules/v2d_foundation_pose/lib/FoundationPose/learning/training/training_config.py @@ -0,0 +1,102 @@ +# Copyright (c) 2023, NVIDIA CORPORATION. All rights reserved. +# +# NVIDIA CORPORATION and its licensors retain all intellectual property +# and proprietary rights in and to this software, related documentation +# and any modifications thereto. Any use, reproduction, disclosure or +# distribution of this software and related documentation without an express +# license agreement from NVIDIA CORPORATION is strictly prohibited. + + +import os,sys +from dataclasses import dataclass, field +from typing import List, Optional, Tuple,Union +import numpy as np +import omegaconf +import torch + + +@dataclass +class TrainingConfig(omegaconf.dictconfig.DictConfig): + input_resize: tuple = (160, 160) + normalize_xyz:Optional[bool] = True + use_mask:Optional[bool] = False + crop_ratio:Optional[float] = None + split_objects_across_gpus: bool = True + max_num_key: Optional[int] = None + use_normal:bool = False + n_view:int = 1 + zfar:float = np.inf + c_in:int = 6 + train_num_pair:Optional[int] = None + make_pair_online:Optional[bool] = False + render_backend:Optional[str] = 'nvdiffrast' + + # Run management + run_id: Optional[str] = None + exp_name:Optional[str] = None + resume_run_id: Optional[str] = None + save_dir: Optional[str] = None + batch_size: int = 64 + epoch_size: int = 115200 + val_size: int = 1280 + n_epochs: int = 25 + save_epoch_interval: int = 100 + n_dataloader_workers: int = 20 + n_rendering_workers: int = 1 + gradient_max_norm:float = np.inf + max_step_per_epoch: Optional[int] = 25000 + + # Network + use_BN:bool = True + loss_type:Optional[str] = 'pairwise_valid' + + # Optimizer + optimizer: str = "adam" + weight_decay: float = 0.0 + clip_grad_norm: float = np.inf + lr: float = 0.0001 + warmup_step: int = -1 # -1 means disable + n_epochs_warmup: int = 1 + + # Visualization + vis_interval: Optional[int] = 1000 + + debug: Optional[bool] = None + + + +@dataclass +class TrainRefinerConfig: + # Datasets + input_resize: tuple = (160, 160) #(W,H) + crop_ratio:Optional[float] = None + max_num_key: Optional[int] = None + use_normal:bool = False + use_mask:Optional[bool] = False + normal_uint8:bool = False + normalize_xyz:Optional[bool] = True + trans_normalizer:Optional[list] = None + rot_normalizer:Optional[float] = None + c_in:int = 6 + n_view:int = 1 + zfar:float = np.inf + trans_rep:str = 'tracknet' # tracknet/deepim + rot_rep:Optional[str] = 'axis_angle' # 6d/axis_angle + save_dir: Optional[str] = None + + # Run management + run_id: Optional[str] = None + exp_name:Optional[str] = None + batch_size: int = 64 + use_BN:bool = True + optimizer: str = "adam" + weight_decay: float = 0.0 + clip_grad_norm: float = np.inf + lr: float = 0.0001 + warmup_step: int = -1 + loss_type:str = 'l2' # l1/l2/add + + vis_interval: Optional[int] = 1000 + debug: Optional[bool] = None + + diff --git a/third-party/video_to_data/reconstruction/modules/v2d_foundation_pose/lib/FoundationPose/mycpp/CMakeLists.txt b/third-party/video_to_data/reconstruction/modules/v2d_foundation_pose/lib/FoundationPose/mycpp/CMakeLists.txt new file mode 100644 index 0000000000000000000000000000000000000000..7c8a9a5cca867d327b7495d98c5cf13bd15fcbe7 --- /dev/null +++ b/third-party/video_to_data/reconstruction/modules/v2d_foundation_pose/lib/FoundationPose/mycpp/CMakeLists.txt @@ -0,0 +1,25 @@ +cmake_minimum_required(VERSION 3.15) +project(mycpp) + + +set(CMAKE_BUILD_TYPE Release) +set(CMAKE_EXPORT_COMPILE_COMMANDS ON) +set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -std=c++14 -fopenmp -g3 -O3") + + +find_package(Boost REQUIRED COMPONENTS system program_options) +find_package(OpenMP REQUIRED) +find_package(Eigen3 REQUIRED) +find_package(pybind11 REQUIRED) + +include_directories( + include + ${BLAS_INCLUDE_DIR} +) + +file(GLOB MY_SRC ${PROJECT_SOURCE_DIR}/src/*.cpp) + +set(PYBIND11_CPP_STANDARD -std=c++14) + +pybind11_add_module(mycpp src/app/pybind_api.cpp ${MY_SRC}) +target_link_libraries(mycpp PRIVATE ${Boost_LIBRARIES} ${OpenMP_CXX_FLAGS} Eigen3::Eigen) \ No newline at end of file diff --git a/third-party/video_to_data/reconstruction/modules/v2d_foundation_pose/lib/FoundationPose/mycpp/include/Utils.h b/third-party/video_to_data/reconstruction/modules/v2d_foundation_pose/lib/FoundationPose/mycpp/include/Utils.h new file mode 100644 index 0000000000000000000000000000000000000000..06141c29c58202f5e950a2252dafde53168b147a --- /dev/null +++ b/third-party/video_to_data/reconstruction/modules/v2d_foundation_pose/lib/FoundationPose/mycpp/include/Utils.h @@ -0,0 +1,46 @@ +/*Copyright (c) 2023, NVIDIA CORPORATION. All rights reserved. +# +# NVIDIA CORPORATION and its licensors retain all intellectual property +# and proprietary rights in and to this software, related documentation +# and any modifications thereto. Any use, reproduction, disclosure or +# distribution of this software and related documentation without an express +# license agreement from NVIDIA CORPORATION is strictly prohibited. +*/ + + +#pragma once + +// STL +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + + +using vectorMatrix4f = std::vector; + + +namespace Utils +{ +float rotationGeodesicDistance(const Eigen::Matrix3f &R1, const Eigen::Matrix3f &R2); + +} // namespace Utils diff --git a/third-party/video_to_data/reconstruction/modules/v2d_foundation_pose/lib/FoundationPose/mycpp/src/Utils.cpp b/third-party/video_to_data/reconstruction/modules/v2d_foundation_pose/lib/FoundationPose/mycpp/src/Utils.cpp new file mode 100644 index 0000000000000000000000000000000000000000..c1455d54b3fab9b602b1e68c4955001d6fc221b9 --- /dev/null +++ b/third-party/video_to_data/reconstruction/modules/v2d_foundation_pose/lib/FoundationPose/mycpp/src/Utils.cpp @@ -0,0 +1,29 @@ +/* +# Copyright (c) 2023, NVIDIA CORPORATION. All rights reserved. +# +# NVIDIA CORPORATION and its licensors retain all intellectual property +# and proprietary rights in and to this software, related documentation +# and any modifications thereto. Any use, reproduction, disclosure or +# distribution of this software and related documentation without an express +# license agreement from NVIDIA CORPORATION is strictly prohibited. +*/ + + +#include "Utils.h" + + + +namespace Utils +{ + + +// Difference angle in radian +float rotationGeodesicDistance(const Eigen::Matrix3f &R1, const Eigen::Matrix3f &R2) +{ + float cos = ((R1 * R2.transpose()).trace()-1) / 2.0; + cos = std::max(std::min(cos, 1.0f), -1.0f); + return std::acos(cos); +} + + +} // namespace Utils diff --git a/third-party/video_to_data/reconstruction/modules/v2d_foundation_pose/lib/FoundationPose/mycpp/src/app/pybind_api.cpp b/third-party/video_to_data/reconstruction/modules/v2d_foundation_pose/lib/FoundationPose/mycpp/src/app/pybind_api.cpp new file mode 100644 index 0000000000000000000000000000000000000000..cf05548059e3016837d338440efd66e677010eee --- /dev/null +++ b/third-party/video_to_data/reconstruction/modules/v2d_foundation_pose/lib/FoundationPose/mycpp/src/app/pybind_api.cpp @@ -0,0 +1,143 @@ +/* +# Copyright (c) 2023, NVIDIA CORPORATION. All rights reserved. +# +# NVIDIA CORPORATION and its licensors retain all intellectual property +# and proprietary rights in and to this software, related documentation +# and any modifications thereto. Any use, reproduction, disclosure or +# distribution of this software and related documentation without an express +# license agreement from NVIDIA CORPORATION is strictly prohibited. +*/ + +#include "Utils.h" +#include +#include +#include +#include + +namespace py = pybind11; + +// Helper to convert numpy array to vector of Matrix4f +std::vector numpy_to_matrix4f_vector(py::array_t arr) { + auto buf = arr.request(); + if (buf.ndim != 3 || buf.shape[1] != 4 || buf.shape[2] != 4) { + throw std::runtime_error("Input must be (N, 4, 4) array"); + } + + int n = buf.shape[0]; + float* ptr = static_cast(buf.ptr); + std::vector result; + result.reserve(n); + + for (int i = 0; i < n; i++) { + Eigen::Matrix4f mat; + for (int r = 0; r < 4; r++) { + for (int c = 0; c < 4; c++) { + mat(r, c) = ptr[i * 16 + r * 4 + c]; + } + } + result.push_back(mat); + } + return result; +} + +// Helper to convert vector of Matrix4f to numpy array +py::array_t matrix4f_vector_to_numpy(const std::vector& matrices) { + int n = matrices.size(); + auto result = py::array_t({n, 4, 4}); + auto buf = result.request(); + float* ptr = static_cast(buf.ptr); + + for (int i = 0; i < n; i++) { + for (int r = 0; r < 4; r++) { + for (int c = 0; c < 4; c++) { + ptr[i * 16 + r * 4 + c] = matrices[i](r, c); + } + } + } + return result; +} + +//@angle_diff: unit is degree +//@dist_diff: unit is meter +std::vector cluster_poses_impl( + float angle_diff, + float dist_diff, + const std::vector& poses_in, + const std::vector& symmetry_tfs) +{ + printf("symmetry_tfs: %d\n", (int)symmetry_tfs.size()); + printf("num original candidates = %d\n", (int)poses_in.size()); + + if (poses_in.empty()) { + printf("ERROR: poses_in is empty!\n"); + return std::vector(); + } + + std::vector poses_out; + poses_out.push_back(poses_in[0]); + + const float radian_thres = angle_diff / 180.0f * M_PI; + + for (size_t i = 1; i < poses_in.size(); i++) { + bool isnew = true; + Eigen::Matrix4f cur_pose = poses_in[i]; + + for (const auto& cluster : poses_out) { + Eigen::Vector3f t0 = cluster.block<3,1>(0,3); + Eigen::Vector3f t1 = cur_pose.block<3,1>(0,3); + + if ((t0 - t1).norm() >= dist_diff) { + continue; + } + + for (const auto& tf : symmetry_tfs) { + Eigen::Matrix4f cur_pose_tmp = cur_pose * tf; + float rot_diff = Utils::rotationGeodesicDistance( + cur_pose_tmp.block<3,3>(0,0), + cluster.block<3,3>(0,0) + ); + + if (rot_diff < radian_thres) { + isnew = false; + break; + } + } + + if (!isnew) break; + } + + if (isnew) { + poses_out.push_back(poses_in[i]); + } + } + + printf("num of pose after clustering: %d\n", (int)poses_out.size()); + return poses_out; +} + +// Python wrapper +py::array_t cluster_poses( + float angle_diff, + float dist_diff, + py::array_t poses_in_np, + py::array_t symmetry_tfs_np) +{ + // Manual conversion from numpy to Eigen + auto poses_in = numpy_to_matrix4f_vector(poses_in_np); + auto symmetry_tfs = numpy_to_matrix4f_vector(symmetry_tfs_np); + + // Call implementation + auto result = cluster_poses_impl(angle_diff, dist_diff, poses_in, symmetry_tfs); + + // Convert back to numpy + return matrix4f_vector_to_numpy(result); +} + +PYBIND11_MODULE(mycpp, m) { + m.def("cluster_poses", &cluster_poses, + py::arg("angle_diff"), + py::arg("dist_diff"), + py::arg("poses_in"), + py::arg("symmetry_tfs"), + "Cluster poses based on angle and distance thresholds"); +} \ No newline at end of file diff --git a/third-party/video_to_data/reconstruction/modules/v2d_foundation_pose/lib/FoundationPose/offscreen_renderer.py b/third-party/video_to_data/reconstruction/modules/v2d_foundation_pose/lib/FoundationPose/offscreen_renderer.py new file mode 100644 index 0000000000000000000000000000000000000000..54e2faf581f610c77820faf8e7f27b80636c873e --- /dev/null +++ b/third-party/video_to_data/reconstruction/modules/v2d_foundation_pose/lib/FoundationPose/offscreen_renderer.py @@ -0,0 +1,79 @@ +# Copyright (c) 2023, NVIDIA CORPORATION. All rights reserved. +# +# NVIDIA CORPORATION and its licensors retain all intellectual property +# and proprietary rights in and to this software, related documentation +# and any modifications thereto. Any use, reproduction, disclosure or +# distribution of this software and related documentation without an express +# license agreement from NVIDIA CORPORATION is strictly prohibited. + + +import os,sys,time,socket +code_path = os.path.dirname(os.path.realpath(__file__)) +sys.path.append(code_path) +import open3d as o3d +import numpy as np +from PIL import Image +import cv2,imageio +import time +import trimesh +import pyrender +from transformations import * +import numpy as np +from PIL import Image +import cv2 +import time +import argparse,pickle +from Utils import * + + +cvcam_in_glcam = np.array([[1,0,0,0], + [0,-1,0,0], + [0,0,-1,0], + [0,0,0,1]]) + +class ModelRendererOffscreen: + def __init__(self, cam_K, H,W, zfar=100): + ''' + @window_sizes: H,W + ''' + self.K = cam_K + self.scene = pyrender.Scene(ambient_light=[1., 1., 1.],bg_color=[0,0,0]) + self.camera = pyrender.IntrinsicsCamera(fx=cam_K[0,0],fy=cam_K[1,1],cx=cam_K[0,2],cy=cam_K[1,2],znear=0.001,zfar=zfar) + self.cam_node = self.scene.add(self.camera, pose=np.eye(4), name='cam') + self.mesh_nodes = [] + + self.H = H + self.W = W + self.r = pyrender.OffscreenRenderer(self.W, self.H) + + + def set_cam_pose(self, cam_pose): + self.cam_node.matrix = cam_pose + + def add_mesh(self, mesh): + mesh = pyrender.Mesh.from_trimesh(mesh, smooth=False) + mesh_node = self.scene.add(mesh,pose=np.eye(4), name='ob') # Object pose parent is cam + self.mesh_nodes.append(mesh_node) + + + def add_point_light(self, intensity=3): + light = pyrender.DirectionalLight(color=[1.0, 1.0, 1.0], intensity=intensity) + self.scene.add(light, pose=np.eye(4)) # Same as camera position + + + def clear_mesh_nodes(self): + for n in self.mesh_nodes: + self.scene.remove_node(n) + + + def render(self,mesh=None,ob_in_cvcam=None, get_normal=False): + if mesh is not None: + mesh = mesh.copy() + mesh.apply_transform(cvcam_in_glcam@ob_in_cvcam) + mesh = pyrender.Mesh.from_trimesh(mesh, smooth=False) + mesh_node = self.scene.add(mesh, pose=np.eye(4), name='ob') # Object pose parent is cam + color, depth = self.r.render(self.scene) # depth: float + if mesh is not None: + self.scene.remove_node(mesh_node) + + return color, depth diff --git a/third-party/video_to_data/reconstruction/modules/v2d_foundation_pose/lib/FoundationPose/requirements.txt b/third-party/video_to_data/reconstruction/modules/v2d_foundation_pose/lib/FoundationPose/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..bc43341c0547221ed9e4a72d3baf90d37bc002c5 --- /dev/null +++ b/third-party/video_to_data/reconstruction/modules/v2d_foundation_pose/lib/FoundationPose/requirements.txt @@ -0,0 +1,82 @@ +# PyTorch 2.1.1 +--extra-index-url https://download.pytorch.org/whl/cu118 +# torch==2.1.1+cu118 +# torchvision==0.16.1+cu118 +torch==2.0.0+cu118 +torchvision==0.15.1+cu118 +torchaudio==2.0.1+cu118 + + +# JupyterLab +jupyterlab==4.1.5 +ipywidgets==8.1.2 + + +# Common Libraries +numpy==1.26.4 +scipy==1.12.0 +scikit-learn==1.4.1.post1 +scikit-image==0.22.0 +pyyaml==6.0.1 +ruamel.yaml==0.18.6 +ninja==1.11.1.1 +h5py==3.10.0 +numba==0.59.1 +pybind11==2.12.0 + +# CV Libraries +imageio==2.34.0 +opencv-python==4.9.0.80 +opencv-contrib-python==4.9.0.80 +plotly==5.20.0 +open3d==0.18.0 +pyglet==1.5.28 +pysdf==0.1.9 + +# Trimesh +trimesh==4.2.2 +xatlas==0.0.9 +rtree==1.2.0 + +# PyRender +pyrender==0.1.45 +pyOpenGL>=3.1.0 +pyOpenGL_accelerate>=3.1.0 + +meshcat==0.3.2 +webdataset==0.2.86 +omegaconf==2.3.0 +pypng==0.20220715.0 +Panda3D==1.10.14 +simplejson==3.19.2 +bokeh==3.4.0 +roma==1.4.4 +seaborn==0.13.2 +pin==2.7.0 +openpyxl==3.1.2 +torchnet==0.0.4 +wandb==0.16.5 +colorama==0.4.6 +GPUtil==1.4.0 +imgaug==0.4.0 +xlsxwriter==3.2.0 +timm==0.9.16 +albumentations==1.4.2 +xatlas==0.0.9 +nodejs==0.1.1 +jupyterlab==4.1.5 +objaverse==0.1.7 +g4f==0.2.7.1 +ultralytics==8.0.120 +pycocotools==2.0.7 +py-spy==0.3.14 +pybullet==3.2.6 +videoio==0.2.8 +kornia==0.7.2 +einops==0.7.0 +transformations==2024.6.1 +joblib==1.3.2 +warp-lang==1.0.2 + +# For PyTorch3D +fvcore==0.1.5.post20221221 diff --git a/third-party/video_to_data/reconstruction/modules/v2d_foundation_pose/lib/FoundationPose/run_demo.py b/third-party/video_to_data/reconstruction/modules/v2d_foundation_pose/lib/FoundationPose/run_demo.py new file mode 100644 index 0000000000000000000000000000000000000000..fc542b4db5eaef59228a478941a8c332bac9292f --- /dev/null +++ b/third-party/video_to_data/reconstruction/modules/v2d_foundation_pose/lib/FoundationPose/run_demo.py @@ -0,0 +1,79 @@ +# Copyright (c) 2023, NVIDIA CORPORATION. All rights reserved. +# +# NVIDIA CORPORATION and its licensors retain all intellectual property +# and proprietary rights in and to this software, related documentation +# and any modifications thereto. Any use, reproduction, disclosure or +# distribution of this software and related documentation without an express +# license agreement from NVIDIA CORPORATION is strictly prohibited. + + +from estimater import * +from datareader import * +import argparse + + +if __name__=='__main__': + parser = argparse.ArgumentParser() + code_dir = os.path.dirname(os.path.realpath(__file__)) + parser.add_argument('--mesh_file', type=str, default=f'{code_dir}/demo_data/mustard0/mesh/textured_simple.obj') + parser.add_argument('--test_scene_dir', type=str, default=f'{code_dir}/demo_data/mustard0') + parser.add_argument('--est_refine_iter', type=int, default=5) + parser.add_argument('--track_refine_iter', type=int, default=2) + parser.add_argument('--debug', type=int, default=1) + parser.add_argument('--debug_dir', type=str, default=f'{code_dir}/debug') + args = parser.parse_args() + + set_logging_format() + set_seed(0) + + mesh = trimesh.load(args.mesh_file) + + debug = args.debug + debug_dir = args.debug_dir + os.system(f'rm -rf {debug_dir}/* && mkdir -p {debug_dir}/track_vis {debug_dir}/ob_in_cam') + + to_origin, extents = trimesh.bounds.oriented_bounds(mesh) + bbox = np.stack([-extents/2, extents/2], axis=0).reshape(2,3) + + scorer = ScorePredictor() + refiner = PoseRefinePredictor() + glctx = dr.RasterizeCudaContext() + est = FoundationPose(model_pts=mesh.vertices, model_normals=mesh.vertex_normals, mesh=mesh, scorer=scorer, refiner=refiner, debug_dir=debug_dir, debug=debug, glctx=glctx) + logging.info("estimator initialization done") + + reader = YcbineoatReader(video_dir=args.test_scene_dir, shorter_side=None, zfar=np.inf) + + for i in range(len(reader.color_files)): + logging.info(f'i:{i}') + color = reader.get_color(i) + depth = reader.get_depth(i) + if i==0: + mask = reader.get_mask(0).astype(bool) + pose = est.register(K=reader.K, rgb=color, depth=depth, ob_mask=mask, iteration=args.est_refine_iter) + + if debug>=3: + m = mesh.copy() + m.apply_transform(pose) + m.export(f'{debug_dir}/model_tf.obj') + xyz_map = depth2xyzmap(depth, reader.K) + valid = depth>=0.001 + pcd = toOpen3dCloud(xyz_map[valid], color[valid]) + o3d.io.write_point_cloud(f'{debug_dir}/scene_complete.ply', pcd) + else: + pose = est.track_one(rgb=color, depth=depth, K=reader.K, iteration=args.track_refine_iter) + + os.makedirs(f'{debug_dir}/ob_in_cam', exist_ok=True) + np.savetxt(f'{debug_dir}/ob_in_cam/{reader.id_strs[i]}.txt', pose.reshape(4,4)) + + if debug>=1: + center_pose = pose@np.linalg.inv(to_origin) + vis = draw_posed_3d_box(reader.K, img=color, ob_in_cam=center_pose, bbox=bbox) + vis = draw_xyz_axis(color, ob_in_cam=center_pose, scale=0.1, K=reader.K, thickness=3, transparency=0, is_input_rgb=True) + cv2.imshow('1', vis[...,::-1]) + cv2.waitKey(1) + + + if debug>=2: + os.makedirs(f'{debug_dir}/track_vis', exist_ok=True) + imageio.imwrite(f'{debug_dir}/track_vis/{reader.id_strs[i]}.png', vis) + diff --git a/third-party/video_to_data/reconstruction/modules/v2d_foundation_pose/lib/FoundationPose/run_linemod.py b/third-party/video_to_data/reconstruction/modules/v2d_foundation_pose/lib/FoundationPose/run_linemod.py new file mode 100644 index 0000000000000000000000000000000000000000..b927bc66c89e712493063ba0ded0cc6d8c43b1cb --- /dev/null +++ b/third-party/video_to_data/reconstruction/modules/v2d_foundation_pose/lib/FoundationPose/run_linemod.py @@ -0,0 +1,149 @@ +# Copyright (c) 2023, NVIDIA CORPORATION. All rights reserved. +# +# NVIDIA CORPORATION and its licensors retain all intellectual property +# and proprietary rights in and to this software, related documentation +# and any modifications thereto. Any use, reproduction, disclosure or +# distribution of this software and related documentation without an express +# license agreement from NVIDIA CORPORATION is strictly prohibited. + + +from Utils import * +import json,uuid,joblib,os,sys +import scipy.spatial as spatial +from multiprocessing import Pool +import multiprocessing +from functools import partial +from itertools import repeat +import itertools +from datareader import * +from estimater import * +code_dir = os.path.dirname(os.path.realpath(__file__)) +sys.path.append(f'{code_dir}/mycpp/build') +import yaml + + + +def get_mask(reader, i_frame, ob_id, detect_type): + if detect_type=='box': + mask = reader.get_mask(i_frame, ob_id) + H,W = mask.shape[:2] + vs,us = np.where(mask>0) + umin = us.min() + umax = us.max() + vmin = vs.min() + vmax = vs.max() + valid = np.zeros((H,W), dtype=bool) + valid[vmin:vmax,umin:umax] = 1 + elif detect_type=='mask': + mask = reader.get_mask(i_frame, ob_id) + if mask is None: + return None + valid = mask>0 + elif detect_type=='detected': + mask = cv2.imread(reader.color_files[i_frame].replace('rgb','mask_cosypose'), -1) + valid = mask==ob_id + else: + raise RuntimeError + return valid + + + +def run_pose_estimation_worker(reader, i_frames, est:FoundationPose=None, debug=0, ob_id=None, device='cuda:0'): + torch.cuda.set_device(device) + est.to_device(device) + est.glctx = dr.RasterizeCudaContext(device=device) + + result = NestDict() + + for i, i_frame in enumerate(i_frames): + logging.info(f"{i}/{len(i_frames)}, i_frame:{i_frame}, ob_id:{ob_id}") + video_id = reader.get_video_id() + color = reader.get_color(i_frame) + depth = reader.get_depth(i_frame) + id_str = reader.id_strs[i_frame] + H,W = color.shape[:2] + + debug_dir =est.debug_dir + + ob_mask = get_mask(reader, i_frame, ob_id, detect_type=detect_type) + if ob_mask is None: + logging.info("ob_mask not found, skip") + result[video_id][id_str][ob_id] = np.eye(4) + return result + + est.gt_pose = reader.get_gt_pose(i_frame, ob_id) + + pose = est.register(K=reader.K, rgb=color, depth=depth, ob_mask=ob_mask, ob_id=ob_id) + logging.info(f"pose:\n{pose}") + + if debug>=3: + m = est.mesh_ori.copy() + tmp = m.copy() + tmp.apply_transform(pose) + tmp.export(f'{debug_dir}/model_tf.obj') + + result[video_id][id_str][ob_id] = pose + + return result + + +def run_pose_estimation(): + wp.force_load(device='cuda') + reader_tmp = LinemodReader(f'{opt.linemod_dir}/lm_test_all/test/000002', split=None) + + debug = opt.debug + use_reconstructed_mesh = opt.use_reconstructed_mesh + debug_dir = opt.debug_dir + + res = NestDict() + glctx = dr.RasterizeCudaContext() + mesh_tmp = trimesh.primitives.Box(extents=np.ones((3)), transform=np.eye(4)).to_mesh() + est = FoundationPose(model_pts=mesh_tmp.vertices.copy(), model_normals=mesh_tmp.vertex_normals.copy(), symmetry_tfs=None, mesh=mesh_tmp, scorer=None, refiner=None, glctx=glctx, debug_dir=debug_dir, debug=debug) + + for ob_id in reader_tmp.ob_ids: + ob_id = int(ob_id) + if use_reconstructed_mesh: + mesh = reader_tmp.get_reconstructed_mesh(ob_id, ref_view_dir=opt.ref_view_dir) + else: + mesh = reader_tmp.get_gt_mesh(ob_id) + symmetry_tfs = reader_tmp.symmetry_tfs[ob_id] + + args = [] + + video_dir = f'{opt.linemod_dir}/lm_test_all/test/{ob_id:06d}' + reader = LinemodReader(video_dir, split=None) + video_id = reader.get_video_id() + est.reset_object(model_pts=mesh.vertices.copy(), model_normals=mesh.vertex_normals.copy(), symmetry_tfs=symmetry_tfs, mesh=mesh) + + for i in range(len(reader.color_files)): + args.append((reader, [i], est, debug, ob_id, "cuda:0")) + + outs = [] + for arg in args: + out = run_pose_estimation_worker(*arg) + outs.append(out) + + for out in outs: + for video_id in out: + for id_str in out[video_id]: + for ob_id in out[video_id][id_str]: + res[video_id][id_str][ob_id] = out[video_id][id_str][ob_id] + + with open(f'{opt.debug_dir}/linemod_res.yml','w') as ff: + yaml.safe_dump(make_yaml_dumpable(res), ff) + + +if __name__=='__main__': + parser = argparse.ArgumentParser() + code_dir = os.path.dirname(os.path.realpath(__file__)) + parser.add_argument('--linemod_dir', type=str, default="/mnt/9a72c439-d0a7-45e8-8d20-d7a235d02763/DATASET/LINEMOD", help="linemod root dir") + parser.add_argument('--use_reconstructed_mesh', type=int, default=0) + parser.add_argument('--ref_view_dir', type=str, default="/mnt/9a72c439-d0a7-45e8-8d20-d7a235d02763/DATASET/YCB_Video/bowen_addon/ref_views_16") + parser.add_argument('--debug', type=int, default=0) + parser.add_argument('--debug_dir', type=str, default=f'{code_dir}/debug') + opt = parser.parse_args() + set_seed(0) + + detect_type = 'mask' # mask / box / detected + + run_pose_estimation() diff --git a/third-party/video_to_data/reconstruction/modules/v2d_foundation_pose/lib/FoundationPose/run_ycb_video.py b/third-party/video_to_data/reconstruction/modules/v2d_foundation_pose/lib/FoundationPose/run_ycb_video.py new file mode 100644 index 0000000000000000000000000000000000000000..5a5968b4c1eac529918c3e9140421343eff41ea9 --- /dev/null +++ b/third-party/video_to_data/reconstruction/modules/v2d_foundation_pose/lib/FoundationPose/run_ycb_video.py @@ -0,0 +1,149 @@ +# Copyright (c) 2023, NVIDIA CORPORATION. All rights reserved. +# +# NVIDIA CORPORATION and its licensors retain all intellectual property +# and proprietary rights in and to this software, related documentation +# and any modifications thereto. Any use, reproduction, disclosure or +# distribution of this software and related documentation without an express +# license agreement from NVIDIA CORPORATION is strictly prohibited. + + +from Utils import * +import json,uuid,joblib,os,sys,argparse +from datareader import * +from estimater import * +code_dir = os.path.dirname(os.path.realpath(__file__)) +sys.path.append(f'{code_dir}/mycpp/build') +import yaml + + +def get_mask(reader, i_frame, ob_id, detect_type): + if detect_type=='box': + mask = reader.get_mask(i_frame, ob_id) + H,W = mask.shape[:2] + vs,us = np.where(mask>0) + umin = us.min() + umax = us.max() + vmin = vs.min() + vmax = vs.max() + valid = np.zeros((H,W), dtype=bool) + valid[vmin:vmax,umin:umax] = 1 + elif detect_type=='mask': + mask = reader.get_mask(i_frame, ob_id, type='mask_visib') + valid = mask>0 + elif detect_type=='cnos': #https://github.com/nv-nguyen/cnos + mask = cv2.imread(reader.color_files[i_frame].replace('rgb','mask_cnos'), -1) + valid = mask==ob_id + else: + raise RuntimeError + + return valid + + + +def run_pose_estimation_worker(reader, i_frames, est:FoundationPose, debug=False, ob_id=None, device:int=0): + result = NestDict() + torch.cuda.set_device(device) + est.to_device(f'cuda:{device}') + est.glctx = dr.RasterizeCudaContext(device) + debug_dir = est.debug_dir + + for i in range(len(i_frames)): + i_frame = i_frames[i] + id_str = reader.id_strs[i_frame] + logging.info(f"{i}/{len(i_frames)}, video:{reader.get_video_id()}, id_str:{id_str}") + color = reader.get_color(i_frame) + depth = reader.get_depth(i_frame) + + H,W = color.shape[:2] + scene_ob_ids = reader.get_instance_ids_in_image(i_frame) + video_id = reader.get_video_id() + + logging.info(f"video:{reader.get_video_id()}, id_str:{id_str}, ob_id:{ob_id}") + if ob_id not in scene_ob_ids: + logging.info(f'skip {ob_id} as it does not exist in this scene') + continue + ob_mask = get_mask(reader, i_frame, ob_id, detect_type=detect_type) + + est.gt_pose = reader.get_gt_pose(i_frame, ob_id) + pose = est.register(K=reader.K, rgb=color, depth=depth, ob_mask=ob_mask, ob_id=ob_id, iteration=5) + logging.info(f"pose:\n{pose}") + + + if debug>=3: + tmp = est.mesh_ori.copy() + tmp.apply_transform(pose) + tmp.export(f'{debug_dir}/model_tf.obj') + + result[video_id][id_str][ob_id] = pose + + return result + + +def run_pose_estimation(): + wp.force_load(device='cuda') + video_dirs = sorted(glob.glob(f'{opt.ycbv_dir}/test/*')) + res = NestDict() + + debug = opt.debug + use_reconstructed_mesh = opt.use_reconstructed_mesh + debug_dir = opt.debug_dir + + reader_tmp = YcbVideoReader(video_dirs[0]) + glctx = dr.RasterizeCudaContext() + mesh_tmp = trimesh.primitives.Box(extents=np.ones((3)), transform=np.eye(4)) + est = FoundationPose(model_pts=mesh_tmp.vertices.copy(), model_normals=mesh_tmp.vertex_normals.copy(), symmetry_tfs=None, mesh=mesh_tmp, scorer=None, refiner=None, glctx=glctx, debug_dir=debug_dir, debug=debug) + + ob_ids = reader_tmp.ob_ids + + for ob_id in ob_ids: + if use_reconstructed_mesh: + mesh = reader_tmp.get_reconstructed_mesh(ob_id, ref_view_dir=opt.ref_view_dir) + else: + mesh = reader_tmp.get_gt_mesh(ob_id) + symmetry_tfs = reader_tmp.symmetry_tfs[ob_id] + + args = [] + for video_dir in video_dirs: + reader = YcbVideoReader(video_dir, zfar=1.5) + scene_ob_ids = reader.get_instance_ids_in_image(0) + if ob_id not in scene_ob_ids: + continue + video_id = reader.get_video_id() + + for i in range(len(reader.color_files)): + if not reader.is_keyframe(i): + continue + args.append((reader, [i], est, debug, ob_id, 0)) + + est.reset_object(model_pts=mesh.vertices.copy(), model_normals=mesh.vertex_normals.copy(), symmetry_tfs=symmetry_tfs, mesh=mesh) + outs = [] + for arg in args: + out = run_pose_estimation_worker(*arg) + outs.append(out) + + for out in outs: + for video_id in out: + for id_str in out[video_id]: + res[video_id][id_str][ob_id] = out[video_id][id_str][ob_id] + + with open(f'{opt.debug_dir}/ycbv_res.yml','w') as ff: + yaml.safe_dump(make_yaml_dumpable(res), ff) + + + +if __name__=='__main__': + parser = argparse.ArgumentParser() + code_dir = os.path.dirname(os.path.realpath(__file__)) + parser.add_argument('--ycbv_dir', type=str, default="/mnt/9a72c439-d0a7-45e8-8d20-d7a235d02763/DATASET/YCB_Video", help="data dir") + parser.add_argument('--use_reconstructed_mesh', type=int, default=0) + parser.add_argument('--ref_view_dir', type=str, default="/mnt/9a72c439-d0a7-45e8-8d20-d7a235d02763/DATASET/YCB_Video/bowen_addon/ref_views_16") + parser.add_argument('--debug', type=int, default=0) + parser.add_argument('--debug_dir', type=str, default=f'{code_dir}/debug') + opt = parser.parse_args() + os.environ["YCB_VIDEO_DIR"] = opt.ycbv_dir + + set_seed(0) + + detect_type = 'mask' # mask / box / detected + + run_pose_estimation() diff --git a/third-party/video_to_data/reconstruction/modules/v2d_foundation_pose/lib/__init__.py b/third-party/video_to_data/reconstruction/modules/v2d_foundation_pose/lib/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..52a7a9daf028f654d6a02f65c99cc609a57b492f --- /dev/null +++ b/third-party/video_to_data/reconstruction/modules/v2d_foundation_pose/lib/__init__.py @@ -0,0 +1,2 @@ +# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 diff --git a/third-party/video_to_data/reconstruction/modules/v2d_foundation_pose/lib/depth_alignment.py b/third-party/video_to_data/reconstruction/modules/v2d_foundation_pose/lib/depth_alignment.py new file mode 100644 index 0000000000000000000000000000000000000000..a1a68f04af3213218191ab1c9b91461fbd7d1a3c --- /dev/null +++ b/third-party/video_to_data/reconstruction/modules/v2d_foundation_pose/lib/depth_alignment.py @@ -0,0 +1,187 @@ +# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 +"""Temporal depth alignment via ICP on scene point clouds. + +Aligns raw monocular depth for each frame to a metric reference depth by +unprojecting both into point clouds, then alternating between: + 1. ICP step — estimates the rigid camera-motion transform. + 2. Affine step — solves for (scale, shift) linearly given the rigid T. + +The foreground mask (object + hands) is excluded from fitting so that +moving objects don't pollute the background-based alignment. +""" +import logging + +import numpy as np +from scipy.spatial import KDTree + +from v2d.common.datatypes import CameraIntrinsics, DepthImage, Mask + +logger = logging.getLogger(__name__) + + +def align_depth_to_reference_depth( + depth_raw: DepthImage, + depth_ref: DepthImage, + intrinsics: CameraIntrinsics, + fg_mask: Mask = None, + fg_mask_ref: Mask = None, + n_iterations: int = 3, + outlier_trim_ratio: float = 0.2, + max_points: int = 20000, +) -> DepthImage: + """Align raw monocular depth to a metric reference depth via ICP + affine solve. + + Finds (scale, shift) such that scale * depth_raw + shift best matches depth_ref + on the static background, accounting for small camera motion via ICP. + + Each iteration: + 1. ICP: find rigid T that aligns the current affine-corrected source cloud + to the reference cloud (handles camera motion). + 2. Affine solve: with T fixed, solve for (scale, shift) via linear least + squares using the ICP inlier correspondences. + + Args: + depth_raw: Raw monocular depth for the current frame. + depth_ref: Metric reference depth (output of align_depth_to_object). + intrinsics: Camera intrinsics (assumed same for both frames). + fg_mask: Foreground mask for current frame (object + hands). + Excluded from fitting. None = use all valid pixels. + fg_mask_ref: Foreground mask for reference frame. If None, fg_mask + is reused as a proxy. + n_iterations: Alternating ICP/affine iterations. Default 3. + outlier_trim_ratio: Fraction of worst-fitting correspondences to discard + each iteration. Default 0.2. + max_points: Max background points to use (random subsample). + Default 20000. + + Returns: + Corrected DepthImage: clip(scale * depth_raw + shift, 0). + """ + K = intrinsics.to_matrix() + H, W = intrinsics.height, intrinsics.width + + bg_mask = _background_mask(depth_raw.depth, fg_mask, H, W) + bg_mask_ref = _background_mask( + depth_ref.depth, + fg_mask_ref if fg_mask_ref is not None else fg_mask, + H, W, + ) + + PC_ref, _ = _unproject(depth_ref.depth, K, bg_mask_ref, max_points) + PC_raw, (us, vs) = _unproject(depth_raw.depth, K, bg_mask, max_points) + dirs = _ray_directions(us, vs, K) # (N, 3) — unit ray directions per pixel + + if len(PC_ref) < 10 or len(PC_raw) < 10: + logger.warning("Insufficient background points for depth alignment — returning raw depth") + return depth_raw + + T = np.eye(4, dtype=np.float64) + s, b = 1.0, 0.0 + + for it in range(n_iterations): + # Apply current affine to raw points + PC_t = s * PC_raw + b * dirs # (N, 3) + + # Apply current rigid transform + R, t_vec = T[:3, :3], T[:3, 3] + PC_t_aligned = (R @ PC_t.T).T + t_vec # (N, 3) + + # Nearest-neighbour matching to reference cloud + tree = KDTree(PC_ref) + dists, nn_idx = tree.query(PC_t_aligned, k=1) + + # Trim outliers (hands, object, noise) + thresh = np.quantile(dists, 1.0 - outlier_trim_ratio) + inliers = dists <= thresh + if inliers.sum() < 10: + logger.warning(f"Iter {it}: too few inliers ({inliers.sum()}) — stopping early") + break + + src_in = PC_t[inliers] # affine-corrected source (pre-T), inliers only + tgt_in = PC_ref[nn_idx[inliers]] # matched reference points + + # ICP step: solve rigid T from affine-corrected source to matched target + T = _solve_rigid(src_in, tgt_in) + R, t_vec = T[:3, :3], T[:3, 3] + + # Affine step: solve (s, b) with T fixed. + # After applying T: R @ (s * P_raw_i + b * dir_i) + t = P_ref_i + # => s * (R @ P_raw_i) + b * (R @ dir_i) = P_ref_i - t (linear in s, b) + rp = (R @ PC_raw[inliers].T).T # (M, 3) + rd = (R @ dirs[inliers].T).T # (M, 3) + rhs = tgt_in - t_vec # (M, 3) + + A = np.stack([rp.ravel(), rd.ravel()], axis=1) # (3M, 2) + y = rhs.ravel() # (3M,) + result, _, _, _ = np.linalg.lstsq(A, y, rcond=None) + s, b = float(result[0]), float(result[1]) + + logger.debug(f"Iter {it}: scale={s:.4f} shift={b:.4f} inliers={inliers.sum()}") + + logger.info(f"Depth alignment: scale={s:.4f} shift={b:.4f}") + corrected = np.clip(s * depth_raw.depth + b, 0.0, None).astype(np.float32) + return DepthImage(depth=corrected) + + +# --------------------------------------------------------------------------- +# Helpers +# --------------------------------------------------------------------------- + +def _background_mask(depth: np.ndarray, fg_mask: Mask, H: int, W: int) -> np.ndarray: + valid = depth > 0.001 + if fg_mask is not None: + valid = valid & ~fg_mask.mask.astype(bool) + return valid + + +def _unproject( + depth: np.ndarray, + K: np.ndarray, + mask: np.ndarray, + max_points: int, +) -> tuple[np.ndarray, tuple[np.ndarray, np.ndarray]]: + """Unproject masked depth pixels to 3D points. + + Returns: + pts: (N, 3) float64 point cloud. + (us, vs): pixel coordinates of the returned points (after subsampling). + """ + H, W = depth.shape + u_grid, v_grid = np.meshgrid(np.arange(W), np.arange(H)) + us = u_grid[mask].astype(np.float64) + vs = v_grid[mask].astype(np.float64) + d = depth[mask].astype(np.float64) + + if len(d) > max_points: + idx = np.random.choice(len(d), max_points, replace=False) + us, vs, d = us[idx], vs[idx], d[idx] + + X = (us - K[0, 2]) * d / K[0, 0] + Y = (vs - K[1, 2]) * d / K[1, 1] + Z = d + return np.stack([X, Y, Z], axis=1), (us, vs) + + +def _ray_directions(us: np.ndarray, vs: np.ndarray, K: np.ndarray) -> np.ndarray: + """Normalised ray direction vectors for each pixel (homogeneous, z=1).""" + dx = (us - K[0, 2]) / K[0, 0] + dy = (vs - K[1, 2]) / K[1, 1] + return np.stack([dx, dy, np.ones_like(dx)], axis=1) + + +def _solve_rigid(src: np.ndarray, tgt: np.ndarray) -> np.ndarray: + """Solve for rigid T (4x4) such that R @ src + t ≈ tgt (SVD method).""" + c_src = src.mean(0) + c_tgt = tgt.mean(0) + H = (src - c_src).T @ (tgt - c_tgt) + U, _, Vt = np.linalg.svd(H) + R = Vt.T @ U.T + if np.linalg.det(R) < 0: + Vt[-1] *= -1 + R = Vt.T @ U.T + t = c_tgt - R @ c_src + T = np.eye(4, dtype=np.float64) + T[:3, :3] = R + T[:3, 3] = t + return T diff --git a/third-party/video_to_data/reconstruction/modules/v2d_foundation_pose/lib/download_weights.py b/third-party/video_to_data/reconstruction/modules/v2d_foundation_pose/lib/download_weights.py new file mode 100644 index 0000000000000000000000000000000000000000..51ee2bbe4931e6a7fa577ddc0e4fac40680e15ce --- /dev/null +++ b/third-party/video_to_data/reconstruction/modules/v2d_foundation_pose/lib/download_weights.py @@ -0,0 +1,80 @@ +# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 +""" +Download FoundationPose weights from Google Drive. + +Scorer weights (2024-01-11-20-02-45): config.yml + model_best.pth +Refiner weights (2023-10-28-18-33-37): config.yml + model_best.pth + +The FoundationPose predictors look for weights under FOUNDATIONPOSE_WEIGHTS_DIR +in subdirectories named by their run_name timestamps. +""" +import argparse +import os +import subprocess +import time + + +SCORER_FOLDER_ID = "12Te_3TELLes5cim1d7F7EBTwUSe7iRBj" +SCORER_RUN_NAME = "2024-01-11-20-02-45" + +REFINER_FOLDER_ID = "1BEQLZH69UO5EOfah-K9bfI3JyP9Hf7wC" +REFINER_RUN_NAME = "2023-10-28-18-33-37" + +GDOWN_MAX_ATTEMPTS = 3 +GDOWN_RETRY_DELAY_SECONDS = 10 + + +def _gdown_folder(folder_id: str, output_dir: str) -> None: + command = [ + "gdown", "--folder", + f"https://drive.google.com/drive/folders/{folder_id}", + "-O", output_dir, + ] + + for attempt in range(1, GDOWN_MAX_ATTEMPTS + 1): + try: + subprocess.run(command, check=True) + return + except subprocess.CalledProcessError as exc: + if attempt == GDOWN_MAX_ATTEMPTS: + raise + + print( + f"gdown failed with exit code {exc.returncode} " + f"(attempt {attempt}/{GDOWN_MAX_ATTEMPTS}); retrying in " + f"{GDOWN_RETRY_DELAY_SECONDS} seconds..." + ) + time.sleep(GDOWN_RETRY_DELAY_SECONDS) + + +def download_weights(output_dir: str) -> None: + os.makedirs(output_dir, exist_ok=True) + + scorer_dir = os.path.join(output_dir, SCORER_RUN_NAME) + refiner_dir = os.path.join(output_dir, REFINER_RUN_NAME) + + scorer_ckpt = os.path.join(scorer_dir, "model_best.pth") + if os.path.isfile(scorer_ckpt): + print(f"Scorer weights already exist at {scorer_dir}, skipping.") + else: + print(f"Downloading scorer weights to {scorer_dir} ...") + _gdown_folder(SCORER_FOLDER_ID, scorer_dir) + + refiner_ckpt = os.path.join(refiner_dir, "model_best.pth") + if os.path.isfile(refiner_ckpt): + print(f"Refiner weights already exist at {refiner_dir}, skipping.") + else: + print(f"Downloading refiner weights to {refiner_dir} ...") + _gdown_folder(REFINER_FOLDER_ID, refiner_dir) + + print("All FoundationPose weights downloaded successfully.") + print(f" Scorer: {scorer_dir}") + print(f" Refiner: {refiner_dir}") + + +if __name__ == "__main__": + parser = argparse.ArgumentParser(description="Download FoundationPose weights from Google Drive") + parser.add_argument("--output_dir", type=str, required=True, help="Output directory for weights") + args = parser.parse_args() + download_weights(args.output_dir) diff --git a/third-party/video_to_data/reconstruction/modules/v2d_foundation_pose/lib/foundation_pose_tracker.py b/third-party/video_to_data/reconstruction/modules/v2d_foundation_pose/lib/foundation_pose_tracker.py new file mode 100644 index 0000000000000000000000000000000000000000..097ce50eec55feae7d86e47235e9caca63853c47 --- /dev/null +++ b/third-party/video_to_data/reconstruction/modules/v2d_foundation_pose/lib/foundation_pose_tracker.py @@ -0,0 +1,691 @@ +# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 +"""Stateful FoundationPose tracker. + +Lifecycle: + tracker = FoundationPoseTracker(mesh, weights_dir) + pose0 = tracker.register(rgb, depth, mask, intrinsics) + pose1 = tracker.track_one(rgb1, depth1, intrinsics) + pose2 = tracker.track_one(rgb2, depth2, intrinsics) + tracker.reset_to_pose(pose0) # rewind for backward pass + pose_bk = tracker.track_one(rgb_prev, depth_prev, intrinsics, iteration=2) + +Particle filter tracking (multi-hypothesis): + pose1 = tracker.track_one_particles(rgb1, depth1, intrinsics, n_particles=20) + pose2 = tracker.track_one_particles(rgb2, depth2, intrinsics, n_particles=20) + +Scale estimation: + scale = tracker.estimate_scale_grid_search(rgb, depth, mask, intrinsics) + # tracker is now in the best-scale state; use it directly for tracking +""" +import logging +import os +import sys + +import numpy as np +import torch +from scipy.spatial import cKDTree as _cKDTree +from scipy.spatial.transform import Rotation as _Rotation + +from v2d.common.datatypes import CameraIntrinsics, DepthImage, Mask, Transform3d +from v2d.common.datatypes import Image as V2dImage +from v2d.mesh.lib.mesh import Mesh + +_FP_DIR = os.path.join(os.path.dirname(os.path.abspath(__file__)), 'FoundationPose') +sys.path.insert(0, _FP_DIR) + +from estimater import FoundationPose # noqa: E402 +from learning.training.predict_score import ScorePredictor # noqa: E402 +from learning.training.predict_pose_refine import PoseRefinePredictor # noqa: E402 +from Utils import nvdiffrast_render, erode_depth, bilateral_filter_depth, depth2xyzmap_batch # noqa: E402 +import nvdiffrast.torch as dr # noqa: E402 + +logger = logging.getLogger(__name__) + + +# --------------------------------------------------------------------------- +# SE(3) particle filter helpers +# --------------------------------------------------------------------------- + +def _perturb_se3(poses: np.ndarray, sigma_t: float, sigma_r: float) -> np.ndarray: + """Add independent SE(3) noise to each pose. + + Translation noise is additive. Rotation noise is a left-perturbation in + so(3): R_new = exp(δr) @ R_old, where δr ~ N(0, σ_r² I). + + Args: + poses: (N, 4, 4) float32 poses. + sigma_t: Translation std (metres). + sigma_r: Rotation std (radians). + + Returns: + (N, 4, 4) float32 perturbed poses. + """ + N = len(poses) + out = poses.copy() + out[:, :3, 3] += np.random.randn(N, 3).astype(np.float32) * sigma_t + delta_r = _Rotation.from_rotvec( + np.random.randn(N, 3).astype(np.float32) * sigma_r + ).as_matrix() # (N, 3, 3) + out[:, :3, :3] = (delta_r @ poses[:, :3, :3]) + return out + + +def _ess(weights: np.ndarray) -> float: + """Effective sample size 1 / Σw².""" + return 1.0 / float(np.sum(weights ** 2)) + + +def _resample(particles: np.ndarray, weights: np.ndarray) -> np.ndarray: + """Multinomial resampling.""" + indices = np.random.choice(len(particles), size=len(particles), p=weights) + return particles[indices].copy() + + +def _weighted_mean_se3(particles: np.ndarray, weights: np.ndarray) -> np.ndarray: + """Weighted Fréchet mean on SE(3). + + Translation is linearly averaged. Rotation uses iterative geodesic mean + on SO(3) (Riemannian gradient descent), converging in ~3 iterations. + + Args: + particles: (N, 4, 4) poses. + weights: (N,) normalised weights summing to 1. + + Returns: + (4, 4) float32 mean pose. + """ + t_mean = (weights[:, None] * particles[:, :3, 3]).sum(0) + + # Initialise at the highest-weight particle + R_mean = _Rotation.from_matrix(particles[int(weights.argmax()), :3, :3]) + for _ in range(5): + # Tangent vectors from R_mean to each particle (left formulation) + tangents = (_Rotation.from_matrix(particles[:, :3, :3]) * R_mean.inv()).as_rotvec() + mean_tangent = (weights[:, None] * tangents).sum(0) + R_mean = _Rotation.from_rotvec(mean_tangent) * R_mean + if np.linalg.norm(mean_tangent) < 1e-7: + break + + M = np.eye(4, dtype=np.float32) + M[:3, :3] = R_mean.as_matrix().astype(np.float32) + M[:3, 3] = t_mean.astype(np.float32) + return M + + +class FoundationPoseTracker: + """Wraps FoundationPose for stateful 6-DoF object tracking.""" + + def __init__(self, mesh: Mesh, weights_dir: str) -> None: + if weights_dir: + os.environ.setdefault("FOUNDATIONPOSE_WEIGHTS_DIR", weights_dir) + + self._scorer = ScorePredictor() + self._refiner = PoseRefinePredictor() + self._glctx = dr.RasterizeCudaContext() + self._original_mesh = mesh + self._mesh = mesh + self._current_scale = 1.0 + self._particles: np.ndarray | None = None # (N, 4, 4) poses in pose_last frame + self._weights: np.ndarray | None = None # (N,) normalised + self._init_fp(mesh) + + def _init_fp(self, mesh: Mesh) -> None: + tm = mesh.to_trimesh() + self._est = FoundationPose( + model_pts=tm.vertices, + model_normals=tm.vertex_normals, + mesh=tm, + scorer=self._scorer, + refiner=self._refiner, + glctx=self._glctx, + debug=0, + debug_dir='/tmp/foundationpose_debug', + ) + + def register( + self, + rgb: V2dImage, + depth: DepthImage, + mask: Mask, + intrinsics: CameraIntrinsics, + iteration: int = 10, + ) -> Transform3d: + """Register initial pose from a reference frame. Returns object-to-camera Transform3d.""" + with torch.no_grad(): + pose = self._est.register( + K=intrinsics.to_matrix(), + rgb=rgb.data, + depth=depth.depth, + ob_mask=mask.mask.astype(bool), + iteration=iteration, + ) + return Transform3d.from_matrix(pose) + + def track_one( + self, + rgb: V2dImage, + depth: DepthImage, + intrinsics: CameraIntrinsics, + iteration: int = 5, + ) -> Transform3d: + """Track pose for the next frame. Returns object-to-camera Transform3d.""" + with torch.no_grad(): + pose = self._est.track_one( + rgb=rgb.data, + depth=depth.depth, + K=intrinsics.to_matrix(), + iteration=iteration, + ) + return Transform3d.from_matrix(pose) + + def track_one_with_recovery( + self, + rgb: V2dImage, + depth: DepthImage, + mask: Mask, + intrinsics: CameraIntrinsics, + iteration: int = 5, + iou_thresh: float = 0.3, + recovery_iteration: int = 10, + ) -> tuple[Transform3d, bool]: + """Track one frame, re-registering if the tracked pose has low mask IoU. + + After tracking, renders the mesh at the tracked pose and computes IoU + against the observed mask. If IoU < iou_thresh, re-registers from + scratch using the current frame's mask. + + Args: + rgb: Current frame image. + depth: Current frame depth. + mask: Current frame segmentation mask. + intrinsics: Camera intrinsics. + iteration: Tracking refinement iterations. + iou_thresh: IoU below this triggers re-registration. Default 0.3. + recovery_iteration: Registration iterations on recovery. Default 10. + + Returns: + (pose, recovered) — recovered is True if re-registration was triggered. + """ + pose = self.track_one(rgb, depth, intrinsics, iteration=iteration) + iou = self._mask_iou(mask, intrinsics, pose) + if iou < iou_thresh: + logger.info(f"Tracking loss detected (IoU={iou:.3f} < {iou_thresh}) — re-registering") + pose = self.register(rgb, depth, mask, intrinsics, iteration=recovery_iteration) + return pose, True + return pose, False + + def track_one_particles( + self, + rgb: V2dImage, + depth: DepthImage, + intrinsics: CameraIntrinsics, + mask: Mask | None = None, + n_particles: int = 20, + process_noise_t: float = 0.005, + process_noise_r: float = 0.02, + iteration: int = 3, + mask_iou_weight: float = 1.0, + ) -> Transform3d: + """Track using a particle filter with FP's refiner and scorer as measurement model. + + Each frame: perturb particles → refine (single batched GPU call) → + score (single batched GPU call) → optionally weight by mask IoU + (single batched render) → softmax weight → conditional resample. + + The scorer captures appearance quality (RGB+depth match); mask IoU adds + an independent geometric silhouette constraint that is robust to lateral + drift. When mask is provided, the combined log-weight is: + log_w_i = scorer_logit_i + mask_iou_weight * log(iou_i + ε) + + Particles are lazily initialised on the first call from pose_last, and + cleared by reset_to_pose() so forward/backward passes are independent. + + Args: + rgb: Current frame image. + depth: Current frame depth. + intrinsics: Camera intrinsics. + mask: Optional segmentation mask for IoU weighting. + When provided, particles are additionally weighted + by their silhouette overlap with this mask. + n_particles: Number of particles. Default 20. + process_noise_t: Per-frame translation perturbation std (metres). + Default 0.005. + process_noise_r: Per-frame rotation perturbation std (radians). + Default 0.02. + iteration: Refiner iterations per particle per frame. Default 3. + mask_iou_weight: Log-space weight for the mask IoU term. Default 1.0. + Set to 0.0 to disable mask weighting. + + Returns: + Weighted mean pose as Transform3d. + """ + if self._est.pose_last is None: + raise RuntimeError("Call register() before track_one_particles()") + + # Lazy-init or reinit if n_particles changed + if self._particles is None or len(self._particles) != n_particles: + seed = np.tile( + self._est.pose_last.cpu().numpy().astype(np.float32), + (n_particles, 1, 1), + ) + self._particles = _perturb_se3(seed, process_noise_t, process_noise_r) + self._weights = np.full(n_particles, 1.0 / n_particles, dtype=np.float32) + + K = intrinsics.to_matrix() + + # Depth preprocessing — mirrors _est.track_one internals + depth_t = torch.as_tensor(depth.depth, device='cuda', dtype=torch.float) + depth_t = erode_depth(depth_t, radius=2, device='cuda') + depth_t = bilateral_filter_depth(depth_t, radius=2, device='cuda') + K_t = torch.as_tensor(K, device='cuda', dtype=torch.float) + xyz_map = depth2xyzmap_batch(depth_t[None], K_t[None], zfar=np.inf)[0] + + # 1. Propagate: perturb each particle + candidates = _perturb_se3(self._particles, process_noise_t, process_noise_r) + + # 2. Refine: single batched call over all particles + with torch.no_grad(): + refined, _ = self._est.refiner.predict( + mesh=self._est.mesh, + mesh_tensors=self._est.mesh_tensors, + rgb=rgb.data, + depth=depth_t, + K=K, + ob_in_cams=candidates, + xyz_map=xyz_map, + mesh_diameter=self._est.diameter, + glctx=self._glctx, + iteration=iteration, + get_vis=False, + ) + refined_np = refined.cpu().numpy() + + # 3. Score: single batched call over all particles + with torch.no_grad(): + scores, _ = self._est.scorer.predict( + mesh=self._est.mesh, + mesh_tensors=self._est.mesh_tensors, + rgb=rgb.data, + depth=depth_t.cpu().numpy(), + K=K, + ob_in_cams=refined_np, + glctx=self._glctx, + mesh_diameter=self._est.diameter, + get_vis=False, + ) + + # 4. Combine scorer logits with optional mask IoU in log-space + log_w = scores.cpu().numpy().astype(np.float64) + + if mask is not None and mask_iou_weight > 0.0: + # Batch render all N refined particles — one GPU call + pose_batch = torch.as_tensor(refined_np, device='cuda', dtype=torch.float) + with torch.no_grad(): + _, rendered_depths, _ = nvdiffrast_render( + K, intrinsics.height, intrinsics.width, pose_batch, + glctx=self._glctx, + mesh_tensors=self._est.mesh_tensors, + get_normal=False, + ) + rendered_masks = rendered_depths.cpu().numpy() > 0.001 # (N, H, W) + obs_mask = mask.mask.astype(bool) + intersection = (obs_mask[None] & rendered_masks).sum(axis=(1, 2)) + union = (obs_mask[None] | rendered_masks).sum(axis=(1, 2)) + iou_scores = intersection / (union + 1e-6) # (N,) + log_w += mask_iou_weight * np.log(np.maximum(iou_scores, 1e-6)) + logger.debug(f" IoU scores — mean={iou_scores.mean():.3f} min={iou_scores.min():.3f}") + + log_w -= log_w.max() # numerical stability + w = np.exp(log_w) + self._weights = (w / w.sum()).astype(np.float32) + self._particles = refined_np + + logger.debug( + f"Particle filter: ESS={_ess(self._weights):.1f}/{n_particles} " + f"best_score={log_w.max():.3f}" + ) + + # 5. Conditional resample when diversity collapses + if _ess(self._weights) < n_particles / 2.0: + logger.debug("Resampling particles") + self._particles = _resample(self._particles, self._weights) + self._weights = np.full(n_particles, 1.0 / n_particles, dtype=np.float32) + + # 6. Keep pose_last = best particle (maintains reset_to_pose compatibility) + best_idx = int(self._weights.argmax()) + self._est.pose_last = torch.as_tensor( + self._particles[best_idx], device='cuda', dtype=torch.float + ) + + # 7. Return weighted mean as Transform3d + mean_centered = _weighted_mean_se3(self._particles, self._weights) + mean_pose = mean_centered @ self._est.get_tf_to_centered_mesh().cpu().numpy() + return Transform3d.from_matrix(mean_pose) + + def _mask_iou( + self, + mask: Mask, + intrinsics: CameraIntrinsics, + pose: Transform3d, + ) -> float: + """Render the mesh at `pose` and return IoU with the observed mask.""" + K = intrinsics.to_matrix() + H, W = intrinsics.height, intrinsics.width + pose_mat = torch.as_tensor(pose.to_matrix()[None], device='cuda', dtype=torch.float) + + with torch.no_grad(): + _, rendered_depth, _ = nvdiffrast_render( + K, H, W, pose_mat, + glctx=self._glctx, + mesh_tensors=self._est.mesh_tensors, + get_normal=False, + ) + + rendered_mask = rendered_depth[0].cpu().numpy() > 0.001 + obs_mask = mask.mask.astype(bool) + + intersection = float((obs_mask & rendered_mask).sum()) + union = float((obs_mask | rendered_mask).sum()) + return intersection / (union + 1e-6) + + def reset_to_pose(self, pose: Transform3d) -> None: + """Reset internal pose state. Use before a backward tracking pass. + + pose is in the caller's frame (with get_tf_to_centered_mesh applied), but + pose_last must be stored in the pre-centering frame that track_one expects. + """ + torch.cuda.empty_cache() + matrix = torch.as_tensor(pose.to_matrix(), device='cuda', dtype=torch.float) + tf_to_center = self._est.get_tf_to_centered_mesh() + self._est.pose_last = matrix @ torch.linalg.inv(tf_to_center) + self._particles = None + self._weights = None + + def rescale_mesh(self, scale: float) -> None: + """Rescale the current mesh by `scale` relative to its current size.""" + self.rescale_to(self._current_scale * scale) + + def rescale_to(self, scale: float) -> None: + """Rescale to `scale` times the *original* mesh size and reinitialize FoundationPose.""" + scaled = Mesh( + vertices=self._original_mesh.vertices * scale, + faces=self._original_mesh.faces, + vertex_colors=self._original_mesh.vertex_colors, + uv=self._original_mesh.uv, + texture=self._original_mesh.texture, + ) + self._mesh = scaled + self._current_scale = scale + self._particles = None + self._weights = None + self._init_fp(scaled) + + def _chamfer_score( + self, + obs_depth: np.ndarray, + rendered_mask: np.ndarray, + intrinsics: CameraIntrinsics, + pose: Transform3d, + max_pts: int = 5000, + ) -> float: + """Symmetric Chamfer score between unprojected depth and mesh vertices. + + Unprojects depth pixels inside `rendered_mask` to camera-space 3D points, + then computes the symmetric mean Chamfer distance against the mesh vertices + transformed to camera space by `pose`. + + Returns exp(-chamfer_dist), so 1.0 is a perfect match and the score + decreases as the two point sets diverge. Returns 0.0 if there are not + enough valid depth points. + """ + valid = rendered_mask & (obs_depth > 0.001) + if valid.sum() < 10: + return 0.0 + + fx, fy = intrinsics.fx, intrinsics.fy + cx, cy = intrinsics.cx, intrinsics.cy + H, W = obs_depth.shape + u, v = np.meshgrid(np.arange(W, dtype=np.float32), np.arange(H, dtype=np.float32)) + z = obs_depth[valid] + obs_pts = np.stack([(u[valid] - cx) / fx * z, + (v[valid] - cy) / fy * z, + z], axis=-1) + if len(obs_pts) > max_pts: + idx = np.random.choice(len(obs_pts), max_pts, replace=False) + obs_pts = obs_pts[idx] + + # Transform mesh vertices to camera space + M = pose.to_matrix().astype(np.float64) + verts = self._mesh.vertices # (N, 3) + verts_h = np.concatenate([verts, np.ones((len(verts), 1))], axis=-1) + mesh_pts = (M @ verts_h.T).T[:, :3].astype(np.float32) + mesh_pts = mesh_pts[mesh_pts[:, 2] > 0.001] # behind-camera cull + if len(mesh_pts) == 0: + return 0.0 + if len(mesh_pts) > max_pts: + idx = np.random.choice(len(mesh_pts), max_pts, replace=False) + mesh_pts = mesh_pts[idx] + + d_obs, _ = _cKDTree(mesh_pts).query(obs_pts, k=1) + d_mesh, _ = _cKDTree(obs_pts).query(mesh_pts, k=1) + chamfer = float(np.mean(d_obs) + np.mean(d_mesh)) + return float(np.exp(-chamfer)) + + def _score_scale( + self, + depth: DepthImage, + mask: Mask, + intrinsics: CameraIntrinsics, + pose: Transform3d, + iou_weight: float = 1.0, + depth_weight: float = 1.0, + chamfer_weight: float = 0.0, + ) -> float: + """Score how well the current mesh scale fits the observed depth and mask. + + Renders the mesh at `pose` and computes a weighted combination of: + - Mask IoU: overlap between rendered and observed masks. + - Depth consistency: exp(-MARE) where MARE = median |obs/rendered - 1| + over valid pixels. Equals 1.0 at perfect match. + - Chamfer: exp(-chamfer_dist) where chamfer_dist is the symmetric mean + Chamfer distance between depth points (inside rendered mask) and mesh + vertices, both in camera space. Equals 1.0 at perfect match. + + Returns a higher value for a better fit. + """ + K = intrinsics.to_matrix() + H, W = intrinsics.height, intrinsics.width + pose_mat = torch.as_tensor(pose.to_matrix()[None], device='cuda', dtype=torch.float) + + with torch.no_grad(): + _, rendered_depth, _ = nvdiffrast_render( + K, H, W, pose_mat, + glctx=self._glctx, + mesh_tensors=self._est.mesh_tensors, + get_normal=False, + ) + + rendered = rendered_depth[0].cpu().numpy() + obs_depth = depth.depth + obs_mask = mask.mask.astype(bool) + rendered_mask = rendered > 0.001 + + score = 0.0 + + if iou_weight > 0.0: + intersection = float((obs_mask & rendered_mask).sum()) + union = float((obs_mask | rendered_mask).sum()) + score += iou_weight * (intersection / (union + 1e-6)) + + if depth_weight > 0.0: + valid = obs_mask & rendered_mask & (obs_depth > 0.001) + if valid.sum() >= 10: + ratios = obs_depth[valid] / rendered[valid] + mare = float(np.median(np.abs(ratios - 1.0))) + score += depth_weight * float(np.exp(-mare)) + + if chamfer_weight > 0.0: + score += chamfer_weight * self._chamfer_score(obs_depth, rendered_mask, intrinsics, pose) + + return score + + def align_depth_to_object( + self, + rgb: V2dImage, + depth_raw: DepthImage, + mask: Mask, + intrinsics: CameraIntrinsics, + scale_lo: float = 0.5, + scale_hi: float = 2.0, + shift_lo: float = -0.5, + shift_hi: float = 0.5, + n_scale_samples: int = 7, + n_shift_samples: int = 5, + n_levels: int = 3, + iou_weight: float = 1.0, + depth_weight: float = 1.0, + chamfer_weight: float = 0.0, + registration_iterations: int = 5, + ) -> DepthImage: + """Find the depth affine (scale, shift) that best aligns raw monocular depth to the mesh. + + Searches over D_aligned = scale * D_raw + shift via coarse-to-fine 2D grid search. + For each candidate, registers with FP and scores via mask IoU + depth MARE + Chamfer. + Leaves the tracker registered at the best-fit depth, ready for tracking. + + Args: + rgb: Reference frame image. + depth_raw: Raw (uncalibrated) monocular depth. + mask: Object segmentation mask. + intrinsics: Camera intrinsics. + scale_lo: Lower bound of scale search range. Default 0.5. + scale_hi: Upper bound of scale search range. Default 2.0. + shift_lo: Lower bound of shift search range (metres). Default -0.5. + shift_hi: Upper bound of shift search range (metres). Default 0.5. + n_scale_samples: Scale candidates per level. Default 7. + n_shift_samples: Shift candidates per level. Default 5. + n_levels: Refinement levels. Default 3. + iou_weight: Weight for mask IoU in score. Default 1.0. + depth_weight: Weight for depth MARE in score. Default 1.0. + chamfer_weight: Weight for Chamfer distance score. Default 0.0 (disabled). + registration_iterations: FP register() iterations per candidate. Default 5. + + Returns: + Corrected DepthImage with the best-fitting affine applied. + """ + best_score = -np.inf + best_scale = 1.0 + best_shift = 0.0 + log_scale_lo = np.log(scale_lo) + log_scale_hi = np.log(scale_hi) + + for level in range(n_levels): + scales = np.exp(np.linspace(log_scale_lo, log_scale_hi, n_scale_samples)) + shifts = np.linspace(shift_lo, shift_hi, n_shift_samples) + + for scale in scales: + for shift in shifts: + depth_candidate = DepthImage( + depth=np.clip(scale * depth_raw.depth + shift, 0.0, None).astype(np.float32) + ) + pose = self.register(rgb, depth_candidate, mask, intrinsics, iteration=registration_iterations) + score = self._score_scale(depth_candidate, mask, intrinsics, pose, iou_weight, depth_weight, chamfer_weight) + logger.debug(f" scale={scale:.4f} shift={shift:.4f} score={score:.4f}") + if score > best_score: + best_score = score + best_scale = float(scale) + best_shift = float(shift) + + logger.info( + f"Level {level + 1}/{n_levels}: " + f"best_scale={best_scale:.4f} best_shift={best_shift:.4f} score={best_score:.4f}" + ) + log_scale_radius = (log_scale_hi - log_scale_lo) / 4 + log_scale_lo = np.log(best_scale) - log_scale_radius + log_scale_hi = np.log(best_scale) + log_scale_radius + shift_radius = (shift_hi - shift_lo) / 4 + shift_lo = best_shift - shift_radius + shift_hi = best_shift + shift_radius + + logger.info(f"Best depth affine: scale={best_scale:.4f} shift={best_shift:.4f}") + corrected = np.clip(best_scale * depth_raw.depth + best_shift, 0.0, None).astype(np.float32) + best_depth = DepthImage(depth=corrected) + # Leave tracker registered at best depth + self.register(rgb, best_depth, mask, intrinsics, iteration=registration_iterations) + return best_depth + + def estimate_scale_grid_search( + self, + rgb: V2dImage, + depth: DepthImage, + mask: Mask, + intrinsics: CameraIntrinsics, + lo: float = 0.5, + hi: float = 2.0, + n_samples: int = 7, + n_levels: int = 3, + iou_weight: float = 1.0, + depth_weight: float = 1.0, + chamfer_weight: float = 0.0, + registration_iterations: int = 5, + ) -> float: + """Coarse-to-fine grid search for the optimal mesh scale. + + Samples `n_samples` scales evenly in log-space across [lo, hi] (relative + to the original mesh). For each candidate, registers the mesh with FP, + renders it, and scores the result. The search range is halved around the + winner each level, giving `n_levels` rounds of refinement. + + Leaves the tracker in the best-scale state so it can be used directly + for subsequent tracking. + + Args: + rgb: Reference frame image. + depth: Corresponding observed depth. + mask: Corresponding segmentation mask. + intrinsics: Camera intrinsics. + lo: Lower bound of initial scale search range + (relative to original mesh). Default 0.5. + hi: Upper bound of initial scale search range. + Default 2.0. + n_samples: Scales to evaluate per level. Default 7. + n_levels: Refinement levels. Default 3. + iou_weight: Weight for mask IoU in the score. Default 1.0. + depth_weight: Weight for depth consistency in the score. Default 1.0. + chamfer_weight: Weight for Chamfer distance score. Computes symmetric + mean Chamfer distance between depth points (inside rendered + mask) and mesh vertices in camera space, scored as + exp(-chamfer_dist). Default 0.0 (disabled). + registration_iterations: FP register() iterations per candidate. Default 5. + + Returns: + Best scale factor relative to the original mesh. + """ + log_lo = np.log(lo) + log_hi = np.log(hi) + best_scale = float(np.sqrt(lo * hi)) # geometric midpoint as initial guess + + for level in range(n_levels): + scales = np.exp(np.linspace(log_lo, log_hi, n_samples)) + best_score = -np.inf + + for scale in scales: + self.rescale_to(scale) + pose = self.register(rgb, depth, mask, intrinsics, iteration=registration_iterations) + score = self._score_scale(depth, mask, intrinsics, pose, iou_weight, depth_weight, chamfer_weight) + logger.debug(f" scale={scale:.4f} score={score:.4f}") + if score > best_score: + best_score = score + best_scale = float(scale) + + logger.info(f"Level {level + 1}/{n_levels}: best_scale={best_scale:.4f} score={best_score:.4f}") + + # Halve the log-space search range around the winner + log_radius = (log_hi - log_lo) / 4 + log_lo = np.log(best_scale) - log_radius + log_hi = np.log(best_scale) + log_radius + + # Leave tracker in the winning state + self.rescale_to(best_scale) + return best_scale diff --git a/third-party/video_to_data/reconstruction/modules/v2d_foundation_pose/lib/fp_utils.py b/third-party/video_to_data/reconstruction/modules/v2d_foundation_pose/lib/fp_utils.py new file mode 100644 index 0000000000000000000000000000000000000000..8e379f6641f7d13a2cb3f7a65c93d09d01c97a1c --- /dev/null +++ b/third-party/video_to_data/reconstruction/modules/v2d_foundation_pose/lib/fp_utils.py @@ -0,0 +1,27 @@ +# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 +""" +Re-export commonly used FoundationPose utility functions. + +This wrapper lets other packages import GPU-accelerated depth filtering +and visualization helpers via a clean package path instead of manipulating +sys.path themselves: + + from v2d.foundation_pose.lib.fp_utils import erode_depth, bilateral_filter_depth, depth2xyzmap +""" +import os +import sys + +_FP_DIR = os.path.join(os.path.dirname(os.path.abspath(__file__)), "FoundationPose") +if _FP_DIR not in sys.path: + sys.path.insert(0, _FP_DIR) + +from Utils import ( # noqa: E402 + erode_depth, + bilateral_filter_depth, + depth2xyzmap, + draw_posed_3d_box, + draw_xyz_axis, + nvdiffrast_render, + make_mesh_tensors, +) diff --git a/third-party/video_to_data/reconstruction/modules/v2d_foundation_pose/lib/multiview_tracker.py b/third-party/video_to_data/reconstruction/modules/v2d_foundation_pose/lib/multiview_tracker.py new file mode 100644 index 0000000000000000000000000000000000000000..dc85febba612a8ea1680915282443a4ad7549007 --- /dev/null +++ b/third-party/video_to_data/reconstruction/modules/v2d_foundation_pose/lib/multiview_tracker.py @@ -0,0 +1,396 @@ +# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 +"""Multi-view 6-DoF object tracker using FoundationPose. + +Creates N FoundationPose estimators with shared weights (scorer, refiner, +glctx) and fuses per-camera poses each frame via visibility-based selection +and anisotropic pose averaging. +""" + +import json +import logging +import os +import sys +from contextlib import contextmanager +from pathlib import Path +import numpy as np +from scipy.spatial.transform import Rotation +import torch +import trimesh + +from v2d.mesh.lib.mesh import Mesh +from v2d.mv.math.numpy_fn import xyz_to_uv, se3_from_rot_trans + + +def _canonicalize_poses_with_indices( + poses: list[np.ndarray], + group: list[np.ndarray], + reference: np.ndarray, +) -> tuple[list[np.ndarray], list[tuple[int, float]]]: + """Canonicalize each pose against `reference`; also return (chosen_index, geodesic_dist_rad).""" + ref_R = np.asarray(reference, dtype=float)[:3, :3] + canonicals: list[np.ndarray] = [] + indices: list[tuple[int, float]] = [] + for pose in poses: + pose = np.asarray(pose, dtype=float) + best_idx = -1 + best_dist = float("inf") + best_pose = None + for k, R_s in enumerate(group): + cand = pose @ R_s + cos_t = (np.trace(ref_R.T @ cand[:3, :3]) - 1.0) / 2.0 + d = float(np.arccos(np.clip(cos_t, -1.0, 1.0))) + if d < best_dist: + best_dist = d + best_idx = k + best_pose = cand + canonicals.append(best_pose) + indices.append((best_idx, best_dist)) + return canonicals, indices + + +def _dump_register_debug( + path: str, + symmetry_group_size: int, + fp_scores: list[float], + visible_ratios: np.ndarray, + select_idx: np.ndarray, + ref_idx: int, + raw_world_poses: list[np.ndarray], + canonical_world_poses: list[np.ndarray], + snap_indices_per_iter: list[list[tuple[int, float]]], + avg_pose: np.ndarray, +) -> None: + p = Path(path) + p.parent.mkdir(parents=True, exist_ok=True) + record = { + "symmetry_group_size": int(symmetry_group_size), + "fp_scores": [float(s) for s in fp_scores], + "visible_ratios": [float(v) for v in visible_ratios], + "select_idx": [bool(v) for v in select_idx], + "ref_idx": int(ref_idx), + "n_iter": len(snap_indices_per_iter), + "raw_world_poses": [np.asarray(p).tolist() for p in raw_world_poses], + "canonical_world_poses": [np.asarray(p).tolist() for p in canonical_world_poses], + "snap_indices_per_iter": [ + [[int(idx), float(dist)] for idx, dist in iter_indices] + for iter_indices in snap_indices_per_iter + ], + "avg_pose": np.asarray(avg_pose).tolist(), + } + with open(p, "w") as f: + json.dump(record, f, indent=2) + print(f"[MultiViewTracker] register debug dumped to {p}") + + +@contextmanager +def _suppress_fp_logging(): + """Temporarily raise root log level to suppress FoundationPose info spam.""" + prev = logging.root.level + logging.root.setLevel(logging.WARNING) + try: + yield + finally: + logging.root.setLevel(prev) + +_FP_DIR = os.path.join(os.path.dirname(os.path.abspath(__file__)), "FoundationPose") +if _FP_DIR not in sys.path: + sys.path.insert(0, _FP_DIR) + +from estimater import FoundationPose # noqa: E402 +from learning.training.predict_score import ScorePredictor # noqa: E402 +from learning.training.predict_pose_refine import PoseRefinePredictor # noqa: E402 +from Utils import set_seed # noqa: E402 +import nvdiffrast.torch as dr # noqa: E402 + + +class MultiViewTracker: + """Coordinate N FoundationPose estimators with shared weights.""" + + def __init__( + self, + mesh: Mesh, + weights_dir: str, + num_cameras: int, + depth_direction_trust: float = 0.5, + visible_ratio_cutoff_high: float = 0.3, + visible_ratio_cutoff_low: float = 0.3, + precision_high: float = 1.0, + precision_low: float = 0.01, + symmetry_group: list[np.ndarray] | None = None, + ): + if weights_dir: + os.environ.setdefault("FOUNDATIONPOSE_WEIGHTS_DIR", weights_dir) + + set_seed(0) + + with _suppress_fp_logging(): + scorer = ScorePredictor() + refiner = PoseRefinePredictor() + glctx = dr.RasterizeCudaContext() + + tm = mesh.to_trimesh() + to_origin, extents = trimesh.bounds.oriented_bounds(tm) + self.to_origin = to_origin + self.bbox = np.stack([-extents / 2, extents / 2], axis=0).reshape(2, 3) + + self._estimators = [ + FoundationPose( + model_pts=tm.vertices, + model_normals=tm.vertex_normals, + mesh=tm, + scorer=scorer, + refiner=refiner, + glctx=glctx, + debug=0, + debug_dir=f"/tmp/fp_debug_{i}", + ) + for i in range(num_cameras) + ] + + self.mesh = mesh + self.pose_last = None + self.depth_direction_trust = depth_direction_trust + self.visible_ratio_cutoff_high = visible_ratio_cutoff_high + self.visible_ratio_cutoff_low = visible_ratio_cutoff_low + self.precision_high = precision_high + self.precision_low = precision_low + self.symmetry_group = symmetry_group + if symmetry_group is None: + print("[MultiViewTracker] symmetry canonicalization disabled (no symmetry annotation)") + else: + print(f"[MultiViewTracker] symmetry canonicalization enabled (group size {len(symmetry_group)})") + + @property + def num_cameras(self) -> int: + return len(self._estimators) + + def register( + self, + rgbs: list[np.ndarray], + depths: list[np.ndarray], + masks: list[np.ndarray], + Ks: list[np.ndarray], + Ts: list[np.ndarray], + iteration: int = 5, + debug_dump_path: str | None = None, + ) -> tuple[np.ndarray, list[np.ndarray], np.ndarray, np.ndarray]: + """Register frame 0 across all cameras. + + Returns: + avg_pose: (4,4) best world-frame pose + world_poses: list of (4,4) per-camera canonicalized world poses + visible_ratios: (D,) per-camera visibility ratios + select_idx: boolean mask of cameras where object is visible + """ + raw_world_poses = [] + fp_scores = [] + with _suppress_fp_logging(): + for j, est in enumerate(self._estimators): + cam_pose = est.register( + K=Ks[j], rgb=rgbs[j], depth=depths[j], + ob_mask=masks[j], iteration=iteration, + ) + raw_world_poses.append(Ts[j] @ cam_pose) + # FoundationPose.register() returns early without setting + # self.scores when the mask has <4 valid depth pixels. + scores = getattr(est, "scores", None) + fp_scores.append(float(scores[0].item()) if scores is not None else float("nan")) + torch.cuda.empty_cache() + + visible_ratios = self._compute_visibility(raw_world_poses, masks, Ks, Ts) + select_idx = visible_ratios > self.visible_ratio_cutoff_low + assert np.sum(select_idx) > 0, "Object not visible from any camera in first frame" + + snap_indices_per_iter: list[list[tuple[int, float]]] = [] + ref_idx = -1 + if self.symmetry_group is not None and len(self.symmetry_group) > 1: + scores_for_ref = visible_ratios.copy() + scores_for_ref[~select_idx] = -np.inf + ref_idx = int(np.argmax(scores_for_ref)) + ref = raw_world_poses[ref_idx] + + n_iter_max = 3 + world_poses = list(raw_world_poses) + for _ in range(n_iter_max): + world_poses, snap_indices = _canonicalize_poses_with_indices( + raw_world_poses, self.symmetry_group, ref, + ) + snap_indices_per_iter.append(snap_indices) + new_ref = self._weighted_se3_mean_from_poses( + world_poses, Ts, visible_ratios, select_idx, + ) + cos_t = (np.trace(ref[:3, :3].T @ new_ref[:3, :3]) - 1.0) / 2.0 + angle_diff = float(np.arccos(np.clip(cos_t, -1.0, 1.0))) + ref = new_ref + if angle_diff < 1e-4: + break + avg_pose = ref + else: + world_poses = list(raw_world_poses) + avg_pose = self._weighted_se3_mean_from_poses( + world_poses, Ts, visible_ratios, select_idx, + ) + + if debug_dump_path is not None: + _dump_register_debug( + path=debug_dump_path, + symmetry_group_size=len(self.symmetry_group) if self.symmetry_group is not None else 1, + fp_scores=fp_scores, + visible_ratios=visible_ratios, + select_idx=select_idx, + ref_idx=ref_idx, + raw_world_poses=raw_world_poses, + canonical_world_poses=world_poses, + snap_indices_per_iter=snap_indices_per_iter, + avg_pose=avg_pose, + ) + + self._sync_to_avg(avg_pose, Ts) + return avg_pose, world_poses, visible_ratios, select_idx + + def track( + self, + rgbs: list[np.ndarray], + depths: list[np.ndarray], + masks: list[np.ndarray], + Ks: list[np.ndarray], + Ts: list[np.ndarray], + iteration: int = 2, + ) -> tuple[np.ndarray, list[np.ndarray], np.ndarray, np.ndarray]: + """Track next frame across all cameras. + + Returns: + avg_pose: (4,4) best world-frame pose + world_poses: list of (4,4) per-camera world poses + visible_ratios: (D,) per-camera visibility ratios + select_idx: boolean mask of cameras where object is visible + """ + world_poses = [] + with _suppress_fp_logging(): + for j, est in enumerate(self._estimators): + cam_pose = est.track_one( + rgb=rgbs[j], depth=depths[j], + K=Ks[j], iteration=iteration, + ) + world_poses.append(Ts[j] @ cam_pose) + + avg_pose, visible_ratios, select_idx = self._avg_poses(world_poses, masks, Ks, Ts) + self._sync_to_avg(avg_pose, Ts) + return avg_pose, world_poses, visible_ratios, select_idx + + def _visible_ratio_to_precision(self, visible_ratio: np.ndarray) -> np.ndarray: + if self.visible_ratio_cutoff_high <= self.visible_ratio_cutoff_low: + return np.full_like(visible_ratio, self.precision_high) + slope = ( + (self.precision_high - self.precision_low) + / (self.visible_ratio_cutoff_high - self.visible_ratio_cutoff_low) + ) + p = self.precision_low + slope * (visible_ratio - self.visible_ratio_cutoff_low) + return np.clip(p, self.precision_low, self.precision_high) + + @staticmethod + def _se3_split_mean_weighted( + poses: np.ndarray, + frame_rotations: np.ndarray, + W_trans: np.ndarray, + w_pose: np.ndarray, + ) -> np.ndarray: + """ + Mean of SE(3) poses with anisotropic translation precision and per-pose + confidence weights. + + Args: + poses: (D, 4, 4) world-frame poses + frame_rotations: (D, 3, 3) rotations defining each pose's local frame + W_trans: (3, 3) diagonal precision matrix of translations in the local frame + w_pose: (D,) per-pose confidence weights. Scales the rotation mean and + the translation precision so low-confidence views contribute less. + Returns: + mean_pose: (4, 4) + """ + rot = poses[:, :3, :3] + trans = poses[:, :3, 3] + mean_rot = Rotation.from_matrix(rot).mean(weights=w_pose).as_matrix() + + P_sum = np.zeros((3, 3)) + Pt_sum = np.zeros(3) + for j in range(len(poses)): + R_j = frame_rotations[j] + P_j = w_pose[j] * (R_j @ W_trans @ R_j.T) + P_sum += P_j + Pt_sum += P_j @ trans[j] + mean_trans = np.linalg.solve(P_sum, Pt_sum) + + return se3_from_rot_trans(mean_rot, mean_trans) + + def _compute_visibility( + self, + world_poses: list[np.ndarray], + masks: list[np.ndarray], + Ks: list[np.ndarray], + Ts: list[np.ndarray], + ) -> np.ndarray: + D = len(world_poses) + visible_ratios = np.zeros(D) + verts_hom = np.hstack([self.mesh.vertices, + np.ones((len(self.mesh.vertices), 1))]) + for j, world_pose in enumerate(world_poses): + world_verts = (verts_hom @ world_pose.T)[:, :3] + H, W = masks[j].shape[:2] + uv, in_bounds = xyz_to_uv( + world_verts, Ks[j], Ts[j], image_size=(W, H), + ) + if in_bounds.sum() == 0: + continue + in_mask = masks[j][uv[in_bounds, 1], uv[in_bounds, 0]].sum() + visible_ratios[j] = in_mask / in_bounds.sum() + return visible_ratios + + def _weighted_se3_mean_from_poses( + self, + world_poses: list[np.ndarray], + Ts: list[np.ndarray], + visible_ratios: np.ndarray, + select_idx: np.ndarray, + ) -> np.ndarray: + selected = np.where(select_idx)[0] + cam_rotations = np.array([Ts[j][:3, :3] for j in selected]) + W_trans = np.diag([1.0, 1.0, self.depth_direction_trust]) + w_pose = self._visible_ratio_to_precision(visible_ratios[selected]) + return self._se3_split_mean_weighted( + np.array(world_poses)[select_idx], + cam_rotations, + W_trans, + w_pose, + ) + + def _avg_poses( + self, + world_poses: list[np.ndarray], + masks: list[np.ndarray], + Ks: list[np.ndarray], + Ts: list[np.ndarray], + ) -> np.ndarray: + visible_ratios = self._compute_visibility(world_poses, masks, Ks, Ts) + select_idx = visible_ratios > self.visible_ratio_cutoff_low + if not select_idx.any(): + print(f"Object not visible from any camera, using last pose") + return self.pose_last, visible_ratios, select_idx + avg_pose = self._weighted_se3_mean_from_poses( + world_poses, Ts, visible_ratios, select_idx, + ) + return avg_pose, visible_ratios, select_idx + + def _sync_to_avg(self, avg_pose: np.ndarray, Ts: list[np.ndarray]): + """Project the fused world pose back into each camera and set pose_last.""" + for j, est in enumerate(self._estimators): + pose_last = ( + np.linalg.inv(Ts[j]) + @ avg_pose + @ np.linalg.inv(est.get_tf_to_centered_mesh().cpu().numpy()) + ) + est.pose_last = torch.as_tensor( + pose_last, device="cuda", dtype=torch.float + ).reshape(1, 4, 4) + self.pose_last = avg_pose diff --git a/third-party/video_to_data/reconstruction/modules/v2d_foundation_pose/lib/mv_videos_to_poses.py b/third-party/video_to_data/reconstruction/modules/v2d_foundation_pose/lib/mv_videos_to_poses.py new file mode 100644 index 0000000000000000000000000000000000000000..6757678d16fa380a6b720c4f7ad270fc4b5579f9 --- /dev/null +++ b/third-party/video_to_data/reconstruction/modules/v2d_foundation_pose/lib/mv_videos_to_poses.py @@ -0,0 +1,421 @@ +# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 +"""Multi-view 6-DoF object tracking with FoundationPose.""" + +import argparse +from pathlib import Path + +import cv2 +import imageio.v3 as iio +import numpy as np +from omegaconf import OmegaConf +from tqdm import tqdm +import trimesh + +from v2d.common.datatypes import DepthImage, Mask +from v2d.mesh.lib.mesh import Mesh +from v2d.common.video import FrameSource, get_video_writer +from v2d.mv.math.numpy_fn import pose_two_euro_filter +from v2d.mv.rig import RigConfig + +from .fp_utils import draw_posed_3d_box, draw_xyz_axis +from .multiview_tracker import MultiViewTracker +from .symmetry import load_symmetry_group + + +def mv_videos_to_poses( + cam_names: list[str], + cam_intrinsics: list[np.ndarray], + cam_extrinsics: list[np.ndarray], + rgb_paths: list[Path], + depth_dirs: list[Path], + mask_dirs: list[Path], + mesh_path: Path, + weights_dir: str, + pose_path: Path, + symmetry_path: Path | None = None, + scale: float = 0.5, + depth_direction_trust: float = 0.5, + visible_ratio_cutoff_high: float = 0.3, + visible_ratio_cutoff_low: float = 0.01, + precision_high: float = 1.0, + precision_low: float = 0.01, + est_refine_iter: int = 5, + track_refine_iter: int = 2, + debug: int = 0, +): + """Run multi-view FoundationPose tracking. + + Args: + cam_names: per-camera names (used for debug output naming). + cam_intrinsics: list of (3,3) K matrices, one per camera. + cam_extrinsics: list of (4,4) cam-to-world transforms, one per camera. + rgb_paths: per-camera paths to RGB frames (image dir, .h5, or video file). + depth_dirs: per-camera depth directories (inverse-depth PNGs via DepthImage). + mask_dirs: per-camera object mask directories (first PNG used for registration). + mesh_path: path to the object mesh file. + weights_dir: path to FoundationPose weights. + pose_path: output path for filtered poses .npy file. + symmetry_path: optional path to a BOP-style symmetry annotation JSON + (typically `/output_symmetry.json`). When provided and + the file exists, per-view registrations at frame 0 are + canonicalized into a common equivalence-class representative + before averaging. If None or missing, behavior matches the + no-symmetry case. + scale: resolution scale factor (e.g. 0.5 for half resolution). Scales + intrinsics and resizes images/depths/masks accordingly. + depth_direction_trust: weight for depth axis in anisotropic translation averaging. + visible_ratio_cutoff_high: visibility ratio at which a camera gets full precision. + visible_ratio_cutoff_low: visibility ratio below which a camera is excluded. + Set equal to cutoff_high for hard cutoff with uniform weighting. + precision_high: precision weight for cameras at or above cutoff_high. + precision_low: precision weight for cameras at cutoff_low. + est_refine_iter: refinement iterations for registration. + track_refine_iter: refinement iterations for tracking. + debug: 0=off, 1=overlay videos after processing, 2=also per-frame images every 30 frames. + """ + pose_path = Path(pose_path) + pose_path.parent.mkdir(parents=True, exist_ok=True) + + num_cameras = len(cam_intrinsics) + Ks = cam_intrinsics + Ts = cam_extrinsics + + mesh = Mesh.load(str(mesh_path)) + tm = mesh.to_trimesh() + _, obb_extents = trimesh.bounds.oriented_bounds(tm) + print(f"Mesh: {len(tm.vertices)} verts, OBB extents={obb_extents}, min={obb_extents.min():.4f}") + + symmetry_group = None + if symmetry_path is not None and Path(symmetry_path).exists(): + symmetry_group = load_symmetry_group(symmetry_path) + print(f"Loaded symmetry group: {len(symmetry_group)} elements from {symmetry_path}") + else: + print(f"No symmetry annotation; canonicalization disabled (symmetry_path={symmetry_path})") + + tracker = MultiViewTracker( + mesh, weights_dir, num_cameras, + depth_direction_trust=depth_direction_trust, + visible_ratio_cutoff_high=visible_ratio_cutoff_high, + visible_ratio_cutoff_low=visible_ratio_cutoff_low, + precision_high=precision_high, + precision_low=precision_low, + symmetry_group=symmetry_group, + ) + + frame_sources = [FrameSource.from_path(p) for p in rgb_paths] + mask_sources = [FrameSource.from_path(d) for d in mask_dirs] + depth_sources = [FrameSource.from_path(d) for d in depth_dirs] + + num_frames = frame_sources[0].n_frames + for j, (fs, ds, ms) in enumerate(zip(frame_sources, depth_sources, mask_sources)): + if fs.n_frames != num_frames or ds.n_frames != num_frames or ms.n_frames != num_frames: + raise ValueError( + f"camera {cam_names[j]}: frame count mismatch " + f"(rgb={fs.n_frames}, depth={ds.n_frames}, mask={ms.n_frames}, expected={num_frames})" + ) + frame_iterators = [fs.iter_frames() for fs in frame_sources] + + all_poses = [] + select_mask = [] + output_poses = [] + + if debug >= 2: + debug_image_dirs = [] + for cam_name in cam_names: + d = pose_path.parent / f"{cam_name}_fp_poses" + d.mkdir(parents=True, exist_ok=True) + debug_image_dirs.append(d) + + Ks_orig = list(Ks) + if scale != 1.0: + W, H = frame_sources[0].image_size + target_size = (int(W * scale), int(H * scale)) + sx, sy = target_size[0] / W, target_size[1] / H + S = np.diag([sx, sy, 1.0]) + Ks = [S @ K for K in Ks] + print(f"Scaling inputs by {scale}: ({W}, {H}) -> {target_size}") + else: + target_size = None + + print(f"Starting multi-view tracking for {num_frames} frames across {num_cameras} cameras") + for i in tqdm(range(num_frames), desc="Tracking"): + rgbs = [next(it) for it in frame_iterators] + depths = [DepthImage.from_array(depth_sources[j][i]).depth for j in range(num_cameras)] + masks = [mask_sources[j][i] > 128 for j in range(num_cameras)] + + for j in range(num_cameras): + if target_size is not None: + rgbs[j] = cv2.resize(rgbs[j], target_size, interpolation=cv2.INTER_AREA) + if depths[j].shape[:2] != rgbs[j].shape[:2]: + depths[j] = cv2.resize( + depths[j], (rgbs[j].shape[1], rgbs[j].shape[0]), + interpolation=cv2.INTER_LINEAR, + ) + if masks[j].shape[:2] != rgbs[j].shape[:2]: + masks[j] = cv2.resize( + masks[j].astype(np.uint8), (rgbs[j].shape[1], rgbs[j].shape[0]), + interpolation=cv2.INTER_NEAREST, + ).astype(bool) + + if i == 0: + avg_pose, world_poses, visible_ratios, select_idx = tracker.register( + rgbs, depths, masks, Ks, Ts, iteration=est_refine_iter, + debug_dump_path=( + str(pose_path.parent / "register_debug.json") if debug >= 1 else None + ), + ) + else: + avg_pose, world_poses, visible_ratios, select_idx = tracker.track( + rgbs, depths, masks, Ks, Ts, iteration=track_refine_iter, + ) + + all_poses.append(world_poses) + frame_mask = np.zeros(num_cameras, dtype=bool) + frame_mask[select_idx] = True + select_mask.append(frame_mask) + output_poses.append(avg_pose.reshape(4, 4)) + + if debug >= 2 and i % 30 == 0: + for j in range(num_cameras): + incam_pose = np.linalg.inv(Ts[j]) @ avg_pose + center_pose = incam_pose @ np.linalg.inv(tracker.to_origin) + vis = draw_posed_3d_box( + Ks[j], img=rgbs[j].copy(), ob_in_cam=center_pose, + bbox=tracker.bbox, linewidth=max(1, round(2 * scale)), + ) + vis = draw_xyz_axis( + vis, ob_in_cam=center_pose, scale=0.1, K=Ks[j], + thickness=max(1, round(3 * scale)), transparency=0, is_input_rgb=True, + ) + iio.imwrite(debug_image_dirs[j] / f"{i:06d}.png", vis) + + output_poses = np.array(output_poses) + + print(f"Applying Two Euro filter to {output_poses.shape[0]} poses") + filtered_poses = pose_two_euro_filter(output_poses) + np.save(pose_path, filtered_poses) + print(f"Saved poses to {pose_path}") + + if debug >= 1: + parent = pose_path.parent + np.save(parent / "poses_raw.npy", output_poses) + np.save(parent / "all_poses_raw.npy", np.array(all_poses)) + np.save(parent / "select_mask.npy", np.array(select_mask)) + + _render_tiled_debug_video( + filtered_poses, cam_names, frame_sources, Ks_orig, Ts, tracker, + np.array(select_mask), pose_path, num_frames, scale=scale, + ) + + # if debug > 1: + # _render_debug_videos( + # filtered_poses, cam_names, frame_sources, Ks_orig, Ts, tracker, + # pose_path, num_frames, + # ) + + +def _render_debug_videos( + poses: np.ndarray, + cam_names: list[str], + frame_sources: list[FrameSource], + Ks: list[np.ndarray], + Ts: list[np.ndarray], + tracker: MultiViewTracker, + pose_path: Path, + num_frames: int, +): + """Render per-camera overlay videos of the smoothed 3D bbox trajectory.""" + for j, (cam_name, fs) in enumerate(zip(cam_names, frame_sources)): + video_path = pose_path.parent / f"{cam_name}_fp_poses.mp4" + writer = get_video_writer(video_path, fps=30, crf=23) + frame_iter = fs.iter_frames() + for i in tqdm(range(num_frames), desc=f"Debug video [{cam_name}]"): + rgb = next(frame_iter) + pose = poses[i] + incam_pose = np.linalg.inv(Ts[j]) @ pose + center_pose = incam_pose @ np.linalg.inv(tracker.to_origin) + vis = draw_posed_3d_box( + Ks[j], img=rgb, ob_in_cam=center_pose, bbox=tracker.bbox, + ) + vis = draw_xyz_axis( + vis, ob_in_cam=center_pose, scale=0.1, K=Ks[j], + thickness=3, transparency=0, is_input_rgb=True, + ) + writer.write_frame(vis) + writer.close() + print(f"Debug video saved: {video_path}") + + +_VIEW_ORDER = {"front": 0, "back": 1, "left": 2, "right": 3} + + +def _view_sort_key(name: str) -> int: + lower = name.lower() + for key, order in _VIEW_ORDER.items(): + if key in lower: + return order + return len(_VIEW_ORDER) + + +def _render_tiled_debug_video( + poses: np.ndarray, + cam_names: list[str], + frame_sources: list[FrameSource], + Ks: list[np.ndarray], + Ts: list[np.ndarray], + tracker: MultiViewTracker, + select_mask: np.ndarray, + pose_path: Path, + num_frames: int, + scale: float, + border_width: int = 10, +): + """Render a 2x2 tiled video with green borders on best-view cameras. + + Views are arranged in Z-order: front (top-left), back (top-right), + left (bottom-left), right (bottom-right). + + Args: + select_mask: (num_frames, num_cameras) boolean array indicating which + cameras were selected as best for each frame. + """ + sorted_cam_indices = sorted(range(len(cam_names)), key=lambda i: _view_sort_key(cam_names[i])) + frame_iters = [frame_sources[j].iter_frames() for j in sorted_cam_indices] + + box_lw = max(1, round(2 * scale)) + axis_thickness = max(1, round(3 * scale)) + border_width = max(1, round(border_width * scale)) + + video_path = pose_path.parent / "mv_tiled_fp_poses.mp4" + writer = None + + for i in tqdm(range(num_frames), desc="Tiled debug video"): + tiles = [] + for slot, orig_j in enumerate(sorted_cam_indices): + rgb = next(frame_iters[slot]) + W_orig, H_orig = rgb.shape[1], rgb.shape[0] + tile_w = int(W_orig * scale) + tile_h = int(H_orig * scale) + vis = cv2.resize(rgb, (tile_w, tile_h), interpolation=cv2.INTER_AREA) + K_tile = Ks[orig_j].copy() + K_tile[0] *= tile_w / W_orig + K_tile[1] *= tile_h / H_orig + pose = poses[i] + incam_pose = np.linalg.inv(Ts[orig_j]) @ pose + center_pose = incam_pose @ np.linalg.inv(tracker.to_origin) + vis = draw_posed_3d_box( + K_tile, img=vis, ob_in_cam=center_pose, bbox=tracker.bbox, + linewidth=box_lw, + ) + vis = draw_xyz_axis( + vis, ob_in_cam=center_pose, scale=0.1, K=K_tile, + thickness=axis_thickness, transparency=0, is_input_rgb=True, + ) + if select_mask[i, orig_j]: + border_color = (0, 255, 0) + else: + border_color = (255, 0, 0) + h, w = vis.shape[:2] + cv2.rectangle(vis, (0, 0), (w - 1, h - 1), border_color, border_width) + tiles.append(vis) + + top = np.concatenate([tiles[0], tiles[1]], axis=1) + bottom = np.concatenate([tiles[2], tiles[3]], axis=1) + tiled = np.concatenate([top, bottom], axis=0) + + if writer is None: + writer = get_video_writer(video_path, fps=30, crf=23) + writer.write_frame(tiled) + + if writer is not None: + writer.close() + print(f"Tiled debug video saved: {video_path}") + + +def mv_videos_to_poses_from_config(cfg): + """Resolve config fields and call mv_videos_to_poses.""" + rig = RigConfig(cfg.rig_config, camera_params_path=cfg.camera_params_path) + scale = cfg.get("scale", 1.0) + + cam_names: list[str] = [] + cam_intrinsics: list[np.ndarray] = [] + cam_extrinsics: list[np.ndarray] = [] + rgb_paths: list[Path] = [] + depth_dirs: list[Path] = [] + mask_dirs: list[Path] = [] + + for cam_id in cfg.cameras: + cam = rig.get_camera(cam_id) + cam_names.append(cam.name) + cam_intrinsics.append(cam.param.K) + cam_extrinsics.append(cam.param.T) + + rgb_paths.append(Path(cfg.rgb_path_template.format(cam_name=cam.name))) + depth_dirs.append(Path(cfg.depth_path_template.format(cam_name=cam.name))) + mask_dirs.append(Path(cfg.mask_path_template.format(cam_name=cam.name))) + + mesh_path = Path(cfg.mesh_path) + symmetry_path = cfg.get("symmetry_path", None) + if symmetry_path is None: + auto = mesh_path.parent / "output_symmetry.json" + if auto.exists(): + symmetry_path = auto + else: + symmetry_path = Path(symmetry_path) + + mv_videos_to_poses( + cam_names=cam_names, + cam_intrinsics=cam_intrinsics, + cam_extrinsics=cam_extrinsics, + rgb_paths=rgb_paths, + depth_dirs=depth_dirs, + mask_dirs=mask_dirs, + mesh_path=mesh_path, + weights_dir=cfg.weights_dir, + pose_path=Path(cfg.pose_path), + symmetry_path=symmetry_path, + scale=scale, + depth_direction_trust=cfg.get("depth_direction_trust", 0.5), + visible_ratio_cutoff_high=cfg.get("visible_ratio_cutoff_high", 0.3), + visible_ratio_cutoff_low=cfg.get("visible_ratio_cutoff_low", 0.3), + precision_high=cfg.get("precision_high", 1.0), + precision_low=cfg.get("precision_low", 0.01), + est_refine_iter=cfg.get("est_refine_iter", 5), + track_refine_iter=cfg.get("track_refine_iter", 2), + debug=cfg.get("debug", 0), + ) + + +if __name__ == "__main__": + parser = argparse.ArgumentParser(description="Multi-view 6-DoF object tracking with FoundationPose") + parser.add_argument("--camera_params_path", type=str, required=True) + parser.add_argument("--rgb_dir", type=str, required=True) + parser.add_argument("--depth_dir", type=str, required=True) + parser.add_argument("--mask_dir", type=str, required=True) + parser.add_argument("--mesh_path", type=str, required=True) + parser.add_argument("--symmetry_path", type=str, default=None, + help="Optional BOP-style symmetry JSON (defaults to /output_symmetry.json)") + parser.add_argument("--weights_dir", type=str, required=True) + parser.add_argument("--output_dir", type=str, required=True) + parser.add_argument("--scale", type=float, default=None, + help="Scale factor for input resolution (e.g. 0.5 for half)") + parser.add_argument("--config_path", type=str, default=None) + parser.add_argument("--debug", type=int, default=None) + args = parser.parse_args() + + cfg = OmegaConf.load(Path(__file__).parent / "mv_videos_to_poses.yaml") + if args.config_path: + cfg = OmegaConf.merge(cfg, OmegaConf.load(args.config_path)) + + overrides = {} + for key in [ + "camera_params_path", "rgb_dir", "depth_dir", + "mask_dir", "mesh_path", "symmetry_path", "weights_dir", "output_dir", "scale", "debug", + ]: + val = getattr(args, key) + if val is not None: + overrides[key] = val + cfg = OmegaConf.merge(cfg, OmegaConf.create(overrides)) + + mv_videos_to_poses_from_config(cfg) diff --git a/third-party/video_to_data/reconstruction/modules/v2d_foundation_pose/lib/mv_videos_to_poses.yaml b/third-party/video_to_data/reconstruction/modules/v2d_foundation_pose/lib/mv_videos_to_poses.yaml new file mode 100644 index 0000000000000000000000000000000000000000..71c3a2e8b204605be5011f8fe3f7fc43181ac9ed --- /dev/null +++ b/third-party/video_to_data/reconstruction/modules/v2d_foundation_pose/lib/mv_videos_to_poses.yaml @@ -0,0 +1,30 @@ +# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 +rig_config: stereo-4 +cameras: [0, 2, 4, 6] +mask_obj_id: 0 + +camera_params_path: ??? +rgb_dir: ??? +depth_dir: ??? +mask_dir: ??? +mesh_path: ??? +symmetry_path: null # optional; defaults to /output_symmetry.json if present +weights_dir: ??? +output_dir: ??? + +rgb_path_template: "${rgb_dir}/{cam_name}" +depth_path_template: "${depth_dir}/{cam_name}/depth" +mask_path_template: "${mask_dir}/{cam_name}/${mask_obj_id}" +pose_path: "${output_dir}/poses.npy" + +scale: 0.5 +depth_direction_trust: 0.5 +visible_ratio_cutoff_high: 0.3 +visible_ratio_cutoff_low: 0.3 +precision_high: 1.0 +precision_low: 1.0 +est_refine_iter: 5 +track_refine_iter: 2 + +debug: 2 diff --git a/third-party/video_to_data/reconstruction/modules/v2d_foundation_pose/lib/pyproject.toml b/third-party/video_to_data/reconstruction/modules/v2d_foundation_pose/lib/pyproject.toml new file mode 100644 index 0000000000000000000000000000000000000000..33f389a1383599fbc821339edca6dc4350443b5c --- /dev/null +++ b/third-party/video_to_data/reconstruction/modules/v2d_foundation_pose/lib/pyproject.toml @@ -0,0 +1,28 @@ +# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 +[build-system] +requires = ["setuptools>=68.0", "wheel"] +build-backend = "setuptools.build_meta" + +[project] +name = "v2d-foundation-pose-lib" +version = "0.1.0" +description = "FoundationPose 6-DoF object pose estimation library" +requires-python = ">=3.10" +dependencies = [ + "numpy", + "Pillow", + "opencv-python", + "trimesh", + "scikit-learn", + "omegaconf", + "v2d-common", + "v2d-mesh-lib", + "v2d-mv[io,math]", +] + +[tool.setuptools] +packages = ["v2d.foundation_pose.lib"] + +[tool.setuptools.package-dir] +"v2d.foundation_pose.lib" = "." diff --git a/third-party/video_to_data/reconstruction/modules/v2d_foundation_pose/lib/render_overlay.py b/third-party/video_to_data/reconstruction/modules/v2d_foundation_pose/lib/render_overlay.py new file mode 100644 index 0000000000000000000000000000000000000000..765562d38d24029fbc1a3d0e4b747bb3caa46457 --- /dev/null +++ b/third-party/video_to_data/reconstruction/modules/v2d_foundation_pose/lib/render_overlay.py @@ -0,0 +1,100 @@ +# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 +""" +Render mesh overlay on video frames using per-frame object-to-camera poses. + +Inputs: + --video_path path to input video + --poses_dir directory of per-frame 4×4 matrix JSONs (T_cam_from_obj) + --mesh_path path to mesh .obj file + --camera_intrinsics_path JSON with {fx, fy, cx, cy, width, height} + --output_dir output directory for overlay frames (%06d.jpg) +""" +import argparse +import json +import os +from pathlib import Path + +os.environ.setdefault("PYOPENGL_PLATFORM", "egl") + +import cv2 +import numpy as np +import pyrender +import trimesh + +# CV camera → OpenGL camera: flip Y and Z axes +_T_CV_TO_GL = np.diag([1.0, -1.0, -1.0, 1.0]) + + +def render_overlay( + video_path: str, + poses_dir: str, + mesh_path: str, + camera_intrinsics_path: str, + output_dir: str, +) -> None: + os.makedirs(output_dir, exist_ok=True) + + with open(camera_intrinsics_path) as f: + intr = json.load(f) + fx, fy = intr["fx"], intr["fy"] + cx, cy = intr["cx"], intr["cy"] + width, height = int(intr["width"]), int(intr["height"]) + + tm = trimesh.load(mesh_path, force="mesh", process=False) + mesh = pyrender.Mesh.from_trimesh(tm) + + poses = {} + for pf in sorted(Path(poses_dir).glob("*.json")): + d = json.loads(pf.read_text()) + if isinstance(d, list): + poses[int(pf.stem)] = np.array(d) + + camera = pyrender.IntrinsicsCamera(fx=fx, fy=fy, cx=cx, cy=cy) + renderer = pyrender.OffscreenRenderer(width, height) + + cap = cv2.VideoCapture(video_path) + frame_idx = 0 + while cap.isOpened(): + ret, frame = cap.read() + if not ret: + break + + if frame_idx in poses: + T_cam_from_obj = poses[frame_idx] + scene = pyrender.Scene(bg_color=[0, 0, 0, 0], ambient_light=[0.4, 0.4, 0.4]) + scene.add(mesh, pose=T_cam_from_obj) + scene.add(camera, pose=_T_CV_TO_GL) + light = pyrender.DirectionalLight(color=np.ones(3), intensity=3.0) + scene.add(light, pose=_T_CV_TO_GL) + + color, depth = renderer.render(scene) + mask = (depth > 0).astype(np.float32)[:, :, np.newaxis] + overlay_bgr = color[:, :, ::-1] # RGB to BGR + out = np.clip(mask * overlay_bgr + (1.0 - mask) * frame, 0, 255).astype(np.uint8) + else: + out = frame + + cv2.imwrite(os.path.join(output_dir, f"{frame_idx:06d}.jpg"), out) + frame_idx += 1 + + cap.release() + renderer.delete() + + +if __name__ == "__main__": + parser = argparse.ArgumentParser(description="Render mesh overlay on video frames") + parser.add_argument("--video_path", required=True) + parser.add_argument("--poses_dir", required=True) + parser.add_argument("--mesh_path", required=True) + parser.add_argument("--camera_intrinsics_path", required=True) + parser.add_argument("--output_dir", required=True) + args = parser.parse_args() + + render_overlay( + args.video_path, + args.poses_dir, + args.mesh_path, + args.camera_intrinsics_path, + args.output_dir, + ) diff --git a/third-party/video_to_data/reconstruction/modules/v2d_foundation_pose/lib/run_align_depth_to_object.py b/third-party/video_to_data/reconstruction/modules/v2d_foundation_pose/lib/run_align_depth_to_object.py new file mode 100644 index 0000000000000000000000000000000000000000..a455a652d085418797db14127c7e0900776336fd --- /dev/null +++ b/third-party/video_to_data/reconstruction/modules/v2d_foundation_pose/lib/run_align_depth_to_object.py @@ -0,0 +1,121 @@ +# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 +"""Align raw monocular depth to an object mesh via FP-guided affine grid search. + +Searches over (scale, shift) in D_aligned = scale * D_raw + shift and returns +the corrected depth image that best fits the mesh at the reference frame. +""" +import argparse +import logging +import os + +import cv2 + +from v2d.common.datatypes import CameraIntrinsics, DepthImage, Mask +from v2d.common.datatypes import Image as V2dImage +from v2d.mesh.lib.mesh import Mesh +from v2d.foundation_pose.lib.foundation_pose_tracker import FoundationPoseTracker + +logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s') +logger = logging.getLogger(__name__) + + +def run_align_depth_to_object( + mesh_path: str, + rgb_path: str, + depth_path: str, + mask_path: str, + intrinsics_path: str, + weights_dir: str, + output_depth_path: str, + scale_lo: float = 0.5, + scale_hi: float = 2.0, + shift_lo: float = -0.5, + shift_hi: float = 0.5, + n_scale_samples: int = 7, + n_shift_samples: int = 5, + n_levels: int = 3, + iou_weight: float = 1.0, + depth_weight: float = 1.0, + registration_iterations: int = 5, +) -> DepthImage: + """Align raw monocular depth to object mesh, saving the corrected depth PNG. + + Args: + mesh_path: Object mesh file. + rgb_path: Reference frame RGB image (PNG). + depth_path: Raw monocular depth PNG (uint16 inverse-depth encoding). + mask_path: Object segmentation mask PNG. + intrinsics_path: Camera intrinsics JSON. + weights_dir: FoundationPose weights directory. + output_depth_path: Output path for the corrected depth PNG. + scale_lo: Lower bound of scale search range. Default 0.5. + scale_hi: Upper bound of scale search range. Default 2.0. + shift_lo: Lower bound of shift search range (metres). Default -0.5. + shift_hi: Upper bound of shift search range (metres). Default 0.5. + n_scale_samples: Scale candidates per level. Default 7. + n_shift_samples: Shift candidates per level. Default 5. + n_levels: Refinement levels. Default 3. + iou_weight: Weight for mask IoU score. Default 1.0. + depth_weight: Weight for depth MARE score. Default 1.0. + registration_iterations: FP register() iterations per candidate. Default 5. + + Returns: + Corrected DepthImage (also saved to output_depth_path). + """ + mesh = Mesh.load(mesh_path) + tracker = FoundationPoseTracker(mesh, weights_dir) + + intrinsics = CameraIntrinsics.load(intrinsics_path) + depth_raw = DepthImage.load(depth_path) + mask = Mask.load(mask_path) + + frame = cv2.imread(rgb_path) + if frame is None: + raise RuntimeError(f"Failed to load RGB image: {rgb_path}") + rgb = V2dImage(data=cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)) + + corrected = tracker.align_depth_to_object( + rgb, depth_raw, mask, intrinsics, + scale_lo=scale_lo, scale_hi=scale_hi, + shift_lo=shift_lo, shift_hi=shift_hi, + n_scale_samples=n_scale_samples, n_shift_samples=n_shift_samples, + n_levels=n_levels, iou_weight=iou_weight, depth_weight=depth_weight, + registration_iterations=registration_iterations, + ) + + os.makedirs(os.path.dirname(os.path.abspath(output_depth_path)), exist_ok=True) + corrected.save(output_depth_path) + logger.info(f"Saved aligned depth to {output_depth_path}") + return corrected + + +if __name__ == "__main__": + parser = argparse.ArgumentParser(description="Align depth to object mesh via FP affine grid search") + parser.add_argument("--mesh_path", required=True) + parser.add_argument("--rgb_path", required=True) + parser.add_argument("--depth_path", required=True) + parser.add_argument("--mask_path", required=True) + parser.add_argument("--intrinsics_path", required=True) + parser.add_argument("--weights_dir", required=True) + parser.add_argument("--output_depth_path", required=True) + parser.add_argument("--scale_lo", type=float, default=0.5) + parser.add_argument("--scale_hi", type=float, default=2.0) + parser.add_argument("--shift_lo", type=float, default=-0.5) + parser.add_argument("--shift_hi", type=float, default=0.5) + parser.add_argument("--n_scale_samples", type=int, default=7) + parser.add_argument("--n_shift_samples", type=int, default=5) + parser.add_argument("--n_levels", type=int, default=3) + parser.add_argument("--iou_weight", type=float, default=1.0) + parser.add_argument("--depth_weight", type=float, default=1.0) + parser.add_argument("--registration_iterations", type=int, default=5) + args = parser.parse_args() + run_align_depth_to_object( + args.mesh_path, args.rgb_path, args.depth_path, args.mask_path, + args.intrinsics_path, args.weights_dir, args.output_depth_path, + scale_lo=args.scale_lo, scale_hi=args.scale_hi, + shift_lo=args.shift_lo, shift_hi=args.shift_hi, + n_scale_samples=args.n_scale_samples, n_shift_samples=args.n_shift_samples, + n_levels=args.n_levels, iou_weight=args.iou_weight, depth_weight=args.depth_weight, + registration_iterations=args.registration_iterations, + ) diff --git a/third-party/video_to_data/reconstruction/modules/v2d_foundation_pose/lib/run_align_depth_to_reference_depth.py b/third-party/video_to_data/reconstruction/modules/v2d_foundation_pose/lib/run_align_depth_to_reference_depth.py new file mode 100644 index 0000000000000000000000000000000000000000..e856711790eed90a64ccb1111c67ca025bb160cb --- /dev/null +++ b/third-party/video_to_data/reconstruction/modules/v2d_foundation_pose/lib/run_align_depth_to_reference_depth.py @@ -0,0 +1,101 @@ +# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 +"""Align a folder of raw depth images to a metric reference depth via ICP + affine solve. + +For each frame in depth_folder, finds (scale, shift) such that +scale * D_raw + shift best matches the reference depth on the static background, +accounting for small camera motion via ICP. The foreground mask excludes the +object and hands from fitting. +""" +import argparse +import logging +import os + +from v2d.common.datatypes import CameraIntrinsics, DepthImage, Mask +from v2d.foundation_pose.lib.depth_alignment import align_depth_to_reference_depth + +logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s') +logger = logging.getLogger(__name__) + + +def run_align_depth_to_reference_depth( + depth_folder: str, + depth_reference_path: str, + intrinsics_path: str, + output_folder: str, + masks_folder: str = None, + reference_mask_path: str = None, + n_iterations: int = 3, + outlier_trim_ratio: float = 0.2, + max_points: int = 20000, +) -> None: + """Align all depth frames in a folder to a metric reference depth. + + Args: + depth_folder: Directory of raw monocular depth PNGs to align. + depth_reference_path: Metric reference depth PNG (from align_depth_to_object). + intrinsics_path: Camera intrinsics JSON. + output_folder: Destination for aligned depth PNGs. + masks_folder: Optional per-frame foreground mask folder. Masks exclude + the object and hands from ICP fitting. + reference_mask_path: Optional foreground mask for the reference frame. + If None, per-frame mask is reused as a proxy. + n_iterations: Alternating ICP/affine iterations per frame. Default 3. + outlier_trim_ratio: Fraction of worst-fitting points discarded per iter. + Default 0.2. + max_points: Max background points per frame (random subsample). + Default 20000. + """ + intrinsics = CameraIntrinsics.load(intrinsics_path) + depth_ref = DepthImage.load(depth_reference_path) + fg_mask_ref = Mask.load(reference_mask_path) if reference_mask_path else None + + depth_files = sorted(f for f in os.listdir(depth_folder) if f.endswith('.png')) + os.makedirs(output_folder, exist_ok=True) + logger.info(f"Aligning {len(depth_files)} depth frames to reference") + + for fname in depth_files: + frame_idx = int(os.path.splitext(fname)[0]) + depth_raw = DepthImage.load(os.path.join(depth_folder, fname)) + + fg_mask = None + if masks_folder is not None: + mask_path = os.path.join(masks_folder, fname) + if os.path.exists(mask_path): + fg_mask = Mask.load(mask_path) + + logger.info(f"Frame {frame_idx}") + corrected = align_depth_to_reference_depth( + depth_raw, depth_ref, intrinsics, + fg_mask=fg_mask, + fg_mask_ref=fg_mask_ref, + n_iterations=n_iterations, + outlier_trim_ratio=outlier_trim_ratio, + max_points=max_points, + ) + corrected.save(os.path.join(output_folder, fname)) + + logger.info(f"Aligned depth written to {output_folder}") + + +if __name__ == "__main__": + parser = argparse.ArgumentParser(description="Align depth folder to reference depth via ICP + affine") + parser.add_argument("--depth_folder", required=True) + parser.add_argument("--depth_reference_path", required=True) + parser.add_argument("--intrinsics_path", required=True) + parser.add_argument("--output_folder", required=True) + parser.add_argument("--masks_folder", default=None) + parser.add_argument("--reference_mask_path", default=None) + parser.add_argument("--n_iterations", type=int, default=3) + parser.add_argument("--outlier_trim_ratio", type=float, default=0.2) + parser.add_argument("--max_points", type=int, default=20000) + args = parser.parse_args() + run_align_depth_to_reference_depth( + args.depth_folder, args.depth_reference_path, args.intrinsics_path, + args.output_folder, + masks_folder=args.masks_folder, + reference_mask_path=args.reference_mask_path, + n_iterations=args.n_iterations, + outlier_trim_ratio=args.outlier_trim_ratio, + max_points=args.max_points, + ) diff --git a/third-party/video_to_data/reconstruction/modules/v2d_foundation_pose/lib/run_correct_depth_scale.py b/third-party/video_to_data/reconstruction/modules/v2d_foundation_pose/lib/run_correct_depth_scale.py new file mode 100644 index 0000000000000000000000000000000000000000..a168176c9dc66b7f377438183440707dfb920bc9 --- /dev/null +++ b/third-party/video_to_data/reconstruction/modules/v2d_foundation_pose/lib/run_correct_depth_scale.py @@ -0,0 +1,202 @@ +# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 +""" +FP-guided per-frame depth scale correction. + +After a first FoundationPose tracking pass, the mesh can be rendered at each +estimated pose to obtain a reliable depth map for the object region. Comparing +this rendered depth against the MoGe depth yields a per-frame scalar correction: + + scale_k = median( rendered_depth[valid] / moge_depth[valid] ) + +where valid = object mask & rendered_depth > 0 & moge_depth > 0. + +This corrects the global scale error that monocular metric depth models exhibit +at close range (where training-distribution coverage is sparse). + +The per-frame scales are smoothed with a temporal median filter before being +applied, avoiding the introduction of frame-to-frame jitter. Frames with +insufficient overlap (< min_valid_pixels) are interpolated from neighbours. +""" +import argparse +import logging +import os +import sys + +import numpy as np +import torch +from scipy.ndimage import median_filter + +_FP_DIR = os.path.join(os.path.dirname(os.path.abspath(__file__)), "FoundationPose") +if _FP_DIR not in sys.path: + sys.path.insert(0, _FP_DIR) + +from v2d.common.datatypes import CameraIntrinsics, DepthImage, Mask, Transform3d +from v2d.foundation_pose.lib.fp_utils import nvdiffrast_render, make_mesh_tensors +from v2d.mesh.lib.mesh import Mesh + +import nvdiffrast.torch as dr + +logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s') +logger = logging.getLogger(__name__) + + +def run_correct_depth_scale( + poses_dir: str, + mesh_path: str, + depth_folder: str, + intrinsics_path: str, + output_folder: str, + masks_folder: str = None, + smoothing_window: int = 11, + min_valid_pixels: int = 50, + batch_size: int = 32, +) -> None: + """ + Correct per-frame MoGe depth scale using FoundationPose rendered depth. + + For each frame, renders the mesh at the FP-estimated pose and computes: + scale_k = median( rendered_depth / moge_depth ) over valid object pixels + + Scales are temporally smoothed then applied to the full depth map. + Frames with too few valid pixels fall back to their neighbours' scale. + + Args: + poses_dir: Directory of per-frame Transform3d JSON files (FP output). + mesh_path: Mesh used during tracking. + depth_folder: Directory of MoGe depth PNGs to correct. + intrinsics_path: Camera intrinsics JSON (stable recommended). + output_folder: Destination for corrected depth PNGs. + masks_folder: Optional SAM2 mask folder. When provided, scale is + computed only at object pixels. When None, all pixels + where both depths are positive are used. + smoothing_window: Temporal median filter window (frames). Default 11. + min_valid_pixels: Minimum valid pixels to compute a reliable scale. + Frames below this threshold are interpolated. Default 50. + batch_size: Poses to render per GPU call. Default 32. + """ + intrinsics = CameraIntrinsics.load(intrinsics_path) + K = intrinsics.to_matrix() + H, W = intrinsics.height, intrinsics.width + + trimesh_mesh = Mesh.load(mesh_path).to_trimesh() + mesh_tensors = make_mesh_tensors(trimesh_mesh) + + pose_files = sorted(f for f in os.listdir(poses_dir) if f.endswith('.json')) + frame_indices = [int(os.path.splitext(f)[0]) for f in pose_files] + N = len(pose_files) + logger.info(f"Computing depth scale corrections for {N} frames") + + glctx = dr.RasterizeCudaContext() + + # ---- Render all poses in batches, compute per-frame raw scales ---- + raw_scales = np.full(N, np.nan) + + for chunk_start in range(0, N, batch_size): + chunk_files = pose_files[chunk_start : chunk_start + batch_size] + chunk_indices = frame_indices[chunk_start : chunk_start + batch_size] + + ob_in_cams = torch.stack([ + torch.as_tensor( + Transform3d.load(os.path.join(poses_dir, f)).to_matrix(), + device='cuda', dtype=torch.float, + ) + for f in chunk_files + ]) + + with torch.no_grad(): + _, rendered_depths, _ = nvdiffrast_render( + K=K, H=H, W=W, + ob_in_cams=ob_in_cams, + glctx=glctx, + mesh_tensors=mesh_tensors, + get_normal=False, + ) + + rendered_np = rendered_depths.cpu().numpy() # (B, H, W) + + for i, (frame_idx, rendered) in enumerate(zip(chunk_indices, rendered_np)): + depth_path = os.path.join(depth_folder, f"{frame_idx:06d}.png") + if not os.path.exists(depth_path): + continue + moge = DepthImage.load(depth_path).depth # (H, W) float32 in metres + + rendered_valid = rendered > 0.001 + moge_valid = moge > 0.001 + + if masks_folder is not None: + mask_path = os.path.join(masks_folder, f"{frame_idx:06d}.png") + if os.path.exists(mask_path): + obj_mask = Mask.load(mask_path).mask.astype(bool) + else: + obj_mask = np.ones((H, W), dtype=bool) + else: + obj_mask = np.ones((H, W), dtype=bool) + + valid = obj_mask & rendered_valid & moge_valid + if valid.sum() < min_valid_pixels: + logger.debug(f"Frame {frame_idx}: only {valid.sum()} valid pixels — will interpolate") + continue + + scale = float(np.median(rendered[valid] / moge[valid])) + raw_scales[chunk_start + i] = scale + logger.debug(f"Frame {frame_idx}: raw scale={scale:.4f}") + + valid_mask = ~np.isnan(raw_scales) + logger.info( + f"Valid scale estimates: {valid_mask.sum()}/{N} " + f"mean={np.nanmean(raw_scales):.4f} " + f"std={np.nanstd(raw_scales):.4f}" + ) + + # ---- Interpolate missing frames ---- + if not valid_mask.all(): + indices = np.arange(N) + raw_scales = np.interp(indices, indices[valid_mask], raw_scales[valid_mask]) + + # ---- Temporal smoothing in log-space ---- + log_scales = np.log(np.clip(raw_scales, 1e-6, None)) + log_smoothed = median_filter(log_scales, size=smoothing_window, mode='reflect') + smooth_scales = np.exp(log_smoothed) + + logger.info( + f"Smoothed scales — mean={smooth_scales.mean():.4f} " + f"min={smooth_scales.min():.4f} max={smooth_scales.max():.4f}" + ) + + # ---- Apply corrections ---- + os.makedirs(output_folder, exist_ok=True) + for i, frame_idx in enumerate(frame_indices): + depth_path = os.path.join(depth_folder, f"{frame_idx:06d}.png") + if not os.path.exists(depth_path): + continue + d = DepthImage.load(depth_path) + corrected = DepthImage(depth=(d.depth * smooth_scales[i]).astype(np.float32)) + corrected.save(os.path.join(output_folder, f"{frame_idx:06d}.png")) + + logger.info(f"Corrected depth written to {output_folder}") + + +if __name__ == "__main__": + parser = argparse.ArgumentParser(description="FP-guided per-frame depth scale correction") + parser.add_argument("--poses_dir", required=True) + parser.add_argument("--mesh_path", required=True) + parser.add_argument("--depth_folder", required=True) + parser.add_argument("--intrinsics_path", required=True) + parser.add_argument("--output_folder", required=True) + parser.add_argument("--masks_folder", default=None) + parser.add_argument("--smoothing_window", type=int, default=11) + parser.add_argument("--min_valid_pixels", type=int, default=50) + parser.add_argument("--batch_size", type=int, default=32) + args = parser.parse_args() + run_correct_depth_scale( + args.poses_dir, + args.mesh_path, + args.depth_folder, + args.intrinsics_path, + args.output_folder, + masks_folder=args.masks_folder, + smoothing_window=args.smoothing_window, + min_valid_pixels=args.min_valid_pixels, + batch_size=args.batch_size, + ) diff --git a/third-party/video_to_data/reconstruction/modules/v2d_foundation_pose/lib/run_ekf_smoothing.py b/third-party/video_to_data/reconstruction/modules/v2d_foundation_pose/lib/run_ekf_smoothing.py new file mode 100644 index 0000000000000000000000000000000000000000..4aa1c5d05eb2270cc91c099f6f73074d31206f33 --- /dev/null +++ b/third-party/video_to_data/reconstruction/modules/v2d_foundation_pose/lib/run_ekf_smoothing.py @@ -0,0 +1,324 @@ +# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 +""" +EKF + RTS smoother for FoundationPose output pose sequences. + +Applies a Bayesian forward-backward smoother to a directory of per-frame +6-DoF poses. Uses an Error-State Kalman Filter (ESKF) with a random walk +process model: + - Translation in R³ (standard linear KF) + - Rotation in SO(3) via error-state representation (perturbation in so(3)) + +Measurement noise is optionally scaled by per-frame mask IoU: low-IoU frames +(likely tracking loss or occlusion) are trusted less, high-IoU frames more. + +The RTS (Rauch-Tung-Striebel) backward smoother pass gives the globally +optimal estimate conditioned on all observations, not just past frames. + +Translation noise is anisotropic: separate XY (lateral) and Z (depth) +parameters are exposed because monocular depth estimates have systematically +higher noise along the optical axis than laterally. Increasing +measurement_noise_z relative to measurement_noise_xy causes the filter to +smooth depth more aggressively while leaving lateral estimates largely intact. + +Tuning guidance: + process_noise_* — how much the pose can change per frame; increase for + fast-moving objects, decrease to enforce more smoothness + measurement_noise_* — baseline trust in FP pose estimates; increase to smooth + more aggressively, decrease to track measurements closely + min_iou — IoU floor that prevents infinite measurement noise on + completely occluded frames +""" +import argparse +import logging +import os + +import numpy as np +from scipy.spatial.transform import Rotation + +from v2d.common.datatypes import CameraIntrinsics, Mask, Transform3d +from v2d.mesh.lib.mesh import Mesh +from v2d.foundation_pose.lib.foundation_pose_tracker import FoundationPoseTracker + +logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s') +logger = logging.getLogger(__name__) + + +# --------------------------------------------------------------------------- +# Internal helpers +# --------------------------------------------------------------------------- + +def _load_poses(poses_dir: str) -> tuple[list[int], list[Transform3d]]: + files = sorted(f for f in os.listdir(poses_dir) if f.endswith('.json')) + indices = [int(os.path.splitext(f)[0]) for f in files] + poses = [Transform3d.load(os.path.join(poses_dir, f)) for f in files] + return indices, poses + + +def _compute_iou_scores( + tracker: FoundationPoseTracker, + poses: list[Transform3d], + intrinsics: CameraIntrinsics, + masks_folder: str | None, + indices: list[int], +) -> np.ndarray: + """Render mesh at each pose and compute IoU against observed mask.""" + if masks_folder is None: + logger.info("No masks_folder provided — using uniform IoU weights") + return np.ones(len(poses)) + + scores = np.ones(len(poses)) + for i, (idx, pose) in enumerate(zip(indices, poses)): + mask_path = os.path.join(masks_folder, f"{idx:06d}.png") + if os.path.exists(mask_path): + mask = Mask.load(mask_path) + scores[i] = tracker._mask_iou(mask, intrinsics, pose) + logger.debug(f"Frame {idx}: IoU={scores[i]:.3f}") + + logger.info(f"IoU scores — mean={scores.mean():.3f} min={scores.min():.3f} " + f"frames<0.3: {(scores < 0.3).sum()}") + return scores + + +def _pose_to_tr(pose: Transform3d) -> tuple[np.ndarray, Rotation]: + M = pose.to_matrix() + return M[:3, 3].copy(), Rotation.from_matrix(M[:3, :3]) + + +def _tr_to_pose(t: np.ndarray, r: Rotation) -> Transform3d: + M = np.eye(4) + M[:3, :3] = r.as_matrix() + M[:3, 3] = t + return Transform3d.from_matrix(M) + + +def _solve_gain(P_pred: np.ndarray, S: np.ndarray) -> np.ndarray: + """Compute Kalman gain K = P_pred @ S^{-1} for symmetric PD matrices.""" + # Solve S @ K.T = P_pred.T → K = (S^{-1} @ P_pred.T).T + return np.linalg.solve(S, P_pred.T).T + + +# --------------------------------------------------------------------------- +# ESKF + RTS core +# --------------------------------------------------------------------------- + +def _eskf_rts( + translations: np.ndarray, # (N, 3) + rotations: list[Rotation], # N elements + iou_scores: np.ndarray, # (N,) in [0, 1] + process_noise_xy: float, + process_noise_z: float, + process_noise_r: float, + measurement_noise_xy: float, + measurement_noise_z: float, + measurement_noise_r: float, + min_iou: float, +) -> tuple[np.ndarray, list[Rotation]]: + """ + Forward ESKF pass followed by RTS backward smoother. + + Process model: random walk for both translation and rotation. + Rotation is handled in error-state (so(3) perturbation) space. + Translation uses anisotropic noise: XY (lateral) and Z (depth) are + tuned separately because monocular depth has higher uncertainty along + the optical axis. + + Returns: + t_smooth: (N, 3) smoothed translations + r_smooth: list of N smoothed Rotation objects + """ + N = len(translations) + Q_t = np.diag([process_noise_xy ** 2, process_noise_xy ** 2, process_noise_z ** 2]) + Q_r = process_noise_r ** 2 * np.eye(3) + I3 = np.eye(3) + + def _R_t(iou: float) -> np.ndarray: + s = 1.0 / iou + return np.diag([(measurement_noise_xy * s) ** 2, + (measurement_noise_xy * s) ** 2, + (measurement_noise_z * s) ** 2]) + + # Forward pass storage + t_filt = np.zeros((N, 3)) + P_t_filt = np.zeros((N, 3, 3)) + t_pred = np.zeros((N, 3)) + P_t_pred = np.zeros((N, 3, 3)) + + r_filt = [None] * N + P_r_filt = np.zeros((N, 3, 3)) + P_r_pred = np.zeros((N, 3, 3)) + + # Initialise with first measurement; uncertainty = measurement noise + iou0 = max(float(iou_scores[0]), min_iou) + t_filt[0] = translations[0] + P_t_filt[0] = _R_t(iou0) + r_filt[0] = rotations[0] + P_r_filt[0] = (measurement_noise_r / iou0) ** 2 * I3 + + # ---- Forward pass ---- + for k in range(1, N): + iou = max(float(iou_scores[k]), min_iou) + R_t_k = _R_t(iou) + R_r_k = (measurement_noise_r / iou) ** 2 * I3 + + # Predict (random walk — nominal rotation carries forward unchanged) + t_pred[k] = t_filt[k - 1] + P_t_pred[k] = P_t_filt[k - 1] + Q_t + P_r_pred[k] = P_r_filt[k - 1] + Q_r + r_pred_k = r_filt[k - 1] # predicted nominal rotation + + # Translation update + S_t = P_t_pred[k] + R_t_k + K_t = _solve_gain(P_t_pred[k], S_t) + t_filt[k] = t_pred[k] + K_t @ (translations[k] - t_pred[k]) + P_t_filt[k] = (I3 - K_t) @ P_t_pred[k] + + # Rotation update (ESKF) + # Innovation in so(3): rotation from predicted nominal to measurement + innov_r = (rotations[k] * r_pred_k.inv()).as_rotvec() + S_r = P_r_pred[k] + R_r_k + K_r = _solve_gain(P_r_pred[k], S_r) + delta_r = K_r @ innov_r + r_filt[k] = Rotation.from_rotvec(delta_r) * r_pred_k + P_r_filt[k] = (I3 - K_r) @ P_r_pred[k] + + # ---- RTS Backward smoother ---- + t_smooth = t_filt.copy() + r_smooth = list(r_filt) + P_t_smooth = P_t_filt.copy() + P_r_smooth = P_r_filt.copy() + + for k in range(N - 2, -1, -1): + # Translation RTS + G_t = _solve_gain(P_t_filt[k], P_t_pred[k + 1]) + t_smooth[k] = t_filt[k] + G_t @ (t_smooth[k + 1] - t_pred[k + 1]) + P_t_smooth[k] = (P_t_filt[k] + + G_t @ (P_t_smooth[k + 1] - P_t_pred[k + 1]) @ G_t.T) + + # Rotation RTS + # Smoothing correction: rotation from r_filt[k] (= predicted r_{k+1|k}) + # to the already-smoothed r_smooth[k+1] + G_r = _solve_gain(P_r_filt[k], P_r_pred[k + 1]) + delta_smooth = (r_smooth[k + 1] * r_filt[k].inv()).as_rotvec() + r_smooth[k] = Rotation.from_rotvec(G_r @ delta_smooth) * r_filt[k] + P_r_smooth[k] = (P_r_filt[k] + + G_r @ (P_r_smooth[k + 1] - P_r_pred[k + 1]) @ G_r.T) + + return t_smooth, r_smooth + + +# --------------------------------------------------------------------------- +# Public entry point +# --------------------------------------------------------------------------- + +def run_ekf_smoothing( + poses_dir: str, + mesh_path: str, + intrinsics_path: str, + weights_dir: str, + output_dir: str, + masks_folder: str = None, + process_noise_xy: float = 0.005, + process_noise_z: float = 0.005, + process_noise_r: float = 0.01, + measurement_noise_xy: float = 0.02, + measurement_noise_z: float = 0.08, + measurement_noise_r: float = 0.05, + min_iou: float = 0.1, +) -> None: + """Smooth a FoundationPose pose sequence with an ESKF + RTS smoother. + + Args: + poses_dir: Directory of per-frame Transform3d JSON files. + mesh_path: Mesh used during tracking (for IoU rendering). + intrinsics_path: Camera intrinsics JSON. + weights_dir: FoundationPose weights directory. + output_dir: Destination for smoothed pose JSON files. + masks_folder: Optional SAM2 mask folder for IoU-weighted noise. + If None, all frames are weighted equally. + process_noise_xy: Lateral (X, Y) random-walk std per frame (metres). + Default 0.005. + process_noise_z: Depth (Z) random-walk std per frame (metres). + Default 0.005 — same as XY, since process noise + models true object dynamics (isotropic). + process_noise_r: Rotation random-walk std per frame (radians). + Default 0.01. + measurement_noise_xy: Baseline lateral measurement std (metres). + Default 0.02. + measurement_noise_z: Baseline depth measurement std (metres). + Default 0.1 — set higher than XY to reflect + monocular depth uncertainty along the optical axis; + increase further to smooth Z more aggressively. + measurement_noise_r: Baseline rotation measurement std (radians). + Default 0.05. + min_iou: IoU floor to cap measurement noise on occluded + frames. Default 0.1. + """ + indices, poses = _load_poses(poses_dir) + logger.info(f"Loaded {len(poses)} poses from {poses_dir}") + + mesh = Mesh.load(mesh_path) + tracker = FoundationPoseTracker(mesh, weights_dir) + intrinsics = CameraIntrinsics.load(intrinsics_path) + + iou_scores = _compute_iou_scores(tracker, poses, intrinsics, masks_folder, indices) + + translations = np.array([_pose_to_tr(p)[0] for p in poses]) + rotations = [_pose_to_tr(p)[1] for p in poses] + + logger.info("Running ESKF forward pass + RTS backward smoother...") + t_smooth, r_smooth = _eskf_rts( + translations, rotations, iou_scores, + process_noise_xy=process_noise_xy, + process_noise_z=process_noise_z, + process_noise_r=process_noise_r, + measurement_noise_xy=measurement_noise_xy, + measurement_noise_z=measurement_noise_z, + measurement_noise_r=measurement_noise_r, + min_iou=min_iou, + ) + + os.makedirs(output_dir, exist_ok=True) + for i, idx in enumerate(indices): + _tr_to_pose(t_smooth[i], r_smooth[i]).save( + os.path.join(output_dir, f"{idx:06d}.json") + ) + + t_delta = np.linalg.norm(t_smooth - translations, axis=1) + logger.info(f"Translation correction — mean={t_delta.mean()*100:.1f}cm " + f"max={t_delta.max()*100:.1f}cm") + logger.info(f"Smoothed poses written to {output_dir}") + + +if __name__ == "__main__": + parser = argparse.ArgumentParser(description="ESKF + RTS pose smoother for FoundationPose output") + parser.add_argument("--poses_dir", required=True) + parser.add_argument("--mesh_path", required=True) + parser.add_argument("--intrinsics_path", required=True) + parser.add_argument("--weights_dir", required=True) + parser.add_argument("--output_dir", required=True) + parser.add_argument("--masks_folder", default=None) + parser.add_argument("--process_noise_xy", type=float, default=0.005) + parser.add_argument("--process_noise_z", type=float, default=0.005) + parser.add_argument("--process_noise_r", type=float, default=0.01) + parser.add_argument("--measurement_noise_xy", type=float, default=0.02) + parser.add_argument("--measurement_noise_z", type=float, default=0.1) + parser.add_argument("--measurement_noise_r", type=float, default=0.05) + parser.add_argument("--min_iou", type=float, default=0.1) + + args = parser.parse_args() + run_ekf_smoothing( + args.poses_dir, + args.mesh_path, + args.intrinsics_path, + args.weights_dir, + args.output_dir, + masks_folder=args.masks_folder, + process_noise_xy=args.process_noise_xy, + process_noise_z=args.process_noise_z, + process_noise_r=args.process_noise_r, + measurement_noise_xy=args.measurement_noise_xy, + measurement_noise_z=args.measurement_noise_z, + measurement_noise_r=args.measurement_noise_r, + min_iou=args.min_iou, + ) diff --git a/third-party/video_to_data/reconstruction/modules/v2d_foundation_pose/lib/run_estimate_mesh_scale.py b/third-party/video_to_data/reconstruction/modules/v2d_foundation_pose/lib/run_estimate_mesh_scale.py new file mode 100644 index 0000000000000000000000000000000000000000..2b213ea8315942316fb72df80b050f19009d41dd --- /dev/null +++ b/third-party/video_to_data/reconstruction/modules/v2d_foundation_pose/lib/run_estimate_mesh_scale.py @@ -0,0 +1,157 @@ +# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 +""" +Estimate the scale factor between a mesh and a scene's metric depth. + +Uses a coarse-to-fine grid search: samples candidate scales in log-space, +registers the mesh with FoundationPose at each scale, renders the result, +and scores it against the observed depth and mask. The search range is halved +around the winner each level. +""" +import argparse +import json +import logging +import os + +import cv2 + +from v2d.common.datatypes import CameraIntrinsics, DepthImage, Mask +from v2d.common.datatypes import Image as V2dImage +from v2d.mesh.lib.mesh import Mesh +from v2d.foundation_pose.lib.foundation_pose_tracker import FoundationPoseTracker + +logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s') +logger = logging.getLogger(__name__) + + +def run_estimate_mesh_scale( + mesh_path: str, + rgb_path: str, + depth_path: str, + mask_path: str, + intrinsics_path: str, + weights_dir: str, + scale_path: str, + rescaled_mesh_path: str = None, + pose_path: str = None, + lo: float = 0.5, + hi: float = 2.0, + n_samples: int = 7, + n_levels: int = 3, + iou_weight: float = 1.0, + depth_weight: float = 1.0, + chamfer_weight: float = 0.0, + registration_iterations: int = 5, +) -> float: + """Estimate mesh scale via coarse-to-fine grid search. + + Args: + mesh_path: Input mesh file. + rgb_path: Single reference frame RGB image (PNG). + depth_path: Corresponding depth PNG (uint16 inverse-depth encoding). + mask_path: Corresponding segmentation mask PNG. + intrinsics_path: Camera intrinsics JSON. + weights_dir: FoundationPose weights directory. + scale_path: Output JSON path for {"scale": }. + rescaled_mesh_path: If provided, saves the rescaled mesh here. + pose_path: If provided, saves the object-to-camera Transform3d JSON + for the best-scale registration (rotation, translation, scale). + lo: Lower bound of initial scale search range. Default 0.5. + hi: Upper bound of initial scale search range. Default 2.0. + n_samples: Scales to evaluate per level. Default 7. + n_levels: Refinement levels. Default 3. + iou_weight: Weight for mask IoU score component. Default 1.0. + depth_weight: Weight for depth consistency score component. Default 1.0. + chamfer_weight: Weight for Chamfer distance score component. Symmetric mean + Chamfer distance between depth points (inside rendered mask) + and mesh vertices in camera space, scored as + exp(-chamfer_dist). Default 0.0 (disabled). + registration_iterations: FP register() iterations per candidate. Default 5. + + Returns: + Best scale factor relative to the original mesh. + """ + mesh = Mesh.load(mesh_path) + tracker = FoundationPoseTracker(mesh, weights_dir) + + intrinsics = CameraIntrinsics.load(intrinsics_path) + depth = DepthImage.load(depth_path) + mask = Mask.load(mask_path) + + frame = cv2.imread(rgb_path) + if frame is None: + raise RuntimeError(f"Failed to load RGB image: {rgb_path}") + rgb = V2dImage(data=cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)) + + scale = tracker.estimate_scale_grid_search( + rgb, depth, mask, intrinsics, + lo=lo, hi=hi, + n_samples=n_samples, n_levels=n_levels, + iou_weight=iou_weight, depth_weight=depth_weight, + chamfer_weight=chamfer_weight, + registration_iterations=registration_iterations, + ) + logger.info(f"Best scale: {scale:.4f}") + + os.makedirs(os.path.dirname(os.path.abspath(scale_path)), exist_ok=True) + with open(scale_path, "w") as f: + json.dump({"scale": scale}, f) + logger.info(f"Saved scale to {scale_path}") + + if rescaled_mesh_path: + tracker._mesh.save(rescaled_mesh_path) + logger.info(f"Saved rescaled mesh to {rescaled_mesh_path}") + + if pose_path: + # Re-register at the winning scale to get the aligned 6-DoF pose. + # estimate_scale_grid_search leaves the mesh at best_scale but the + # tracker's internal pose is from the last candidate evaluated, not + # necessarily the best one — so we register once more here. + pose = tracker.register(rgb, depth, mask, intrinsics) + os.makedirs(os.path.dirname(os.path.abspath(pose_path)), exist_ok=True) + pose.save(pose_path) + logger.info(f"Saved aligned pose to {pose_path}") + + return scale + + +if __name__ == "__main__": + parser = argparse.ArgumentParser(description="Estimate mesh scale via coarse-to-fine grid search") + parser.add_argument("--mesh_path", required=True) + parser.add_argument("--rgb_path", required=True) + parser.add_argument("--depth_path", required=True) + parser.add_argument("--mask_path", required=True) + parser.add_argument("--intrinsics_path", required=True) + parser.add_argument("--weights_dir", required=True) + parser.add_argument("--scale_path", required=True) + parser.add_argument("--rescaled_mesh_path", default=None) + parser.add_argument("--pose_path", default=None) + parser.add_argument("--lo", type=float, default=0.5) + parser.add_argument("--hi", type=float, default=2.0) + parser.add_argument("--n_samples", type=int, default=7) + parser.add_argument("--n_levels", type=int, default=3) + parser.add_argument("--iou_weight", type=float, default=1.0) + parser.add_argument("--depth_weight", type=float, default=1.0) + parser.add_argument("--chamfer_weight", type=float, default=0.0) + parser.add_argument("--registration_iterations", type=int, default=5) + + args = parser.parse_args() + run_estimate_mesh_scale( + args.mesh_path, + args.rgb_path, + args.depth_path, + args.mask_path, + args.intrinsics_path, + args.weights_dir, + args.scale_path, + rescaled_mesh_path=args.rescaled_mesh_path, + pose_path=args.pose_path, + lo=args.lo, + hi=args.hi, + n_samples=args.n_samples, + n_levels=args.n_levels, + iou_weight=args.iou_weight, + depth_weight=args.depth_weight, + chamfer_weight=args.chamfer_weight, + registration_iterations=args.registration_iterations, + ) diff --git a/third-party/video_to_data/reconstruction/modules/v2d_foundation_pose/lib/run_render_poses.py b/third-party/video_to_data/reconstruction/modules/v2d_foundation_pose/lib/run_render_poses.py new file mode 100644 index 0000000000000000000000000000000000000000..5443c08969144da7acfbb6ddf34c6dee32147266 --- /dev/null +++ b/third-party/video_to_data/reconstruction/modules/v2d_foundation_pose/lib/run_render_poses.py @@ -0,0 +1,145 @@ +# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 +""" +GPU-batched mesh overlay renderer using nvdiffrast. + +Renders a mesh at every pose in poses_dir and composites over the matching +background frames from frames_dir. All poses in a batch are rasterised in a +single nvdiffrast call, so throughput scales with GPU parallelism rather than +frame count. + +Supports both UV-textured meshes and vertex-coloured meshes (detected +automatically via make_mesh_tensors). +""" +import argparse +import logging +import os + +import cv2 +import numpy as np +import nvdiffrast.torch as dr +import torch + +from v2d.common.datatypes import CameraIntrinsics, Transform3d +from v2d.foundation_pose.lib.fp_utils import nvdiffrast_render, make_mesh_tensors +from v2d.mesh.lib.mesh import Mesh + +logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s') +logger = logging.getLogger(__name__) + + +def run_render_poses( + mesh_path: str, + poses_dir: str, + frames_dir: str, + intrinsics_path: str, + output_dir: str, + batch_size: int = 32, + use_light: bool = True, +) -> None: + """ + Render mesh overlays for every pose in poses_dir using nvdiffrast (GPU-batched). + + Args: + mesh_path: Mesh to render (GLB, OBJ, etc.). + poses_dir: Directory of per-frame Transform3d JSON files. + frames_dir: Directory of per-frame background PNG images (000000.png, ...). + intrinsics_path: Camera intrinsics JSON. + output_dir: Destination for composited overlay PNGs. + batch_size: Number of poses to rasterise in one GPU call. + Reduce if you hit VRAM limits. Default 32. + use_light: If True, apply front-facing diffuse lighting. + If False, render raw texture/vertex colours. Default True. + """ + intrinsics = CameraIntrinsics.load(intrinsics_path) + K = intrinsics.to_matrix() + H, W = intrinsics.height, intrinsics.width + + # Upload mesh to GPU once + trimesh_mesh = Mesh.load(mesh_path).to_trimesh() + mesh_tensors = make_mesh_tensors(trimesh_mesh) + logger.info( + f"Mesh loaded: {len(trimesh_mesh.vertices)} verts, " + f"{'UV-textured' if 'tex' in mesh_tensors else 'vertex-coloured'}" + ) + + # Enumerate poses + pose_files = sorted(f for f in os.listdir(poses_dir) if f.endswith('.json')) + frame_indices = [int(os.path.splitext(f)[0]) for f in pose_files] + logger.info(f"Rendering {len(pose_files)} frames (batch_size={batch_size})") + + glctx = dr.RasterizeCudaContext() + os.makedirs(output_dir, exist_ok=True) + + for chunk_start in range(0, len(pose_files), batch_size): + chunk_files = pose_files[chunk_start : chunk_start + batch_size] + chunk_indices = frame_indices[chunk_start : chunk_start + batch_size] + + # Stack (N, 4, 4) pose batch + ob_in_cams = torch.stack([ + torch.as_tensor( + Transform3d.load(os.path.join(poses_dir, f)).to_matrix(), + device='cuda', dtype=torch.float, + ) + for f in chunk_files + ]) + + # Single GPU render call for the whole batch + with torch.no_grad(): + colors, depths, _ = nvdiffrast_render( + K=K, H=H, W=W, + ob_in_cams=ob_in_cams, + glctx=glctx, + mesh_tensors=mesh_tensors, + use_light=use_light, + ) + + # colors: (N, H, W, 3) float32 [0, 1], background pixels = 0 + # depths: (N, H, W) float32, background pixels = 0 + colors_np = (colors.cpu().numpy() * 255).clip(0, 255).astype(np.uint8) + depths_np = depths.cpu().numpy() + + for frame_idx, color_np, depth_np in zip(chunk_indices, colors_np, depths_np): + bg_path = os.path.join(frames_dir, f"{frame_idx:06d}.png") + if os.path.exists(bg_path): + bg = cv2.cvtColor(cv2.imread(bg_path), cv2.COLOR_BGR2RGB) + if bg.shape[:2] != (H, W): + bg = cv2.resize(bg, (W, H), interpolation=cv2.INTER_LINEAR) + else: + bg = np.zeros((H, W, 3), dtype=np.uint8) + + # Alpha from depth: 1 where mesh was rasterised, 0 elsewhere + alpha = (depth_np > 0.001).astype(np.float32)[..., None] + composited = ( + color_np.astype(np.float32) * alpha + + bg.astype(np.float32) * (1.0 - alpha) + ).clip(0, 255).astype(np.uint8) + + out_path = os.path.join(output_dir, f"{frame_idx:06d}.png") + cv2.imwrite(out_path, cv2.cvtColor(composited, cv2.COLOR_RGB2BGR)) + + logger.info(f" Batch {chunk_indices[0]:06d}–{chunk_indices[-1]:06d} done") + + logger.info(f"Rendered {len(pose_files)} overlays → {output_dir}") + + +if __name__ == "__main__": + parser = argparse.ArgumentParser(description="GPU-batched mesh overlay renderer") + parser.add_argument("--mesh_path", required=True) + parser.add_argument("--poses_dir", required=True) + parser.add_argument("--frames_dir", required=True) + parser.add_argument("--intrinsics_path", required=True) + parser.add_argument("--output_dir", required=True) + parser.add_argument("--batch_size", type=int, default=32) + parser.add_argument("--use_light", action="store_true", default=True) + parser.add_argument("--no_light", dest="use_light", action="store_false") + args = parser.parse_args() + run_render_poses( + args.mesh_path, + args.poses_dir, + args.frames_dir, + args.intrinsics_path, + args.output_dir, + batch_size=args.batch_size, + use_light=args.use_light, + ) diff --git a/third-party/video_to_data/reconstruction/modules/v2d_foundation_pose/lib/run_video_to_poses.py b/third-party/video_to_data/reconstruction/modules/v2d_foundation_pose/lib/run_video_to_poses.py new file mode 100644 index 0000000000000000000000000000000000000000..2000f4e3f1726328a7207c8148826d3e6cc2c209 --- /dev/null +++ b/third-party/video_to_data/reconstruction/modules/v2d_foundation_pose/lib/run_video_to_poses.py @@ -0,0 +1,229 @@ +# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 +""" +FoundationPose video-to-poses processing function. +Can be called directly from command line or imported as a function. +""" +import os +import argparse +import logging +from pathlib import Path + +import numpy as np +import cv2 + +from v2d.common.datatypes import CameraIntrinsics, DepthImage, Mask, Transform3d +from v2d.common.datatypes import Image as V2dImage +from v2d.mesh.lib.mesh import Mesh +from v2d.foundation_pose.lib.foundation_pose_tracker import FoundationPoseTracker + +logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s') +logger = logging.getLogger(__name__) + + +def run_video_to_poses( + video_path: str, + depth_folder: str, + masks_folder: str, + camera_intrinsics_path: str, + mesh_path: str, + poses_dir: str, + weights_dir: str, + reference_frame: int = 0, + target_width: int = None, + target_height: int = None, + reregister_iou_thresh: float = None, + register_iteration: int = 10, + track_iteration: int = 5, + n_particles: int = 1, + particle_process_noise_t: float = 0.005, + particle_process_noise_r: float = 0.02, + particle_iteration: int = 3, + particle_mask_iou_weight: float = 1.0, + mask_depth: bool = False, +) -> None: + """Process a video to track object poses and save per-frame Transform3d JSON files. + + When n_particles=1 (default), uses the original track_one / track_one_with_recovery + logic unchanged. When n_particles>1, uses a particle filter: + each frame runs a batched refine+score over all particles, weights them by + the scorer's logits, resamples on diversity collapse, and returns the + weighted mean pose. reregister_iou_thresh is ignored in particle mode + (the particle filter handles tracking loss implicitly via diversity). + + mask_depth: if True, zero out depth pixels outside the object mask before passing + to FoundationPose. FoundationPose applies its own internal masking during crop + creation so this is not standard; it may help when background depth bleeds into + the object region. Default False. + """ + mesh = Mesh.load(mesh_path, force_mesh=Path(mesh_path).suffix.lower() == ".glb") + tracker = FoundationPoseTracker(mesh, weights_dir) + + camera_intrinsics = CameraIntrinsics.load(camera_intrinsics_path) + K = camera_intrinsics.to_matrix() + + cap = cv2.VideoCapture(video_path) + num_frames = int(cap.get(cv2.CAP_PROP_FRAME_COUNT)) + orig_width = int(cap.get(cv2.CAP_PROP_FRAME_WIDTH)) + orig_height = int(cap.get(cv2.CAP_PROP_FRAME_HEIGHT)) + + if target_width and target_height: + scale_x = target_width / orig_width + scale_y = target_height / orig_height + K_scaled = K.copy() + K_scaled[0, 0] *= scale_x + K_scaled[1, 1] *= scale_y + K_scaled[0, 2] *= scale_x + K_scaled[1, 2] *= scale_y + logger.info(f"Scaling {orig_width}x{orig_height} → {target_width}x{target_height}") + else: + target_width, target_height = orig_width, orig_height + K_scaled = K + + scaled_intrinsics = CameraIntrinsics( + fx=float(K_scaled[0, 0]), fy=float(K_scaled[1, 1]), + cx=float(K_scaled[0, 2]), cy=float(K_scaled[1, 2]), + width=target_width, height=target_height, + ) + + def _load_frame(idx: int) -> tuple: + cap.set(cv2.CAP_PROP_POS_FRAMES, idx) + ret, frame = cap.read() + if not ret: + return None, None, None + rgb_arr = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB) + if (target_width, target_height) != (orig_width, orig_height): + rgb_arr = cv2.resize(rgb_arr, (target_width, target_height), interpolation=cv2.INTER_LINEAR) + + depth_p = os.path.join(depth_folder, f"{idx:06d}.png") + depth = None + if os.path.exists(depth_p): + d = DepthImage.load(depth_p) + if (target_width, target_height) != (orig_width, orig_height): + d = DepthImage(depth=cv2.resize(d.depth, (target_width, target_height), interpolation=cv2.INTER_NEAREST)) + depth = d + + mask_p = os.path.join(masks_folder, f"{idx:06d}.png") + mask = None + if os.path.exists(mask_p): + m = Mask.load(mask_p) + if (target_width, target_height) != (orig_width, orig_height): + m = Mask(mask=cv2.resize(m.mask.astype(np.float32), (target_width, target_height), interpolation=cv2.INTER_NEAREST)) + mask = m + + return V2dImage(data=rgb_arr), depth, mask + + def _save_pose(frame_idx: int, pose: Transform3d) -> None: + os.makedirs(poses_dir, exist_ok=True) + pose.save(os.path.join(poses_dir, f"{frame_idx:06d}.json")) + + def _apply_mask(depth: DepthImage, mask: Mask | None) -> DepthImage: + """Zero out depth outside the object mask.""" + if mask is None: + return depth + masked = depth.depth.copy() + masked[~mask.mask.astype(bool)] = 0.0 + return DepthImage(depth=masked) + + # Register at reference frame + logger.info(f"Registering at reference frame {reference_frame}") + rgb, depth, mask = _load_frame(reference_frame) + if rgb is None or depth is None or mask is None: + raise RuntimeError(f"Failed to load data for reference frame {reference_frame}") + + initial_pose = tracker.register(rgb, _apply_mask(depth, mask) if mask_depth else depth, mask, scaled_intrinsics, iteration=register_iteration) + _save_pose(reference_frame, initial_pose) + logger.info("Registered at reference frame") + + def _track_one(rgb, depth, mask) -> Transform3d: + masked_depth = _apply_mask(depth, mask) if mask_depth else depth + if n_particles > 1: + return tracker.track_one_particles( + rgb, masked_depth, scaled_intrinsics, + mask=mask, + n_particles=n_particles, + process_noise_t=particle_process_noise_t, + process_noise_r=particle_process_noise_r, + iteration=particle_iteration, + mask_iou_weight=particle_mask_iou_weight, + ) + if reregister_iou_thresh is not None and mask is not None: + pose, recovered = tracker.track_one_with_recovery( + rgb, masked_depth, mask, scaled_intrinsics, + iteration=track_iteration, iou_thresh=reregister_iou_thresh, + recovery_iteration=register_iteration, + ) + if recovered: + logger.info(f" Re-registered at frame {frame_idx}") + return pose + return tracker.track_one(rgb, masked_depth, scaled_intrinsics, iteration=track_iteration) + + # Forward tracking + logger.info(f"Tracking forward: {reference_frame + 1} → {num_frames - 1}") + tracker.reset_to_pose(initial_pose) + for frame_idx in range(reference_frame + 1, num_frames): + rgb, depth, mask = _load_frame(frame_idx) + if rgb is None or depth is None: + break + logger.info(f"Forward frame {frame_idx}/{num_frames}") + _save_pose(frame_idx, _track_one(rgb, depth, mask)) + + # Backward tracking + if reference_frame > 0: + logger.info(f"Tracking backward: {reference_frame - 1} → 0") + tracker.reset_to_pose(initial_pose) + for frame_idx in range(reference_frame - 1, -1, -1): + rgb, depth, mask = _load_frame(frame_idx) + if rgb is None or depth is None: + break + logger.info(f"Backward frame {frame_idx}/{num_frames}") + _save_pose(frame_idx, _track_one(rgb, depth, mask)) + + cap.release() + logger.info(f"Completed {num_frames} frames") + + +if __name__ == "__main__": + parser = argparse.ArgumentParser(description="Process video to poses using FoundationPose") + parser.add_argument("--video_path", required=True) + parser.add_argument("--depth_folder", required=True) + parser.add_argument("--masks_folder", required=True) + parser.add_argument("--camera_intrinsics_path", required=True) + parser.add_argument("--mesh_path", required=True) + parser.add_argument("--poses_dir", required=True) + parser.add_argument("--weights_dir", required=True) + parser.add_argument("--reference_frame", type=int, default=0) + parser.add_argument("--target_width", type=int, default=None) + parser.add_argument("--target_height", type=int, default=None) + parser.add_argument("--reregister_iou_thresh", type=float, default=None) + parser.add_argument("--register_iteration", type=int, default=10) + parser.add_argument("--track_iteration", type=int, default=5) + parser.add_argument("--n_particles", type=int, default=1) + parser.add_argument("--particle_process_noise_t", type=float, default=0.005) + parser.add_argument("--particle_process_noise_r", type=float, default=0.02) + parser.add_argument("--particle_iteration", type=int, default=3) + parser.add_argument("--particle_mask_iou_weight", type=float, default=1.0) + parser.add_argument("--mask_depth", action="store_true") + + args = parser.parse_args() + run_video_to_poses( + args.video_path, + args.depth_folder, + args.masks_folder, + args.camera_intrinsics_path, + args.mesh_path, + args.poses_dir, + args.weights_dir, + reference_frame=args.reference_frame, + target_width=args.target_width, + target_height=args.target_height, + reregister_iou_thresh=args.reregister_iou_thresh, + register_iteration=args.register_iteration, + track_iteration=args.track_iteration, + n_particles=args.n_particles, + particle_process_noise_t=args.particle_process_noise_t, + particle_process_noise_r=args.particle_process_noise_r, + particle_iteration=args.particle_iteration, + particle_mask_iou_weight=args.particle_mask_iou_weight, + mask_depth=args.mask_depth, + ) diff --git a/third-party/video_to_data/reconstruction/modules/v2d_foundation_pose/lib/symmetry.py b/third-party/video_to_data/reconstruction/modules/v2d_foundation_pose/lib/symmetry.py new file mode 100644 index 0000000000000000000000000000000000000000..42cc17e0092851ffca2f5b78009f4b52a72e8d80 --- /dev/null +++ b/third-party/video_to_data/reconstruction/modules/v2d_foundation_pose/lib/symmetry.py @@ -0,0 +1,114 @@ +# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 +"""Symmetry-aware pose canonicalization for multi-view FoundationPose. + +Loads BOP-style symmetry annotations produced by hoi-tools' compute_symmetry +script and picks the equivalence-class representative of a per-view 6D pose +that lies closest to a reference pose. The convention is right-multiplication: +P and `P @ R_s` render identical images for any self-symmetry R_s, so the +canonical form is `P @ R_s*` minimizing rotational geodesic distance from the +reference. Translation enters only through R_s and is zero for +centroid-aligned BOP symmetries. +""" + +import json +from pathlib import Path + +import numpy as np + + +def _rotation_matrix(axis: np.ndarray, angle: float) -> np.ndarray: + axis = np.asarray(axis, dtype=float) + axis = axis / np.linalg.norm(axis) + c, s = np.cos(angle), np.sin(angle) + t = 1 - c + x, y, z = axis + return np.array([ + [t*x*x + c, t*x*y - s*z, t*x*z + s*y], + [t*x*y + s*z, t*y*y + c, t*y*z - s*x], + [t*x*z - s*y, t*y*z + s*x, t*z*z + c ], + ]) + + +def _close_group(transforms: list[np.ndarray], atol: float = 1e-6, + max_size: int = 1024) -> list[np.ndarray]: + elems: list[np.ndarray] = [np.eye(4)] + for T in transforms: + T = np.asarray(T, dtype=float) + if not any(np.allclose(T, e, atol=atol) for e in elems): + elems.append(T) + while True: + new: list[np.ndarray] = [] + for a in elems: + for b in elems: + p = a @ b + if any(np.allclose(p, e, atol=atol) for e in elems): + continue + if any(np.allclose(p, n, atol=atol) for n in new): + continue + new.append(p) + if len(elems) + len(new) > max_size: + raise ValueError( + f"group closure exceeded {max_size} elements; " + "inputs may not generate a finite group" + ) + if not new: + break + elems.extend(new) + return elems + + +def load_symmetry_group( + json_path: str | Path, + continuous_step_deg: float = 5.0, +) -> list[np.ndarray]: + """Load a BOP-style symmetry JSON and return a flat list of (4,4) SE(3) group elements. + + Identity is included. Discrete transforms are closed under composition + (idempotent if the JSON already stores a closed group). Continuous axes + are discretized at `continuous_step_deg` and layered via Cartesian + product. Continuous-axis offsets are ignored (BOP convention places the + object centroid on the axis, so the axis line passes through the origin + of the aligned mesh). + """ + with open(json_path) as f: + data = json.load(f) + + discrete = [ + np.array(t, dtype=float).reshape(4, 4) + for t in data.get("symmetries_discrete", []) + ] + group = _close_group(discrete) + + n_steps = max(1, int(round(360.0 / continuous_step_deg))) + for cont in data.get("symmetries_continuous", []): + axis = np.asarray(cont["axis"], dtype=float) + rotations: list[np.ndarray] = [] + for s in range(n_steps): + R = _rotation_matrix(axis, 2 * np.pi * s / n_steps) + T = np.eye(4) + T[:3, :3] = R + rotations.append(T) + group = [b @ r for b in group for r in rotations] + + return group + + +def canonicalize_pose( + pose: np.ndarray, + group: list[np.ndarray], + reference: np.ndarray, +) -> np.ndarray: + """Pick `pose @ R_s*` (R_s ∈ group) minimizing rotational geodesic distance to reference.""" + ref_R = np.asarray(reference, dtype=float)[:3, :3] + pose = np.asarray(pose, dtype=float) + best = None + best_dist = float("inf") + for R_s in group: + candidate = pose @ R_s + cos_theta = (np.trace(ref_R.T @ candidate[:3, :3]) - 1.0) / 2.0 + d = float(np.arccos(np.clip(cos_theta, -1.0, 1.0))) + if d < best_dist: + best_dist = d + best = candidate + return best diff --git a/third-party/video_to_data/reconstruction/modules/v2d_foundation_pose/lib/tests/test_download_weights.py b/third-party/video_to_data/reconstruction/modules/v2d_foundation_pose/lib/tests/test_download_weights.py new file mode 100644 index 0000000000000000000000000000000000000000..c6b8dae906cb2ce70b447f9d45746ab441f2c377 --- /dev/null +++ b/third-party/video_to_data/reconstruction/modules/v2d_foundation_pose/lib/tests/test_download_weights.py @@ -0,0 +1,57 @@ +# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 +import subprocess + +import pytest + +from v2d.foundation_pose.lib import download_weights + + +def test_gdown_folder_retries_transient_failures(monkeypatch, tmp_path): + calls = [] + sleeps = [] + + def fake_run(command, check): + calls.append((command, check)) + if len(calls) < download_weights.GDOWN_MAX_ATTEMPTS: + raise subprocess.CalledProcessError(1, command) + + monkeypatch.setattr(download_weights.subprocess, "run", fake_run) + monkeypatch.setattr(download_weights.time, "sleep", sleeps.append) + + download_weights._gdown_folder("folder-id", str(tmp_path)) + + expected_command = [ + "gdown", "--folder", + "https://drive.google.com/drive/folders/folder-id", + "-O", str(tmp_path), + ] + assert calls == [ + (expected_command, True), + (expected_command, True), + (expected_command, True), + ] + assert sleeps == [ + download_weights.GDOWN_RETRY_DELAY_SECONDS, + download_weights.GDOWN_RETRY_DELAY_SECONDS, + ] + + +def test_gdown_folder_raises_after_final_attempt(monkeypatch, tmp_path): + error = subprocess.CalledProcessError(1, ["gdown"]) + calls = [] + sleeps = [] + + def fake_run(command, check): + calls.append((command, check)) + raise error + + monkeypatch.setattr(download_weights.subprocess, "run", fake_run) + monkeypatch.setattr(download_weights.time, "sleep", sleeps.append) + + with pytest.raises(subprocess.CalledProcessError) as exc_info: + download_weights._gdown_folder("folder-id", str(tmp_path)) + + assert exc_info.value is error + assert len(calls) == download_weights.GDOWN_MAX_ATTEMPTS + assert len(sleeps) == download_weights.GDOWN_MAX_ATTEMPTS - 1 diff --git a/third-party/video_to_data/reconstruction/modules/v2d_foundation_stereo/.gitignore b/third-party/video_to_data/reconstruction/modules/v2d_foundation_stereo/.gitignore new file mode 100644 index 0000000000000000000000000000000000000000..36bd334954c9a58089761f30eb0b5ed86a7672e0 --- /dev/null +++ b/third-party/video_to_data/reconstruction/modules/v2d_foundation_stereo/.gitignore @@ -0,0 +1,7 @@ +data/ +checkpoints/ +*.pt +*.pth +*.zip +__pycache__/ +tests/test_data/output/ diff --git a/third-party/video_to_data/reconstruction/modules/v2d_foundation_stereo/LICENSE b/third-party/video_to_data/reconstruction/modules/v2d_foundation_stereo/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..10caffae439b956cdda2b1ded9ecbe51ac10befb --- /dev/null +++ b/third-party/video_to_data/reconstruction/modules/v2d_foundation_stereo/LICENSE @@ -0,0 +1,15 @@ +# Apache License 2.0 + +Copyright 2025 NVIDIA CORPORATION + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. diff --git a/third-party/video_to_data/reconstruction/modules/v2d_foundation_stereo/assets/calibration.json b/third-party/video_to_data/reconstruction/modules/v2d_foundation_stereo/assets/calibration.json new file mode 100644 index 0000000000000000000000000000000000000000..4eeb55c906d10c117f5421b627c6611fa1252e70 --- /dev/null +++ b/third-party/video_to_data/reconstruction/modules/v2d_foundation_stereo/assets/calibration.json @@ -0,0 +1,7 @@ +{ + "fx": 844.67822265625, + "fy": 844.67822265625, + "cx": 927.3002319335938, + "cy": 566.7403564453125, + "baseline": 0.14999972966613306 +} diff --git a/third-party/video_to_data/reconstruction/modules/v2d_foundation_stereo/assets/left/1707938736136244532.jpeg b/third-party/video_to_data/reconstruction/modules/v2d_foundation_stereo/assets/left/1707938736136244532.jpeg new file mode 100644 index 0000000000000000000000000000000000000000..b424582f0d5996e475658b3841523e923215ba0c --- /dev/null +++ b/third-party/video_to_data/reconstruction/modules/v2d_foundation_stereo/assets/left/1707938736136244532.jpeg @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:6ffdfce1d5d29b3721df5c5ad3fe1da842fb42452078d5ba006de8333c2b4f34 +size 421354 diff --git a/third-party/video_to_data/reconstruction/modules/v2d_foundation_stereo/assets/left/1707938736169573532.jpeg b/third-party/video_to_data/reconstruction/modules/v2d_foundation_stereo/assets/left/1707938736169573532.jpeg new file mode 100644 index 0000000000000000000000000000000000000000..0871a1ab2704a4912109837402e5d8a1b5d12a35 --- /dev/null +++ b/third-party/video_to_data/reconstruction/modules/v2d_foundation_stereo/assets/left/1707938736169573532.jpeg @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:1e9e3466cc89dbccc96a0d1c647030733ad353619e677ea837e7467183d41862 +size 416371 diff --git a/third-party/video_to_data/reconstruction/modules/v2d_foundation_stereo/assets/left/1707938736202920532.jpeg b/third-party/video_to_data/reconstruction/modules/v2d_foundation_stereo/assets/left/1707938736202920532.jpeg new file mode 100644 index 0000000000000000000000000000000000000000..6caaf6dc2101075a740c657eccbcb7cb3bba75d6 --- /dev/null +++ b/third-party/video_to_data/reconstruction/modules/v2d_foundation_stereo/assets/left/1707938736202920532.jpeg @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:e90de9787ed405001090a5871436ddaf3c01dce138fb6f8924e9a8594f130dbe +size 425625 diff --git a/third-party/video_to_data/reconstruction/modules/v2d_foundation_stereo/assets/right/1707938736136244532.jpeg b/third-party/video_to_data/reconstruction/modules/v2d_foundation_stereo/assets/right/1707938736136244532.jpeg new file mode 100644 index 0000000000000000000000000000000000000000..77839ac6a0cf377ec9302dce1104cf70226f44f2 --- /dev/null +++ b/third-party/video_to_data/reconstruction/modules/v2d_foundation_stereo/assets/right/1707938736136244532.jpeg @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:338651585339817985b1b7e43e9fe7215e47bdb631f2354dcdddc0ec7503ddb7 +size 401534 diff --git a/third-party/video_to_data/reconstruction/modules/v2d_foundation_stereo/assets/right/1707938736169573532.jpeg b/third-party/video_to_data/reconstruction/modules/v2d_foundation_stereo/assets/right/1707938736169573532.jpeg new file mode 100644 index 0000000000000000000000000000000000000000..eeda10df85ae1a666f18d95f87a9d54e5e7f360b --- /dev/null +++ b/third-party/video_to_data/reconstruction/modules/v2d_foundation_stereo/assets/right/1707938736169573532.jpeg @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:f7d56fd83a325128341ca31dac46fc206eaaa0295664e838293656b24379fe3c +size 390751 diff --git a/third-party/video_to_data/reconstruction/modules/v2d_foundation_stereo/assets/right/1707938736202920532.jpeg b/third-party/video_to_data/reconstruction/modules/v2d_foundation_stereo/assets/right/1707938736202920532.jpeg new file mode 100644 index 0000000000000000000000000000000000000000..5042761dfbd4206a39578447e36010d9ce873168 --- /dev/null +++ b/third-party/video_to_data/reconstruction/modules/v2d_foundation_stereo/assets/right/1707938736202920532.jpeg @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:90b3ae34d4d068a4061c935b7ea7da1ed2593d75df71f5f1220c5e8f98f9d920 +size 398396 diff --git a/third-party/video_to_data/reconstruction/modules/v2d_foundation_stereo/docker/Dockerfile b/third-party/video_to_data/reconstruction/modules/v2d_foundation_stereo/docker/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..b7faa745552d2ad7651ca893947abab067c65256 --- /dev/null +++ b/third-party/video_to_data/reconstruction/modules/v2d_foundation_stereo/docker/Dockerfile @@ -0,0 +1,14 @@ +FROM nvcr.io/nvidia/tensorrt:24.12-py3 + +ENV DEBIAN_FRONTEND=noninteractive + +RUN apt-get update && apt-get install -y \ + libgl1 \ + libglib2.0-0 \ + && rm -rf /var/lib/apt/lists/* + +RUN pip install opencv-python-headless numpy Pillow "cuda-python==12.6.*" + +COPY . /workspace + +RUN pip install -e "/workspace/v2d_common[io]" -e /workspace/v2d_mv -e /workspace/v2d_foundation_stereo/lib diff --git a/third-party/video_to_data/reconstruction/modules/v2d_foundation_stereo/docker/__init__.py b/third-party/video_to_data/reconstruction/modules/v2d_foundation_stereo/docker/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..52a7a9daf028f654d6a02f65c99cc609a57b492f --- /dev/null +++ b/third-party/video_to_data/reconstruction/modules/v2d_foundation_stereo/docker/__init__.py @@ -0,0 +1,2 @@ +# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 diff --git a/third-party/video_to_data/reconstruction/modules/v2d_foundation_stereo/docker/_config.py b/third-party/video_to_data/reconstruction/modules/v2d_foundation_stereo/docker/_config.py new file mode 100644 index 0000000000000000000000000000000000000000..06ac88540e41bdbec05f0ac73975a45770f53b20 --- /dev/null +++ b/third-party/video_to_data/reconstruction/modules/v2d_foundation_stereo/docker/_config.py @@ -0,0 +1,6 @@ +# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 +import os + +IMAGE_NAME = "v2d_foundation_stereo" +MODULES_DIR = os.path.abspath(os.path.join(os.path.dirname(os.path.abspath(__file__)), "..", "..")) diff --git a/third-party/video_to_data/reconstruction/modules/v2d_foundation_stereo/docker/build.py b/third-party/video_to_data/reconstruction/modules/v2d_foundation_stereo/docker/build.py new file mode 100644 index 0000000000000000000000000000000000000000..346020e224cc922f5dec89517f410c4f4b151405 --- /dev/null +++ b/third-party/video_to_data/reconstruction/modules/v2d_foundation_stereo/docker/build.py @@ -0,0 +1,17 @@ +# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 +import subprocess +import os + +IMAGE_NAME = "v2d_foundation_stereo" + +current_dir = os.path.dirname(os.path.abspath(__file__)) +module_dir = os.path.join(current_dir, "..") +root_dir = os.path.join(module_dir, "..") +dockerfile_path = os.path.join(current_dir, "Dockerfile") + +def build_docker_image() -> None: + subprocess.run(["docker", "build", "-t", IMAGE_NAME, "-f", dockerfile_path, root_dir], check=True) + +if __name__ == "__main__": + build_docker_image() diff --git a/third-party/video_to_data/reconstruction/modules/v2d_foundation_stereo/docker/pyproject.toml b/third-party/video_to_data/reconstruction/modules/v2d_foundation_stereo/docker/pyproject.toml new file mode 100644 index 0000000000000000000000000000000000000000..0ec5bf91cd2e5eeb47e32f8ae0aa3613078c1fb3 --- /dev/null +++ b/third-party/video_to_data/reconstruction/modules/v2d_foundation_stereo/docker/pyproject.toml @@ -0,0 +1,18 @@ +# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 +[build-system] +requires = ["setuptools>=68.0", "wheel"] +build-backend = "setuptools.build_meta" + +[project] +name = "v2d-foundation-stereo-docker" +version = "0.1.0" +description = "Docker orchestration scripts for Foundation Stereo" +requires-python = ">=3.10" +dependencies = ["v2d-docker"] + +[tool.setuptools] +packages = ["v2d.foundation_stereo.docker"] + +[tool.setuptools.package-dir] +"v2d.foundation_stereo.docker" = "." diff --git a/third-party/video_to_data/reconstruction/modules/v2d_foundation_stereo/docker/run_download_weights.py b/third-party/video_to_data/reconstruction/modules/v2d_foundation_stereo/docker/run_download_weights.py new file mode 100644 index 0000000000000000000000000000000000000000..1225045ba6e92195aca1c1fa552460dd6167a6a4 --- /dev/null +++ b/third-party/video_to_data/reconstruction/modules/v2d_foundation_stereo/docker/run_download_weights.py @@ -0,0 +1,36 @@ +# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 +import subprocess +import os +from v2d.foundation_stereo.docker._config import IMAGE_NAME, MODULES_DIR + + +def run_download(output_dir: str, dev: bool = False) -> None: + os.makedirs(output_dir, exist_ok=True) + output_dir = os.path.abspath(output_dir) + + cmd = [ + "docker", "run", "--rm", + "--gpus", "all", + "--user", f"{os.getuid()}:{os.getgid()}", + "-e", "HOME=/tmp", + "-v", f"{output_dir}:/data/models", + ] + if dev: + cmd += ["-v", f"{MODULES_DIR}:/workspace"] + cmd += [ + IMAGE_NAME, + "python", "-m", "v2d.foundation_stereo.lib.download_weights", + "--output_dir", "/data/models", + ] + subprocess.run(cmd, check=True) + + +if __name__ == "__main__": + import argparse + + parser = argparse.ArgumentParser(description="Download Foundation Stereo ONNX model") + parser.add_argument("--output_dir", type=str, required=True, help="Output directory for model files") + parser.add_argument("--dev", action="store_true", help="Mount local modules for development") + args = parser.parse_args() + run_download(output_dir=args.output_dir, dev=args.dev) diff --git a/third-party/video_to_data/reconstruction/modules/v2d_foundation_stereo/docker/run_export_engine.py b/third-party/video_to_data/reconstruction/modules/v2d_foundation_stereo/docker/run_export_engine.py new file mode 100644 index 0000000000000000000000000000000000000000..43d4c03c1f66773a8db3d490facc241b0f0e430c --- /dev/null +++ b/third-party/video_to_data/reconstruction/modules/v2d_foundation_stereo/docker/run_export_engine.py @@ -0,0 +1,36 @@ +# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 +import subprocess +import os +from v2d.foundation_stereo.docker._config import IMAGE_NAME, MODULES_DIR + + +def run_export_engine(model_dir: str, dev: bool = False) -> None: + model_dir = os.path.abspath(model_dir) + + cmd = [ + "docker", "run", "--rm", + "--gpus", "all", + "--user", f"{os.getuid()}:{os.getgid()}", + "-e", "HOME=/tmp", + "-v", f"{model_dir}:/data/models", + ] + if dev: + cmd += ["-v", f"{MODULES_DIR}:/workspace"] + cmd += [ + IMAGE_NAME, + "python", "-c", + "from v2d.foundation_stereo.lib.export_engine import ensure_engine; ensure_engine('/data/models')", + ] + subprocess.run(cmd, check=True) + + +if __name__ == "__main__": + import argparse + + parser = argparse.ArgumentParser(description="Export Foundation Stereo ONNX to TensorRT engine") + parser.add_argument("--model_dir", type=str, required=True, + help="Directory containing the ONNX model (engine will be saved here)") + parser.add_argument("--dev", action="store_true", help="Mount local modules for development") + args = parser.parse_args() + run_export_engine(model_dir=args.model_dir, dev=args.dev) diff --git a/third-party/video_to_data/reconstruction/modules/v2d_foundation_stereo/docker/run_image_list_to_depth.py b/third-party/video_to_data/reconstruction/modules/v2d_foundation_stereo/docker/run_image_list_to_depth.py new file mode 100644 index 0000000000000000000000000000000000000000..5b5f6703b156f07dd7d2af14206c9fb59f3849be --- /dev/null +++ b/third-party/video_to_data/reconstruction/modules/v2d_foundation_stereo/docker/run_image_list_to_depth.py @@ -0,0 +1,57 @@ +# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 +from v2d.docker.container import run_in_container +from v2d.foundation_stereo.docker._config import IMAGE_NAME, MODULES_DIR + + +def run_image_list_to_depth( + left_dir: str, + right_dir: str, + depth_folder: str, + intrinsics_folder: str, + model_dir: str, + calibration_file: str = None, + fx: float = None, fy: float = None, cx: float = None, cy: float = None, + baseline: float = None, + dev: bool = False, +) -> None: + run_in_container( + image=IMAGE_NAME, + module="v2d.foundation_stereo.lib.image_list_to_depth", + inputs={"left_dir": left_dir, "right_dir": right_dir, "model_dir": model_dir, "calibration_file": calibration_file}, + outputs={"depth_folder": depth_folder, "intrinsics_folder": intrinsics_folder}, + extra_args={"fx": fx, "fy": fy, "cx": cx, "cy": cy, "baseline": baseline}, + dev=dev, + modules_dir=MODULES_DIR, + gpus=True, + ) + + +if __name__ == "__main__": + import argparse + + parser = argparse.ArgumentParser(description="Foundation Stereo: image list to depth maps") + parser.add_argument('--left_dir', required=True) + parser.add_argument('--right_dir', required=True) + parser.add_argument('--depth_folder', required=True) + parser.add_argument('--intrinsics_folder', required=True) + parser.add_argument('--model_dir', required=True) + + cal_group = parser.add_mutually_exclusive_group(required=True) + cal_group.add_argument('--calibration_file') + cal_group.add_argument('--fx', type=float) + + parser.add_argument('--fy', type=float) + parser.add_argument('--cx', type=float) + parser.add_argument('--cy', type=float) + parser.add_argument('--baseline', type=float) + parser.add_argument('--dev', action='store_true', help='Mount local modules for development') + + args = parser.parse_args() + run_image_list_to_depth( + args.left_dir, args.right_dir, + args.depth_folder, args.intrinsics_folder, args.model_dir, + calibration_file=args.calibration_file, + fx=args.fx, fy=args.fy, cx=args.cx, cy=args.cy, + baseline=args.baseline, dev=args.dev, + ) diff --git a/third-party/video_to_data/reconstruction/modules/v2d_foundation_stereo/docker/run_image_to_depth.py b/third-party/video_to_data/reconstruction/modules/v2d_foundation_stereo/docker/run_image_to_depth.py new file mode 100644 index 0000000000000000000000000000000000000000..c94ec584b34a83a488859d0f4b1dfb5729ae0410 --- /dev/null +++ b/third-party/video_to_data/reconstruction/modules/v2d_foundation_stereo/docker/run_image_to_depth.py @@ -0,0 +1,57 @@ +# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 +from v2d.docker.container import run_in_container +from v2d.foundation_stereo.docker._config import IMAGE_NAME, MODULES_DIR + + +def run_image_to_depth( + left_image_path: str, + right_image_path: str, + depth_path: str, + intrinsics_path: str, + model_dir: str, + calibration_file: str = None, + fx: float = None, fy: float = None, cx: float = None, cy: float = None, + baseline: float = None, + dev: bool = False, +) -> None: + run_in_container( + image=IMAGE_NAME, + module="v2d.foundation_stereo.lib.image_to_depth", + inputs={"left_image_path": left_image_path, "right_image_path": right_image_path, "model_dir": model_dir, "calibration_file": calibration_file}, + outputs={"depth_path": depth_path, "intrinsics_path": intrinsics_path}, + extra_args={"fx": fx, "fy": fy, "cx": cx, "cy": cy, "baseline": baseline}, + dev=dev, + modules_dir=MODULES_DIR, + gpus=True, + ) + + +if __name__ == "__main__": + import argparse + + parser = argparse.ArgumentParser(description="Foundation Stereo: single stereo pair to depth") + parser.add_argument('--left_image_path', required=True) + parser.add_argument('--right_image_path', required=True) + parser.add_argument('--depth_path', required=True) + parser.add_argument('--intrinsics_path', required=True) + parser.add_argument('--model_dir', required=True) + + cal_group = parser.add_mutually_exclusive_group(required=True) + cal_group.add_argument('--calibration_file') + cal_group.add_argument('--fx', type=float) + + parser.add_argument('--fy', type=float) + parser.add_argument('--cx', type=float) + parser.add_argument('--cy', type=float) + parser.add_argument('--baseline', type=float) + parser.add_argument('--dev', action='store_true', help='Mount local modules for development') + + args = parser.parse_args() + run_image_to_depth( + args.left_image_path, args.right_image_path, + args.depth_path, args.intrinsics_path, args.model_dir, + calibration_file=args.calibration_file, + fx=args.fx, fy=args.fy, cx=args.cx, cy=args.cy, + baseline=args.baseline, dev=args.dev, + ) diff --git a/third-party/video_to_data/reconstruction/modules/v2d_foundation_stereo/docker/run_mv_image_list_to_depth.py b/third-party/video_to_data/reconstruction/modules/v2d_foundation_stereo/docker/run_mv_image_list_to_depth.py new file mode 100644 index 0000000000000000000000000000000000000000..05d2bb2a9268a4081e1759c7e65cc162a70d70e3 --- /dev/null +++ b/third-party/video_to_data/reconstruction/modules/v2d_foundation_stereo/docker/run_mv_image_list_to_depth.py @@ -0,0 +1,76 @@ +# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 +from pathlib import Path + +from v2d.docker.container import run_in_container +from v2d.foundation_stereo.docker._config import IMAGE_NAME, MODULES_DIR + +_LIB_CONFIG = Path(__file__).parent.parent / "lib" / "mv_image_list_to_depth.yaml" + + +def run_mv_image_list_to_depth( + camera_params_path: str, + rgb_dir: str, + output_dir: str, + model_dir: str, + scale: float | None = None, + config_path: str = str(_LIB_CONFIG), + dev: bool = False, +) -> None: + inputs = { + "camera_params_path": camera_params_path, + "rgb_dir": rgb_dir, + "config_path": config_path, + } + outputs = { + "output_dir": output_dir, + "model_dir": model_dir, + } + + extra_args: dict = {} + if scale is not None: + extra_args["scale"] = scale + + run_in_container( + image=IMAGE_NAME, + module="v2d.foundation_stereo.lib.mv_image_list_to_depth", + inputs=inputs, + outputs=outputs, + extra_args=extra_args or None, + dev=dev, + modules_dir=MODULES_DIR, + gpus=True, + env={"PYTHONUNBUFFERED": "1"}, + ) + + +if __name__ == "__main__": + import argparse + + parser = argparse.ArgumentParser( + description="Multi-view stereo depth estimation with Foundation Stereo TRT" + ) + parser.add_argument("--camera_params_path", type=str, required=True, + help="Path to EDEX file with camera calibration") + parser.add_argument("--rgb_dir", type=str, required=True, + help="Root directory containing per-camera image folders") + parser.add_argument("--output_dir", type=str, required=True, + help="Output directory for depth and intrinsics") + parser.add_argument("--model_dir", type=str, required=True, + help="Directory containing Foundation Stereo ONNX/engine") + parser.add_argument("--scale", type=float, default=None, + help="Scale factor for output resolution (e.g. 0.5 for half)") + parser.add_argument("--config_path", type=str, default=str(_LIB_CONFIG), + help="Path to config YAML") + parser.add_argument("--dev", action="store_true") + args = parser.parse_args() + + run_mv_image_list_to_depth( + camera_params_path=args.camera_params_path, + rgb_dir=args.rgb_dir, + output_dir=args.output_dir, + model_dir=args.model_dir, + scale=args.scale, + config_path=args.config_path, + dev=args.dev, + ) diff --git a/third-party/video_to_data/reconstruction/modules/v2d_foundation_stereo/docker/run_shell.py b/third-party/video_to_data/reconstruction/modules/v2d_foundation_stereo/docker/run_shell.py new file mode 100644 index 0000000000000000000000000000000000000000..f087ff9c8496a113bdd84858c9e5a5c80296209f --- /dev/null +++ b/third-party/video_to_data/reconstruction/modules/v2d_foundation_stereo/docker/run_shell.py @@ -0,0 +1,27 @@ +# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 +import subprocess +import os +from v2d.foundation_stereo.docker._config import IMAGE_NAME, MODULES_DIR + + +def run_shell(dev: bool = False) -> None: + cmd = [ + "docker", "run", "-it", "--rm", + "--gpus", "all", + "--user", f"{os.getuid()}:{os.getgid()}", + "-e", "HOME=/tmp", + ] + if dev: + cmd += ["-v", f"{MODULES_DIR}:/workspace"] + cmd += [IMAGE_NAME, "bash"] + subprocess.run(cmd, check=True) + + +if __name__ == "__main__": + import argparse + + parser = argparse.ArgumentParser(description="Run shell in v2d_foundation_stereo container") + parser.add_argument("--dev", action="store_true", help="Mount local modules for development") + args = parser.parse_args() + run_shell(dev=args.dev) diff --git a/third-party/video_to_data/reconstruction/modules/v2d_foundation_stereo/lib/__init__.py b/third-party/video_to_data/reconstruction/modules/v2d_foundation_stereo/lib/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..52a7a9daf028f654d6a02f65c99cc609a57b492f --- /dev/null +++ b/third-party/video_to_data/reconstruction/modules/v2d_foundation_stereo/lib/__init__.py @@ -0,0 +1,2 @@ +# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 diff --git a/third-party/video_to_data/reconstruction/modules/v2d_foundation_stereo/lib/download_weights.py b/third-party/video_to_data/reconstruction/modules/v2d_foundation_stereo/lib/download_weights.py new file mode 100644 index 0000000000000000000000000000000000000000..d028b8d44b781fa4a1e7bee94191fdd9c63fbbf0 --- /dev/null +++ b/third-party/video_to_data/reconstruction/modules/v2d_foundation_stereo/lib/download_weights.py @@ -0,0 +1,35 @@ +# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 +"""Download Foundation Stereo ONNX model from NVIDIA NGC. + +The TensorRT engine is compiled at runtime (GPU-architecture-specific). +""" +import argparse +import os +import urllib.request + +ONNX_FILENAME = "deployable_foundationstereo_small_576x960_v2.0.onnx" +ONNX_URL = ( + "https://api.ngc.nvidia.com/v2/models/org/nvidia/team/tao/" + f"foundationstereo/deployable_v2.0/files?redirect=true&path={ONNX_FILENAME}" +) + + +def download_weights(output_dir: str): + os.makedirs(output_dir, exist_ok=True) + dest = os.path.join(output_dir, ONNX_FILENAME) + + if os.path.exists(dest): + print(f"ONNX already exists at {dest}, skipping download.") + return + + print(f"Downloading Foundation Stereo ONNX to {dest} ...") + urllib.request.urlretrieve(ONNX_URL, dest) + print(f"Download complete: {dest}") + + +if __name__ == "__main__": + parser = argparse.ArgumentParser(description="Download Foundation Stereo ONNX model") + parser.add_argument("--output_dir", type=str, required=True, help="Output directory for model files") + args = parser.parse_args() + download_weights(args.output_dir) diff --git a/third-party/video_to_data/reconstruction/modules/v2d_foundation_stereo/lib/export_engine.py b/third-party/video_to_data/reconstruction/modules/v2d_foundation_stereo/lib/export_engine.py new file mode 100644 index 0000000000000000000000000000000000000000..a5baef7fa5a02c380e5a18a29bfe881d8aab7822 --- /dev/null +++ b/third-party/video_to_data/reconstruction/modules/v2d_foundation_stereo/lib/export_engine.py @@ -0,0 +1,141 @@ +# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 +"""Export Foundation Stereo ONNX model to a TensorRT engine. + +The engine filename is versioned by TensorRT version + GPU SM to allow caching +across multiple GPU architectures and TRT versions. +""" + +import os +import subprocess + +import tensorrt as trt +from cuda.bindings import runtime as cuda_runtime + +TRTEXEC_PATH = '/usr/src/tensorrt/bin/trtexec' +BASE_MODEL_NAME = 'deployable_foundationstereo_small_576x960_v2.0' + + +def _get_gpu_sm() -> tuple[int, int]: + """Return (major, minor) GPU compute capability of the current device. + + Tries cuda.bindings first; falls back to nvidia-smi if the runtime API + returns an error (e.g. in CUDA forward-compatibility mode). + """ + try: + cuda_runtime.cudaFree(0) + err, device_id = cuda_runtime.cudaGetDevice() + if err == cuda_runtime.cudaError_t.cudaSuccess and device_id is not None: + err, props = cuda_runtime.cudaGetDeviceProperties(int(device_id)) + if err == cuda_runtime.cudaError_t.cudaSuccess: + return props.major, props.minor + except Exception: + pass + + # Fallback: parse compute capability from nvidia-smi + result = subprocess.run( + ['nvidia-smi', '--query-gpu=compute_cap', '--format=csv,noheader'], + capture_output=True, text=True, + ) + if result.returncode == 0 and result.stdout.strip(): + cap = result.stdout.strip().split('\n')[0] + major, minor = cap.split('.') + return int(major), int(minor) + + raise RuntimeError( + "Cannot determine GPU SM version via cuda.bindings or nvidia-smi. " + "Ensure a GPU is available." + ) + + +def get_versioned_engine_filename(base_model_name: str = BASE_MODEL_NAME) -> str: + """Return a versioned engine filename encoding TRT version and GPU SM. + + Format: {model}_{trt_major}_{trt_minor}_{trt_patch}_{trt_build}_sm_{major}_{minor}.engine + """ + parts = trt.__version__.split('.') + parts += ['0'] * (4 - len(parts)) + trt_major, trt_minor, trt_patch, trt_build = parts[:4] + + sm_major, sm_minor = _get_gpu_sm() + + return ( + f"{base_model_name}_{trt_major}_{trt_minor}_{trt_patch}_{trt_build}" + f"_sm_{sm_major}_{sm_minor}.engine" + ) + + +def get_engine_path(model_dir: str) -> str: + """Return the full path to the versioned engine file in model_dir.""" + return os.path.join(model_dir, get_versioned_engine_filename()) + + +def export_engine(onnx_path: str, output_dir: str, force: bool = False) -> str: + """Convert Foundation Stereo ONNX to a TensorRT engine. + + Args: + onnx_path: Path to the ONNX file. + output_dir: Directory where the .engine file will be saved. + force: Rebuild even if the engine already exists. + + Returns: + Path to the generated engine file. + """ + if not os.path.exists(onnx_path): + raise FileNotFoundError(f"ONNX not found: {onnx_path}") + + os.makedirs(output_dir, exist_ok=True) + engine_path = get_engine_path(output_dir) + + if os.path.exists(engine_path) and not force: + print(f"Engine already exists (skipping): {engine_path}") + return engine_path + + cmd = [ + TRTEXEC_PATH, + f'--onnx={onnx_path}', + f'--saveEngine={engine_path}', + '--noDataTransfers', + ] + + print(f"Building TensorRT engine (this may take several minutes)...") + print(f"Command: {' '.join(cmd)}") + + result = subprocess.run(cmd, capture_output=False, text=True) + if result.returncode != 0: + raise RuntimeError( + f"trtexec failed (exit {result.returncode}). " + "Check GPU memory, TRT version, and ONNX compatibility." + ) + + print(f"Engine saved: {engine_path}") + return engine_path + + +def ensure_engine(model_dir: str) -> str: + """Return an engine path, auto-exporting from ONNX if the engine is missing. + + Args: + model_dir: Directory containing the ONNX and (optionally) the engine. + + Returns: + Path to a valid TensorRT engine file. + + Raises: + FileNotFoundError: If neither engine nor ONNX is present. + RuntimeError: If trtexec fails. + """ + engine_path = get_engine_path(model_dir) + if os.path.exists(engine_path): + return engine_path + + onnx_filename = f"{BASE_MODEL_NAME}.onnx" + onnx_path = os.path.join(model_dir, onnx_filename) + if not os.path.exists(onnx_path): + raise FileNotFoundError( + f"Neither engine nor ONNX found in {model_dir}.\n" + f"Run download.sh to download the ONNX first." + ) + + print(f"Engine not found — exporting from ONNX: {onnx_path}") + return export_engine(onnx_path, model_dir) diff --git a/third-party/video_to_data/reconstruction/modules/v2d_foundation_stereo/lib/image_list_to_depth.py b/third-party/video_to_data/reconstruction/modules/v2d_foundation_stereo/lib/image_list_to_depth.py new file mode 100644 index 0000000000000000000000000000000000000000..c6dc5ebfbedf3f18bd12da292fd7f37fb2f81d6e --- /dev/null +++ b/third-party/video_to_data/reconstruction/modules/v2d_foundation_stereo/lib/image_list_to_depth.py @@ -0,0 +1,233 @@ +# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 +"""Foundation Stereo: process a synchronized stereo image directory pair to depth maps. + +Takes two directories of images with matching filenames (left_dir and right_dir), +runs Foundation Stereo TensorRT inference on each pair, and writes: + - {depth_folder}/{stem}.png -- 16-bit inverse-depth PNG (DepthImage format) + - {intrinsics_folder}/{stem}.json -- CameraIntrinsics JSON + +Camera calibration must be supplied either as a JSON file or as individual args. + +Usage: + python -m v2d.foundation_stereo.lib.image_list_to_depth \ + --left_dir /data/left \ + --right_dir /data/right \ + --depth_folder /data/depth \ + --intrinsics_folder /data/intrinsics \ + --calibration_file /data/calibration.json \ + --model_dir /data/models + + # process a subset of frames (for parallel workers): + python -m v2d.foundation_stereo.lib.image_list_to_depth ... --start_idx 0 --end_idx 505 + python -m v2d.foundation_stereo.lib.image_list_to_depth ... --start_idx 505 --end_idx 1010 +""" + +import argparse +import json +import os +from pathlib import Path + +import cv2 +import numpy as np + +from v2d.common.datatypes import CameraIntrinsics, DepthImage +from v2d.common.video import FrameSource, FrameWriter +from v2d.foundation_stereo.lib.export_engine import ensure_engine +from v2d.foundation_stereo.lib.trt_inference import ( + FoundationStereoInference, + disparity_to_depth, +) + +_inference: FoundationStereoInference | None = None + + +def _get_inference(model_dir: str) -> FoundationStereoInference: + global _inference + if _inference is None: + engine_path = ensure_engine(model_dir) + _inference = FoundationStereoInference(engine_path) + return _inference + + +def _load_calibration(args) -> dict: + """Return calibration dict with keys: fx, fy, cx, cy, baseline.""" + if args.calibration_file: + with open(args.calibration_file) as f: + cal = json.load(f) + required = {'fx', 'fy', 'cx', 'cy', 'baseline'} + missing = required - cal.keys() + if missing: + raise ValueError(f"calibration_file is missing keys: {missing}") + return cal + + for attr in ('fx', 'fy', 'cx', 'cy', 'baseline'): + if getattr(args, attr) is None: + raise ValueError( + f"--{attr} is required when --calibration_file is not provided." + ) + return { + 'fx': args.fx, + 'fy': args.fy, + 'cx': args.cx, + 'cy': args.cy, + 'baseline': args.baseline, + } + + +def image_list_to_depth( + left_dir: str, + right_dir: str, + depth_folder: str, + intrinsics_folder: str, + calibration: dict, + model_dir: str, + start_idx: int = 0, + end_idx: int | None = None, + scale: float = 1.0, +): + """Process image pairs from left_dir / right_dir and write outputs. + + start_idx / end_idx slice the sorted file list, enabling parallel workers + to process non-overlapping frame ranges concurrently. + + scale: if != 1.0, images are resized before inference and outputs are at + the scaled resolution. The calibration dict should already reflect the + scaled intrinsics. + + ``depth_folder`` is auto-detected: if it ends in ``.h5``, depth maps are + packed into an HDF5 file (uint16 inverse-depth). Otherwise they are + written as individual PNGs in a directory. + """ + os.makedirs(intrinsics_folder, exist_ok=True) + + fx = float(calibration['fx']) + fy = float(calibration['fy']) + cx = float(calibration['cx']) + cy = float(calibration['cy']) + baseline = float(calibration['baseline']) + + inference = _get_inference(model_dir) + + left_source = FrameSource.from_path(left_dir) + right_source = FrameSource.from_path(right_dir) + + if left_source.n_frames != right_source.n_frames: + print(f" [warn] frame count mismatch: left={left_source.n_frames}, " + f"right={right_source.n_frames}") + + right_stem_to_idx = {s: i for i, s in enumerate(right_source.stems)} + left_stems = left_source.stems[start_idx:end_idx] + + is_png_output = Path(depth_folder).suffix.lower() not in (".h5", ".hdf5") + depth_writer = FrameWriter.from_path(depth_folder) + processed = 0 + skipped = 0 + + try: + for left_idx, stem in enumerate(left_stems, start=start_idx): + if is_png_output: + out_path = os.path.join(depth_folder, f"{stem}.png") + if os.path.exists(out_path): + skipped += 1 + continue + + if stem not in right_stem_to_idx: + print(f" [skip] no matching right frame for: {stem}") + skipped += 1 + continue + + right_idx = right_stem_to_idx[stem] + + try: + left_image = left_source[left_idx] + right_image = right_source[right_idx] + except Exception as e: + print(f" [skip] failed to read frame {stem}: {e}") + skipped += 1 + continue + + left_bgr = cv2.cvtColor(left_image, cv2.COLOR_RGB2BGR) + right_bgr = cv2.cvtColor(right_image, cv2.COLOR_RGB2BGR) + + if scale != 1.0: + h, w = left_bgr.shape[:2] + new_w = int(w * scale) + new_h = int(h * scale) + interp = cv2.INTER_AREA if scale < 1.0 else cv2.INTER_CUBIC + left_bgr = cv2.resize(left_bgr, (new_w, new_h), interpolation=interp) + right_bgr = cv2.resize(right_bgr, (new_w, new_h), interpolation=interp) + + disparity_px, _ = inference.infer(left_bgr, right_bgr) + depth_m = disparity_to_depth(disparity_px, fx, baseline) + + depth_img = DepthImage(depth=depth_m) + depth_uint16 = np.array(depth_img.to_pil_image(), dtype=np.uint16) + depth_writer.write_frame(depth_uint16, stem=stem) + + h, w = left_bgr.shape[:2] + intrinsics = CameraIntrinsics(fx=fx, fy=fy, cx=cx, cy=cy, width=w, height=h) + intrinsics.save(os.path.join(intrinsics_folder, f"{stem}.json")) + + processed += 1 + if processed % 10 == 0: + print(f" processed {processed} pairs...") + finally: + depth_writer.close() + + print(f"Done. processed={processed}, skipped={skipped}") + + +def main(): + parser = argparse.ArgumentParser( + description="Foundation Stereo: image list to depth maps" + ) + parser.add_argument('--left_dir', required=True, + help='Directory of left camera images') + parser.add_argument('--right_dir', required=True, + help='Directory of right camera images (same filenames as left_dir)') + parser.add_argument('--depth_folder', required=True, + help='Output directory for depth PNG files') + parser.add_argument('--intrinsics_folder', required=True, + help='Output directory for camera intrinsics JSON files') + + cal_group = parser.add_mutually_exclusive_group(required=True) + cal_group.add_argument('--calibration_file', + help='JSON file with keys: fx, fy, cx, cy, baseline') + cal_group.add_argument('--fx', type=float, help='Focal length x (pixels)') + + parser.add_argument('--fy', type=float, help='Focal length y (pixels)') + parser.add_argument('--cx', type=float, help='Principal point x (pixels)') + parser.add_argument('--cy', type=float, help='Principal point y (pixels)') + parser.add_argument('--baseline', type=float, help='Stereo baseline (meters)') + + parser.add_argument('--model_dir', required=True, + help='Directory containing ONNX/engine files') + parser.add_argument('--start_idx', type=int, default=0, + help='Index of first frame to process, inclusive (default: 0)') + parser.add_argument('--end_idx', type=int, default=None, + help='Index of last frame to process, exclusive (default: all)') + + args = parser.parse_args() + + if args.fx is not None: + for attr in ('fy', 'cx', 'cy', 'baseline'): + if getattr(args, attr) is None: + parser.error(f"--{attr} is required when using individual calibration args") + + calibration = _load_calibration(args) + + image_list_to_depth( + left_dir=args.left_dir, + right_dir=args.right_dir, + depth_folder=args.depth_folder, + intrinsics_folder=args.intrinsics_folder, + calibration=calibration, + model_dir=args.model_dir, + start_idx=args.start_idx, + end_idx=args.end_idx, + ) + + +if __name__ == '__main__': + main() diff --git a/third-party/video_to_data/reconstruction/modules/v2d_foundation_stereo/lib/image_to_depth.py b/third-party/video_to_data/reconstruction/modules/v2d_foundation_stereo/lib/image_to_depth.py new file mode 100644 index 0000000000000000000000000000000000000000..1f87bf8b9d0acecfe6a8e7c742372d3a074055ee --- /dev/null +++ b/third-party/video_to_data/reconstruction/modules/v2d_foundation_stereo/lib/image_to_depth.py @@ -0,0 +1,127 @@ +# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 +"""Foundation Stereo: process a single stereo image pair to a depth map. + +Usage: + python -m v2d.foundation_stereo.lib.image_to_depth \ + --left_image_path /data/left/frame.jpg \ + --right_image_path /data/right/frame.jpg \ + --depth_path /data/depth/frame.png \ + --intrinsics_path /data/intrinsics/frame.json \ + --calibration_file /data/calibration.json \ + --model_dir /data/models +""" + +import argparse +import json +import os + +import cv2 + +from v2d.common.datatypes import CameraIntrinsics, DepthImage +from v2d.foundation_stereo.lib.export_engine import ensure_engine +from v2d.foundation_stereo.lib.trt_inference import FoundationStereoInference, disparity_to_depth + +_inference: FoundationStereoInference | None = None + + +def _get_inference(model_dir: str) -> FoundationStereoInference: + global _inference + if _inference is None: + engine_path = ensure_engine(model_dir) + _inference = FoundationStereoInference(engine_path) + return _inference + + +def _load_calibration(args) -> dict: + if args.calibration_file: + with open(args.calibration_file) as f: + return json.load(f) + return { + 'fx': args.fx, + 'fy': args.fy, + 'cx': args.cx, + 'cy': args.cy, + 'baseline': args.baseline, + } + + +def image_to_depth( + left_image_path: str, + right_image_path: str, + depth_path: str, + intrinsics_path: str, + calibration: dict, + model_dir: str, +): + left_image = cv2.imread(left_image_path, cv2.IMREAD_COLOR) + right_image = cv2.imread(right_image_path, cv2.IMREAD_COLOR) + if left_image is None: + raise FileNotFoundError(f"Cannot read left image: {left_image_path}") + if right_image is None: + raise FileNotFoundError(f"Cannot read right image: {right_image_path}") + + inference = _get_inference(model_dir) + disparity_px, _ = inference.infer(left_image, right_image) + + fx = float(calibration['fx']) + fy = float(calibration['fy']) + cx = float(calibration['cx']) + cy = float(calibration['cy']) + baseline_m = float(calibration['baseline']) + + depth_m = disparity_to_depth(disparity_px, fx, baseline_m) + + os.makedirs(os.path.dirname(depth_path) or '.', exist_ok=True) + DepthImage(depth=depth_m).to_pil_image().save(depth_path) + + os.makedirs(os.path.dirname(intrinsics_path) or '.', exist_ok=True) + h, w = left_image.shape[:2] + intrinsics = CameraIntrinsics(fx=fx, fy=fy, cx=cx, cy=cy, width=w, height=h) + intrinsics.save(intrinsics_path) + + print(f"Saved depth: {depth_path}") + print(f"Saved intrinsics: {intrinsics_path}") + + +def main(): + parser = argparse.ArgumentParser( + description="Foundation Stereo: single stereo pair to depth" + ) + parser.add_argument('--left_image_path', required=True) + parser.add_argument('--right_image_path', required=True) + parser.add_argument('--depth_path', required=True, help='Output depth PNG path') + parser.add_argument('--intrinsics_path', required=True, help='Output intrinsics JSON path') + + cal_group = parser.add_mutually_exclusive_group(required=True) + cal_group.add_argument('--calibration_file', + help='JSON file with keys: fx, fy, cx, cy, baseline') + cal_group.add_argument('--fx', type=float) + + parser.add_argument('--fy', type=float) + parser.add_argument('--cx', type=float) + parser.add_argument('--cy', type=float) + parser.add_argument('--baseline', type=float) + + parser.add_argument('--model_dir', required=True, + help='Directory containing ONNX/engine files') + + args = parser.parse_args() + + if args.fx is not None: + for attr in ('fy', 'cx', 'cy', 'baseline'): + if getattr(args, attr) is None: + parser.error(f"--{attr} is required when using individual calibration args") + + image_to_depth( + left_image_path=args.left_image_path, + right_image_path=args.right_image_path, + depth_path=args.depth_path, + intrinsics_path=args.intrinsics_path, + calibration=_load_calibration(args), + model_dir=args.model_dir, + ) + + +if __name__ == '__main__': + main() diff --git a/third-party/video_to_data/reconstruction/modules/v2d_foundation_stereo/lib/mv_image_list_to_depth.py b/third-party/video_to_data/reconstruction/modules/v2d_foundation_stereo/lib/mv_image_list_to_depth.py new file mode 100644 index 0000000000000000000000000000000000000000..b23bacdfa1a00a25ad5e573e7069dc4cbddd5b62 --- /dev/null +++ b/third-party/video_to_data/reconstruction/modules/v2d_foundation_stereo/lib/mv_image_list_to_depth.py @@ -0,0 +1,125 @@ +# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 +"""Multi-view stereo depth estimation using Foundation Stereo TRT. + +Iterates over stereo pairs from a rig config, reads calibration from EDEX, +and runs TRT inference per pair. Supports optional scale for output resolution. +""" + +from __future__ import annotations + +import argparse +from pathlib import Path + +import numpy as np + +from v2d.mv.rig import RigConfig, CameraParam + +from .image_list_to_depth import image_list_to_depth + + +def baseline_from_stereo_pair(left_param: CameraParam, right_param: CameraParam) -> float: + """Extract stereo baseline (meters) from rectified camera parameters. + + For rectified pairs, the right camera's projection matrix P encodes: + P_right[0, 3] = -fx * baseline + """ + if right_param.P is None: + raise ValueError("Right camera has no projection matrix P; cannot extract baseline") + fx = right_param.P[0, 0] + tx = right_param.P[0, 3] + return abs(tx) / fx + + +def mv_image_list_to_depth_from_config(cfg): + """Run stereo depth estimation for each stereo pair in the rig.""" + rig = RigConfig(cfg.rig_config, camera_params_path=cfg.camera_params_path) + + scale = cfg.get("scale", 1.0) + + for pair in rig.get_stereo_pairs(): + print(f"\n=== Stereo pair: {pair.name} ===") + + left_param = pair.left.param + right_param = pair.right.param + if left_param is None or right_param is None: + raise ValueError( + f"Missing camera params for pair '{pair.name}'; " + "ensure camera_params_path points to a valid EDEX" + ) + + baseline = baseline_from_stereo_pair(left_param, right_param) + print(f" Baseline: {baseline:.4f} m") + + if scale != 1.0: + left_param = left_param.scale(scale) + right_param = right_param.scale(scale) + print(f" Scale: {scale} -> resolution {left_param.resolution}") + + fx = float(left_param.K[0, 0]) + fy = float(left_param.K[1, 1]) + cx = float(left_param.K[0, 2]) + cy = float(left_param.K[1, 2]) + + calibration = { + "fx": fx, "fy": fy, "cx": cx, "cy": cy, "baseline": baseline, + } + + left_dir = cfg.rgb_path_template.format(cam_name=pair.left.name) + right_dir = cfg.rgb_path_template.format(cam_name=pair.right.name) + + depth_folder = cfg.depth_path_template.format(cam_name=pair.left.name) + intrinsics_folder = cfg.intrinsics_path_template.format(cam_name=pair.left.name) + + print(f" Left: {left_dir}") + print(f" Right: {right_dir}") + print(f" Depth: {depth_folder}") + print(f" Calibration: fx={fx:.1f} fy={fy:.1f} cx={cx:.1f} cy={cy:.1f} b={baseline:.4f}") + + image_list_to_depth( + left_dir=left_dir, + right_dir=right_dir, + depth_folder=depth_folder, + intrinsics_folder=intrinsics_folder, + calibration=calibration, + model_dir=cfg.model_dir, + scale=scale, + ) + + print(f" Done: {pair.name}") + + +if __name__ == "__main__": + from omegaconf import OmegaConf + + parser = argparse.ArgumentParser( + description="Multi-view stereo depth estimation with Foundation Stereo TRT" + ) + parser.add_argument("--camera_params_path", type=str, required=True, + help="Path to EDEX file with camera calibration") + parser.add_argument("--rgb_dir", type=str, required=True, + help="Root directory containing per-camera input frames") + parser.add_argument("--output_dir", type=str, required=True, + help="Output directory for depth and intrinsics") + parser.add_argument("--model_dir", type=str, required=True, + help="Directory containing Foundation Stereo ONNX/engine") + parser.add_argument("--scale", type=float, default=None, + help="Scale factor for output resolution (e.g. 0.5 for half)") + parser.add_argument("--config_path", type=str, default=None, + help="Optional override config (merged on top of defaults)") + args = parser.parse_args() + + cfg = OmegaConf.load(Path(__file__).parent / "mv_image_list_to_depth.yaml") + if args.config_path: + cfg = OmegaConf.merge(cfg, OmegaConf.load(args.config_path)) + overrides: dict = { + "camera_params_path": args.camera_params_path, + "rgb_dir": args.rgb_dir, + "output_dir": args.output_dir, + "model_dir": args.model_dir, + } + if args.scale is not None: + overrides["scale"] = args.scale + + cfg = OmegaConf.merge(cfg, overrides) + mv_image_list_to_depth_from_config(cfg) diff --git a/third-party/video_to_data/reconstruction/modules/v2d_foundation_stereo/lib/mv_image_list_to_depth.yaml b/third-party/video_to_data/reconstruction/modules/v2d_foundation_stereo/lib/mv_image_list_to_depth.yaml new file mode 100644 index 0000000000000000000000000000000000000000..c0f141059c697d7c8e64dafb61e35837244153ca --- /dev/null +++ b/third-party/video_to_data/reconstruction/modules/v2d_foundation_stereo/lib/mv_image_list_to_depth.yaml @@ -0,0 +1,14 @@ +# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 +camera_params_path: ??? +rgb_dir: ??? +output_dir: ??? +model_dir: ??? + +rig_config: stereo-4 + +scale: 0.5 + +rgb_path_template: "${rgb_dir}/{cam_name}" +depth_path_template: "${output_dir}/{cam_name}/depth" +intrinsics_path_template: "${output_dir}/{cam_name}/intrinsics" diff --git a/third-party/video_to_data/reconstruction/modules/v2d_foundation_stereo/lib/pyproject.toml b/third-party/video_to_data/reconstruction/modules/v2d_foundation_stereo/lib/pyproject.toml new file mode 100644 index 0000000000000000000000000000000000000000..dce7671589539cd596f2f47c264e1d13a859c0cc --- /dev/null +++ b/third-party/video_to_data/reconstruction/modules/v2d_foundation_stereo/lib/pyproject.toml @@ -0,0 +1,23 @@ +# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 +[build-system] +requires = ["setuptools>=68.0", "wheel"] +build-backend = "setuptools.build_meta" + +[project] +name = "v2d-foundation-stereo-lib" +version = "0.1.0" +description = "Foundation Stereo depth estimation library (TensorRT)" +requires-python = ">=3.10" +dependencies = [ + "numpy", + "Pillow", + "opencv-python-headless", + "v2d-common", +] + +[tool.setuptools] +packages = ["v2d.foundation_stereo.lib"] + +[tool.setuptools.package-dir] +"v2d.foundation_stereo.lib" = "." diff --git a/third-party/video_to_data/reconstruction/modules/v2d_foundation_stereo/lib/trt_inference.py b/third-party/video_to_data/reconstruction/modules/v2d_foundation_stereo/lib/trt_inference.py new file mode 100644 index 0000000000000000000000000000000000000000..a324151524fef3f568477a253ac22a3dd3ea1c32 --- /dev/null +++ b/third-party/video_to_data/reconstruction/modules/v2d_foundation_stereo/lib/trt_inference.py @@ -0,0 +1,319 @@ +# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 +"""TensorRT-based Foundation Stereo inference for stereo depth estimation. + +Adapted from real2sim's tensorrt_inference_base.py, stereo_inference_base.py, +and foundation_stereo.py into a single self-contained module. +""" + +import numpy as np +import cv2 +import tensorrt as trt +from cuda.bindings import driver as cuda_driver +from cuda.bindings import runtime as cuda_runtime + + +# Foundation Stereo model constants +MODEL_INPUT_HEIGHT = 576 +MODEL_INPUT_WIDTH = 960 +BASE_MODEL_NAME = 'deployable_foundationstereo_small_576x960_v2.0' + +# ImageNet normalization parameters used during training +IMAGENET_MEAN = [123.675, 116.28, 103.53] +IMAGENET_STDDEV = [58.395, 57.12, 57.375] + +# Stereo depth conversion constants +MIN_DISPARITY_THRESHOLD = 0.01 +MAX_DEPTH_METERS = 655.35 # clip before inverse-depth encoding; beyond this quantization error grows large + + +class FoundationStereoInference: + """TensorRT-based Foundation Stereo inference engine. + + Takes a stereo image pair (left + right BGR images) and returns a metric + depth map (in meters) in the original image resolution. + + Usage: + with FoundationStereoInference(engine_path) as inference: + depth = inference.run(left_image, right_image, fx, baseline) + """ + + def __init__(self, engine_file_path: str, verbose: bool = False): + self.engine_file_path = engine_file_path + self.verbose = verbose + self._initialized = False + + self._check_cuda() + self._init_trt() + self._load_engine() + self._setup_bindings() + self._initialized = True + + if verbose: + print(f"FoundationStereoInference initialized: {engine_file_path}") + print(f"TensorRT version: {trt.__version__}") + print(f"Input shapes: {self.input_shapes}") + print(f"Output shapes: {self.output_shapes}") + + # ------------------------------------------------------------------ + # Context manager + # ------------------------------------------------------------------ + + def __enter__(self): + return self + + def __exit__(self, exc_type, exc_val, exc_tb): + self.cleanup() + + def __del__(self): + self.cleanup() + + def cleanup(self): + if not self._initialized: + return + try: + for mem_info in self._inputs.values(): + cuda_runtime.cudaFree(mem_info[0]) + for mem_info in self._outputs.values(): + cuda_runtime.cudaFree(mem_info[0]) + if hasattr(self, '_context'): + del self._context + if hasattr(self, '_engine'): + del self._engine + if hasattr(self, '_stream'): + cuda_runtime.cudaStreamDestroy(self._stream) + except Exception as e: + print(f"Warning: error during CUDA cleanup: {e}") + finally: + self._initialized = False + + # ------------------------------------------------------------------ + # Initialization helpers + # ------------------------------------------------------------------ + + def _check_cuda(self): + err, = cuda_driver.cuInit(0) + if err != cuda_driver.CUresult.CUDA_SUCCESS: + raise RuntimeError(f"CUDA init failed: {err}") + err, count = cuda_driver.cuDeviceGetCount() + if count == 0: + raise RuntimeError("No CUDA devices found") + + def _init_trt(self): + self._logger = trt.Logger(trt.Logger.VERBOSE if self.verbose else trt.Logger.WARNING) + self._runtime = trt.Runtime(self._logger) + trt.init_libnvinfer_plugins(self._logger, "") + + def _load_engine(self): + try: + with open(self.engine_file_path, 'rb') as f: + self._engine = self._runtime.deserialize_cuda_engine(f.read()) + except Exception as e: + raise RuntimeError( + f"Failed to load TensorRT engine from {self.engine_file_path}: {e}" + ) from e + if self._engine is None: + raise RuntimeError( + f"TensorRT engine is None after loading {self.engine_file_path}. " + "Check TRT version compatibility." + ) + self._context = self._engine.create_execution_context() + # Set static input shapes + for i in range(self._engine.num_io_tensors): + name = self._engine.get_tensor_name(i) + if self._engine.get_tensor_mode(name) == trt.TensorIOMode.INPUT: + shape = self._engine.get_tensor_shape(name) + self._context.set_input_shape(name, shape) + + def _setup_bindings(self): + INPUT_NAMES = ['left_image', 'right_image'] + OUTPUT_NAMES = ['disparity'] + + self._inputs = {} + self._outputs = {} + self.input_shapes = {} + self.output_shapes = {} + + for i in range(self._engine.num_io_tensors): + name = self._engine.get_tensor_name(i) + shape = tuple(self._engine.get_tensor_shape(name)) + dtype = trt.nptype(self._engine.get_tensor_dtype(name)) + is_input = self._engine.get_tensor_mode(name) == trt.TensorIOMode.INPUT + + # Replace any -1 dims with 1 for memory allocation + alloc_shape = tuple(max(1, d) for d in shape) + volume = int(np.prod(alloc_shape)) + size = volume * np.dtype(dtype).itemsize + + err, ptr = cuda_runtime.cudaMalloc(size) + if err != cuda_runtime.cudaError_t.cudaSuccess: + raise RuntimeError(f"cudaMalloc failed for {name}: {err}") + + if is_input and name in INPUT_NAMES: + self._inputs[name] = (ptr, size, alloc_shape, dtype) + self.input_shapes[name] = shape + elif not is_input and name in OUTPUT_NAMES: + self._outputs[name] = (ptr, size, alloc_shape, dtype) + self.output_shapes[name] = shape + + err, self._stream = cuda_runtime.cudaStreamCreate() + if err != cuda_runtime.cudaError_t.cudaSuccess: + raise RuntimeError(f"cudaStreamCreate failed: {err}") + + # ------------------------------------------------------------------ + # Preprocessing + # ------------------------------------------------------------------ + + def preprocess_image(self, image: np.ndarray): + """Preprocess a BGR image for Foundation Stereo. + + Args: + image: BGR uint8 image (H×W×3) + + Returns: + (nchw_array, metadata) where nchw_array is float32 (1×3×576×960) + and metadata contains scale/padding info for coordinate transformation. + """ + h, w = image.shape[:2] + scale_w = MODEL_INPUT_WIDTH / w + scale_h = MODEL_INPUT_HEIGHT / h + scale = min(scale_w, scale_h) + + new_w = int(w * scale) + new_h = int(h * scale) + + interp = cv2.INTER_CUBIC if scale > 1.0 else cv2.INTER_AREA + resized = cv2.resize(image, (new_w, new_h), interpolation=interp) + + pad_w = MODEL_INPUT_WIDTH - new_w + pad_h = MODEL_INPUT_HEIGHT - new_h + padded = cv2.copyMakeBorder(resized, 0, pad_h, 0, pad_w, cv2.BORDER_REPLICATE) + + rgb = cv2.cvtColor(padded, cv2.COLOR_BGR2RGB).astype(np.float32) + for c in range(3): + rgb[:, :, c] = (rgb[:, :, c] - IMAGENET_MEAN[c]) / IMAGENET_STDDEV[c] + + nchw = np.ascontiguousarray(rgb.transpose(2, 0, 1)[np.newaxis]) # (1,3,H,W) + + metadata = { + 'scale': scale, + 'resized_w': new_w, + 'resized_h': new_h, + 'pad_w': pad_w, + 'pad_h': pad_h, + 'orig_w': w, + 'orig_h': h, + } + return nchw, metadata + + # ------------------------------------------------------------------ + # Inference + # ------------------------------------------------------------------ + + def _copy_to_device(self, name: str, array: np.ndarray): + if not array.flags.c_contiguous: + array = np.ascontiguousarray(array) + ptr, size, _, _ = self._inputs[name] + err, = cuda_runtime.cudaMemcpyAsync( + ptr, array.ctypes.data, size, + cuda_runtime.cudaMemcpyKind.cudaMemcpyHostToDevice, + self._stream, + ) + if err != cuda_runtime.cudaError_t.cudaSuccess: + raise RuntimeError(f"cudaMemcpyAsync H→D failed for {name}: {err}") + + def _copy_from_device(self, name: str) -> np.ndarray: + ptr, size, _, dtype = self._outputs[name] + runtime_shape = tuple(self._context.get_tensor_shape(name)) + result = np.empty(runtime_shape, dtype=dtype) + err, = cuda_runtime.cudaMemcpyAsync( + result.ctypes.data, ptr, size, + cuda_runtime.cudaMemcpyKind.cudaMemcpyDeviceToHost, + self._stream, + ) + if err != cuda_runtime.cudaError_t.cudaSuccess: + raise RuntimeError(f"cudaMemcpyAsync D→H failed for {name}: {err}") + return result + + def infer(self, left_image: np.ndarray, right_image: np.ndarray): + """Run stereo inference. + + Args: + left_image: BGR uint8 image (H×W×3) + right_image: BGR uint8 image (H×W×3), same size as left_image + + Returns: + (disparity, metadata) — float32 disparity in original image resolution + and preprocessing metadata from the left image. + """ + left_nchw, metadata = self.preprocess_image(left_image) + right_nchw, _ = self.preprocess_image(right_image) + + # Copy inputs + self._copy_to_device('left_image', left_nchw) + self._copy_to_device('right_image', right_nchw) + + # Set dynamic shapes and tensor addresses + for name, arr in [('left_image', left_nchw), ('right_image', right_nchw)]: + self._context.set_input_shape(name, arr.shape) + self._context.set_tensor_address(name, int(self._inputs[name][0])) + for name in self._outputs: + self._context.set_tensor_address(name, int(self._outputs[name][0])) + + # Execute + self._context.execute_async_v3(stream_handle=self._stream) + + # Retrieve output + raw_disparity = self._copy_from_device('disparity') + + # Synchronize + err, = cuda_runtime.cudaStreamSynchronize(self._stream) + if err != cuda_runtime.cudaError_t.cudaSuccess: + raise RuntimeError(f"cudaStreamSynchronize failed: {err}") + + # Collapse batch/channel dims → (H, W) + d = raw_disparity + if d.ndim == 4: + d = d[0] + if d.ndim == 3: + d = d[0] if d.shape[0] == 1 else d[:, :, 0] if d.shape[2] == 1 else d[0] + + # Transform back to original image coordinates + disparity = self._transform_to_original(d, metadata) + return disparity, metadata + + # ------------------------------------------------------------------ + # Postprocessing + # ------------------------------------------------------------------ + + def _transform_to_original(self, disparity: np.ndarray, metadata: dict) -> np.ndarray: + """Crop padding, scale disparity values, resize to original dims.""" + cropped = disparity[:metadata['resized_h'], :metadata['resized_w']] + scaled = cropped / metadata['scale'] + return cv2.resize( + scaled, + (metadata['orig_w'], metadata['orig_h']), + interpolation=cv2.INTER_LINEAR, + ) + + +def disparity_to_depth(disparity_px: np.ndarray, fx_px: float, baseline_m: float) -> np.ndarray: + """Convert a disparity map to metric depth in meters. + + Formula: depth_m = fx_px * baseline_m / disparity_px + + Args: + disparity_px: float32 disparity map (H×W) in pixels, at original image resolution + fx_px: focal length in pixels (x-axis) + baseline_m: stereo baseline in meters + + Returns: + float32 depth map in meters (H×W); invalid/zero-disparity pixels are 0. + """ + depth_m = np.zeros_like(disparity_px, dtype=np.float32) + valid = disparity_px > MIN_DISPARITY_THRESHOLD + if np.any(valid): + depth_m_vals = (fx_px * baseline_m) / disparity_px[valid] + depth_m_vals = np.clip(depth_m_vals, 0.0, MAX_DEPTH_METERS) + depth_m[valid] = depth_m_vals + return depth_m diff --git a/third-party/video_to_data/reconstruction/modules/v2d_geocalib/LICENSE b/third-party/video_to_data/reconstruction/modules/v2d_geocalib/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..10caffae439b956cdda2b1ded9ecbe51ac10befb --- /dev/null +++ b/third-party/video_to_data/reconstruction/modules/v2d_geocalib/LICENSE @@ -0,0 +1,15 @@ +# Apache License 2.0 + +Copyright 2025 NVIDIA CORPORATION + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. diff --git a/third-party/video_to_data/reconstruction/modules/v2d_geocalib/docker/Dockerfile b/third-party/video_to_data/reconstruction/modules/v2d_geocalib/docker/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..4a24ddd91cd3781eadb20ebe0a4cb7f8a7a1e9ee --- /dev/null +++ b/third-party/video_to_data/reconstruction/modules/v2d_geocalib/docker/Dockerfile @@ -0,0 +1,15 @@ +FROM pytorch/pytorch:2.5.1-cuda12.4-cudnn9-devel +ENV DEBIAN_FRONTEND=noninteractive +WORKDIR /app + +RUN apt-get update && apt-get install -y \ + libgl1 \ + libglib2.0-0 \ + git \ + ffmpeg \ + && rm -rf /var/lib/apt/lists/* + +COPY . /workspace + +RUN pip install -e /workspace/v2d_common -e /workspace/v2d_geocalib/lib + diff --git a/third-party/video_to_data/reconstruction/modules/v2d_geocalib/docker/__init__.py b/third-party/video_to_data/reconstruction/modules/v2d_geocalib/docker/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..a4d636226b9a4b5130dfd8e94f2cece5fd290e53 --- /dev/null +++ b/third-party/video_to_data/reconstruction/modules/v2d_geocalib/docker/__init__.py @@ -0,0 +1,3 @@ +# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 + diff --git a/third-party/video_to_data/reconstruction/modules/v2d_geocalib/docker/_config.py b/third-party/video_to_data/reconstruction/modules/v2d_geocalib/docker/_config.py new file mode 100644 index 0000000000000000000000000000000000000000..b8db3ea31dbdddf71a3f12be10b8cc30088ff8e5 --- /dev/null +++ b/third-party/video_to_data/reconstruction/modules/v2d_geocalib/docker/_config.py @@ -0,0 +1,7 @@ +# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 +import os + +IMAGE_NAME = "v2d_geocalib" +MODULES_DIR = os.path.abspath(os.path.join(os.path.dirname(os.path.abspath(__file__)), "..", "..")) + diff --git a/third-party/video_to_data/reconstruction/modules/v2d_geocalib/docker/build.py b/third-party/video_to_data/reconstruction/modules/v2d_geocalib/docker/build.py new file mode 100644 index 0000000000000000000000000000000000000000..479304b439d7ccd3c5c7f593b6da1be160abf809 --- /dev/null +++ b/third-party/video_to_data/reconstruction/modules/v2d_geocalib/docker/build.py @@ -0,0 +1,21 @@ +# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 +import os +import subprocess + +from v2d.geocalib.docker._config import IMAGE_NAME + + +current_dir = os.path.dirname(os.path.abspath(__file__)) +module_dir = os.path.join(current_dir, "..") +root_dir = os.path.join(module_dir, "..") +dockerfile_path = os.path.join(current_dir, "Dockerfile") + + +def build_docker_image() -> None: + subprocess.run(["docker", "build", "-t", IMAGE_NAME, "-f", dockerfile_path, root_dir], check=True) + + +if __name__ == "__main__": + build_docker_image() + diff --git a/third-party/video_to_data/reconstruction/modules/v2d_geocalib/docker/pyproject.toml b/third-party/video_to_data/reconstruction/modules/v2d_geocalib/docker/pyproject.toml new file mode 100644 index 0000000000000000000000000000000000000000..0ab9db2a5d0e142bdf035d2c68a457c32bedd5d2 --- /dev/null +++ b/third-party/video_to_data/reconstruction/modules/v2d_geocalib/docker/pyproject.toml @@ -0,0 +1,19 @@ +# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 +[build-system] +requires = ["setuptools>=68.0", "wheel"] +build-backend = "setuptools.build_meta" + +[project] +name = "v2d-geocalib-docker" +version = "0.1.0" +description = "Docker orchestration scripts for GeoCalib" +requires-python = ">=3.10" +dependencies = ["v2d-docker"] + +[tool.setuptools] +packages = ["v2d.geocalib.docker"] + +[tool.setuptools.package-dir] +"v2d.geocalib.docker" = "." + diff --git a/third-party/video_to_data/reconstruction/modules/v2d_geocalib/docker/run_download_weights.py b/third-party/video_to_data/reconstruction/modules/v2d_geocalib/docker/run_download_weights.py new file mode 100644 index 0000000000000000000000000000000000000000..6853bfb67dfbe214d11e1259920dab4c8a3aefac --- /dev/null +++ b/third-party/video_to_data/reconstruction/modules/v2d_geocalib/docker/run_download_weights.py @@ -0,0 +1,32 @@ +# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 +from v2d.docker.container import run_in_container +from v2d.geocalib.docker._config import IMAGE_NAME, MODULES_DIR + + +def run_download_weights( + output_dir: str, + weights: str = "pinhole", + dev: bool = False, +) -> None: + run_in_container( + image=IMAGE_NAME, + module="v2d.geocalib.lib.download_weights", + inputs={}, + outputs={"output_dir": output_dir}, + extra_args={"weights": weights}, + dev=dev, + modules_dir=MODULES_DIR, + gpus=True, + ) + + +if __name__ == "__main__": + import argparse + + parser = argparse.ArgumentParser(description="Download GeoCalib checkpoint") + parser.add_argument("--output_dir", required=True) + parser.add_argument("--weights", choices=("pinhole", "distorted"), default="pinhole") + parser.add_argument("--dev", action="store_true") + args = parser.parse_args() + run_download_weights(output_dir=args.output_dir, weights=args.weights, dev=args.dev) diff --git a/third-party/video_to_data/reconstruction/modules/v2d_geocalib/docker/run_video_to_calibration.py b/third-party/video_to_data/reconstruction/modules/v2d_geocalib/docker/run_video_to_calibration.py new file mode 100644 index 0000000000000000000000000000000000000000..7516eae617dfa3840f2e27eccec80b2144b0a524 --- /dev/null +++ b/third-party/video_to_data/reconstruction/modules/v2d_geocalib/docker/run_video_to_calibration.py @@ -0,0 +1,75 @@ +# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 +from v2d.docker.container import run_in_container +from v2d.geocalib.docker._config import IMAGE_NAME, MODULES_DIR + + +def run_video_to_calibration( + video_path: str, + intrinsics_path: str, + distortion_path: str, + gravity_path: str, + calibration_path: str, + weights_path: str | None = None, + weights: str = "pinhole", + camera_model: str = "pinhole", + num_samples: int = 8, + device: str | None = None, + dev: bool = False, +) -> None: + inputs = {"video_path": video_path} + if weights_path is not None: + inputs["weights_path"] = weights_path + run_in_container( + image=IMAGE_NAME, + module="v2d.geocalib.lib.video_to_calibration", + inputs=inputs, + outputs={ + "intrinsics_path": intrinsics_path, + "distortion_path": distortion_path, + "gravity_path": gravity_path, + "calibration_path": calibration_path, + }, + extra_args={ + "weights": weights, + "camera_model": camera_model, + "num_samples": num_samples, + "device": device, + }, + dev=dev, + modules_dir=MODULES_DIR, + gpus=True, + ) + + +if __name__ == "__main__": + import argparse + + parser = argparse.ArgumentParser(description="Estimate GeoCalib calibration from a video") + parser.add_argument("--video_path", required=True) + parser.add_argument("--intrinsics_path", required=True) + parser.add_argument("--distortion_path", required=True) + parser.add_argument("--gravity_path", required=True) + parser.add_argument("--calibration_path", required=True) + parser.add_argument("--weights_path", default=None) + parser.add_argument("--weights", choices=("pinhole", "distorted"), default="pinhole") + parser.add_argument("--camera_model", default="pinhole", + choices=("pinhole", "simple_radial", "radial", "simple_divisional")) + parser.add_argument("--num_samples", type=int, default=8) + parser.add_argument("--device", default=None) + parser.add_argument("--dev", action="store_true") + args = parser.parse_args() + run_video_to_calibration( + video_path=args.video_path, + intrinsics_path=args.intrinsics_path, + distortion_path=args.distortion_path, + gravity_path=args.gravity_path, + calibration_path=args.calibration_path, + weights_path=args.weights_path, + weights=args.weights, + camera_model=args.camera_model, + num_samples=args.num_samples, + device=args.device, + dev=args.dev, + ) + diff --git a/third-party/video_to_data/reconstruction/modules/v2d_geocalib/lib/__init__.py b/third-party/video_to_data/reconstruction/modules/v2d_geocalib/lib/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..a4d636226b9a4b5130dfd8e94f2cece5fd290e53 --- /dev/null +++ b/third-party/video_to_data/reconstruction/modules/v2d_geocalib/lib/__init__.py @@ -0,0 +1,3 @@ +# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 + diff --git a/third-party/video_to_data/reconstruction/modules/v2d_geocalib/lib/_geocalib.py b/third-party/video_to_data/reconstruction/modules/v2d_geocalib/lib/_geocalib.py new file mode 100644 index 0000000000000000000000000000000000000000..cdb9b9742c9e24b5e3014ff40ad08e38e366893c --- /dev/null +++ b/third-party/video_to_data/reconstruction/modules/v2d_geocalib/lib/_geocalib.py @@ -0,0 +1,203 @@ +# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 +"""GeoCalib model loader and serialization helpers.""" +from __future__ import annotations + +import os +from typing import Any + +import numpy as np +import torch + +from v2d.common.datatypes import CameraDistortion, CameraIntrinsics + + +_MODEL_CACHE: dict[tuple[str, str | None, str], object] = {} + + +def _scalar(value: Any) -> float: + if hasattr(value, "detach"): + value = value.detach().cpu().numpy() + arr = np.asarray(value) + return float(arr.reshape(-1)[0]) + + +def _array(value: Any) -> np.ndarray: + if hasattr(value, "detach"): + value = value.detach().cpu().numpy() + elif hasattr(value, "numpy"): + value = value.numpy() + return np.asarray(value, dtype=np.float64) + + +def _to_builtin(value: Any) -> Any: + if value is None: + return None + if hasattr(value, "detach"): + value = value.detach().cpu().numpy() + elif hasattr(value, "numpy"): + value = value.numpy() + if isinstance(value, np.ndarray): + if value.size == 1: + return float(value.reshape(-1)[0]) + return value.tolist() + if isinstance(value, np.generic): + return value.item() + if isinstance(value, dict): + return {k: _to_builtin(v) for k, v in value.items()} + return value + + +def _get_model(weights_path: str | None, weights: str, device: str): + cache_key = (weights, os.path.abspath(weights_path) if weights_path else None, device) + if cache_key in _MODEL_CACHE: + return _MODEL_CACHE[cache_key] + + if weights_path: + weights_path = os.path.abspath(weights_path) + if os.path.isdir(weights_path): + os.environ["TORCH_HOME"] = weights_path + model_weights = weights + elif os.path.isfile(weights_path): + model_weights = weights_path + else: + raise FileNotFoundError(f"GeoCalib weights path not found: {weights_path}") + else: + model_weights = weights + + from geocalib import GeoCalib + + print(f"Loading GeoCalib weights={model_weights!r} on {device}") + model = GeoCalib(weights=model_weights).to(device).eval() + _MODEL_CACHE[cache_key] = model + return model + + +def _camera_to_intrinsics(camera: Any) -> CameraIntrinsics: + size = _array(camera.size).reshape(-1, 2)[0] + focal = _array(camera.f).reshape(-1, 2)[0] + center = _array(camera.c).reshape(-1, 2)[0] + return CameraIntrinsics( + fx=float(focal[0]), + fy=float(focal[1]), + cx=float(center[0]), + cy=float(center[1]), + width=int(round(float(size[0]))), + height=int(round(float(size[1]))), + ) + + +def _camera_to_distortion(camera: Any, camera_model: str) -> CameraDistortion: + if camera_model == "pinhole" or not hasattr(camera, "dist"): + return CameraDistortion(model="pinhole", params=[]) + dist = _array(camera.dist).reshape(-1) + if hasattr(camera, "num_dist_params"): + dist = dist[: int(camera.num_dist_params())] + model = { + "simple_radial": "geocalib_simple_radial", + "radial": "geocalib_radial", + "simple_divisional": "geocalib_simple_divisional", + }.get(camera_model, f"geocalib_{camera_model}") + return CameraDistortion(model=model, params=[float(v) for v in dist]) + + +def _gravity_record(gravity: Any) -> dict: + vec = _array(gravity.vec3d).reshape(-1, 3)[0] + roll = _scalar(gravity.roll) + pitch = _scalar(gravity.pitch) + R = _array(gravity.R).reshape(-1, 3, 3)[0] + return { + "vector_camera": [float(v) for v in vec], + "roll_rad": roll, + "pitch_rad": pitch, + "roll_deg": float(np.degrees(roll)), + "pitch_deg": float(np.degrees(pitch)), + "rotation_matrix": R.tolist(), + } + + +def predict_calibration( + image: torch.Tensor, + weights_path: str | None, + weights: str = "pinhole", + camera_model: str = "pinhole", + device: str | None = None, +) -> tuple[CameraIntrinsics, CameraDistortion, dict]: + """Run GeoCalib on one image tensor in RGB CHW/BCHW [0, 1] format.""" + if device is None: + device = "cuda" if torch.cuda.is_available() else "cpu" + model = _get_model(weights_path, weights=weights, device=device) + image = image.to(device) + result = model.calibrate(image, camera_model=camera_model) + intrinsics = _camera_to_intrinsics(result["camera"]) + distortion = _camera_to_distortion(result["camera"], camera_model) + gravity = _gravity_record(result["gravity"]) + extra = { + "weights": weights, + "camera_model": camera_model, + "gravity": gravity, + "uncertainty": { + k: _to_builtin(v) + for k, v in result.items() + if "uncertainty" in k + }, + "covariance": _to_builtin(result.get("covariance")), + } + return intrinsics, distortion, extra + + +def aggregate_calibrations(records: list[dict]) -> tuple[CameraIntrinsics, CameraDistortion, dict]: + """Median intrinsics/distortion and normalized mean gravity over samples.""" + if not records: + raise ValueError("No GeoCalib records to aggregate") + + intrinsics = [CameraIntrinsics.from_dict(r["intrinsics"]) for r in records] + distortions = [CameraDistortion.from_dict(r["distortion"]) for r in records] + dist_models = {d.model for d in distortions} + if len(dist_models) != 1: + raise ValueError(f"Cannot aggregate mixed distortion models: {dist_models}") + + dist_len = len(distortions[0].params) + if any(len(d.params) != dist_len for d in distortions): + raise ValueError("Cannot aggregate GeoCalib distortions with different lengths") + + gravity_vectors = np.asarray( + [r["gravity"]["vector_camera"] for r in records], + dtype=np.float64, + ) + gravity = gravity_vectors.mean(axis=0) + norm = float(np.linalg.norm(gravity)) + if norm < 1e-8: + raise RuntimeError("GeoCalib gravity estimates cancelled out during aggregation") + gravity /= norm + + fx = float(np.median([k.fx for k in intrinsics])) + fy = float(np.median([k.fy for k in intrinsics])) + cx = float(np.median([k.cx for k in intrinsics])) + cy = float(np.median([k.cy for k in intrinsics])) + width = int(round(float(np.median([k.width for k in intrinsics])))) + height = int(round(float(np.median([k.height for k in intrinsics])))) + if dist_len: + params = np.median( + np.asarray([d.params for d in distortions], dtype=np.float64), + axis=0, + ).tolist() + else: + params = [] + + agg_intrinsics = CameraIntrinsics( + fx=fx, fy=fy, cx=cx, cy=cy, width=width, height=height, + ) + agg_distortion = CameraDistortion( + model=next(iter(dist_models)), + params=[float(v) for v in params], + ) + aggregate = { + "gravity": { + "vector_camera": [float(v) for v in gravity], + "sample_vectors_camera": gravity_vectors.tolist(), + }, + "num_samples": len(records), + } + return agg_intrinsics, agg_distortion, aggregate + diff --git a/third-party/video_to_data/reconstruction/modules/v2d_geocalib/lib/download_weights.py b/third-party/video_to_data/reconstruction/modules/v2d_geocalib/lib/download_weights.py new file mode 100644 index 0000000000000000000000000000000000000000..d29bfe3955f23ff3cfb012adbd2aaa81b338e797 --- /dev/null +++ b/third-party/video_to_data/reconstruction/modules/v2d_geocalib/lib/download_weights.py @@ -0,0 +1,34 @@ +# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 +"""Pre-download GeoCalib weights into a torch hub cache directory.""" +from __future__ import annotations + +import argparse +import os + + +def download_geocalib(output_dir: str | None = None, weights: str = "pinhole") -> None: + if weights not in {"pinhole", "distorted"}: + raise ValueError("weights must be 'pinhole' or 'distorted'") + if output_dir is None: + output_dir = os.environ.get("CHECKPOINT_DIR") + if output_dir is None: + raise ValueError("CHECKPOINT_DIR environment variable must be set") + output_dir = os.path.abspath(output_dir) + os.makedirs(output_dir, exist_ok=True) + os.environ["TORCH_HOME"] = output_dir + + from geocalib import GeoCalib + + print(f"Downloading GeoCalib weights={weights!r} into {output_dir}") + GeoCalib(weights=weights) + print("Done.") + + +if __name__ == "__main__": + parser = argparse.ArgumentParser(description="Download GeoCalib checkpoint") + parser.add_argument("--output_dir", type=str, default=None) + parser.add_argument("--weights", choices=("pinhole", "distorted"), default="pinhole") + args = parser.parse_args() + download_geocalib(output_dir=args.output_dir, weights=args.weights) + diff --git a/third-party/video_to_data/reconstruction/modules/v2d_geocalib/lib/pyproject.toml b/third-party/video_to_data/reconstruction/modules/v2d_geocalib/lib/pyproject.toml new file mode 100644 index 0000000000000000000000000000000000000000..e9827acb026d5e5331ab8cbfafca7cb3dab9420a --- /dev/null +++ b/third-party/video_to_data/reconstruction/modules/v2d_geocalib/lib/pyproject.toml @@ -0,0 +1,24 @@ +# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 +[build-system] +requires = ["setuptools>=68.0", "wheel"] +build-backend = "setuptools.build_meta" + +[project] +name = "v2d-geocalib-lib" +version = "0.1.0" +description = "GeoCalib-based monocular calibration and gravity estimation" +requires-python = ">=3.10" +dependencies = [ + "numpy", + "opencv-python", + "geocalib @ git+https://github.com/cvg/GeoCalib.git", + "v2d-common", +] + +[tool.setuptools] +packages = ["v2d.geocalib.lib"] + +[tool.setuptools.package-dir] +"v2d.geocalib.lib" = "." + diff --git a/third-party/video_to_data/reconstruction/modules/v2d_geocalib/lib/video_to_calibration.py b/third-party/video_to_data/reconstruction/modules/v2d_geocalib/lib/video_to_calibration.py new file mode 100644 index 0000000000000000000000000000000000000000..84410b1885585dd6c2f4f65690eefc2e4082bbe9 --- /dev/null +++ b/third-party/video_to_data/reconstruction/modules/v2d_geocalib/lib/video_to_calibration.py @@ -0,0 +1,141 @@ +# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 +"""GeoCalib: estimate intrinsics + camera-frame gravity from a video. + +The video path is sampled uniformly, GeoCalib is run on each sampled RGB frame, +and the aggregate intrinsics/distortion/gravity are written as JSON files. The +full per-sample records are also written so downstream bundle alignment can +combine frame-specific gravity estimates with a camera trajectory. +""" +from __future__ import annotations + +import argparse +import json +import os + +import cv2 +import numpy as np +import torch + +from v2d.geocalib.lib._geocalib import aggregate_calibrations, predict_calibration + + +def _sample_frame_indices(total: int, num_samples: int) -> list[int]: + if total <= 0: + raise ValueError("Empty video") + if num_samples >= total: + return list(range(total)) + return np.linspace(0, total - 1, num_samples, dtype=int).tolist() + + +def _frame_to_tensor(frame_bgr: np.ndarray) -> torch.Tensor: + rgb = cv2.cvtColor(frame_bgr, cv2.COLOR_BGR2RGB) + t = torch.from_numpy(rgb).permute(2, 0, 1).float() / 255.0 + return t + + +def video_to_calibration( + video_path: str, + intrinsics_path: str, + distortion_path: str, + gravity_path: str, + calibration_path: str, + weights_path: str | None = None, + weights: str = "pinhole", + camera_model: str = "pinhole", + num_samples: int = 8, + device: str | None = None, +) -> None: + cap = cv2.VideoCapture(video_path) + records: list[dict] = [] + try: + total = int(cap.get(cv2.CAP_PROP_FRAME_COUNT)) + sample_indices = _sample_frame_indices(total, num_samples) + for idx in sample_indices: + cap.set(cv2.CAP_PROP_POS_FRAMES, idx) + ok, frame = cap.read() + if not ok: + continue + intr, dist, extra = predict_calibration( + _frame_to_tensor(frame), + weights_path=weights_path, + weights=weights, + camera_model=camera_model, + device=device, + ) + records.append({ + "frame_index": int(idx), + "intrinsics": intr.to_dict(), + "distortion": dist.to_dict(), + **extra, + }) + print(f" sampled frame {idx} ({len(records)}/{len(sample_indices)})") + finally: + cap.release() + + if not records: + raise RuntimeError(f"Could not read any frames from {video_path}") + + intrinsics, distortion, aggregate = aggregate_calibrations(records) + os.makedirs(os.path.dirname(os.path.abspath(intrinsics_path)), exist_ok=True) + os.makedirs(os.path.dirname(os.path.abspath(distortion_path)), exist_ok=True) + os.makedirs(os.path.dirname(os.path.abspath(gravity_path)), exist_ok=True) + os.makedirs(os.path.dirname(os.path.abspath(calibration_path)), exist_ok=True) + + intrinsics.save(intrinsics_path) + distortion.save(distortion_path) + + gravity_record = { + "model": "GeoCalib", + "weights": weights, + "camera_model": camera_model, + "vector_camera": aggregate["gravity"]["vector_camera"], + "num_samples": aggregate["num_samples"], + } + with open(gravity_path, "w") as f: + json.dump(gravity_record, f, indent=2) + + with open(calibration_path, "w") as f: + json.dump({ + "model": "GeoCalib", + "weights": weights, + "camera_model": camera_model, + "intrinsics": intrinsics.to_dict(), + "distortion": distortion.to_dict(), + "gravity": gravity_record, + "samples": records, + }, f, indent=2) + + print(f"Saved GeoCalib intrinsics → {intrinsics_path}") + print(f"Saved GeoCalib distortion → {distortion_path}") + print(f"Saved GeoCalib gravity → {gravity_path}") + print(f"Saved GeoCalib samples → {calibration_path}") + + +if __name__ == "__main__": + parser = argparse.ArgumentParser(description="Estimate GeoCalib calibration from a video") + parser.add_argument("--video_path", required=True) + parser.add_argument("--intrinsics_path", required=True) + parser.add_argument("--distortion_path", required=True) + parser.add_argument("--gravity_path", required=True) + parser.add_argument("--calibration_path", required=True) + parser.add_argument("--weights_path", default=None) + parser.add_argument("--weights", choices=("pinhole", "distorted"), default="pinhole") + parser.add_argument("--camera_model", default="pinhole", + choices=("pinhole", "simple_radial", "radial", "simple_divisional")) + parser.add_argument("--num_samples", type=int, default=8) + parser.add_argument("--device", default=None) + args = parser.parse_args() + video_to_calibration( + video_path=args.video_path, + intrinsics_path=args.intrinsics_path, + distortion_path=args.distortion_path, + gravity_path=args.gravity_path, + calibration_path=args.calibration_path, + weights_path=args.weights_path, + weights=args.weights, + camera_model=args.camera_model, + num_samples=args.num_samples, + device=args.device, + ) + diff --git a/third-party/video_to_data/reconstruction/modules/v2d_grounding_dino/.gitignore b/third-party/video_to_data/reconstruction/modules/v2d_grounding_dino/.gitignore new file mode 100644 index 0000000000000000000000000000000000000000..36bd334954c9a58089761f30eb0b5ed86a7672e0 --- /dev/null +++ b/third-party/video_to_data/reconstruction/modules/v2d_grounding_dino/.gitignore @@ -0,0 +1,7 @@ +data/ +checkpoints/ +*.pt +*.pth +*.zip +__pycache__/ +tests/test_data/output/ diff --git a/third-party/video_to_data/reconstruction/modules/v2d_grounding_dino/LICENSE b/third-party/video_to_data/reconstruction/modules/v2d_grounding_dino/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..10caffae439b956cdda2b1ded9ecbe51ac10befb --- /dev/null +++ b/third-party/video_to_data/reconstruction/modules/v2d_grounding_dino/LICENSE @@ -0,0 +1,15 @@ +# Apache License 2.0 + +Copyright 2025 NVIDIA CORPORATION + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. diff --git a/third-party/video_to_data/reconstruction/modules/v2d_grounding_dino/assets/test_image.jpg b/third-party/video_to_data/reconstruction/modules/v2d_grounding_dino/assets/test_image.jpg new file mode 100644 index 0000000000000000000000000000000000000000..cfcca747f93b7da5201df13c94a25eed9eb8e6f5 --- /dev/null +++ b/third-party/video_to_data/reconstruction/modules/v2d_grounding_dino/assets/test_image.jpg @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:62d8283c61d7d54f777945e0382abe087927b594d89ca4dd47e18a3b789c13ea +size 136663 diff --git a/third-party/video_to_data/reconstruction/modules/v2d_grounding_dino/docker/Dockerfile b/third-party/video_to_data/reconstruction/modules/v2d_grounding_dino/docker/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..a65c815aaa419542e6b7c5959b8dafe28326c777 --- /dev/null +++ b/third-party/video_to_data/reconstruction/modules/v2d_grounding_dino/docker/Dockerfile @@ -0,0 +1,25 @@ +FROM pytorch/pytorch:2.5.1-cuda12.4-cudnn9-devel +ENV DEBIAN_FRONTEND=noninteractive +WORKDIR /app + +RUN apt-get update && apt-get install -y \ + libgl1 \ + libglib2.0-0 \ + git \ + wget \ + && rm -rf /var/lib/apt/lists/* + +RUN git clone https://github.com/IDEA-Research/GroundingDINO.git /tmp/GroundingDINO && \ + cd /tmp/GroundingDINO && \ + FORCE_CUDA=1 TORCH_CUDA_ARCH_LIST="7.0;7.5;8.0;8.6;8.9;9.0" \ + pip install --no-build-isolation . && \ + rm -rf /tmp/GroundingDINO + +RUN pip install "transformers==4.27.4" +RUN pip install huggingface-hub requests Pillow opencv-python + +COPY . /workspace + +RUN pip install -e "/workspace/v2d_common[io]" \ + -e /workspace/v2d_mv \ + -e /workspace/v2d_grounding_dino/lib diff --git a/third-party/video_to_data/reconstruction/modules/v2d_grounding_dino/docker/__init__.py b/third-party/video_to_data/reconstruction/modules/v2d_grounding_dino/docker/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..52a7a9daf028f654d6a02f65c99cc609a57b492f --- /dev/null +++ b/third-party/video_to_data/reconstruction/modules/v2d_grounding_dino/docker/__init__.py @@ -0,0 +1,2 @@ +# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 diff --git a/third-party/video_to_data/reconstruction/modules/v2d_grounding_dino/docker/_config.py b/third-party/video_to_data/reconstruction/modules/v2d_grounding_dino/docker/_config.py new file mode 100644 index 0000000000000000000000000000000000000000..a8a9ff7c4273ac6f25584fb0d5e41e66d839c2d9 --- /dev/null +++ b/third-party/video_to_data/reconstruction/modules/v2d_grounding_dino/docker/_config.py @@ -0,0 +1,6 @@ +# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 +import os + +IMAGE_NAME = "v2d_grounding_dino" +MODULES_DIR = os.path.abspath(os.path.join(os.path.dirname(os.path.abspath(__file__)), "..", "..")) diff --git a/third-party/video_to_data/reconstruction/modules/v2d_grounding_dino/docker/build.py b/third-party/video_to_data/reconstruction/modules/v2d_grounding_dino/docker/build.py new file mode 100644 index 0000000000000000000000000000000000000000..bb9e3accf456aaad62fbe244b8a85e70bb7a3f20 --- /dev/null +++ b/third-party/video_to_data/reconstruction/modules/v2d_grounding_dino/docker/build.py @@ -0,0 +1,17 @@ +# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 +import subprocess +import os + +IMAGE_NAME = "v2d_grounding_dino" + +current_dir = os.path.dirname(os.path.abspath(__file__)) +module_dir = os.path.join(current_dir, "..") +root_dir = os.path.join(module_dir, "..") +dockerfile_path = os.path.join(current_dir, "Dockerfile") + +def build_docker_image() -> None: + subprocess.run(["docker", "build", "-t", IMAGE_NAME, "-f", dockerfile_path, root_dir], check=True) + +if __name__ == "__main__": + build_docker_image() diff --git a/third-party/video_to_data/reconstruction/modules/v2d_grounding_dino/docker/pyproject.toml b/third-party/video_to_data/reconstruction/modules/v2d_grounding_dino/docker/pyproject.toml new file mode 100644 index 0000000000000000000000000000000000000000..cf093166f8aefe17648d8092587e28baad675226 --- /dev/null +++ b/third-party/video_to_data/reconstruction/modules/v2d_grounding_dino/docker/pyproject.toml @@ -0,0 +1,18 @@ +# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 +[build-system] +requires = ["setuptools>=68.0", "wheel"] +build-backend = "setuptools.build_meta" + +[project] +name = "v2d-grounding-dino-docker" +version = "0.1.0" +description = "Docker orchestration scripts for Grounding DINO" +requires-python = ">=3.10" +dependencies = ["v2d-docker"] + +[tool.setuptools] +packages = ["v2d.grounding_dino.docker"] + +[tool.setuptools.package-dir] +"v2d.grounding_dino.docker" = "." diff --git a/third-party/video_to_data/reconstruction/modules/v2d_grounding_dino/docker/run_download_weights.py b/third-party/video_to_data/reconstruction/modules/v2d_grounding_dino/docker/run_download_weights.py new file mode 100644 index 0000000000000000000000000000000000000000..d754224e67df4aeb5a91121cc355e875a20eb8eb --- /dev/null +++ b/third-party/video_to_data/reconstruction/modules/v2d_grounding_dino/docker/run_download_weights.py @@ -0,0 +1,35 @@ +# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 +import subprocess +import os +from v2d.grounding_dino.docker._config import IMAGE_NAME, MODULES_DIR + + +def run_download(output_dir: str, dev: bool = False) -> None: + os.makedirs(output_dir, exist_ok=True) + output_dir = os.path.abspath(output_dir) + + cmd = [ + "docker", "run", "--rm", + "--user", f"{os.getuid()}:{os.getgid()}", + "-e", "HOME=/tmp", + "-v", f"{output_dir}:/data/models", + ] + if dev: + cmd += ["-v", f"{MODULES_DIR}:/workspace"] + cmd += [ + IMAGE_NAME, + "python", "-m", "v2d.grounding_dino.lib.download_weights", + "--output_dir", "/data/models", + ] + subprocess.run(cmd, check=True) + + +if __name__ == "__main__": + import argparse + + parser = argparse.ArgumentParser(description="Download GroundingDINO checkpoint") + parser.add_argument("--output_dir", type=str, required=True, help="Output directory for checkpoint") + parser.add_argument("--dev", action="store_true", help="Mount local modules for development") + args = parser.parse_args() + run_download(output_dir=args.output_dir, dev=args.dev) diff --git a/third-party/video_to_data/reconstruction/modules/v2d_grounding_dino/docker/run_image_list_to_object_bboxes.py b/third-party/video_to_data/reconstruction/modules/v2d_grounding_dino/docker/run_image_list_to_object_bboxes.py new file mode 100644 index 0000000000000000000000000000000000000000..b23b39da4b286ccf9560edd28275980bf3c112ac --- /dev/null +++ b/third-party/video_to_data/reconstruction/modules/v2d_grounding_dino/docker/run_image_list_to_object_bboxes.py @@ -0,0 +1,47 @@ +# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 +from v2d.docker.container import run_in_container +from v2d.grounding_dino.docker._config import IMAGE_NAME, MODULES_DIR + + +def run_image_list_to_object_bboxes( + image_dir: str, + output_path: str, + prompt: str, + model_dir: str, + box_threshold: float = 0.35, + text_threshold: float = 0.25, + debug_output: str = None, + dev: bool = False, +) -> None: + run_in_container( + image=IMAGE_NAME, + module="v2d.grounding_dino.lib.image_list_to_object_bboxes", + inputs={"image_dir": image_dir, "model_dir": model_dir}, + outputs={"output_path": output_path, "debug_output": debug_output}, + extra_args={"prompt": prompt, "box_threshold": box_threshold, "text_threshold": text_threshold}, + dev=dev, + modules_dir=MODULES_DIR, + gpus=True, + ) + + +if __name__ == "__main__": + import argparse + + parser = argparse.ArgumentParser(description="Grounding DINO: detect objects in image directory") + parser.add_argument('--image_dir', required=True) + parser.add_argument('--output_path', required=True) + parser.add_argument('--prompt', required=True) + parser.add_argument('--model_dir', required=True) + parser.add_argument('--box_threshold', type=float, default=0.35) + parser.add_argument('--text_threshold', type=float, default=0.25) + parser.add_argument('--debug_output', type=str, default=None, + help='Directory to save annotated debug images') + parser.add_argument('--dev', action='store_true', help='Mount local modules for development') + args = parser.parse_args() + run_image_list_to_object_bboxes( + args.image_dir, args.output_path, args.prompt, args.model_dir, + box_threshold=args.box_threshold, text_threshold=args.text_threshold, + debug_output=args.debug_output, dev=args.dev, + ) diff --git a/third-party/video_to_data/reconstruction/modules/v2d_grounding_dino/docker/run_image_to_object_bboxes.py b/third-party/video_to_data/reconstruction/modules/v2d_grounding_dino/docker/run_image_to_object_bboxes.py new file mode 100644 index 0000000000000000000000000000000000000000..ab5a55292b391e5b3e4a5fcc755d27f3e1752dd7 --- /dev/null +++ b/third-party/video_to_data/reconstruction/modules/v2d_grounding_dino/docker/run_image_to_object_bboxes.py @@ -0,0 +1,47 @@ +# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 +from v2d.docker.container import run_in_container +from v2d.grounding_dino.docker._config import IMAGE_NAME, MODULES_DIR + + +def run_image_to_object_bboxes( + image_path: str, + output_path: str, + prompt: str, + model_dir: str, + box_threshold: float = 0.35, + text_threshold: float = 0.25, + debug_output: str = None, + dev: bool = False, +) -> None: + run_in_container( + image=IMAGE_NAME, + module="v2d.grounding_dino.lib.image_to_object_bboxes", + inputs={"image_path": image_path, "model_dir": model_dir}, + outputs={"output_path": output_path, "debug_output": debug_output}, + extra_args={"prompt": prompt, "box_threshold": box_threshold, "text_threshold": text_threshold}, + dev=dev, + modules_dir=MODULES_DIR, + gpus=True, + ) + + +if __name__ == "__main__": + import argparse + + parser = argparse.ArgumentParser(description="Grounding DINO: detect objects in an image") + parser.add_argument('--image_path', required=True) + parser.add_argument('--output_path', required=True) + parser.add_argument('--prompt', required=True) + parser.add_argument('--model_dir', required=True) + parser.add_argument('--box_threshold', type=float, default=0.35) + parser.add_argument('--text_threshold', type=float, default=0.25) + parser.add_argument('--debug_output', type=str, default=None, + help='Directory to save annotated debug images') + parser.add_argument('--dev', action='store_true', help='Mount local modules for development') + args = parser.parse_args() + run_image_to_object_bboxes( + args.image_path, args.output_path, args.prompt, args.model_dir, + box_threshold=args.box_threshold, text_threshold=args.text_threshold, + debug_output=args.debug_output, dev=args.dev, + ) diff --git a/third-party/video_to_data/reconstruction/modules/v2d_grounding_dino/docker/run_mv_image_list_to_object_bboxes.py b/third-party/video_to_data/reconstruction/modules/v2d_grounding_dino/docker/run_mv_image_list_to_object_bboxes.py new file mode 100644 index 0000000000000000000000000000000000000000..47a0e3d4b6d670fc0d044079cce40cf81aa73695 --- /dev/null +++ b/third-party/video_to_data/reconstruction/modules/v2d_grounding_dino/docker/run_mv_image_list_to_object_bboxes.py @@ -0,0 +1,62 @@ +# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 +from pathlib import Path + +from v2d.docker.container import run_in_container +from v2d.grounding_dino.docker._config import IMAGE_NAME, MODULES_DIR + +_LIB_CONFIG = Path(__file__).parent.parent / "lib" / "mv_image_list_to_object_bboxes.yaml" + + +def run_mv_image_list_to_object_bboxes( + rgb_dir: str, + prompt_path: str, + output_dir: str, + model_dir: str, + config_path: str = str(_LIB_CONFIG), + dev: bool = False, +) -> None: + run_in_container( + image=IMAGE_NAME, + module="v2d.grounding_dino.lib.mv_image_list_to_object_bboxes", + inputs={ + "rgb_dir": rgb_dir, + "prompt_path": prompt_path, + "model_dir": model_dir, + "config_path": config_path, + }, + outputs={"output_dir": output_dir}, + dev=dev, + modules_dir=MODULES_DIR, + gpus=True, + env={"PYTHONUNBUFFERED": "1"}, + ) + + +if __name__ == "__main__": + import argparse + + parser = argparse.ArgumentParser( + description="Multi-view Grounding DINO object detection" + ) + parser.add_argument("--rgb_dir", type=str, required=True, + help="Root directory containing per-camera image folders") + parser.add_argument("--prompt_path", type=str, required=True, + help="Path to plain-text file containing the object prompt") + parser.add_argument("--output_dir", type=str, required=True, + help="Output directory for per-camera bbox JSONs") + parser.add_argument("--model_dir", type=str, required=True, + help="Directory with Grounding DINO weights") + parser.add_argument("--config_path", type=str, default=str(_LIB_CONFIG), + help="Path to mv_image_list_to_object_bboxes.yaml") + parser.add_argument("--dev", action="store_true") + args = parser.parse_args() + + run_mv_image_list_to_object_bboxes( + rgb_dir=args.rgb_dir, + prompt_path=args.prompt_path, + output_dir=args.output_dir, + model_dir=args.model_dir, + config_path=args.config_path, + dev=args.dev, + ) diff --git a/third-party/video_to_data/reconstruction/modules/v2d_grounding_dino/docker/run_shell.py b/third-party/video_to_data/reconstruction/modules/v2d_grounding_dino/docker/run_shell.py new file mode 100644 index 0000000000000000000000000000000000000000..f6d2fe98696137f845fa8bebac7fb2ad0737c8e5 --- /dev/null +++ b/third-party/video_to_data/reconstruction/modules/v2d_grounding_dino/docker/run_shell.py @@ -0,0 +1,27 @@ +# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 +import subprocess +import os +from v2d.grounding_dino.docker._config import IMAGE_NAME, MODULES_DIR + + +def run_shell(dev: bool = False) -> None: + cmd = [ + "docker", "run", "-it", "--rm", + "--gpus", "all", + "--user", f"{os.getuid()}:{os.getgid()}", + "-e", "HOME=/tmp", + ] + if dev: + cmd += ["-v", f"{MODULES_DIR}:/workspace"] + cmd += [IMAGE_NAME, "bash"] + subprocess.run(cmd, check=True) + + +if __name__ == "__main__": + import argparse + + parser = argparse.ArgumentParser(description="Run shell in v2d_grounding_dino container") + parser.add_argument("--dev", action="store_true", help="Mount local modules for development") + args = parser.parse_args() + run_shell(dev=args.dev) diff --git a/third-party/video_to_data/reconstruction/modules/v2d_grounding_dino/docker/run_video_to_object_bboxes.py b/third-party/video_to_data/reconstruction/modules/v2d_grounding_dino/docker/run_video_to_object_bboxes.py new file mode 100644 index 0000000000000000000000000000000000000000..234e3cb33df7a1a8cf68c30d9903a3844d9aced8 --- /dev/null +++ b/third-party/video_to_data/reconstruction/modules/v2d_grounding_dino/docker/run_video_to_object_bboxes.py @@ -0,0 +1,47 @@ +# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 +from v2d.docker.container import run_in_container +from v2d.grounding_dino.docker._config import IMAGE_NAME, MODULES_DIR + + +def run_video_to_object_bboxes( + video_path: str, + output_path: str, + prompt: str, + model_dir: str, + box_threshold: float = 0.35, + text_threshold: float = 0.25, + debug_output: str = None, + dev: bool = False, +) -> None: + run_in_container( + image=IMAGE_NAME, + module="v2d.grounding_dino.lib.video_to_object_bboxes", + inputs={"video_path": video_path, "model_dir": model_dir}, + outputs={"output_path": output_path, "debug_output": debug_output}, + extra_args={"prompt": prompt, "box_threshold": box_threshold, "text_threshold": text_threshold}, + dev=dev, + modules_dir=MODULES_DIR, + gpus=True, + ) + + +if __name__ == "__main__": + import argparse + + parser = argparse.ArgumentParser(description="Grounding DINO: detect objects in video frames") + parser.add_argument('--video_path', required=True) + parser.add_argument('--output_path', required=True) + parser.add_argument('--prompt', required=True) + parser.add_argument('--model_dir', required=True) + parser.add_argument('--box_threshold', type=float, default=0.35) + parser.add_argument('--text_threshold', type=float, default=0.25) + parser.add_argument('--debug_output', type=str, default=None, + help='Directory to save annotated debug frames') + parser.add_argument('--dev', action='store_true', help='Mount local modules for development') + args = parser.parse_args() + run_video_to_object_bboxes( + args.video_path, args.output_path, args.prompt, args.model_dir, + box_threshold=args.box_threshold, text_threshold=args.text_threshold, + debug_output=args.debug_output, dev=args.dev, + ) diff --git a/third-party/video_to_data/reconstruction/modules/v2d_grounding_dino/lib/__init__.py b/third-party/video_to_data/reconstruction/modules/v2d_grounding_dino/lib/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..52a7a9daf028f654d6a02f65c99cc609a57b492f --- /dev/null +++ b/third-party/video_to_data/reconstruction/modules/v2d_grounding_dino/lib/__init__.py @@ -0,0 +1,2 @@ +# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 diff --git a/third-party/video_to_data/reconstruction/modules/v2d_grounding_dino/lib/download_weights.py b/third-party/video_to_data/reconstruction/modules/v2d_grounding_dino/lib/download_weights.py new file mode 100644 index 0000000000000000000000000000000000000000..3d51dbdab820d9175f8320bab9d6eb0a336e73bb --- /dev/null +++ b/third-party/video_to_data/reconstruction/modules/v2d_grounding_dino/lib/download_weights.py @@ -0,0 +1,32 @@ +# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 +"""Download GroundingDINO SwinT-OGC checkpoint.""" +import argparse +import os +import urllib.request + +CHECKPOINT_URL = ( + "https://github.com/IDEA-Research/GroundingDINO/releases/download/" + "v0.1.0-alpha/groundingdino_swint_ogc.pth" +) +CHECKPOINT_FILENAME = "groundingdino_swint_ogc.pth" + + +def download_weights(output_dir: str): + os.makedirs(output_dir, exist_ok=True) + dest = os.path.join(output_dir, CHECKPOINT_FILENAME) + + if os.path.exists(dest): + print(f"Checkpoint already exists at {dest}, skipping download.") + return + + print(f"Downloading GroundingDINO SwinT-OGC checkpoint to {dest}...") + urllib.request.urlretrieve(CHECKPOINT_URL, dest) + print(f"Download complete: {dest}") + + +if __name__ == "__main__": + parser = argparse.ArgumentParser(description="Download GroundingDINO checkpoint") + parser.add_argument("--output_dir", type=str, required=True, help="Output directory for checkpoint") + args = parser.parse_args() + download_weights(args.output_dir) diff --git a/third-party/video_to_data/reconstruction/modules/v2d_grounding_dino/lib/image_list_to_object_bboxes.py b/third-party/video_to_data/reconstruction/modules/v2d_grounding_dino/lib/image_list_to_object_bboxes.py new file mode 100644 index 0000000000000000000000000000000000000000..8945b206695b0cf23b7f1618febfbdddbf2f0674 --- /dev/null +++ b/third-party/video_to_data/reconstruction/modules/v2d_grounding_dino/lib/image_list_to_object_bboxes.py @@ -0,0 +1,163 @@ +# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 +"""Grounding DINO: detect objects in a directory of images using a text prompt. + +Usage: + python -m v2d.grounding_dino.lib.image_list_to_object_bboxes \ + --image_dir /data/frames \ + --output_path /data/bboxes.json \ + --prompt "robot arm" \ + --model_dir /data/models +""" + +import argparse +import json +import os +import subprocess +from pathlib import Path + +import numpy as np +from PIL import Image + +import groundingdino +import groundingdino.datasets.transforms as T +from groundingdino.util.inference import load_model, predict +from torchvision.ops import box_convert + +from v2d.common.datatypes import BoundingBox +from v2d.common.video import FrameSource + +_CHECKPOINT_URL = ( + "https://github.com/IDEA-Research/GroundingDINO/releases/download/" + "v0.1.0-alpha/groundingdino_swint_ogc.pth" +) +_model = None + + +def _get_model(model_dir: str): + global _model + if _model is None: + config_path = os.path.join( + groundingdino.__path__[0], 'config', 'GroundingDINO_SwinT_OGC.py' + ) + model_path = os.path.join(model_dir, 'groundingdino_swint_ogc.pth') + if not os.path.exists(config_path): + raise FileNotFoundError(f"GroundingDINO config not found: {config_path}") + if not os.path.exists(model_path): + print(f"Checkpoint not found at {model_path}. Downloading...") + os.makedirs(model_dir, exist_ok=True) + subprocess.run( + ["wget", "-q", "--show-progress", _CHECKPOINT_URL, "-O", model_path], + check=True, + ) + _model = load_model(config_path, model_path) + return _model + + +_TRANSFORM = T.Compose([ + T.RandomResize([800], max_size=1333), + T.ToTensor(), + T.Normalize([0.485, 0.456, 0.406], [0.229, 0.224, 0.225]), +]) + + +def _preprocess_image(image_rgb: np.ndarray): + """Apply GroundingDINO preprocessing to a numpy RGB array.""" + pil_image = Image.fromarray(image_rgb) + image_transformed, _ = _TRANSFORM(pil_image, None) + return image_transformed + + +def _detect(model, image_rgb: np.ndarray, prompt: str, + box_threshold: float, text_threshold: float) -> list[dict]: + h, w = image_rgb.shape[:2] + image = _preprocess_image(image_rgb) + + boxes_cxcywh, logits, phrases = predict( + model=model, + image=image, + caption=prompt, + box_threshold=box_threshold, + text_threshold=text_threshold, + ) + + boxes_xyxy = box_convert(boxes=boxes_cxcywh, in_fmt='cxcywh', out_fmt='xyxy') + boxes_xyxy = boxes_xyxy * boxes_xyxy.new_tensor([w, h, w, h]) + + detections = [] + for box, logit, phrase in zip(boxes_xyxy.tolist(), logits.tolist(), phrases): + x0, y0, x1, y1 = box + detections.append({ + 'label': phrase, + 'confidence': round(logit, 4), + 'box': BoundingBox(x0=x0, y0=y0, x1=x1, y1=y1).to_dict(), + }) + + detections.sort(key=lambda d: d['confidence'], reverse=True) + return detections + + +def image_list_to_object_bboxes( + image_dir: str, + output_path: str, + prompt: str, + model_dir: str, + box_threshold: float = 0.35, + text_threshold: float = 0.25, +) -> dict: + """Run Grounding DINO on all images in a directory or HDF5 and write JSON.""" + source = FrameSource.from_path(image_dir) + + os.makedirs(os.path.dirname(output_path) or '.', exist_ok=True) + model = _get_model(model_dir) + + results = {} + for i in range(source.n_frames): + detections = _detect(model, source[i], prompt, box_threshold, text_threshold) + results[source.stems[i]] = detections + if (i + 1) % 10 == 0: + print(f" processed {i + 1}/{source.n_frames} images...") + + with open(output_path, 'w') as f: + json.dump(results, f, indent=2) + + print(f"Done. processed={len(results)}. Saved to: {output_path}") + return results + + +def main(): + parser = argparse.ArgumentParser( + description="Grounding DINO: detect objects in a directory of images" + ) + parser.add_argument('--image_dir', required=True, help='Directory of input images') + parser.add_argument('--output_path', required=True, + help='Output JSON file path (keyed by image stem)') + parser.add_argument('--prompt', required=True, + help='Text prompt for object detection (e.g. "robot arm")') + parser.add_argument('--box_threshold', type=float, default=0.35, + help='Minimum box confidence score (default: 0.35)') + parser.add_argument('--text_threshold', type=float, default=0.25, + help='Minimum text confidence score (default: 0.25)') + parser.add_argument('--model_dir', required=True, + help='Directory with groundingdino_swint_ogc.pth') + parser.add_argument('--debug_output', type=str, default=None, + help='Directory to save annotated debug images') + + args = parser.parse_args() + + results = image_list_to_object_bboxes( + image_dir=args.image_dir, + output_path=args.output_path, + prompt=args.prompt, + model_dir=args.model_dir, + box_threshold=args.box_threshold, + text_threshold=args.text_threshold, + ) + + if args.debug_output: + from v2d.grounding_dino.lib.vis import visualize_image_list_bboxes + visualize_image_list_bboxes(args.image_dir, results, args.debug_output) + + +if __name__ == '__main__': + main() diff --git a/third-party/video_to_data/reconstruction/modules/v2d_grounding_dino/lib/image_to_object_bboxes.py b/third-party/video_to_data/reconstruction/modules/v2d_grounding_dino/lib/image_to_object_bboxes.py new file mode 100644 index 0000000000000000000000000000000000000000..29503482330c19f239a6aa2396be6bfb98194961 --- /dev/null +++ b/third-party/video_to_data/reconstruction/modules/v2d_grounding_dino/lib/image_to_object_bboxes.py @@ -0,0 +1,134 @@ +# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 +"""Grounding DINO: detect objects in a single image using a text prompt. + +Usage: + python -m v2d.grounding_dino.lib.image_to_object_bboxes \ + --image_path /data/frame.jpg \ + --output_path /data/bboxes/frame.json \ + --prompt "robot arm" \ + --model_dir /data/models +""" + +import argparse +import json +import os +import subprocess + +import imageio.v3 as iio +import groundingdino +from groundingdino.util.inference import load_model, predict +from torchvision.ops import box_convert + +from v2d.common.datatypes import BoundingBox +from .image_list_to_object_bboxes import _preprocess_image + +_CHECKPOINT_URL = ( + "https://github.com/IDEA-Research/GroundingDINO/releases/download/" + "v0.1.0-alpha/groundingdino_swint_ogc.pth" +) +_model = None + + +def _get_model(model_dir: str): + global _model + if _model is None: + config_path = os.path.join( + groundingdino.__path__[0], 'config', 'GroundingDINO_SwinT_OGC.py' + ) + model_path = os.path.join(model_dir, 'groundingdino_swint_ogc.pth') + if not os.path.exists(config_path): + raise FileNotFoundError(f"GroundingDINO config not found: {config_path}") + if not os.path.exists(model_path): + print(f"Checkpoint not found at {model_path}. Downloading...") + os.makedirs(model_dir, exist_ok=True) + subprocess.run( + ["wget", "-q", "--show-progress", _CHECKPOINT_URL, "-O", model_path], + check=True, + ) + _model = load_model(config_path, model_path) + return _model + + +def image_to_bboxes( + image_path: str, + output_path: str, + prompt: str, + model_dir: str, + box_threshold: float = 0.35, + text_threshold: float = 0.25, +) -> list[dict]: + """Run Grounding DINO on a single image and write detections to JSON.""" + if not os.path.exists(image_path): + raise FileNotFoundError(f"Image not found: {image_path}") + + model = _get_model(model_dir) + image_source = iio.imread(image_path) + h, w = image_source.shape[:2] + image = _preprocess_image(image_source) + + boxes_cxcywh, logits, phrases = predict( + model=model, + image=image, + caption=prompt, + box_threshold=box_threshold, + text_threshold=text_threshold, + ) + + boxes_xyxy = box_convert(boxes=boxes_cxcywh, in_fmt='cxcywh', out_fmt='xyxy') + boxes_xyxy = boxes_xyxy * boxes_xyxy.new_tensor([w, h, w, h]) + + detections = [] + for box, logit, phrase in zip(boxes_xyxy.tolist(), logits.tolist(), phrases): + x0, y0, x1, y1 = box + detections.append({ + 'label': phrase, + 'confidence': round(logit, 4), + 'box': BoundingBox(x0=x0, y0=y0, x1=x1, y1=y1).to_dict(), + }) + + detections.sort(key=lambda d: d['confidence'], reverse=True) + + os.makedirs(os.path.dirname(output_path) or '.', exist_ok=True) + with open(output_path, 'w') as f: + json.dump(detections, f, indent=2) + + print(f"Detected {len(detections)} object(s). Saved to: {output_path}") + return detections + + +def main(): + parser = argparse.ArgumentParser( + description="Grounding DINO: detect objects in an image using a text prompt" + ) + parser.add_argument('--image_path', required=True, help='Path to input image') + parser.add_argument('--output_path', required=True, help='Path to output JSON file') + parser.add_argument('--prompt', required=True, + help='Text prompt for object detection (e.g. "robot arm")') + parser.add_argument('--box_threshold', type=float, default=0.35, + help='Minimum box confidence score (default: 0.35)') + parser.add_argument('--text_threshold', type=float, default=0.25, + help='Minimum text confidence score (default: 0.25)') + parser.add_argument('--model_dir', required=True, + help='Directory with groundingdino_swint_ogc.pth') + parser.add_argument('--debug_output', type=str, default=None, + help='Directory to save annotated debug images') + + args = parser.parse_args() + + detections = image_to_bboxes( + image_path=args.image_path, + output_path=args.output_path, + prompt=args.prompt, + model_dir=args.model_dir, + box_threshold=args.box_threshold, + text_threshold=args.text_threshold, + ) + + if args.debug_output: + from v2d.grounding_dino.lib.vis import visualize_image_bboxes + visualize_image_bboxes(args.image_path, detections, args.debug_output) + + +if __name__ == '__main__': + main() diff --git a/third-party/video_to_data/reconstruction/modules/v2d_grounding_dino/lib/mv_image_list_to_object_bboxes.py b/third-party/video_to_data/reconstruction/modules/v2d_grounding_dino/lib/mv_image_list_to_object_bboxes.py new file mode 100644 index 0000000000000000000000000000000000000000..04124250e03280e8cad93f38101765a2df912600 --- /dev/null +++ b/third-party/video_to_data/reconstruction/modules/v2d_grounding_dino/lib/mv_image_list_to_object_bboxes.py @@ -0,0 +1,91 @@ +# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 +"""Multi-view Grounding DINO: detect objects across cameras using a text prompt. + +Reads the object prompt from a plain-text file and runs detection on a subset +of rectified frames for each camera defined by the rig config. +""" + +import json +from pathlib import Path + +from tqdm import tqdm + +from v2d.mv.rig import RigConfig + +from v2d.common.video import FrameSource + +from .image_list_to_object_bboxes import _detect, _get_model +from .vis import visualize_image_list_bboxes + + +def mv_image_list_to_object_bboxes_from_config(cfg): + """Run Grounding DINO object detection across multiple cameras.""" + rig = RigConfig(cfg.rig_config) + + prompt = Path(cfg.prompt_path).read_text().strip() + + frames_slice = slice(cfg.get("start", 0), cfg.get("stop"), cfg.get("step", 10)) + box_threshold = cfg.get("box_threshold", 0.35) + text_threshold = cfg.get("text_threshold", 0.25) + debug = cfg.get("debug", 0) + + model = _get_model(cfg.model_dir) + + for cam_id in cfg.cameras: + cam = rig.get_camera(cam_id) + image_path = Path(cfg.rgb_path_template.format(cam_name=cam.name)) + output_path = Path(cfg.output_path_template.format(cam_name=cam.name)) + + source = FrameSource.from_path(image_path, frames_slice=frames_slice) + + results = {} + for i in tqdm(range(source.n_frames), desc=f"Grounding DINO [{cam.name}]"): + detections = _detect(model, source[i], prompt, box_threshold, text_threshold) + results[source.stems[i]] = detections + + output_path.parent.mkdir(parents=True, exist_ok=True) + with open(output_path, "w") as f: + json.dump(results, f, indent=2) + + print(f" Saved {len(results)} frame detections to {output_path}") + + if debug > 0: + debug_dir = output_path.parent / f"{cam.name}_vis" + visualize_image_list_bboxes(str(image_path), results, str(debug_dir)) + + +if __name__ == "__main__": + import argparse + + from omegaconf import OmegaConf + + parser = argparse.ArgumentParser( + description="Multi-view Grounding DINO object detection" + ) + parser.add_argument("--rgb_dir", type=str, required=True, + help="Root directory containing per-camera input frames") + parser.add_argument("--prompt_path", type=str, required=True, + help="Path to plain-text file containing the object prompt") + parser.add_argument("--output_dir", type=str, required=True, + help="Output directory for per-camera bbox JSONs") + parser.add_argument("--model_dir", type=str, required=True, + help="Directory with Grounding DINO weights") + parser.add_argument("--config_path", type=str, default=None, + help="Optional override config (merged on top of defaults)") + parser.add_argument("--debug", type=int, default=None, help="Debug level override") + args = parser.parse_args() + + cfg = OmegaConf.load(Path(__file__).parent / "mv_image_list_to_object_bboxes.yaml") + if args.config_path: + cfg = OmegaConf.merge(cfg, OmegaConf.load(args.config_path)) + overrides = { + "rgb_dir": args.rgb_dir, + "prompt_path": args.prompt_path, + "output_dir": args.output_dir, + "model_dir": args.model_dir, + } + if args.debug is not None: + overrides["debug"] = args.debug + cfg = OmegaConf.merge(cfg, overrides) + mv_image_list_to_object_bboxes_from_config(cfg) diff --git a/third-party/video_to_data/reconstruction/modules/v2d_grounding_dino/lib/mv_image_list_to_object_bboxes.yaml b/third-party/video_to_data/reconstruction/modules/v2d_grounding_dino/lib/mv_image_list_to_object_bboxes.yaml new file mode 100644 index 0000000000000000000000000000000000000000..8417f347d5be5275a49dc40bd07b174e1a13c315 --- /dev/null +++ b/third-party/video_to_data/reconstruction/modules/v2d_grounding_dino/lib/mv_image_list_to_object_bboxes.yaml @@ -0,0 +1,21 @@ +# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 +rig_config: stereo-4 +cameras: [0, 2, 4, 6] + +rgb_dir: ??? +prompt_path: ??? +output_dir: ??? +model_dir: ??? + +rgb_path_template: "${rgb_dir}/{cam_name}" +output_path_template: "${output_dir}/{cam_name}.json" + +start: 0 +stop: null +step: 10 + +box_threshold: 0.35 +text_threshold: 0.25 + +debug: 1 diff --git a/third-party/video_to_data/reconstruction/modules/v2d_grounding_dino/lib/pyproject.toml b/third-party/video_to_data/reconstruction/modules/v2d_grounding_dino/lib/pyproject.toml new file mode 100644 index 0000000000000000000000000000000000000000..c1b44ef3d0696732c6a211fa06c3ca32ed0ab4e1 --- /dev/null +++ b/third-party/video_to_data/reconstruction/modules/v2d_grounding_dino/lib/pyproject.toml @@ -0,0 +1,25 @@ +# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 +[build-system] +requires = ["setuptools>=68.0", "wheel"] +build-backend = "setuptools.build_meta" + +[project] +name = "v2d-grounding-dino-lib" +version = "0.1.0" +description = "Grounding DINO object detection library" +requires-python = ">=3.10" +dependencies = [ + "numpy", + "Pillow", + "opencv-python", + "omegaconf", + "v2d-common", + "v2d-mv", +] + +[tool.setuptools] +packages = ["v2d.grounding_dino.lib"] + +[tool.setuptools.package-dir] +"v2d.grounding_dino.lib" = "." diff --git a/third-party/video_to_data/reconstruction/modules/v2d_grounding_dino/lib/video_to_object_bboxes.py b/third-party/video_to_data/reconstruction/modules/v2d_grounding_dino/lib/video_to_object_bboxes.py new file mode 100644 index 0000000000000000000000000000000000000000..89d5be788ae4d4f311b98b5ec54770937f326444 --- /dev/null +++ b/third-party/video_to_data/reconstruction/modules/v2d_grounding_dino/lib/video_to_object_bboxes.py @@ -0,0 +1,175 @@ +# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 +"""Grounding DINO: detect objects in every frame of a video using a text prompt. + +Usage: + python -m v2d.grounding_dino.lib.video_to_object_bboxes \ + --video_path /data/video.mp4 \ + --output_path /data/bboxes.json \ + --prompt "robot arm" \ + --model_dir /data/models +""" + +import argparse +import json +import os +import subprocess + +import cv2 +import groundingdino +import groundingdino.datasets.transforms as T +from groundingdino.util.inference import load_model, predict +import numpy as np +from PIL import Image +import torch +from torchvision.ops import box_convert + +from v2d.common.datatypes import BoundingBox + +_CHECKPOINT_URL = ( + "https://github.com/IDEA-Research/GroundingDINO/releases/download/" + "v0.1.0-alpha/groundingdino_swint_ogc.pth" +) +_model = None + + +def _get_model(model_dir: str): + global _model + if _model is None: + config_path = os.path.join( + groundingdino.__path__[0], 'config', 'GroundingDINO_SwinT_OGC.py' + ) + model_path = os.path.join(model_dir, 'groundingdino_swint_ogc.pth') + if not os.path.exists(config_path): + raise FileNotFoundError(f"GroundingDINO config not found: {config_path}") + if not os.path.exists(model_path): + print(f"Checkpoint not found at {model_path}. Downloading...") + os.makedirs(model_dir, exist_ok=True) + subprocess.run( + ["wget", "-q", "--show-progress", _CHECKPOINT_URL, "-O", model_path], + check=True, + ) + _model = load_model(config_path, model_path) + return _model + + +_transform = T.Compose([ + T.RandomResize([800], max_size=1333), + T.ToTensor(), + T.Normalize([0.485, 0.456, 0.406], [0.229, 0.224, 0.225]), +]) + + +def _frame_to_gdino_tensor(frame_bgr: np.ndarray) -> torch.Tensor: + """Convert a BGR OpenCV frame to a normalized RGB tensor for Grounding DINO.""" + pil_image = Image.fromarray(cv2.cvtColor(frame_bgr, cv2.COLOR_BGR2RGB)) + tensor, _ = _transform(pil_image, None) + return tensor + + +def _detect_frame(model, frame_bgr: np.ndarray, prompt: str, + box_threshold: float, text_threshold: float) -> list[dict]: + h, w = frame_bgr.shape[:2] + image_tensor = _frame_to_gdino_tensor(frame_bgr) + + boxes_cxcywh, logits, phrases = predict( + model=model, + image=image_tensor, + caption=prompt, + box_threshold=box_threshold, + text_threshold=text_threshold, + ) + + boxes_xyxy = box_convert(boxes=boxes_cxcywh, in_fmt='cxcywh', out_fmt='xyxy') + boxes_xyxy = boxes_xyxy * boxes_xyxy.new_tensor([w, h, w, h]) + + detections = [] + for box, logit, phrase in zip(boxes_xyxy.tolist(), logits.tolist(), phrases): + x0, y0, x1, y1 = box + detections.append({ + 'label': phrase, + 'confidence': round(logit, 4), + 'box': BoundingBox(x0=x0, y0=y0, x1=x1, y1=y1).to_dict(), + }) + + detections.sort(key=lambda d: d['confidence'], reverse=True) + return detections + + +def video_to_object_bboxes( + video_path: str, + output_path: str, + prompt: str, + model_dir: str, + box_threshold: float = 0.35, + text_threshold: float = 0.25, +) -> dict: + """Run Grounding DINO on every frame of a video and write a single JSON.""" + if not os.path.exists(video_path): + raise FileNotFoundError(f"Video not found: {video_path}") + + os.makedirs(os.path.dirname(output_path) or '.', exist_ok=True) + model = _get_model(model_dir) + + cap = cv2.VideoCapture(video_path) + total_frames = int(cap.get(cv2.CAP_PROP_FRAME_COUNT)) + results = {} + frame_idx = 0 + + while True: + ret, frame_bgr = cap.read() + if not ret: + break + + detections = _detect_frame(model, frame_bgr, prompt, box_threshold, text_threshold) + results[str(frame_idx)] = detections + + frame_idx += 1 + if frame_idx % 10 == 0: + print(f" processed {frame_idx}/{total_frames} frames...") + + cap.release() + + with open(output_path, 'w') as f: + json.dump(results, f, indent=2) + + print(f"Done. processed={frame_idx} frames. Saved to: {output_path}") + return results + + +def main(): + parser = argparse.ArgumentParser( + description="Grounding DINO: detect objects in every frame of a video" + ) + parser.add_argument('--video_path', required=True, help='Path to input video file') + parser.add_argument('--output_path', required=True, + help='Output JSON file path (keyed by frame index)') + parser.add_argument('--prompt', required=True, + help='Text prompt for object detection (e.g. "robot arm")') + parser.add_argument('--box_threshold', type=float, default=0.35, + help='Minimum box confidence score (default: 0.35)') + parser.add_argument('--text_threshold', type=float, default=0.25, + help='Minimum text confidence score (default: 0.25)') + parser.add_argument('--model_dir', required=True, + help='Directory with groundingdino_swint_ogc.pth') + parser.add_argument('--debug_output', type=str, default=None, + help='Directory to save annotated debug frames') + + args = parser.parse_args() + + results = video_to_object_bboxes( + video_path=args.video_path, + output_path=args.output_path, + prompt=args.prompt, + model_dir=args.model_dir, + box_threshold=args.box_threshold, + text_threshold=args.text_threshold, + ) + + if args.debug_output: + from v2d.grounding_dino.lib.vis import visualize_video_bboxes + visualize_video_bboxes(args.video_path, results, args.debug_output) + + +if __name__ == '__main__': + main() diff --git a/third-party/video_to_data/reconstruction/modules/v2d_grounding_dino/lib/vis.py b/third-party/video_to_data/reconstruction/modules/v2d_grounding_dino/lib/vis.py new file mode 100644 index 0000000000000000000000000000000000000000..4a4f7520aca1f3eadc649ebe4754b502cd160a5d --- /dev/null +++ b/third-party/video_to_data/reconstruction/modules/v2d_grounding_dino/lib/vis.py @@ -0,0 +1,124 @@ +# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 +"""Visualization utilities for Grounding DINO bounding box outputs. + +Draws detected bounding boxes on images/video frames and saves debug images. +""" + +import json +import os +from pathlib import Path + +import cv2 +import numpy as np + +# BGR colors cycled per label for visual variety +_COLORS = [ + (0, 255, 0), # green + (255, 0, 0), # blue + (0, 0, 255), # red + (0, 255, 255), # yellow + (255, 0, 255), # magenta + (255, 165, 0), # orange +] + + +def _color_for(label: str) -> tuple: + return _COLORS[hash(label) % len(_COLORS)] + + +def _draw_detections(image_bgr: np.ndarray, detections: list[dict]) -> np.ndarray: + """Draw bounding boxes and labels on a BGR image. Returns annotated copy.""" + out = image_bgr.copy() + for det in detections: + box = det['box'] + x0, y0, x1, y1 = int(box['x0']), int(box['y0']), int(box['x1']), int(box['y1']) + label = det['label'] + conf = det['confidence'] + color = _color_for(label) + + cv2.rectangle(out, (x0, y0), (x1, y1), color, thickness=2) + + text = f"{label} {conf:.2f}" + (tw, th), baseline = cv2.getTextSize(text, cv2.FONT_HERSHEY_SIMPLEX, 0.6, 1) + ty = max(y0 - 6, th + baseline) + cv2.rectangle(out, (x0, ty - th - baseline), (x0 + tw, ty + baseline), color, -1) + cv2.putText(out, text, (x0, ty), cv2.FONT_HERSHEY_SIMPLEX, 0.6, (0, 0, 0), 1, + cv2.LINE_AA) + return out + + +def visualize_image_bboxes(image_path: str, detections: list[dict], debug_dir: str): + """Draw detections on a single image and save to debug_dir. + + Args: + image_path: Path to the source image. + detections: List of detection dicts from image_to_object_bboxes. + debug_dir: Directory to save the annotated image. + """ + os.makedirs(debug_dir, exist_ok=True) + image = cv2.imread(image_path) + if image is None: + raise FileNotFoundError(f"Cannot read image: {image_path}") + annotated = _draw_detections(image, detections) + stem = Path(image_path).stem + out_path = os.path.join(debug_dir, f"{stem}.jpg") + cv2.imwrite(out_path, annotated) + return out_path + + +def visualize_image_list_bboxes(rgb_path: str, results: dict, debug_dir: str): + """Draw detections on each image and save to debug_dir. + + Args: + rgb_path: Path to source frames (image dir, .h5, or video file). + results: Dict mapping image stem → list of detection dicts + (output of image_list_to_object_bboxes). + debug_dir: Directory to save annotated images. + """ + from v2d.common.video import FrameSource + + os.makedirs(debug_dir, exist_ok=True) + source = FrameSource.from_path(rgb_path) + stem_to_idx = {s: i for i, s in enumerate(source.stems)} + + written = 0 + for stem, detections in results.items(): + if stem not in stem_to_idx: + continue + image = source[stem_to_idx[stem]] + image_bgr = cv2.cvtColor(image, cv2.COLOR_RGB2BGR) + annotated = _draw_detections(image_bgr, detections) + out_path = os.path.join(debug_dir, f"{stem}.jpg") + cv2.imwrite(out_path, annotated) + written += 1 + print(f" [vis] saved {written} annotated images to: {debug_dir}") + + +def visualize_video_bboxes(video_path: str, results: dict, debug_dir: str): + """Draw detections on each frame of a video and save annotated frames to debug_dir. + + Args: + video_path: Path to the source video file. + results: Dict mapping frame index (str) → list of detection dicts + (output of video_to_object_bboxes). + debug_dir: Directory to save annotated frame images. + """ + os.makedirs(debug_dir, exist_ok=True) + cap = cv2.VideoCapture(video_path) + frame_idx = 0 + written = 0 + + while True: + ret, frame_bgr = cap.read() + if not ret: + break + detections = results.get(str(frame_idx), []) + annotated = _draw_detections(frame_bgr, detections) + out_path = os.path.join(debug_dir, f"{frame_idx:06d}.jpg") + cv2.imwrite(out_path, annotated) + frame_idx += 1 + written += 1 + + cap.release() + print(f" [vis] saved {written} annotated frames to: {debug_dir}") diff --git a/third-party/video_to_data/reconstruction/modules/v2d_gsplat_refinement/LICENSE b/third-party/video_to_data/reconstruction/modules/v2d_gsplat_refinement/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..10caffae439b956cdda2b1ded9ecbe51ac10befb --- /dev/null +++ b/third-party/video_to_data/reconstruction/modules/v2d_gsplat_refinement/LICENSE @@ -0,0 +1,15 @@ +# Apache License 2.0 + +Copyright 2025 NVIDIA CORPORATION + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. diff --git a/third-party/video_to_data/reconstruction/modules/v2d_gsplat_refinement/docker/Dockerfile b/third-party/video_to_data/reconstruction/modules/v2d_gsplat_refinement/docker/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..8e562d557dafa0ff1500115ca4ef2f73601953f6 --- /dev/null +++ b/third-party/video_to_data/reconstruction/modules/v2d_gsplat_refinement/docker/Dockerfile @@ -0,0 +1,42 @@ +FROM pytorch/pytorch:2.5.1-cuda12.4-cudnn9-devel +ENV DEBIAN_FRONTEND=noninteractive +WORKDIR /app + +RUN apt-get update && apt-get install -y --no-install-recommends \ + git wget ffmpeg \ + libgl1 libglib2.0-0 libxrender1 libsm6 libxext6 \ + libglm-dev \ + && rm -rf /var/lib/apt/lists/* + +# Build native CUDA extensions for the same arches as the rest of the repo. +ENV TORCH_CUDA_ARCH_LIST="8.0 8.6 8.9 9.0" +ENV FORCE_CUDA=1 + +RUN pip install --no-cache-dir \ + "numpy<2" \ + Pillow opencv-python tqdm \ + trimesh \ + imageio imageio-ffmpeg \ + scipy \ + roma + +# manotorch (and chumpy, its transitive runtime dep) aren't on PyPI for 3.11. +RUN pip install --no-cache-dir \ + git+https://github.com/lixiny/manotorch.git \ + git+https://github.com/mattloper/chumpy.git + +# gsplat builds CUDA kernels at install time; pinning a known-good tag keeps +# Dockerfile reproducibility independent of upstream HEAD. +RUN pip install --no-cache-dir --no-binary gsplat gsplat==1.4.0 + +RUN pip install rtree + +COPY . /workspace +RUN pip install -e /workspace/v2d_common \ + -e /workspace/v2d_gsplat_refinement/lib + +# Sanity-check imports at build time. +RUN python -c "import gsplat; from gsplat.rendering import rasterization; \ + from manotorch.manolayer import ManoLayer; \ + from v2d.gsplat_refinement.lib import refine; \ + print('gsplat_refinement imports OK')" diff --git a/third-party/video_to_data/reconstruction/modules/v2d_gsplat_refinement/docker/__init__.py b/third-party/video_to_data/reconstruction/modules/v2d_gsplat_refinement/docker/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..52a7a9daf028f654d6a02f65c99cc609a57b492f --- /dev/null +++ b/third-party/video_to_data/reconstruction/modules/v2d_gsplat_refinement/docker/__init__.py @@ -0,0 +1,2 @@ +# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 diff --git a/third-party/video_to_data/reconstruction/modules/v2d_gsplat_refinement/docker/_config.py b/third-party/video_to_data/reconstruction/modules/v2d_gsplat_refinement/docker/_config.py new file mode 100644 index 0000000000000000000000000000000000000000..26bbee166f0101c0f2a99ec596677c4dbb6844b2 --- /dev/null +++ b/third-party/video_to_data/reconstruction/modules/v2d_gsplat_refinement/docker/_config.py @@ -0,0 +1,6 @@ +# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 +import os + +IMAGE_NAME = "v2d_gsplat_refinement" +MODULES_DIR = os.path.abspath(os.path.join(os.path.dirname(os.path.abspath(__file__)), "..", "..")) diff --git a/third-party/video_to_data/reconstruction/modules/v2d_gsplat_refinement/docker/build.py b/third-party/video_to_data/reconstruction/modules/v2d_gsplat_refinement/docker/build.py new file mode 100644 index 0000000000000000000000000000000000000000..cbb099f18402123e0a57a61fca9469d0feeabd28 --- /dev/null +++ b/third-party/video_to_data/reconstruction/modules/v2d_gsplat_refinement/docker/build.py @@ -0,0 +1,19 @@ +# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 +import os +import subprocess + +IMAGE_NAME = "v2d_gsplat_refinement" + +current_dir = os.path.dirname(os.path.abspath(__file__)) +module_dir = os.path.join(current_dir, "..") +root_dir = os.path.join(module_dir, "..") +dockerfile_path = os.path.join(current_dir, "Dockerfile") + + +def build_docker_image() -> None: + subprocess.run(["docker", "build", "-t", IMAGE_NAME, "-f", dockerfile_path, root_dir], check=True) + + +if __name__ == "__main__": + build_docker_image() diff --git a/third-party/video_to_data/reconstruction/modules/v2d_gsplat_refinement/docker/pyproject.toml b/third-party/video_to_data/reconstruction/modules/v2d_gsplat_refinement/docker/pyproject.toml new file mode 100644 index 0000000000000000000000000000000000000000..8dfae2ec8ee650416c66b173519479fc88720b7a --- /dev/null +++ b/third-party/video_to_data/reconstruction/modules/v2d_gsplat_refinement/docker/pyproject.toml @@ -0,0 +1,18 @@ +# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 +[build-system] +requires = ["setuptools>=68.0", "wheel"] +build-backend = "setuptools.build_meta" + +[project] +name = "v2d-gsplat-refinement-docker" +version = "0.1.0" +description = "Docker orchestration for v2d_gsplat_refinement" +requires-python = ">=3.10" +dependencies = ["v2d-docker"] + +[tool.setuptools] +packages = ["v2d.gsplat_refinement.docker"] + +[tool.setuptools.package-dir] +"v2d.gsplat_refinement.docker" = "." diff --git a/third-party/video_to_data/reconstruction/modules/v2d_gsplat_refinement/docker/run_download_weights.py b/third-party/video_to_data/reconstruction/modules/v2d_gsplat_refinement/docker/run_download_weights.py new file mode 100644 index 0000000000000000000000000000000000000000..088c216e59c41645f684d899347fa2d9a37e55a5 --- /dev/null +++ b/third-party/video_to_data/reconstruction/modules/v2d_gsplat_refinement/docker/run_download_weights.py @@ -0,0 +1,22 @@ +# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 +"""No-op weights downloader. + +This module has no model weights of its own — gsplat ships its CUDA kernels +in the Docker image, manotorch loads MANO assets from the v2d_hamer weights +directory (caller passes ``--mano_assets_root``). Kept as a stub so the +build_containers.sh / weights-download orchestration is uniform across modules. +""" +from __future__ import annotations + + +def run_download(weights_path: str | None = None) -> None: + print(f"v2d_gsplat_refinement has no weights to download (got: {weights_path}).") + + +if __name__ == "__main__": + import argparse + p = argparse.ArgumentParser(description=__doc__) + p.add_argument("--weights_path", default=None) + args = p.parse_args() + run_download(args.weights_path) diff --git a/third-party/video_to_data/reconstruction/modules/v2d_gsplat_refinement/docker/run_refine.py b/third-party/video_to_data/reconstruction/modules/v2d_gsplat_refinement/docker/run_refine.py new file mode 100644 index 0000000000000000000000000000000000000000..eb153702e5a78d4b3f95d8062b1d336192b88bd9 --- /dev/null +++ b/third-party/video_to_data/reconstruction/modules/v2d_gsplat_refinement/docker/run_refine.py @@ -0,0 +1,732 @@ +# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 +from v2d.docker.container import run_in_container +from v2d.gsplat_refinement.docker._config import IMAGE_NAME, MODULES_DIR + + +def run_refine( + frames_dir: str, + intrinsics_path: str, + object_mesh_path: str, + object_poses_dir: str, + object_mask_dir: str, + refined_object_poses_dir: str, + overlay_path: str, + refined_object_scale_path: str | None = None, + left_hand_pose_dir: str | None = None, + left_hand_mask_dir: str | None = None, + right_hand_pose_dir: str | None = None, + right_hand_mask_dir: str | None = None, + refined_left_hand_pose_dir: str | None = None, + refined_right_hand_pose_dir: str | None = None, + depth_dir: str | None = None, + mano_assets_root: str | None = None, + n_epochs: int = 30, + n_gaussian_only_epochs: int = 5, + batch_size: int = 16, + lr_gaussians: float = 1e-2, + lr_hand_gaussians: float | None = None, + lr_mul_delta_p: float = 1.0, + lr_mul_quat: float = 1.0, + lr_mul_scale: float = 1.0, + lr_mul_opacity: float = 1.0, + lr_mul_color: float = 1.0, + lr_mul_obj_global_scale: float = 1.0, + lr_object_pose: float = 1e-2, + lr_object_rot: float | None = None, + lr_object_trans: float | None = None, + lr_hand_pose: float = 1e-2, + lr_hand_global_orient: float | None = None, + lr_hand_finger: float | None = None, + lr_hand_trans: float | None = None, + lr_betas: float = 1e-3, + learn_hand_scale: bool = False, + lr_hand_scale: float = 1e-3, + w_hand_scale_prior: float = 10.0, + render_every: int = 25, + progress_dir: str | None = None, + debug_frame_idx: int | None = None, + w_photometric: float = 1.0, + w_silhouette: float = 0.5, + w_silhouette_obj: float = 1.0, + w_silhouette_hand: float = 1.0, + w_depth: float = 0.05, + w_log_depth_grad: float = 0.0, + w_photometric_ssim: float = 0.0, + w_depth_ssim: float = 0.0, + w_smooth_obj_rot: float = 0.01, + w_smooth_obj_trans: float = 0.01, + w_smooth_hand_rot: float = 0.01, + w_smooth_hand_finger: float = 0.001, + w_smooth_hand_trans: float = 0.01, + w_beta_prior: float = 1.0, + w_delta_p_reg: float = 100.0, + w_delta_p_reg_obj: float | None = None, + w_delta_p_reg_hand: float | None = None, + w_delta_p_reg_bg: float | None = None, + w_obj_scale_prior: float = 1.0, + mask_background_to_black: bool = False, + balance_photometric_by_mask: bool = False, + freeze_object_rot: bool = False, + freeze_object_trans: bool = False, + freeze_object_scale: bool = False, + freeze_hand_rot: bool = False, + freeze_hand_trans: bool = False, + with_background: bool = False, + bg_ref_frame: int | None = None, + lr_bg_gaussians: float | None = None, + lr_bg_pose: float = 1e-3, + lr_bg_rot: float | None = None, + lr_bg_trans: float | None = None, + bg_max_points: int = 50000, + background_pose_init_dir: str | None = None, + bg_init_stride: int = 10, + bg_voxel_size: float = 0.005, + w_scale_aniso_bg: float = 0.0, + w_density_bg: float = 0.0, + n_density_neighbors: int = 8, + density_subsample_frac_bg: float = 0.2, + w_sdf_density_bg: float = 0.0, + w_normal_consistency_bg: float = 0.0, + n_sdf_samples_bg: int = 1000, + n_sdf_neighbors_bg: int = 8, + valid_mask_threshold: float = 0.04, + valid_mask_erode_iters: int = 2, + n_obj_gaussians: int | None = None, + n_hand_gaussians: int | None = None, + object_anchor_mode: str = "vertex", + hand_anchor_mode: str = "vertex", + face_normal_thin_factor_obj: float = 0.25, + face_normal_thin_factor_hand: float = 0.25, + init_opacity_obj: float = 0.9, + init_opacity_hand: float = 0.9, + init_opacity_bg: float = 0.9, + init_opacity_wrist: float = 0.5, + init_gaussian_scale_factor: float = 1.0, + init_hand_color_from_mask: bool = True, + smooth_obj_in_world: bool = False, + smooth_hand_in_world: bool = False, + n_wrist_gaussians: int = 0, + wrist_init_scale: float = 0.03, + wrist_init_radius: float = 0.0, + lr_wrist_gaussians: float | None = None, + w_delta_p_reg_wrist: float = 0.01, + learn_focal: bool = False, + learn_principal_point: bool = False, + lr_intrinsics: float = 1e-4, + w_intrinsics_prior: float = 1e3, + snap_rotation_outliers_every: int = 0, + snap_rotation_threshold: float = 1.0, + snap_rotation_window: int = 3, + snap_rotation_targets: str = "obj,hand_wrist", + snap_rotation_verbose: bool = False, + w_face_delta_p_tangent_obj: float = 1.0, + w_face_delta_p_normal_outward_obj: float = 100.0, + w_face_delta_p_normal_inward_obj: float = 0.0, + w_face_delta_p_tangent_hand: float = 1.0, + w_face_delta_p_normal_outward_hand: float = 100.0, + w_face_delta_p_normal_inward_hand: float = 0.0, + w_opacity_binary: float = 0.0, + w_opacity_binary_obj: float | None = None, + w_opacity_binary_hand: float | None = None, + w_opacity_binary_bg: float | None = None, + w_depth_variance: float = 0.0, + w_depth_ordering: float = 0.0, + depth_ordering_margin: float = 0.0, + use_cosine_lr_schedule: bool = False, + cosine_lr_min_ratio: float = 0.0, + coarse_init_scale_factor: float = 1.0, + coarse_decay_epochs: int | None = None, + pose_confidence_decay: float = 0.0, + pose_confidence_ref_frame: int | None = None, + pose_confidence_dynamic_tau: float = 0.0, + w_pose_init_prior: float = 0.0, + rotation_search_n_candidates: int = 0, + rotation_search_period: int = 0, + rotation_search_local_frac: float = 0.5, + rotation_search_local_max_deg: float = 30.0, + rotation_search_silhouette_weight: float = 1.0, + rotation_search_smoothness_weight: float = 1.0, + use_l2_photometric: bool = False, + use_l2_silhouette: bool = False, + train_resolution_scale: float = 1.0, + multiview_include_background: bool = False, + checkpoint_path: str | None = None, + checkpoint_every: int = 0, + resume_from_checkpoint: str | None = None, + ignore_optimizer_state: bool = False, + freeze_gaussians: bool = False, + random_init_obj_pose: bool = False, + random_init_obj_pose_trans_std: float = 0.1, + freeze_bg_rot: bool = False, + freeze_bg_trans: bool = False, + w_smooth_bg_rot: float = 0.1, + w_smooth_bg_trans: float = 0.1, + seed: int = 0, + dev: bool = False, +) -> None: + inputs: dict[str, str] = { + "frames_dir": frames_dir, + "intrinsics_path": intrinsics_path, + "object_mesh_path": object_mesh_path, + "object_poses_dir": object_poses_dir, + "object_mask_dir": object_mask_dir, + } + for k, v in { + "left_hand_pose_dir": left_hand_pose_dir, + "left_hand_mask_dir": left_hand_mask_dir, + "right_hand_pose_dir": right_hand_pose_dir, + "right_hand_mask_dir": right_hand_mask_dir, + "depth_dir": depth_dir, + "mano_assets_root": mano_assets_root, + "resume_from_checkpoint": resume_from_checkpoint, + "background_pose_init_dir": background_pose_init_dir, + }.items(): + if v is not None: + inputs[k] = v + + outputs: dict[str, str] = { + "refined_object_poses_dir": refined_object_poses_dir, + "overlay_path": overlay_path, + } + if refined_object_scale_path is not None: + outputs["refined_object_scale_path"] = refined_object_scale_path + for k, v in { + "refined_left_hand_pose_dir": refined_left_hand_pose_dir, + "refined_right_hand_pose_dir": refined_right_hand_pose_dir, + "progress_dir": progress_dir, + "checkpoint_path": checkpoint_path, + }.items(): + if v is not None: + outputs[k] = v + + extra_args: dict[str, object] = { + "n_epochs": n_epochs, + "n_gaussian_only_epochs": n_gaussian_only_epochs, + "batch_size": batch_size, + "lr_gaussians": lr_gaussians, + "lr_hand_gaussians": lr_hand_gaussians, + "lr_mul_delta_p": lr_mul_delta_p, + "lr_mul_quat": lr_mul_quat, + "lr_mul_scale": lr_mul_scale, + "lr_mul_opacity": lr_mul_opacity, + "lr_mul_color": lr_mul_color, + "lr_mul_obj_global_scale": lr_mul_obj_global_scale, + "lr_object_pose": lr_object_pose, + "lr_object_rot": lr_object_rot, + "lr_object_trans": lr_object_trans, + "lr_hand_pose": lr_hand_pose, + "lr_hand_global_orient": lr_hand_global_orient, + "lr_hand_finger": lr_hand_finger, + "lr_hand_trans": lr_hand_trans, + "lr_betas": lr_betas, + "learn_hand_scale": learn_hand_scale, + "lr_hand_scale": lr_hand_scale, + "w_hand_scale_prior": w_hand_scale_prior, + "render_every": render_every, + "debug_frame_idx": debug_frame_idx, + "w_photometric": w_photometric, + "w_silhouette": w_silhouette, + "w_silhouette_obj": w_silhouette_obj, + "w_silhouette_hand": w_silhouette_hand, + "w_depth": w_depth, + "w_log_depth_grad": w_log_depth_grad, + "w_photometric_ssim": w_photometric_ssim, + "w_depth_ssim": w_depth_ssim, + "w_smooth_obj_rot": w_smooth_obj_rot, + "w_smooth_obj_trans": w_smooth_obj_trans, + "w_smooth_hand_rot": w_smooth_hand_rot, + "w_smooth_hand_finger": w_smooth_hand_finger, + "w_smooth_hand_trans": w_smooth_hand_trans, + "w_beta_prior": w_beta_prior, + "w_delta_p_reg": w_delta_p_reg, + "w_delta_p_reg_obj": w_delta_p_reg_obj, + "w_delta_p_reg_hand": w_delta_p_reg_hand, + "w_delta_p_reg_bg": w_delta_p_reg_bg, + "w_obj_scale_prior": w_obj_scale_prior, + "mask_background_to_black": mask_background_to_black, + "balance_photometric_by_mask": balance_photometric_by_mask, + "freeze_object_rot": freeze_object_rot, + "freeze_object_trans": freeze_object_trans, + "freeze_object_scale": freeze_object_scale, + "freeze_hand_rot": freeze_hand_rot, + "freeze_hand_trans": freeze_hand_trans, + "with_background": with_background, + "bg_ref_frame": bg_ref_frame, + "lr_bg_gaussians": lr_bg_gaussians, + "lr_bg_pose": lr_bg_pose, + "lr_bg_rot": lr_bg_rot, + "lr_bg_trans": lr_bg_trans, + "bg_max_points": bg_max_points, + "bg_init_stride": bg_init_stride, + "bg_voxel_size": bg_voxel_size, + "w_scale_aniso_bg": w_scale_aniso_bg, + "w_density_bg": w_density_bg, + "n_density_neighbors": n_density_neighbors, + "density_subsample_frac_bg": density_subsample_frac_bg, + "w_sdf_density_bg": w_sdf_density_bg, + "w_normal_consistency_bg": w_normal_consistency_bg, + "n_sdf_samples_bg": n_sdf_samples_bg, + "n_sdf_neighbors_bg": n_sdf_neighbors_bg, + "valid_mask_threshold": valid_mask_threshold, + "valid_mask_erode_iters": valid_mask_erode_iters, + "n_obj_gaussians": n_obj_gaussians, + "n_hand_gaussians": n_hand_gaussians, + "object_anchor_mode": object_anchor_mode, + "hand_anchor_mode": hand_anchor_mode, + "face_normal_thin_factor_obj": face_normal_thin_factor_obj, + "face_normal_thin_factor_hand": face_normal_thin_factor_hand, + "init_opacity_obj": init_opacity_obj, + "init_opacity_hand": init_opacity_hand, + "init_opacity_bg": init_opacity_bg, + "init_opacity_wrist": init_opacity_wrist, + "init_gaussian_scale_factor": init_gaussian_scale_factor, + # Lib accepts only the negated form (--no_init_hand_color_from_mask) + # because the lib default is True. Flip the polarity so the + # container emits nothing in the default case and emits the flag + # only when the user opts out. + "no_init_hand_color_from_mask": not init_hand_color_from_mask, + "smooth_obj_in_world": smooth_obj_in_world, + "smooth_hand_in_world": smooth_hand_in_world, + "n_wrist_gaussians": n_wrist_gaussians, + "wrist_init_scale": wrist_init_scale, + "wrist_init_radius": wrist_init_radius, + "lr_wrist_gaussians": lr_wrist_gaussians, + "w_delta_p_reg_wrist": w_delta_p_reg_wrist, + "learn_focal": learn_focal, + "learn_principal_point": learn_principal_point, + "lr_intrinsics": lr_intrinsics, + "w_intrinsics_prior": w_intrinsics_prior, + "snap_rotation_outliers_every": snap_rotation_outliers_every, + "snap_rotation_threshold": snap_rotation_threshold, + "snap_rotation_window": snap_rotation_window, + "snap_rotation_targets": snap_rotation_targets, + "snap_rotation_verbose": snap_rotation_verbose, + "w_face_delta_p_tangent_obj": w_face_delta_p_tangent_obj, + "w_face_delta_p_normal_outward_obj": w_face_delta_p_normal_outward_obj, + "w_face_delta_p_normal_inward_obj": w_face_delta_p_normal_inward_obj, + "w_face_delta_p_tangent_hand": w_face_delta_p_tangent_hand, + "w_face_delta_p_normal_outward_hand": w_face_delta_p_normal_outward_hand, + "w_face_delta_p_normal_inward_hand": w_face_delta_p_normal_inward_hand, + "w_opacity_binary": w_opacity_binary, + "w_opacity_binary_obj": w_opacity_binary_obj, + "w_opacity_binary_hand": w_opacity_binary_hand, + "w_opacity_binary_bg": w_opacity_binary_bg, + "w_depth_variance": w_depth_variance, + "w_depth_ordering": w_depth_ordering, + "depth_ordering_margin": depth_ordering_margin, + "use_cosine_lr_schedule": use_cosine_lr_schedule, + "cosine_lr_min_ratio": cosine_lr_min_ratio, + "coarse_init_scale_factor": coarse_init_scale_factor, + "coarse_decay_epochs": coarse_decay_epochs, + "pose_confidence_decay": pose_confidence_decay, + "pose_confidence_ref_frame": pose_confidence_ref_frame, + "pose_confidence_dynamic_tau": pose_confidence_dynamic_tau, + "w_pose_init_prior": w_pose_init_prior, + "rotation_search_n_candidates": rotation_search_n_candidates, + "rotation_search_period": rotation_search_period, + "rotation_search_local_frac": rotation_search_local_frac, + "rotation_search_local_max_deg": rotation_search_local_max_deg, + "rotation_search_silhouette_weight": rotation_search_silhouette_weight, + "rotation_search_smoothness_weight": rotation_search_smoothness_weight, + "use_l2_photometric": use_l2_photometric, + "use_l2_silhouette": use_l2_silhouette, + "train_resolution_scale": train_resolution_scale, + "multiview_include_background": multiview_include_background, + "ignore_optimizer_state": ignore_optimizer_state, + "freeze_gaussians": freeze_gaussians, + "random_init_obj_pose": random_init_obj_pose, + "random_init_obj_pose_trans_std": random_init_obj_pose_trans_std, + "freeze_bg_rot": freeze_bg_rot, + "freeze_bg_trans": freeze_bg_trans, + "w_smooth_bg_rot": w_smooth_bg_rot, + "w_smooth_bg_trans": w_smooth_bg_trans, + "checkpoint_every": checkpoint_every, + "seed": seed, + } + + run_in_container( + image = IMAGE_NAME, + module = "v2d.gsplat_refinement.lib.refine", + inputs = inputs, + outputs = outputs, + extra_args = extra_args, + dev = dev, + modules_dir = MODULES_DIR, + gpus = True, + ) + + +if __name__ == "__main__": + import argparse + + p = argparse.ArgumentParser(description="Joint hand+object pose refinement via Gaussian splatting") + p.add_argument("--frames_dir", required=True) + p.add_argument("--intrinsics_path", required=True) + p.add_argument("--object_mesh_path", required=True) + p.add_argument("--object_poses_dir", required=True) + p.add_argument("--object_mask_dir", required=True) + p.add_argument("--refined_object_poses_dir", required=True) + p.add_argument("--overlay_path", required=True) + p.add_argument("--left_hand_pose_dir", default=None) + p.add_argument("--left_hand_mask_dir", default=None) + p.add_argument("--right_hand_pose_dir", default=None) + p.add_argument("--right_hand_mask_dir", default=None) + p.add_argument("--refined_left_hand_pose_dir", default=None) + p.add_argument("--refined_right_hand_pose_dir", default=None) + p.add_argument("--depth_dir", default=None) + p.add_argument("--mano_assets_root", default=None) + p.add_argument("--n_epochs", type=int, default=30) + p.add_argument("--n_gaussian_only_epochs", type=int, default=5) + p.add_argument("--batch_size", type=int, default=4) + p.add_argument("--lr_gaussians", type=float, default=1e-2) + p.add_argument("--lr_hand_gaussians", type=float, default=None) + p.add_argument("--lr_mul_delta_p", type=float, default=1.0) + p.add_argument("--lr_mul_quat", type=float, default=1.0) + p.add_argument("--lr_mul_scale", type=float, default=1.0) + p.add_argument("--lr_mul_opacity", type=float, default=1.0) + p.add_argument("--lr_mul_color", type=float, default=1.0) + p.add_argument("--lr_mul_obj_global_scale", type=float, default=1.0) + p.add_argument("--lr_object_pose", type=float, default=1e-3) + p.add_argument("--lr_object_rot", type=float, default=None) + p.add_argument("--lr_object_trans", type=float, default=None) + p.add_argument("--lr_hand_pose", type=float, default=1e-3) + p.add_argument("--lr_hand_global_orient", type=float, default=None) + p.add_argument("--lr_hand_finger", type=float, default=None) + p.add_argument("--lr_hand_trans", type=float, default=None) + p.add_argument("--lr_betas", type=float, default=1e-4) + p.add_argument("--learn_hand_scale", action="store_true") + p.add_argument("--lr_hand_scale", type=float, default=1e-3) + p.add_argument("--w_hand_scale_prior", type=float, default=10.0) + p.add_argument("--render_every", type=int, default=0) + p.add_argument("--progress_dir", default=None) + p.add_argument("--debug_frame_idx", type=int, default=None) + p.add_argument("--w_photometric", type=float, default=1.0) + p.add_argument("--w_silhouette", type=float, default=0.5) + p.add_argument("--w_silhouette_obj", type=float, default=1.0) + p.add_argument("--w_silhouette_hand", type=float, default=1.0) + p.add_argument("--w_depth", type=float, default=0.05) + p.add_argument("--w_log_depth_grad", type=float, default=0.0) + p.add_argument("--w_photometric_ssim", type=float, default=0.0, + help="SSIM photometric loss weight (1 - SSIM, 11x11 " + "Gaussian window). 3DGS pairs at ~0.2 with L1=1.0.") + p.add_argument("--w_depth_ssim", type=float, default=0.0, + help="SSIM depth loss weight (1 - SSIM on log-depth, " + "percentile-normalized). Try ~0.1.") + p.add_argument("--w_smooth_obj_rot", type=float, default=0.01) + p.add_argument("--w_smooth_obj_trans", type=float, default=0.01) + p.add_argument("--w_smooth_hand_rot", type=float, default=0.01) + p.add_argument("--w_smooth_hand_finger", type=float, default=0.001) + p.add_argument("--w_smooth_hand_trans", type=float, default=0.01) + p.add_argument("--w_beta_prior", type=float, default=10.0) + p.add_argument("--w_delta_p_reg", type=float, default=100.0) + p.add_argument("--w_delta_p_reg_obj", type=float, default=None) + p.add_argument("--w_delta_p_reg_hand", type=float, default=None) + p.add_argument("--w_delta_p_reg_bg", type=float, default=None) + p.add_argument("--w_obj_scale_prior", type=float, default=1.0) + p.add_argument("--mask_background_to_black", action="store_true") + p.add_argument("--balance_photometric_by_mask", action="store_true") + p.add_argument("--freeze_object_rot", action="store_true") + p.add_argument("--freeze_object_trans", action="store_true") + p.add_argument("--freeze_object_scale", action="store_true") + p.add_argument("--freeze_hand_rot", action="store_true") + p.add_argument("--freeze_hand_trans", action="store_true") + p.add_argument("--with_background", action="store_true") + p.add_argument("--bg_ref_frame", type=int, default=None) + p.add_argument("--lr_bg_gaussians", type=float, default=None) + p.add_argument("--lr_bg_pose", type=float, default=1e-3) + p.add_argument("--lr_bg_rot", type=float, default=None) + p.add_argument("--lr_bg_trans", type=float, default=None) + p.add_argument("--bg_max_points", type=int, default=50000) + p.add_argument("--background_pose_init_dir", default=None, + help="Optional folder of per-frame Transform3d JSONs " + "(cam-to-world; DROID/COLMAP convention) used to " + "seed the background pose field.") + p.add_argument("--bg_init_stride", type=int, default=10, + help="Stride for multi-frame BG point-cloud init " + "(used only with --background_pose_init_dir).") + p.add_argument("--bg_voxel_size", type=float, default=0.005, + help="Voxel size (m) for BG point-cloud dedup before " + "random subsample.") + p.add_argument("--w_scale_aniso_bg", type=float, default=0.0) + p.add_argument("--w_density_bg", type=float, default=0.0) + p.add_argument("--n_density_neighbors", type=int, default=8) + p.add_argument("--density_subsample_frac_bg", type=float, default=0.2) + p.add_argument("--w_sdf_density_bg", type=float, default=0.0) + p.add_argument("--w_normal_consistency_bg", type=float, default=0.0) + p.add_argument("--n_sdf_samples_bg", type=int, default=1000) + p.add_argument("--n_sdf_neighbors_bg", type=int, default=8) + p.add_argument("--valid_mask_threshold", type=float, default=0.04, + help="Max-brightness threshold (in [0,1] image scale) for " + "the static valid-pixel mask derived from the input " + "video. Pixels whose max brightness across all frames " + "is below this are treated as fixed dead/black " + "regions (fisheye crop, vignette) and excluded from " + "photometric / depth / SuGaR supervision. Set to 0 " + "to disable.") + p.add_argument("--valid_mask_erode_iters", type=int, default=2, + help="Number of 3x3 erosion passes on the valid-pixel " + "mask to peel back the soft boundary transition.") + p.add_argument("--n_obj_gaussians", type=int, default=None) + p.add_argument("--n_hand_gaussians", type=int, default=None) + p.add_argument("--object_anchor_mode", choices=["vertex", "face"], + default="vertex", + help="Anchor mode for object Gaussians. 'face' switches to " + "one Gaussian per mesh face with Δp in face-local " + "(T, B, N) coords. See lib CLI for details.") + p.add_argument("--hand_anchor_mode", choices=["vertex", "face"], + default="vertex", + help="Anchor mode for hand Gaussians (same options).") + p.add_argument("--face_normal_thin_factor_obj", type=float, default=0.25) + p.add_argument("--face_normal_thin_factor_hand", type=float, default=0.25) + p.add_argument("--init_opacity_obj", type=float, default=0.9) + p.add_argument("--init_opacity_hand", type=float, default=0.9) + p.add_argument("--init_opacity_bg", type=float, default=0.9) + p.add_argument("--init_opacity_wrist", type=float, default=0.5) + p.add_argument("--init_gaussian_scale_factor", type=float, default=1.0) + p.add_argument("--no_init_hand_color_from_mask", + dest="init_hand_color_from_mask", + action="store_false", + help="Disable per-hand Gaussian color init from the SAM2 " + "mask mean at the reference frame. Default is on.") + p.set_defaults(init_hand_color_from_mask=True) + p.add_argument("--smooth_obj_in_world", action="store_true", + help="Measure object pose smoothness in world frame " + "(via bg_pose_field). Requires --with_background.") + p.add_argument("--smooth_hand_in_world", action="store_true", + help="Measure hand wrist (global_orient + cam_t) " + "smoothness in world frame. Finger smoothness " + "stays in cam frame. Requires --with_background.") + p.add_argument("--n_wrist_gaussians", type=int, default=0, + help="Per-hand count of wrist-attached arm Gaussians " + "(rigidly attached to MANO wrist; not skinned). " + "0 disables.") + p.add_argument("--wrist_init_scale", type=float, default=0.03) + p.add_argument("--wrist_init_radius", type=float, default=0.0) + p.add_argument("--lr_wrist_gaussians", type=float, default=None) + p.add_argument("--w_delta_p_reg_wrist", type=float, default=0.01) + p.add_argument("--learn_focal", action="store_true", + help="Refine fx, fy. Caution: degenerate with scene " + "scale without depth supervision.") + p.add_argument("--learn_principal_point", action="store_true", + help="Refine cx, cy. Safer than --learn_focal.") + p.add_argument("--lr_intrinsics", type=float, default=1e-4) + p.add_argument("--w_intrinsics_prior", type=float, default=1e3) + p.add_argument("--snap_rotation_outliers_every", type=int, default=0, + help="Periodicity (in optimizer steps) of the rotation " + "outlier median-snap pass. 0 disables.") + p.add_argument("--snap_rotation_threshold", type=float, default=1.0) + p.add_argument("--snap_rotation_window", type=int, default=3) + p.add_argument("--snap_rotation_targets", type=str, + default="obj,hand_wrist", + help="Comma-sep subset of {obj, hand_wrist, hand_finger}.") + p.add_argument("--snap_rotation_verbose", action="store_true") + p.add_argument("--w_face_delta_p_tangent_obj", type=float, default=1.0) + p.add_argument("--w_face_delta_p_normal_outward_obj", type=float, default=100.0) + p.add_argument("--w_face_delta_p_normal_inward_obj", type=float, default=0.0) + p.add_argument("--w_face_delta_p_tangent_hand", type=float, default=1.0) + p.add_argument("--w_face_delta_p_normal_outward_hand", type=float, default=100.0) + p.add_argument("--w_face_delta_p_normal_inward_hand", type=float, default=0.0) + p.add_argument("--w_opacity_binary", type=float, default=0.0, + help="α(1-α) opacity binarization weight (fallback for " + "obj/hand/bg unless overridden). 0 disables.") + p.add_argument("--w_opacity_binary_obj", type=float, default=None) + p.add_argument("--w_opacity_binary_hand", type=float, default=None) + p.add_argument("--w_opacity_binary_bg", type=float, default=None) + p.add_argument("--w_depth_variance", type=float, default=0.0, + help="Depth-variance distortion proxy weight " + "(Mip-NeRF 360 distloss approximation). 0 disables.") + p.add_argument("--w_depth_ordering", type=float, default=0.0, + help="FG/BG depth-ordering penetration weight: penalize " + "fg Gaussians sitting behind the bg at fg-mask " + "pixels. Requires --with_background. Units: [depth]. " + "0 disables.") + p.add_argument("--depth_ordering_margin", type=float, default=0.0, + help="Slack (m) in the depth-ordering inequality. Positive " + "margin enforces a gap, zero allows touching.") + p.add_argument("--use_cosine_lr_schedule", action="store_true") + p.add_argument("--cosine_lr_min_ratio", type=float, default=0.0) + p.add_argument("--coarse_init_scale_factor", type=float, default=1.0) + p.add_argument("--coarse_decay_epochs", type=int, default=None) + p.add_argument("--pose_confidence_decay", type=float, default=0.0) + p.add_argument("--pose_confidence_ref_frame", type=int, default=None) + p.add_argument("--pose_confidence_dynamic_tau", type=float, default=0.0) + p.add_argument("--w_pose_init_prior", type=float, default=0.0) + p.add_argument("--rotation_search_n_candidates", type=int, default=0) + p.add_argument("--rotation_search_period", type=int, default=0) + p.add_argument("--rotation_search_local_frac", type=float, default=0.5) + p.add_argument("--rotation_search_local_max_deg", type=float, default=30.0) + p.add_argument("--rotation_search_silhouette_weight", type=float, default=1.0) + p.add_argument("--rotation_search_smoothness_weight", type=float, default=1.0) + p.add_argument("--use_l2_photometric", action="store_true") + p.add_argument("--use_l2_silhouette", action="store_true") + p.add_argument("--train_resolution_scale", type=float, default=1.0) + p.add_argument("--multiview_include_background", action="store_true") + p.add_argument("--ignore_optimizer_state", action="store_true") + p.add_argument("--freeze_gaussians", action="store_true") + p.add_argument("--random_init_obj_pose", action="store_true") + p.add_argument("--random_init_obj_pose_trans_std", type=float, default=0.1) + p.add_argument("--freeze_bg_rot", action="store_true") + p.add_argument("--freeze_bg_trans", action="store_true") + p.add_argument("--w_smooth_bg_rot", type=float, default=0.1) + p.add_argument("--w_smooth_bg_trans", type=float, default=0.1) + p.add_argument("--seed", type=int, default=0) + p.add_argument("--dev", action="store_true") + args = p.parse_args() + run_refine( + frames_dir = args.frames_dir, + intrinsics_path = args.intrinsics_path, + object_mesh_path = args.object_mesh_path, + object_poses_dir = args.object_poses_dir, + object_mask_dir = args.object_mask_dir, + refined_object_poses_dir = args.refined_object_poses_dir, + overlay_path = args.overlay_path, + left_hand_pose_dir = args.left_hand_pose_dir, + left_hand_mask_dir = args.left_hand_mask_dir, + right_hand_pose_dir = args.right_hand_pose_dir, + right_hand_mask_dir = args.right_hand_mask_dir, + refined_left_hand_pose_dir = args.refined_left_hand_pose_dir, + refined_right_hand_pose_dir = args.refined_right_hand_pose_dir, + depth_dir = args.depth_dir, + mano_assets_root = args.mano_assets_root, + n_epochs = args.n_epochs, + n_gaussian_only_epochs = args.n_gaussian_only_epochs, + batch_size = args.batch_size, + lr_gaussians = args.lr_gaussians, + lr_hand_gaussians = args.lr_hand_gaussians, + lr_mul_delta_p = args.lr_mul_delta_p, + lr_mul_quat = args.lr_mul_quat, + lr_mul_scale = args.lr_mul_scale, + lr_mul_opacity = args.lr_mul_opacity, + lr_mul_color = args.lr_mul_color, + lr_mul_obj_global_scale = args.lr_mul_obj_global_scale, + lr_object_pose = args.lr_object_pose, + lr_object_rot = args.lr_object_rot, + lr_object_trans = args.lr_object_trans, + lr_hand_global_orient = args.lr_hand_global_orient, + lr_hand_finger = args.lr_hand_finger, + lr_hand_trans = args.lr_hand_trans, + lr_bg_rot = args.lr_bg_rot, + lr_bg_trans = args.lr_bg_trans, + lr_hand_pose = args.lr_hand_pose, + lr_betas = args.lr_betas, + learn_hand_scale = args.learn_hand_scale, + lr_hand_scale = args.lr_hand_scale, + w_hand_scale_prior = args.w_hand_scale_prior, + render_every = args.render_every, + progress_dir = args.progress_dir, + debug_frame_idx = args.debug_frame_idx, + w_photometric = args.w_photometric, + w_silhouette = args.w_silhouette, + w_silhouette_obj = args.w_silhouette_obj, + w_silhouette_hand = args.w_silhouette_hand, + w_depth = args.w_depth, + w_log_depth_grad = args.w_log_depth_grad, + w_photometric_ssim = args.w_photometric_ssim, + w_depth_ssim = args.w_depth_ssim, + w_smooth_obj_rot = args.w_smooth_obj_rot, + w_smooth_obj_trans = args.w_smooth_obj_trans, + w_smooth_hand_rot = args.w_smooth_hand_rot, + w_smooth_hand_finger = args.w_smooth_hand_finger, + w_smooth_hand_trans = args.w_smooth_hand_trans, + w_beta_prior = args.w_beta_prior, + w_delta_p_reg = args.w_delta_p_reg, + w_delta_p_reg_obj = args.w_delta_p_reg_obj, + w_delta_p_reg_hand = args.w_delta_p_reg_hand, + w_delta_p_reg_bg = args.w_delta_p_reg_bg, + w_obj_scale_prior = args.w_obj_scale_prior, + mask_background_to_black = args.mask_background_to_black, + balance_photometric_by_mask = args.balance_photometric_by_mask, + freeze_object_rot = args.freeze_object_rot, + freeze_object_trans = args.freeze_object_trans, + freeze_object_scale = args.freeze_object_scale, + freeze_hand_rot = args.freeze_hand_rot, + freeze_hand_trans = args.freeze_hand_trans, + with_background = args.with_background, + bg_ref_frame = args.bg_ref_frame, + lr_bg_gaussians = args.lr_bg_gaussians, + lr_bg_pose = args.lr_bg_pose, + bg_max_points = args.bg_max_points, + background_pose_init_dir = args.background_pose_init_dir, + bg_init_stride = args.bg_init_stride, + bg_voxel_size = args.bg_voxel_size, + w_scale_aniso_bg = args.w_scale_aniso_bg, + w_density_bg = args.w_density_bg, + n_density_neighbors = args.n_density_neighbors, + density_subsample_frac_bg = args.density_subsample_frac_bg, + w_sdf_density_bg = args.w_sdf_density_bg, + w_normal_consistency_bg = args.w_normal_consistency_bg, + n_sdf_samples_bg = args.n_sdf_samples_bg, + n_sdf_neighbors_bg = args.n_sdf_neighbors_bg, + valid_mask_threshold = args.valid_mask_threshold, + valid_mask_erode_iters = args.valid_mask_erode_iters, + n_obj_gaussians = args.n_obj_gaussians, + n_hand_gaussians = args.n_hand_gaussians, + object_anchor_mode = args.object_anchor_mode, + hand_anchor_mode = args.hand_anchor_mode, + face_normal_thin_factor_obj = args.face_normal_thin_factor_obj, + face_normal_thin_factor_hand = args.face_normal_thin_factor_hand, + init_opacity_obj = args.init_opacity_obj, + init_opacity_hand = args.init_opacity_hand, + init_opacity_bg = args.init_opacity_bg, + init_opacity_wrist = args.init_opacity_wrist, + init_gaussian_scale_factor = args.init_gaussian_scale_factor, + init_hand_color_from_mask = args.init_hand_color_from_mask, + smooth_obj_in_world = args.smooth_obj_in_world, + smooth_hand_in_world = args.smooth_hand_in_world, + n_wrist_gaussians = args.n_wrist_gaussians, + wrist_init_scale = args.wrist_init_scale, + wrist_init_radius = args.wrist_init_radius, + lr_wrist_gaussians = args.lr_wrist_gaussians, + w_delta_p_reg_wrist = args.w_delta_p_reg_wrist, + learn_focal = args.learn_focal, + learn_principal_point = args.learn_principal_point, + lr_intrinsics = args.lr_intrinsics, + w_intrinsics_prior = args.w_intrinsics_prior, + snap_rotation_outliers_every = args.snap_rotation_outliers_every, + snap_rotation_threshold = args.snap_rotation_threshold, + snap_rotation_window = args.snap_rotation_window, + snap_rotation_targets = args.snap_rotation_targets, + snap_rotation_verbose = args.snap_rotation_verbose, + w_face_delta_p_tangent_obj = args.w_face_delta_p_tangent_obj, + w_face_delta_p_normal_outward_obj = args.w_face_delta_p_normal_outward_obj, + w_face_delta_p_normal_inward_obj = args.w_face_delta_p_normal_inward_obj, + w_face_delta_p_tangent_hand = args.w_face_delta_p_tangent_hand, + w_face_delta_p_normal_outward_hand = args.w_face_delta_p_normal_outward_hand, + w_face_delta_p_normal_inward_hand = args.w_face_delta_p_normal_inward_hand, + w_opacity_binary = args.w_opacity_binary, + w_opacity_binary_obj = args.w_opacity_binary_obj, + w_opacity_binary_hand = args.w_opacity_binary_hand, + w_opacity_binary_bg = args.w_opacity_binary_bg, + w_depth_variance = args.w_depth_variance, + w_depth_ordering = args.w_depth_ordering, + depth_ordering_margin = args.depth_ordering_margin, + use_cosine_lr_schedule = args.use_cosine_lr_schedule, + cosine_lr_min_ratio = args.cosine_lr_min_ratio, + coarse_init_scale_factor = args.coarse_init_scale_factor, + coarse_decay_epochs = args.coarse_decay_epochs, + pose_confidence_decay = args.pose_confidence_decay, + pose_confidence_ref_frame = args.pose_confidence_ref_frame, + pose_confidence_dynamic_tau = args.pose_confidence_dynamic_tau, + w_pose_init_prior = args.w_pose_init_prior, + rotation_search_n_candidates = args.rotation_search_n_candidates, + rotation_search_period = args.rotation_search_period, + rotation_search_local_frac = args.rotation_search_local_frac, + rotation_search_local_max_deg = args.rotation_search_local_max_deg, + rotation_search_silhouette_weight = args.rotation_search_silhouette_weight, + rotation_search_smoothness_weight = args.rotation_search_smoothness_weight, + use_l2_photometric = args.use_l2_photometric, + use_l2_silhouette = args.use_l2_silhouette, + train_resolution_scale = args.train_resolution_scale, + multiview_include_background = args.multiview_include_background, + ignore_optimizer_state = args.ignore_optimizer_state, + freeze_gaussians = args.freeze_gaussians, + random_init_obj_pose = args.random_init_obj_pose, + random_init_obj_pose_trans_std = args.random_init_obj_pose_trans_std, + freeze_bg_rot = args.freeze_bg_rot, + freeze_bg_trans = args.freeze_bg_trans, + w_smooth_bg_rot = args.w_smooth_bg_rot, + w_smooth_bg_trans = args.w_smooth_bg_trans, + seed = args.seed, + dev = args.dev, + ) diff --git a/third-party/video_to_data/reconstruction/modules/v2d_gsplat_refinement/docker/run_refine_simple.py b/third-party/video_to_data/reconstruction/modules/v2d_gsplat_refinement/docker/run_refine_simple.py new file mode 100644 index 0000000000000000000000000000000000000000..f68cb911780533deb28b8a424702a8258b719636 --- /dev/null +++ b/third-party/video_to_data/reconstruction/modules/v2d_gsplat_refinement/docker/run_refine_simple.py @@ -0,0 +1,278 @@ +# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 +import os +from v2d.docker.container import run_in_container +from v2d.gsplat_refinement.docker._config import IMAGE_NAME, MODULES_DIR + + +def run_refine_simple( + frames_dir: str, + depth_dir: str | None, + intrinsics_path: str, + object_mesh_path: str, + object_poses_dir: str, + object_mask_dir: str, + refined_object_poses_dir: str, + overlay_path: str, + left_hand_pose_dir: str | None = None, + left_hand_mask_dir: str | None = None, + right_hand_pose_dir: str | None = None, + right_hand_mask_dir: str | None = None, + refined_left_hand_pose_dir: str | None = None, + refined_right_hand_pose_dir: str | None = None, + refined_camera_poses_dir: str | None = None, + mano_assets_root: str | None = None, + background_pose_init_dir: str | None = None, + n_epochs: int = 20, + batch_size: int = 32, + train_resolution_scale: float = 0.5, + lr_gaussians: float = 3e-3, + lr_object_pose: float = 3e-3, + lr_object_scale: float = 0.0, + lr_hand_pose: float = 3e-3, + lr_hand_articulation: float = 0.0, + lr_hand_shape: float = 0.0, + lr_hand_scale: float = 0.0, + lr_camera_pose: float = 3e-3, + lr_schedule: str = "constant", + lr_cosine_min_factor: float = 0.0, + w_smooth_object_rot: float = 0.1, + w_smooth_object_trans: float = 0.1, + w_smooth_hand_rot: float = 0.1, + w_smooth_hand_articulation: float = 0.1, + w_smooth_hand_trans: float = 0.1, + w_smooth_hand_object_relative_rot: float = 0.0, + w_smooth_hand_object_relative_trans: float = 0.0, + w_smooth_camera_rot: float = 0.1, + w_smooth_camera_trans: float = 0.1, + w_mask: float = 1.0, + w_relative_depth: float = 0.0, + w_perceptual: float = 0.0, + vgg_weights_path: str | None = None, + perceptual_resize: int = 224, + w_hand_object_penetration: float = 0.0, + hand_object_penetration_margin: float = 0.003, + object_sdf_resolution: int = 96, + hand_object_penetration_max_verts: int = 0, + mask_background: bool = False, + bg_ref_frame: int | None = None, + bg_init_stride: int = 10, + bg_voxel_size: float = 0.005, + bg_max_points: int = 50000, + valid_mask_threshold: float = 0.04, + valid_mask_erode_iters: int = 2, + face_normal_thin_factor_obj: float = 0.25, + face_normal_thin_factor_hand: float = 0.25, + init_opacity_obj: float = 0.9, + init_opacity_hand: float = 0.9, + init_opacity_bg: float = 0.9, + init_gaussian_scale_factor: float = 1.0, + render_every: int = 25, + progress_dir: str | None = None, + debug_frame_idx: int | None = None, + fps: float = 30.0, + seed: int = 0, + dev: bool = False, +) -> None: + if not mask_background and depth_dir is None: + raise ValueError("depth_dir is required unless --mask-background is set") + if float(w_relative_depth) > 0.0 and depth_dir is None: + raise ValueError("depth_dir is required when w_relative_depth is nonzero") + if vgg_weights_path is not None: + os.makedirs( + os.path.dirname(os.path.abspath(vgg_weights_path)) or ".", + exist_ok=True, + ) + + inputs: dict[str, str] = { + "frames_dir": frames_dir, + "intrinsics_path": intrinsics_path, + "object_mesh_path": object_mesh_path, + "object_poses_dir": object_poses_dir, + "object_mask_dir": object_mask_dir, + } + if depth_dir is not None: + inputs["depth_dir"] = depth_dir + for k, v in { + "left_hand_pose_dir": left_hand_pose_dir, + "left_hand_mask_dir": left_hand_mask_dir, + "right_hand_pose_dir": right_hand_pose_dir, + "right_hand_mask_dir": right_hand_mask_dir, + "mano_assets_root": mano_assets_root, + "background_pose_init_dir": background_pose_init_dir, + "vgg_weights_path": vgg_weights_path, + }.items(): + if v is not None: + inputs[k] = v + + outputs: dict[str, str] = { + "refined_object_poses_dir": refined_object_poses_dir, + "overlay_path": overlay_path, + } + for k, v in { + "refined_left_hand_pose_dir": refined_left_hand_pose_dir, + "refined_right_hand_pose_dir": refined_right_hand_pose_dir, + "refined_camera_poses_dir": refined_camera_poses_dir, + "progress_dir": progress_dir, + }.items(): + if v is not None: + outputs[k] = v + + extra_args: dict[str, object] = { + "n_epochs": n_epochs, + "batch_size": batch_size, + "train_resolution_scale": train_resolution_scale, + "lr_gaussians": lr_gaussians, + "lr_object_pose": lr_object_pose, + "lr_object_scale": lr_object_scale, + "lr_hand_pose": lr_hand_pose, + "lr_hand_articulation": lr_hand_articulation, + "lr_hand_shape": lr_hand_shape, + "lr_hand_scale": lr_hand_scale, + "lr_camera_pose": lr_camera_pose, + "lr_schedule": lr_schedule, + "lr_cosine_min_factor": lr_cosine_min_factor, + "w_smooth_object_rot": w_smooth_object_rot, + "w_smooth_object_trans": w_smooth_object_trans, + "w_smooth_hand_rot": w_smooth_hand_rot, + "w_smooth_hand_articulation": w_smooth_hand_articulation, + "w_smooth_hand_trans": w_smooth_hand_trans, + "w_smooth_hand_object_relative_rot": w_smooth_hand_object_relative_rot, + "w_smooth_hand_object_relative_trans": w_smooth_hand_object_relative_trans, + "w_smooth_camera_rot": w_smooth_camera_rot, + "w_smooth_camera_trans": w_smooth_camera_trans, + "w_mask": w_mask, + "w_relative_depth": w_relative_depth, + "w_perceptual": w_perceptual, + "perceptual_resize": perceptual_resize, + "w_hand_object_penetration": w_hand_object_penetration, + "hand_object_penetration_margin": hand_object_penetration_margin, + "object_sdf_resolution": object_sdf_resolution, + "hand_object_penetration_max_verts": hand_object_penetration_max_verts, + "mask-background": mask_background, + "bg_ref_frame": bg_ref_frame, + "bg_init_stride": bg_init_stride, + "bg_voxel_size": bg_voxel_size, + "bg_max_points": bg_max_points, + "valid_mask_threshold": valid_mask_threshold, + "valid_mask_erode_iters": valid_mask_erode_iters, + "face_normal_thin_factor_obj": face_normal_thin_factor_obj, + "face_normal_thin_factor_hand": face_normal_thin_factor_hand, + "init_opacity_obj": init_opacity_obj, + "init_opacity_hand": init_opacity_hand, + "init_opacity_bg": init_opacity_bg, + "init_gaussian_scale_factor": init_gaussian_scale_factor, + "render_every": render_every, + "debug_frame_idx": debug_frame_idx, + "fps": fps, + "seed": seed, + } + + run_in_container( + image = IMAGE_NAME, + module = "v2d.gsplat_refinement.lib.refine_simple", + inputs = inputs, + outputs = outputs, + extra_args = extra_args, + dev = dev, + modules_dir = MODULES_DIR, + gpus = True, + ) + + +if __name__ == "__main__": + import argparse + + p = argparse.ArgumentParser(description="Minimal 2DGS hand/object/camera refinement") + p.add_argument("--frames_dir", required=True) + p.add_argument("--depth_dir", default=None, + help="Depth frames for background initialization. Required unless --mask-background is set.") + p.add_argument("--intrinsics_path", required=True) + p.add_argument("--object_mesh_path", required=True) + p.add_argument("--object_poses_dir", required=True) + p.add_argument("--object_mask_dir", required=True) + p.add_argument("--refined_object_poses_dir", required=True) + p.add_argument("--overlay_path", required=True) + p.add_argument("--left_hand_pose_dir", default=None) + p.add_argument("--left_hand_mask_dir", default=None) + p.add_argument("--right_hand_pose_dir", default=None) + p.add_argument("--right_hand_mask_dir", default=None) + p.add_argument("--refined_left_hand_pose_dir", default=None) + p.add_argument("--refined_right_hand_pose_dir", default=None) + p.add_argument("--refined_camera_poses_dir", default=None) + p.add_argument("--mano_assets_root", default=None) + p.add_argument("--background_pose_init_dir", default=None) + p.add_argument("--n_epochs", type=int, default=20) + p.add_argument("--batch_size", type=int, default=4) + p.add_argument("--train_resolution_scale", type=float, default=0.5) + p.add_argument("--lr_gaussians", type=float, default=3e-4) + p.add_argument("--lr_object_pose", type=float, default=3e-4) + p.add_argument("--lr_object_scale", type=float, default=0.0, + help="LR for global object scale. 0 disables.") + p.add_argument("--lr_hand_pose", type=float, default=3e-4, + help="LR for hand root global_orient and cam_t. 0 disables root pose refinement.") + p.add_argument("--lr_hand_articulation", type=float, default=0.0, + help="LR for MANO finger articulation hand_pose. 0 disables.") + p.add_argument("--lr_hand_shape", type=float, default=0.0, + help="LR for shared MANO betas/shape per hand track. 0 disables.") + p.add_argument("--lr_hand_scale", type=float, default=0.0, + help="LR for shared per-track hand_scale. 0 disables.") + p.add_argument("--lr_camera_pose", type=float, default=3e-4) + p.add_argument("--lr_schedule", choices=["constant", "cosine"], default="constant", + help="Learning-rate schedule for all optimizer groups.") + p.add_argument("--lr_cosine_min_factor", type=float, default=0.0, + help="Final LR multiplier for --lr_schedule cosine. 0 decays to zero.") + p.add_argument("--w_smooth_object_rot", type=float, default=0.1) + p.add_argument("--w_smooth_object_trans", type=float, default=0.1) + p.add_argument("--w_smooth_hand_rot", type=float, default=0.1) + p.add_argument("--w_smooth_hand_articulation", type=float, default=0.1, + help="Temporal rotation smoothness for MANO finger hand_pose.") + p.add_argument("--w_smooth_hand_trans", type=float, default=0.1) + p.add_argument("--w_smooth_hand_object_relative_rot", type=float, default=0.0, + help="Temporal smoothness for hand root rotation relative to object pose. 0 disables.") + p.add_argument("--w_smooth_hand_object_relative_trans", type=float, default=0.0, + help="Temporal smoothness for hand root translation in the object frame. " + "0 disables.") + p.add_argument("--w_smooth_camera_rot", type=float, default=0.1) + p.add_argument("--w_smooth_camera_trans", type=float, default=0.1) + p.add_argument("--w_mask", type=float, default=1.0, + help="Weight for L1 segmentation mask loss. 0 disables.") + p.add_argument("--w_relative_depth", type=float, default=0.0, + help="Weight for log-depth-gradient loss against MoGe depth. 0 disables.") + p.add_argument("--w_perceptual", type=float, default=0.0, + help="Weight for VGG16 perceptual feature L1 loss. 0 disables.") + p.add_argument("--vgg_weights_path", default=None, + help="Optional local VGG16 state_dict path. If missing, torchvision ImageNet weights are downloaded there.") + p.add_argument("--perceptual_resize", type=int, default=224, + help="Square resize for VGG perceptual loss. <=0 uses training resolution.") + p.add_argument("--w_hand_object_penetration", type=float, default=0.0, + help="Weight for 3D hand/object SDF penetration loss. 0 disables.") + p.add_argument("--hand_object_penetration_margin", type=float, default=0.003, + help="Signed-distance margin in meters/object units for hand/object separation.") + p.add_argument("--object_sdf_resolution", type=int, default=96, + help="Resolution per axis for the object SDF grid used by hand/object penetration.") + p.add_argument("--hand_object_penetration_max_verts", type=int, default=0, + help="Max MANO verts per hand for penetration loss. 0 uses all vertices.") + p.add_argument("--mask-background", "--mask_background", dest="mask_background", action="store_true", + help="Black out target background and omit background Gaussians/camera refinement.") + p.add_argument("--bg_ref_frame", type=int, default=None) + p.add_argument("--bg_init_stride", type=int, default=10) + p.add_argument("--bg_voxel_size", type=float, default=0.005) + p.add_argument("--bg_max_points", type=int, default=50000) + p.add_argument("--valid_mask_threshold", type=float, default=0.04) + p.add_argument("--valid_mask_erode_iters", type=int, default=2) + p.add_argument("--face_normal_thin_factor_obj", type=float, default=0.25) + p.add_argument("--face_normal_thin_factor_hand", type=float, default=0.25) + p.add_argument("--init_opacity_obj", type=float, default=0.9) + p.add_argument("--init_opacity_hand", type=float, default=0.9) + p.add_argument("--init_opacity_bg", type=float, default=0.9) + p.add_argument("--init_gaussian_scale_factor", type=float, default=1.0, + help="Multiplier for all initial Gaussian scales/radii.") + p.add_argument("--render_every", type=int, default=25) + p.add_argument("--progress_dir", default=None) + p.add_argument("--debug_frame_idx", type=int, default=None) + p.add_argument("--fps", type=float, default=30.0) + p.add_argument("--seed", type=int, default=0) + p.add_argument("--dev", action="store_true") + args = p.parse_args() + run_refine_simple(**vars(args)) diff --git a/third-party/video_to_data/reconstruction/modules/v2d_gsplat_refinement/docker/run_visualize.py b/third-party/video_to_data/reconstruction/modules/v2d_gsplat_refinement/docker/run_visualize.py new file mode 100644 index 0000000000000000000000000000000000000000..a4a20eabb4d75218d34f8c5067fff9258745ff2e --- /dev/null +++ b/third-party/video_to_data/reconstruction/modules/v2d_gsplat_refinement/docker/run_visualize.py @@ -0,0 +1,116 @@ +# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 +"""Interactive viewer for a trained gsplat checkpoint. + +Docker orchestration around ``v2d.gsplat_refinement.lib.visualize``. Runs the +container in interactive mode with X11 forwarding so OpenCV's ``imshow`` +window appears on the host display. Tested on Linux hosts; for remote/SSH +sessions you'll need to forward X11 (``ssh -X``) before invoking. + +If you see ``cv2.error: ... could not connect to display`` make sure +``$DISPLAY`` is set on the host and run:: + + xhost +local:docker # one-off, allows containers to talk to your X server + +Usage: + python -m v2d.gsplat_refinement.docker.run_visualize \\ + --checkpoint data/clean/03_undist/output_wilor/refine_checkpoint.pt \\ + --intrinsics_path data/clean/03_undist/output_wilor/intrinsics_stable.json \\ + --mano_assets_root data/weights/wilor/pretrained_models +""" + +import argparse +import os +import subprocess + +from v2d.gsplat_refinement.docker._config import IMAGE_NAME, MODULES_DIR + + +def run_visualize( + checkpoint: str, + intrinsics_path: str, + mano_assets_root: str, + width: int | None = None, + height: int | None = None, + fps: float = 30.0, + dev: bool = False, +) -> None: + checkpoint = os.path.abspath(checkpoint) + intrinsics_path = os.path.abspath(intrinsics_path) + mano_assets_root = os.path.abspath(mano_assets_root) + + # One bind mount per distinct host directory. + ckpt_dir = os.path.dirname(checkpoint) + intr_dir = os.path.dirname(intrinsics_path) + mano_dir = mano_assets_root + + # Container-side paths (claim the bind names by argument order). + dir_mounts: dict[str, str] = {} + def _bind(host_dir: str, mount_name: str) -> str: + if host_dir not in dir_mounts: + dir_mounts[host_dir] = f"/data/{mount_name}" + return dir_mounts[host_dir] + ckpt_mount = _bind(ckpt_dir, "checkpoint") + intr_mount = _bind(intr_dir, "intrinsics") + mano_mount = _bind(mano_dir, "mano") + ckpt_in_c = f"{ckpt_mount}/{os.path.basename(checkpoint)}" + intr_in_c = f"{intr_mount}/{os.path.basename(intrinsics_path)}" + + display = os.environ.get("DISPLAY", "") + if not display: + raise RuntimeError( + "No $DISPLAY in the environment. The viewer needs an X11 display " + "to forward into the container. On a local Linux session this is " + "set automatically; over SSH use `ssh -X`. You may also need to " + "run `xhost +local:docker` once on the host." + ) + + cmd = [ + "docker", "run", "-it", "--rm", + "--gpus", "all", + "--user", f"{os.getuid()}:{os.getgid()}", + "-e", "HOME=/tmp", + "-e", f"DISPLAY={display}", + "-e", "QT_X11_NO_MITSHM=1", + # X11 socket + Xauthority for non-root user access. + "-v", "/tmp/.X11-unix:/tmp/.X11-unix", + ] + xauth = os.environ.get("XAUTHORITY") + if xauth and os.path.exists(xauth): + cmd += ["-v", f"{xauth}:{xauth}:ro", "-e", f"XAUTHORITY={xauth}"] + + for host_dir, container_dir in dir_mounts.items(): + cmd += ["-v", f"{host_dir}:{container_dir}"] + if dev: + cmd += ["-v", f"{MODULES_DIR}:/workspace"] + + cmd += [IMAGE_NAME, "python", "-m", "v2d.gsplat_refinement.lib.visualize", + "--checkpoint", ckpt_in_c, + "--intrinsics_path", intr_in_c, + "--mano_assets_root", mano_mount] + if width is not None: cmd += ["--width", str(int(width))] + if height is not None: cmd += ["--height", str(int(height))] + if fps is not None: cmd += ["--fps", str(float(fps))] + + subprocess.run(cmd, check=True) + + +if __name__ == "__main__": + parser = argparse.ArgumentParser(description="Interactive gsplat-checkpoint viewer") + parser.add_argument("--checkpoint", required=True) + parser.add_argument("--intrinsics_path", required=True) + parser.add_argument("--mano_assets_root", required=True) + parser.add_argument("--width", type=int, default=None) + parser.add_argument("--height", type=int, default=None) + parser.add_argument("--fps", type=float, default=30.0) + parser.add_argument("--dev", action="store_true") + args = parser.parse_args() + run_visualize( + checkpoint = args.checkpoint, + intrinsics_path = args.intrinsics_path, + mano_assets_root = args.mano_assets_root, + width = args.width, + height = args.height, + fps = args.fps, + dev = args.dev, + ) diff --git a/third-party/video_to_data/reconstruction/modules/v2d_gsplat_refinement/lib/__init__.py b/third-party/video_to_data/reconstruction/modules/v2d_gsplat_refinement/lib/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..52a7a9daf028f654d6a02f65c99cc609a57b492f --- /dev/null +++ b/third-party/video_to_data/reconstruction/modules/v2d_gsplat_refinement/lib/__init__.py @@ -0,0 +1,2 @@ +# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 diff --git a/third-party/video_to_data/reconstruction/modules/v2d_gsplat_refinement/lib/background.py b/third-party/video_to_data/reconstruction/modules/v2d_gsplat_refinement/lib/background.py new file mode 100644 index 0000000000000000000000000000000000000000..884ef3e2df5b435fb311982676700935ee722e00 --- /dev/null +++ b/third-party/video_to_data/reconstruction/modules/v2d_gsplat_refinement/lib/background.py @@ -0,0 +1,302 @@ +# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 +"""Background Gaussian set + per-frame rigid background→camera pose. + +Models the static scene behind the foreground hand+object so the +photometric loss can be applied to the *full* image rather than just the +mask region. Initialized from a reference frame's MoGe depth: every pixel +outside the foreground union mask and with finite depth becomes one +Gaussian in 3D, anchored in the world frame defined by that reference +frame's camera frame. + +Background pose is parameterized as world→camera (axis_angle, translation) +per frame, mirroring ``ObjectPoseField``. The reference frame's pose is +identity by construction; all other frames are also initialized identity +and the optimizer discovers camera motion via photometric drift. + +Caveat: identity-init is only a good basin for sequences with small +camera motion. For freely-moving (egocentric) cameras you'd want to seed +from an external VO/SfM solution before this kicks in. +""" +from __future__ import annotations + +import torch +import torch.nn as nn + +from .gaussians import ( + GaussianFrame, + _logit, + axis_angle_to_quat, + quat_mul, + quat_to_rotmat, + rotmat_to_quat, +) + + +# --------------------------------------------------------------------------- +# Background Gaussians: same parameter set as ObjectGaussians, but anchored +# to a depth-unprojected world-frame point cloud rather than a mesh. +# --------------------------------------------------------------------------- + +class BackgroundGaussians(nn.Module): + def __init__( + self, + anchor_positions: torch.Tensor, # (N, 3) in world (= ref-frame camera) frame + init_color: torch.Tensor, # (N, 3) RGB in [0, 1] + init_scale: torch.Tensor, # (N,) per-point initial Gaussian size + init_opacity: float = 0.9, + init_scale_factor: float = 1.0, + ) -> None: + super().__init__() + N = anchor_positions.shape[0] + device = anchor_positions.device + + self.register_buffer("anchor", anchor_positions.contiguous()) + self._delta_p = nn.Parameter(torch.zeros(N, 3, device=device)) + self._quat_canon = nn.Parameter( + torch.tensor([1.0, 0.0, 0.0, 0.0], device=device).repeat(N, 1) + ) + # Per-point init scale (depth-aware: farther points get larger Gaussians + # so 1-pixel image coverage holds at any depth). + log_scale = (init_scale * float(init_scale_factor)).clamp_min(1e-6).log().unsqueeze(-1).expand(-1, 3).contiguous() + self._log_scale = nn.Parameter(log_scale.to(device).clone()) + self._opacity_logit = nn.Parameter( + torch.full((N,), float(_logit(init_opacity)), device=device) + ) + self._color = nn.Parameter(init_color.contiguous().clone()) + + def num_gaussians(self) -> int: + return self.anchor.shape[0] + + def forward( + self, + R_bg: torch.Tensor, # (3, 3) world→camera rotation + t_bg: torch.Tensor, # (3,) world→camera translation + ) -> GaussianFrame: + p_world = self.anchor + self._delta_p + means = p_world @ R_bg.T + t_bg + q_bg = rotmat_to_quat(R_bg).expand_as(self._quat_canon) + quats = quat_mul(q_bg, self._quat_canon) + return GaussianFrame( + means = means, + quats = quats, + scales = self._log_scale.exp(), + opacities = torch.sigmoid(self._opacity_logit), + colors = self._color, + ) + + +# --------------------------------------------------------------------------- +# Background pose field: per-frame rigid world→camera transform. +# --------------------------------------------------------------------------- + +class BackgroundPoseField(nn.Module): + def __init__(self, n_frames: int, device, ref_frame_t: int = 0) -> None: + super().__init__() + # Identity init for every frame. The reference frame's pose is + # *exactly* identity by construction; other frames start there and + # the optimizer picks up camera motion via photometric drift. + self.axis_angle = nn.Parameter(torch.zeros(n_frames, 3, device=device)) + self.translation = nn.Parameter(torch.zeros(n_frames, 3, device=device)) + self.ref_frame_t = int(ref_frame_t) + + def num_frames(self) -> int: + return self.axis_angle.shape[0] + + def forward(self, t: int) -> tuple[torch.Tensor, torch.Tensor]: + q = axis_angle_to_quat(self.axis_angle[t]) + R = quat_to_rotmat(q) + return R, self.translation[t] + + def batched_forward( + self, t_idx: torch.Tensor # (B,) long tensor of positional indices + ) -> tuple[torch.Tensor, torch.Tensor]: + aa = self.axis_angle[t_idx] # (B, 3) + q = axis_angle_to_quat(aa) # (B, 4) + R = quat_to_rotmat(q) # (B, 3, 3) + return R, self.translation[t_idx] # (B, 3, 3), (B, 3) + + +# --------------------------------------------------------------------------- +# Initialization from a reference frame's depth + RGB. +# --------------------------------------------------------------------------- + +def _unproject_frame_to_world( + rgb: torch.Tensor, # (H, W, 3) in [0, 1] + depth: torch.Tensor, # (H, W) metric depth, possibly +inf for invalid + union_mask: torch.Tensor, # (H, W) in {0, 1} — foreground (object + hands) + K: torch.Tensor, # (3, 3) intrinsics + T_w2c: torch.Tensor | None = None, # (4, 4); identity == "world is this cam" + max_points: int | None = None, + scale_factor: float = 1.5, +) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor]: + """Unproject background pixels of a single frame into the gsplat world. + + Pixels outside ``union_mask`` with finite positive depth are unprojected + through K to camera-frame 3D points, then transformed to world via + ``T_w2c^{-1}`` (== ``T_c2w``). Returns ``(anchors_world, colors, + init_scales)``. ``init_scales = z_in_camera * scale_factor / fx`` so each + Gaussian covers ~one image pixel projection at the depth where it lives. + + Identity ``T_w2c`` means "world == this frame's camera frame" and the + output is in that frame. + """ + H, W, _ = rgb.shape + device = rgb.device + fx = K[0, 0] + fy = K[1, 1] + cx = K[0, 2] + cy = K[1, 2] + + valid = (union_mask < 0.5) & torch.isfinite(depth) & (depth > 0.0) + valid_idx = torch.nonzero(valid, as_tuple=False) # (M, 2) [v, u] + if valid_idx.shape[0] == 0: + return (torch.zeros(0, 3, device=device), + torch.zeros(0, 3, device=device), + torch.zeros(0, device=device)) + + if max_points is not None and valid_idx.shape[0] > max_points: + perm = torch.randperm(valid_idx.shape[0], device=device)[:max_points] + valid_idx = valid_idx[perm] + + v = valid_idx[:, 0].to(torch.float32) + u = valid_idx[:, 1].to(torch.float32) + z = depth[valid_idx[:, 0], valid_idx[:, 1]] + x = (u - cx) * z / fx + y = (v - cy) * z / fy + + pts_cam = torch.stack([x, y, z], dim=-1) # (N, 3) + if T_w2c is not None: + T_c2w = torch.linalg.inv(T_w2c) + pts_h = torch.cat([pts_cam, torch.ones_like(pts_cam[:, :1])], dim=-1) + pts_world = (pts_h @ T_c2w.T)[:, :3] + else: + pts_world = pts_cam + + colors = rgb[valid_idx[:, 0], valid_idx[:, 1]] # (N, 3) + init_scales = (z / fx) * scale_factor # (N,) + return pts_world, colors, init_scales + + +def _voxel_dedup( + points: torch.Tensor, # (N, 3) world coords + colors: torch.Tensor, # (N, 3) + scales: torch.Tensor, # (N,) + voxel_size: float, +) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor]: + """One point per occupied voxel. Keeps the first point that lands in each + voxel. Cheap and stable; quality matches voxel size, not the per-voxel + aggregation method. + """ + if points.shape[0] == 0 or voxel_size <= 0: + return points, colors, scales + keys = torch.floor(points / voxel_size).to(torch.int64) + keys_np = keys.detach().cpu().numpy() + import numpy as np + _, first = np.unique(keys_np, axis=0, return_index=True) + first_t = torch.from_numpy(first).to(points.device) + return points[first_t], colors[first_t], scales[first_t] + + +def init_background_multiframe( + rgbs: list[torch.Tensor], # each (H, W, 3) in [0, 1] + depths: list[torch.Tensor], # each (H, W) metric depth (+inf allowed) + union_masks: list[torch.Tensor], # each (H, W) in {0, 1} + T_w2c_list: list[torch.Tensor], # each (4, 4) world→camera; gsplat world + K: torch.Tensor, # (3, 3) shared intrinsics + voxel_size: float = 0.005, + max_points: int = 50000, + per_frame_max_points: int = 200000, + scale_factor: float = 1.5, +) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor]: + """Fuse per-frame depth unprojections into a single gsplat-world cloud. + + Each frame contributes its background pixels (outside its own foreground + mask) lifted to world via the supplied world→camera pose. Voxel dedup + removes near-duplicate points where multiple frames see the same surface; + a final random subsample caps the total Gaussian count. + """ + if not rgbs: + raise RuntimeError("init_background_multiframe: no frames provided.") + parts_p: list[torch.Tensor] = [] + parts_c: list[torch.Tensor] = [] + parts_s: list[torch.Tensor] = [] + for rgb, depth, mask, T_w2c in zip(rgbs, depths, union_masks, T_w2c_list): + p, c, s = _unproject_frame_to_world( + rgb=rgb, depth=depth, union_mask=mask, K=K, + T_w2c=T_w2c, max_points=per_frame_max_points, + scale_factor=scale_factor, + ) + if p.shape[0] > 0: + parts_p.append(p); parts_c.append(c); parts_s.append(s) + if not parts_p: + raise RuntimeError( + "init_background_multiframe: every frame's background was empty " + "(foreground masks cover everything or depth is all invalid)." + ) + points = torch.cat(parts_p, dim=0) + colors = torch.cat(parts_c, dim=0) + scales = torch.cat(parts_s, dim=0) + + points, colors, scales = _voxel_dedup(points, colors, scales, voxel_size) + + if points.shape[0] > max_points: + perm = torch.randperm(points.shape[0], device=points.device)[:max_points] + points = points[perm]; colors = colors[perm]; scales = scales[perm] + + return points, colors, scales + + +def init_background_from_depth( + rgb: torch.Tensor, # (H, W, 3) in [0, 1] + depth: torch.Tensor, # (H, W) metric depth, possibly +inf for invalid + union_mask: torch.Tensor, # (H, W) in {0, 1} — foreground (object + hands) + K: torch.Tensor, # (3, 3) intrinsics + max_points: int = 50000, + scale_factor: float = 1.5, +) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor]: + """Unproject every background pixel to a 3D point in the camera frame. + + Returns: + anchors: (N, 3) point cloud in camera-frame == world-frame + colors: (N, 3) RGB in [0, 1] + init_scales: (N,) per-point Gaussian scale ≈ z * pixel_pitch * factor + + Filters out foreground pixels and pixels with invalid depth, then + optionally subsamples to ``max_points`` for tractable rasterization + (a 1080p frame can yield ~2M background pixels — way more than gsplat + needs to cover the scene at typical Gaussian sizes). + """ + H, W, _ = rgb.shape + device = rgb.device + fx = K[0, 0] + fy = K[1, 1] + cx = K[0, 2] + cy = K[1, 2] + + valid = (union_mask < 0.5) & torch.isfinite(depth) & (depth > 0.0) + valid_idx = torch.nonzero(valid, as_tuple=False) # (M, 2) [v, u] + if valid_idx.shape[0] == 0: + raise RuntimeError( + "Background init: no valid pixels in reference frame " + "(every pixel is either foreground or has invalid MoGe depth)." + ) + + if valid_idx.shape[0] > max_points: + perm = torch.randperm(valid_idx.shape[0], device=device)[:max_points] + valid_idx = valid_idx[perm] + + v = valid_idx[:, 0].to(torch.float32) + u = valid_idx[:, 1].to(torch.float32) + z = depth[valid_idx[:, 0], valid_idx[:, 1]] + x = (u - cx) * z / fx + y = (v - cy) * z / fy + + anchors = torch.stack([x, y, z], dim=-1) # (N, 3) + colors = rgb[valid_idx[:, 0], valid_idx[:, 1]] # (N, 3) + # Per-point init scale: 1-pixel projected size at depth z is ~ z / fx. + # Multiply by scale_factor (~1-2) so neighboring Gaussians overlap + # enough to fill the surface without gaps. + init_scales = (z / fx) * scale_factor # (N,) + + return anchors, colors, init_scales diff --git a/third-party/video_to_data/reconstruction/modules/v2d_gsplat_refinement/lib/gaussians.py b/third-party/video_to_data/reconstruction/modules/v2d_gsplat_refinement/lib/gaussians.py new file mode 100644 index 0000000000000000000000000000000000000000..50a155a6874c624998a90f226a76abad862c7c9a --- /dev/null +++ b/third-party/video_to_data/reconstruction/modules/v2d_gsplat_refinement/lib/gaussians.py @@ -0,0 +1,826 @@ +# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 +"""Gaussian primitive sets for joint hand+object refinement. + +Two sets, both following the standard 3DGS parameterization (means / quats / +scales / opacities / colors), but with different per-frame deformation: + + ObjectGaussians -- anchored to mesh vertices in object frame; per frame the + whole set is rigidly transformed by the object pose + (R_obj_t, t_obj_t). + HandGaussians -- anchored to MANO rest-pose vertices; per frame each + Gaussian's world position is the corresponding posed + vertex (LBS via manotorch). Hand Gaussians are isotropic + to avoid having to also rotate per-Gaussian quaternions + under articulation -- one less coupled DOF and the + photometric loss isn't sensitive to it at typical + Gaussian sizes. + +Both sets expose canonical-frame parameters as ``nn.Parameter``s so they're +captured by a single ``optim.Adam(model.parameters(), ...)`` in the trainer. +Per-frame attributes are computed in ``forward(frame_idx)`` and returned as +a flat record the renderer consumes. + +Object pose, MANO global rot+trans, MANO articulation, and (optionally) MANO +shape are *not* attributes of these classes -- they live in their own +``nn.Module`` wrappers (``ObjectPoseField`` / ``HandPoseField``) so the +canonical Gaussians are decoupled from the per-frame state. +""" +from __future__ import annotations + +from dataclasses import dataclass + +import torch +import torch.nn as nn +import torch.nn.functional as F + + +# --------------------------------------------------------------------------- +# Quaternion helpers +# --------------------------------------------------------------------------- + +def axis_angle_to_quat(aa: torch.Tensor) -> torch.Tensor: + """(..., 3) axis-angle → (..., 4) quaternion (w, x, y, z).""" + angle = aa.norm(dim=-1, keepdim=True).clamp_min(1e-8) + axis = aa / angle + half = angle * 0.5 + w = torch.cos(half) + xyz = axis * torch.sin(half) + return torch.cat([w, xyz], dim=-1) + + +def quat_mul(a: torch.Tensor, b: torch.Tensor) -> torch.Tensor: + """Quaternion multiplication a*b. Both (..., 4) in (w, x, y, z).""" + aw, ax, ay, az = a.unbind(-1) + bw, bx, by, bz = b.unbind(-1) + return torch.stack([ + aw*bw - ax*bx - ay*by - az*bz, + aw*bx + ax*bw + ay*bz - az*by, + aw*by - ax*bz + ay*bw + az*bx, + aw*bz + ax*by - ay*bx + az*bw, + ], dim=-1) + + +def quat_to_rotmat(q: torch.Tensor) -> torch.Tensor: + """(..., 4) quat (w, x, y, z) → (..., 3, 3) rotation matrix.""" + q = F.normalize(q, dim=-1) + w, x, y, z = q.unbind(-1) + return torch.stack([ + torch.stack([1 - 2*(y*y + z*z), 2*(x*y - w*z), 2*(x*z + w*y)], dim=-1), + torch.stack([2*(x*y + w*z), 1 - 2*(x*x + z*z), 2*(y*z - w*x)], dim=-1), + torch.stack([2*(x*z - w*y), 2*(y*z + w*x), 1 - 2*(x*x + y*y)], dim=-1), + ], dim=-2) + + +# --------------------------------------------------------------------------- +# Frame record (per-frame world-space Gaussians, ready for the rasterizer) +# --------------------------------------------------------------------------- + +@dataclass +class GaussianFrame: + """World-space Gaussian attributes for a single camera at a single frame. + + means: (N, 3) + quats: (N, 4) -- (w, x, y, z), unnormalized OK; rasterizer normalizes + scales: (N, 3) + opacities: (N,) -- in [0, 1] + colors: (N, 3) -- in [0, 1] approx; rasterizer treats as RGB + """ + means: torch.Tensor + quats: torch.Tensor + scales: torch.Tensor + opacities: torch.Tensor + colors: torch.Tensor + + +def concat_frames(frames: list[GaussianFrame]) -> GaussianFrame: + if len(frames) == 1: + return frames[0] + return GaussianFrame( + means = torch.cat([f.means for f in frames], dim=0), + quats = torch.cat([f.quats for f in frames], dim=0), + scales = torch.cat([f.scales for f in frames], dim=0), + opacities = torch.cat([f.opacities for f in frames], dim=0), + colors = torch.cat([f.colors for f in frames], dim=0), + ) + + +# --------------------------------------------------------------------------- +# Object Gaussians: rigidly attached to a mesh in object frame +# --------------------------------------------------------------------------- + +class ObjectGaussians(nn.Module): + """One Gaussian per anchor point (typically mesh vertex), in object frame. + + Learnable params (all in canonical / object frame): + _delta_p : (N, 3) -- offset from anchor, init 0 + _quat_canon : (N, 4) -- canonical orientation, init identity + _log_scale : (N, 3) -- log of axis-aligned scales + _opacity_logit: (N,) + _color : (N, 3) -- raw RGB in [0, 1]-ish; clamped at render + + Anchor positions and the object pose are *inputs* to ``forward``. + """ + + def __init__( + self, + anchor_positions: torch.Tensor, # (N, 3) in object frame + init_color: torch.Tensor, # (N, 3) in [0, 1] + init_scale: float, # mean edge-length / 3 is typical + init_opacity: float = 0.9, + ) -> None: + super().__init__() + N = anchor_positions.shape[0] + device = anchor_positions.device + + self.register_buffer("anchor", anchor_positions.contiguous()) + self._delta_p = nn.Parameter(torch.zeros(N, 3, device=device)) + self._quat_canon = nn.Parameter( + torch.tensor([1.0, 0.0, 0.0, 0.0], device=device).repeat(N, 1) + ) + self._log_scale = nn.Parameter( + torch.full((N, 3), float(torch.log(torch.tensor(init_scale))), + device=device) + ) + self._opacity_logit = nn.Parameter( + torch.full((N,), float(_logit(init_opacity)), device=device) + ) + self._color = nn.Parameter(init_color.contiguous().clone()) + # Single global object scale, learned in log-space (init log=0 ⇒ s=1). + # Multiplies anchor positions AND per-Gaussian scales so the visual + # Gaussian sizes track geometric scale. Saved into the refined + # Transform3d JSON's scale field at export time. + self._log_scale_global = nn.Parameter(torch.zeros((), device=device)) + + def num_gaussians(self) -> int: + return self.anchor.shape[0] + + def forward( + self, + R_obj: torch.Tensor, # (3, 3) object-to-camera rotation + t_obj: torch.Tensor, # (3,) object-to-camera translation + ) -> GaussianFrame: + """Transform canonical Gaussians into camera/world frame for one camera. + + We render in *camera* frame (viewmat = identity), so the object pose + is applied directly: positions go to camera frame, and so do quats. + Global object scale ``s_obj = exp(_log_scale_global)`` multiplies + canonical positions and per-Gaussian scales together — visual size + and geometric extent stay coupled so the rendered object grows / + shrinks coherently rather than producing a sparse-or-clumped splat + cloud at the wrong scale. + """ + s_obj = self._log_scale_global.exp() # () + # Canonical position in object frame, scaled by s_obj. + p_obj = (self.anchor + self._delta_p) * s_obj # (N, 3) + # Apply object pose: x_cam = R_obj @ x_obj + t_obj. + means = p_obj @ R_obj.T + t_obj # (N, 3) + # Compose object rotation onto canonical quat: q_cam = q_obj * q_canon. + q_obj = _rotmat_to_quat(R_obj).expand_as(self._quat_canon) # (N, 4) + quats = quat_mul(q_obj, self._quat_canon) # (N, 4) + scales = self._log_scale.exp() * s_obj # (N, 3) + opacities = torch.sigmoid(self._opacity_logit) + colors = self._color + return GaussianFrame(means, quats, scales, opacities, colors) + + def object_scale(self) -> torch.Tensor: + """Current learned global object scale (scalar).""" + return self._log_scale_global.exp() + + +# --------------------------------------------------------------------------- +# Hand Gaussians: anchored to MANO rest-pose verts, deformed each frame by +# manotorch (LBS). Isotropic so we don't have to articulate per-Gaussian quat. +# --------------------------------------------------------------------------- + +class HandGaussians(nn.Module): + """One Gaussian per MANO vertex (778 typically), per hand. Same + parameterization as ``ObjectGaussians`` (anisotropic scale + per-Gaussian + quaternion + Δp position offset) so the two sets have comparable degrees + of freedom. + + Positions and rotations follow MANO's LBS each frame: + - ``posed_verts_cam`` (from manotorch) is the MANO-rest vertex + transported into world / camera frame. + - ``per_vertex_rotmat_cam`` is the per-vertex deformation rotation in + camera frame, computed by skinning the per-joint deformation + rotations with MANO's vertex weights. + + Forward uses these to: + - Apply Δp_canon as a rest-frame offset transformed by the vertex's + LBS rotation, so Δp follows finger articulation. + - Compose the LBS rotation onto the canonical per-Gaussian quat. + + Learnable params: + _delta_p : (N, 3) -- Δp in MANO-rest frame, init 0 + _quat_canon : (N, 4) -- canonical orientation in rest frame, init identity + _log_scale : (N, 3) -- anisotropic axis-aligned scale, init from skin spacing + _opacity_logit : (N,) + _color : (N, 3) + """ + + def __init__( + self, + n_verts: int, + is_right: bool, + init_scale: float, + init_color: torch.Tensor, # (3,) skin tone + init_opacity: float = 0.9, + device: str | torch.device = "cuda", + subsample_indices: torch.Tensor | None = None, + ) -> None: + super().__init__() + self.is_right = bool(is_right) + # Optionally allocate params for a strict subset of MANO vertices + # to control hand Gaussian count without the LBS skinning getting + # complex. The forward pass gathers the corresponding posed verts + # and rotation matrices by these indices. + if subsample_indices is not None: + self.register_buffer( + "_subsample_idx", + subsample_indices.to(device, dtype=torch.long).contiguous(), + ) + n_g = int(subsample_indices.numel()) + else: + n_g = n_verts + self._delta_p = nn.Parameter(torch.zeros(n_g, 3, device=device)) + self._quat_canon = nn.Parameter( + torch.tensor([1.0, 0.0, 0.0, 0.0], device=device).repeat(n_g, 1) + ) + self._log_scale = nn.Parameter( + torch.full((n_g, 3), float(torch.log(torch.tensor(init_scale))), + device=device) + ) + self._opacity_logit = nn.Parameter( + torch.full((n_g,), float(_logit(init_opacity)), device=device) + ) + self._color = nn.Parameter( + init_color.to(device).expand(n_g, 3).contiguous().clone() + ) + + def num_gaussians(self) -> int: + return self._log_scale.shape[0] + + def forward( + self, + posed_verts_cam: torch.Tensor, # (N_verts, 3) + per_vertex_rotmat_cam: torch.Tensor, # (N_verts, 3, 3) + ) -> GaussianFrame: + # Subsample down to the Gaussian set if requested, otherwise use + # all vertices. + if hasattr(self, "_subsample_idx"): + posed_verts_cam = posed_verts_cam[self._subsample_idx] + per_vertex_rotmat_cam = per_vertex_rotmat_cam[self._subsample_idx] + # Δp is in MANO-rest frame; the vertex's LBS rotation carries it into + # world frame so it follows finger articulation rather than dangling + # in fixed world coordinates. + delta_world = torch.einsum("nij,nj->ni", per_vertex_rotmat_cam, self._delta_p) + means = posed_verts_cam + delta_world + # Compose LBS rotation onto canonical Gaussian rotation. + q_lbs = rotmat_to_quat(per_vertex_rotmat_cam) # (N, 4) + quats = quat_mul(q_lbs, self._quat_canon) # (N, 4) + return GaussianFrame( + means = means, + quats = quats, + scales = self._log_scale.exp(), + opacities = torch.sigmoid(self._opacity_logit), + colors = self._color, + ) + + +# --------------------------------------------------------------------------- +# Helpers +# --------------------------------------------------------------------------- + +def _logit(p: float) -> float: + p = max(min(p, 1 - 1e-6), 1e-6) + return float(torch.logit(torch.tensor(p))) + + +def rotmat_to_quat(R: torch.Tensor) -> torch.Tensor: + """(..., 3, 3) → (..., 4) quat in (w, x, y, z) convention. Differentiable + and robust for arbitrary rotations. + + Wraps roma.rotmat_to_unitquat (which uses xyzw) and reorders to wxyz to + match the convention used elsewhere in this module. + """ + import roma # local import — keeps this file usable without roma for tests + q_xyzw = roma.rotmat_to_unitquat(R) # (..., 4) + return torch.cat([q_xyzw[..., 3:4], q_xyzw[..., :3]], dim=-1) + + +def _rotmat_to_quat(R: torch.Tensor) -> torch.Tensor: + """Single-matrix wrapper around ``rotmat_to_quat`` for backward + compatibility with code that passes (3, 3).""" + return rotmat_to_quat(R) + + +# --------------------------------------------------------------------------- +# Initialization helpers +# --------------------------------------------------------------------------- + +def resample_mesh_surface( + vertices: torch.Tensor, # (V, 3) + vertex_colors: torch.Tensor, # (V, 3) in [0, 1] + faces: "np.ndarray", # (F, 3) + n: int, +) -> tuple[torch.Tensor, torch.Tensor]: + """Sample ``n`` points uniformly on the mesh surface with barycentric + color interpolation. Decouples Gaussian count from mesh topology. + + Used to control object Gaussian density independent of whatever vertex + count SAM3D / FoundationPose produced. Returns (positions, colors) + matching the device/dtype of ``vertices``/``vertex_colors``. + """ + import numpy as np + import trimesh + + verts_np = vertices.detach().cpu().numpy() + colors_np = vertex_colors.detach().cpu().numpy() + mesh = trimesh.Trimesh(vertices=verts_np, faces=faces, process=False) + + pts, face_idx = trimesh.sample.sample_surface_even(mesh, n) + # sample_surface_even drops points that fail an even-spacing check; + # top up via plain random sampling so we end up at exactly ``n``. + if pts.shape[0] < n: + extra_pts, extra_face = trimesh.sample.sample_surface( + mesh, n - pts.shape[0]) + pts = np.vstack([pts, extra_pts]) + face_idx = np.concatenate([face_idx, extra_face]) + + # Barycentric interpolation of vertex colors on the sampled triangles. + face_verts = faces[face_idx] # (n, 3) + tri_verts = mesh.vertices[face_verts] # (n, 3, 3) + bary = trimesh.triangles.points_to_barycentric(tri_verts, pts) # (n, 3) + tri_colors = colors_np[face_verts] # (n, 3, 3) + sampled_colors = (bary[:, :, None] * tri_colors).sum(axis=1) # (n, 3) + + return ( + torch.from_numpy(pts.astype(np.float32)).to(vertices.device), + torch.from_numpy(sampled_colors.astype(np.float32)).to(vertices.device), + ) + + +def init_object_gaussians_from_mesh( + vertices: torch.Tensor, # (N, 3) object frame + vertex_colors: torch.Tensor, # (N, 3) in [0, 1] + scale_factor: float = 1.0, # Gaussian scale = scale_factor * mean + # nearest-neighbor vertex distance. + # 1.0 fills the mesh surface; smaller + # values leave gaps that no single + # Gaussian "owns". + init_opacity: float = 0.9, + init_scale_factor: float = 1.0, +) -> ObjectGaussians: + """Initialize Gaussians at mesh vertices with scale set from inter-vertex spacing.""" + if vertices.shape[0] < 2: + init_scale = 0.005 + else: + # Approx mean nearest-neighbor distance via random pairs. + n = min(vertices.shape[0], 4096) + idx = torch.randperm(vertices.shape[0], device=vertices.device)[:n] + sub = vertices[idx] + d = torch.cdist(sub, sub) + d.fill_diagonal_(float("inf")) + init_scale = float(d.min(dim=1).values.mean()) * scale_factor + init_scale = max(init_scale, 1e-4) + return ObjectGaussians( + anchor_positions = vertices, + init_color = vertex_colors, + init_scale = init_scale * float(init_scale_factor), + init_opacity = init_opacity, + ) + + +def init_hand_gaussians( + n_verts: int, + is_right: bool, + init_scale: float = 0.005, # ~5 mm: MANO has ~5 mm vertex spacing + # (778 verts spread over a ~10 cm hand); + # smaller scales leave gaps between + # Gaussians that no single splat + # "owns", which weakens the per-vert + # gradient and slows hand convergence. + init_opacity: float = 0.9, + init_scale_factor: float = 1.0, + skin_tone: tuple[float, float, float] = (0.72, 0.55, 0.45), + device: str | torch.device = "cuda", + subsample_indices: torch.Tensor | None = None, +) -> HandGaussians: + init_color = torch.tensor(skin_tone, dtype=torch.float32) + return HandGaussians( + n_verts = n_verts, + is_right = is_right, + init_scale = init_scale * float(init_scale_factor), + init_opacity = init_opacity, + init_color = init_color, + device = device, + subsample_indices = subsample_indices, + ) + + +# --------------------------------------------------------------------------- +# Wrist-attached Gaussians: rigidly attached to a hand's wrist 6DOF pose. +# +# Same parameterization as ObjectGaussians (anchor + Δp + per-Gaussian quat +# + anisotropic scale + opacity + color), but per-frame transform comes from +# the hand's wrist (HandPoseField.batched_wrist_pose_camera), not an +# independent pose field. Used for arm geometry that we don't want to +# distort MANO to represent. +# +# Class labels are all-zero in the trainer's labels_static tensor — these +# Gaussians get no silhouette supervision (no arm mask), only photometric. +# --------------------------------------------------------------------------- + +class WristAttachedGaussians(nn.Module): + """Free 3D Gaussians attached to a hand wrist's rigid 6DOF pose. + + Learnable params (canonical wrist-local frame): + _delta_p : (N, 3) -- offset from anchor, init 0. Loosely + regularized so Gaussians can drift to fill + the arm volume far from the wrist. + _quat_canon : (N, 4) + _log_scale : (N, 3) + _opacity_logit: (N,) + _color : (N, 3) + + No ``_log_scale_global`` — there's no exported scale field for these. + """ + + def __init__( + self, + anchor_positions: torch.Tensor, # (N, 3) in wrist-local frame + init_color: torch.Tensor, # (N, 3) in [0, 1] + init_scale: float, # large by default (~3 cm) — these + # are arm-sized blobs at init. + init_opacity: float = 0.5, # mid-opacity so opacity_binary can + # drive each to either extreme. + ) -> None: + super().__init__() + N = anchor_positions.shape[0] + device = anchor_positions.device + + self.register_buffer("anchor", anchor_positions.contiguous()) + self._delta_p = nn.Parameter(torch.zeros(N, 3, device=device)) + self._quat_canon = nn.Parameter( + torch.tensor([1.0, 0.0, 0.0, 0.0], device=device).repeat(N, 1) + ) + self._log_scale = nn.Parameter( + torch.full((N, 3), float(torch.log(torch.tensor(init_scale))), + device=device) + ) + self._opacity_logit = nn.Parameter( + torch.full((N,), float(_logit(init_opacity)), device=device) + ) + self._color = nn.Parameter(init_color.contiguous().clone()) + + def num_gaussians(self) -> int: + return self.anchor.shape[0] + + def forward( + self, + R_wrist: torch.Tensor, # (3, 3) wrist-to-camera rotation + t_wrist: torch.Tensor, # (3,) wrist-to-camera translation + ) -> GaussianFrame: + """Rigidly transform canonical Gaussians by the wrist pose.""" + p_local = self.anchor + self._delta_p # (N, 3) + means = p_local @ R_wrist.T + t_wrist # (N, 3) + q_wrist = _rotmat_to_quat(R_wrist).expand_as(self._quat_canon) + quats = quat_mul(q_wrist, self._quat_canon) + return GaussianFrame( + means = means, + quats = quats, + scales = self._log_scale.exp(), + opacities = torch.sigmoid(self._opacity_logit), + colors = self._color, + ) + + +def init_wrist_attached_gaussians( + n: int, + init_scale: float = 0.03, # ~3 cm + init_radius: float = 0.0, # 0 → all at origin + init_opacity: float = 0.5, + init_scale_factor: float = 1.0, + skin_tone: tuple[float, float, float] = (0.72, 0.55, 0.45), + device: str | torch.device = "cuda", + seed: int = 0, +) -> WristAttachedGaussians: + """Sprinkle ``n`` Gaussians clustered at the wrist origin. + + ``init_radius=0`` → all anchors exactly at (0, 0, 0) in wrist-local frame. + ``init_radius>0`` → anchors sampled uniformly in a ball of that radius + (useful if you want some initial spatial spread; otherwise the optimizer + has to break the perfect overlap via gradient noise). + """ + g = torch.Generator(device="cpu").manual_seed(seed) + if init_radius > 0: + # Uniform-in-ball sampling. + v = torch.randn(n, 3, generator=g) + v = v / v.norm(dim=-1, keepdim=True).clamp_min(1e-8) + r = torch.rand(n, 1, generator=g) ** (1.0 / 3.0) + anchors = (v * r * float(init_radius)).to(device) + else: + anchors = torch.zeros(n, 3, device=device) + init_color = torch.tensor(skin_tone, dtype=torch.float32).expand(n, 3).contiguous() + return WristAttachedGaussians( + anchor_positions = anchors, + init_color = init_color.to(device), + init_scale = init_scale * float(init_scale_factor), + init_opacity = init_opacity, + ) + + +# --------------------------------------------------------------------------- +# Face-anchored Gaussians +# +# One Gaussian per mesh face. Anchor = face centroid; orientation derived from +# the face's TBN frame (tangent = an edge, normal = face normal, bitangent = +# N x T). Δp is parameterized in face-local (T, B, N) coordinates, so its +# three components have physical meaning: +# [0] tangent slide — along the face surface +# [1] bitangent slide — along the face surface (orthogonal to T) +# [2] normal depth — into the volume (negative N) or outside (+N) +# Combined with an asymmetric per-axis regularizer (face_delta_p_regularizer in +# losses.py), this lets Gaussians slide freely on / sink into the mesh while +# being strongly penalized for leaking outside the surface. +# +# Same parameter-name conventions as ObjectGaussians / HandGaussians so the +# trainer's parameter-group builder works unchanged. +# --------------------------------------------------------------------------- + +def _faces_to_centroid_and_tbn( + vertices: torch.Tensor, # (V, 3) + faces: torch.Tensor, # (F, 3) long +) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor]: + """Compute (centroid, TBN, mean_edge_length) for each face. + + Returns: + centroid: (F, 3) — face centroids. + TBN: (F, 3, 3) — columns are (T, B, N), an orthonormal frame + per face. T is the v0->v1 edge direction, N is the + outward face normal (using v0->v1 × v0->v2), + B = N × T. + mean_edge_length: (F,) — mean of the three edge lengths, used as a + scale init for the Gaussian. + """ + v0 = vertices[faces[:, 0]] # (F, 3) + v1 = vertices[faces[:, 1]] + v2 = vertices[faces[:, 2]] + centroid = (v0 + v1 + v2) / 3.0 + e01 = v1 - v0 + e02 = v2 - v0 + t = F.normalize(e01, dim=-1) + n_unnorm = torch.cross(e01, e02, dim=-1) + n = F.normalize(n_unnorm, dim=-1) + b = torch.cross(n, t, dim=-1) + TBN = torch.stack([t, b, n], dim=-1) # cols T,B,N + edge_len = ( + e01.norm(dim=-1) + + (v2 - v1).norm(dim=-1) + + (v0 - v2).norm(dim=-1) + ) / 3.0 + return centroid, TBN, edge_len + + +class FaceGaussians(nn.Module): + """One Gaussian per mesh face, rigidly attached to the object frame. + + Forward signature matches ``ObjectGaussians``: ``(R_obj, t_obj)`` returns + a per-frame ``GaussianFrame`` in camera-/world-frame. + + Learnable params (all interpreted in face-local frame): + _delta_p : (F, 3) — offset from face centroid in (T, B, N) coords. + Init 0. Component 2 is the outward-normal axis; one-sided + regularization on it expresses "stay inside the mesh". + _quat_canon : (F, 4) — extra rotation in the face-local frame, composed + onto the face's TBN. Init identity. Provides a small + amount of in-plane / cross-axis freedom on top of TBN. + _log_scale : (F, 3) — anisotropic axis-aligned log-scale. Init from + mean edge length: (edge/2, edge/2, edge/8) — disk-shaped + by default (thin along the normal axis). + _opacity_logit: (F,) + _color : (F, 3) — per-face RGB; init as the mean of the three + vertex colors. + _log_scale_global: scalar — same role as in ObjectGaussians; multiplies + positions and per-Gaussian scales together so the visual + extent tracks geometric extent. + + Buffers: + centroid_canon: (F, 3) — face centroids in object/rest frame. + TBN_canon: (F, 3, 3) — orthonormal face frame in object/rest frame. + """ + + is_face_anchored = True + + def __init__( + self, + vertices: torch.Tensor, # (V, 3) in object/rest frame + faces: torch.Tensor, # (F, 3) long + face_colors: torch.Tensor, # (F, 3) in [0, 1] + normal_thin_factor: float = 0.25, # init normal-axis sigma = factor*tangent + init_opacity: float = 0.9, + init_scale_factor: float = 1.0, + ) -> None: + super().__init__() + device = vertices.device + centroid, TBN, edge_len = _faces_to_centroid_and_tbn(vertices, faces) + Fn = faces.shape[0] + + self.register_buffer("centroid_canon", centroid.contiguous()) + self.register_buffer("TBN_canon", TBN.contiguous()) + + self._delta_p = nn.Parameter(torch.zeros(Fn, 3, device=device)) + self._quat_canon = nn.Parameter( + torch.tensor([1.0, 0.0, 0.0, 0.0], device=device).repeat(Fn, 1) + ) + s_in_plane = (edge_len * 0.5).clamp_min(1e-4) # (F,) + s_normal = (s_in_plane * float(normal_thin_factor)).clamp_min(1e-4) + init_scale = torch.stack([s_in_plane, s_in_plane, s_normal], dim=-1) + init_scale = (init_scale * float(init_scale_factor)).clamp_min(1e-6) + self._log_scale = nn.Parameter(init_scale.log()) + self._opacity_logit = nn.Parameter( + torch.full((Fn,), float(_logit(init_opacity)), device=device) + ) + self._color = nn.Parameter(face_colors.contiguous().clone()) + # Same role as in ObjectGaussians. + self._log_scale_global = nn.Parameter(torch.zeros((), device=device)) + + def num_gaussians(self) -> int: + return self.centroid_canon.shape[0] + + def forward( + self, + R_obj: torch.Tensor, # (3, 3) object-to-camera rotation + t_obj: torch.Tensor, # (3,) object-to-camera translation + ) -> GaussianFrame: + s_obj = self._log_scale_global.exp() # () + # Δp lives in face-local (T, B, N) coords; transport to canonical + # (object) frame by TBN_canon, then scale together with the centroid. + delta_canon = torch.einsum("fij,fj->fi", self.TBN_canon, self._delta_p) + p_canon = (self.centroid_canon + delta_canon) * s_obj # (F, 3) + means = p_canon @ R_obj.T + t_obj # (F, 3) + # Per-face world rotation: R_obj @ TBN_canon composed with _quat_canon. + TBN_world = torch.einsum("ij,fjk->fik", R_obj, self.TBN_canon) # (F, 3, 3) + q_face_world = rotmat_to_quat(TBN_world) # (F, 4) + quats = quat_mul(q_face_world, self._quat_canon) # (F, 4) + scales = self._log_scale.exp() * s_obj # (F, 3) + opacities = torch.sigmoid(self._opacity_logit) + colors = self._color + return GaussianFrame(means, quats, scales, opacities, colors) + + def object_scale(self) -> torch.Tensor: + return self._log_scale_global.exp() + + +class HandFaceGaussians(nn.Module): + """One Gaussian per MANO face. TBN frame is recomputed each frame from + the deformed face vertices — exact (no LBS-weight inheritance), because + the three vertices' deformed positions fully determine the face's local + frame and centroid. + + Forward signature matches ``HandGaussians``: ``(posed_verts_cam, + per_vertex_rotmat_cam)``. The per-vertex rotmat input is *ignored* in + this class (we derive the face rotation from the deformed face vertices + instead). + + Learnable params: same names and roles as ``FaceGaussians`` (minus + ``_log_scale_global``, matching HandGaussians). + """ + + is_face_anchored = True + + def __init__( + self, + rest_vertices: torch.Tensor, # (V, 3) MANO rest-pose vertices + faces: torch.Tensor, # (F, 3) MANO faces (long) + is_right: bool, + init_color: torch.Tensor, # (3,) skin tone + normal_thin_factor: float = 0.25, + init_opacity: float = 0.9, + init_scale_factor: float = 1.0, + device: str | torch.device = "cuda", + subsample_face_indices: torch.Tensor | None = None, + ) -> None: + super().__init__() + self.is_right = bool(is_right) + rest_vertices = rest_vertices.to(device) + faces = faces.to(device, dtype=torch.long) + if subsample_face_indices is not None: + faces = faces[subsample_face_indices.to(device, dtype=torch.long)] + # Buffer the face indices so per-frame TBN reconstruction can look up + # the right vertices from posed_verts_cam. + self.register_buffer("_faces", faces.contiguous()) + + # Canonical (rest-frame) centroid + TBN + edge length, used purely for + # initialization (scale, color); the runtime path recomputes TBN. + centroid, _TBN, edge_len = _faces_to_centroid_and_tbn(rest_vertices, faces) + Fn = faces.shape[0] + + self._delta_p = nn.Parameter(torch.zeros(Fn, 3, device=device)) + self._quat_canon = nn.Parameter( + torch.tensor([1.0, 0.0, 0.0, 0.0], device=device).repeat(Fn, 1) + ) + s_in_plane = (edge_len * 0.5).clamp_min(1e-4) + s_normal = (s_in_plane * float(normal_thin_factor)).clamp_min(1e-4) + init_scale = torch.stack([s_in_plane, s_in_plane, s_normal], dim=-1) + init_scale = (init_scale * float(init_scale_factor)).clamp_min(1e-6) + self._log_scale = nn.Parameter(init_scale.log()) + self._opacity_logit = nn.Parameter( + torch.full((Fn,), float(_logit(init_opacity)), device=device) + ) + self._color = nn.Parameter( + init_color.to(device).expand(Fn, 3).contiguous().clone() + ) + + def num_gaussians(self) -> int: + return self._faces.shape[0] + + def forward( + self, + posed_verts_cam: torch.Tensor, # (N_verts, 3) + per_vertex_rotmat_cam: torch.Tensor, # (N_verts, 3, 3) -- unused + ) -> GaussianFrame: + del per_vertex_rotmat_cam # face rotation comes from vertex positions + v0 = posed_verts_cam[self._faces[:, 0]] + v1 = posed_verts_cam[self._faces[:, 1]] + v2 = posed_verts_cam[self._faces[:, 2]] + centroid = (v0 + v1 + v2) / 3.0 + e01 = v1 - v0 + e02 = v2 - v0 + t = F.normalize(e01, dim=-1) + n_unnorm = torch.cross(e01, e02, dim=-1) + n = F.normalize(n_unnorm, dim=-1) + b = torch.cross(n, t, dim=-1) + TBN_world = torch.stack([t, b, n], dim=-1) # (F, 3, 3) + delta_world = torch.einsum("fij,fj->fi", TBN_world, self._delta_p) + means = centroid + delta_world + q_face_world = rotmat_to_quat(TBN_world) + quats = quat_mul(q_face_world, self._quat_canon) + return GaussianFrame( + means = means, + quats = quats, + scales = self._log_scale.exp(), + opacities = torch.sigmoid(self._opacity_logit), + colors = self._color, + ) + + +def init_object_face_gaussians_from_mesh( + vertices: torch.Tensor, # (V, 3) object frame + faces: "np.ndarray | torch.Tensor", # (F, 3) + vertex_colors: torch.Tensor, # (V, 3) in [0, 1] + normal_thin_factor: float = 0.25, + init_opacity: float = 0.9, + init_scale_factor: float = 1.0, +) -> FaceGaussians: + """One Gaussian per object face. ``faces`` may be numpy or torch.""" + import numpy as np + if isinstance(faces, np.ndarray): + faces_t = torch.from_numpy(faces.astype(np.int64)).to(vertices.device) + else: + faces_t = faces.to(vertices.device, dtype=torch.long) + # Face colors = mean of the three vertex colors. + face_colors = vertex_colors[faces_t].mean(dim=1) # (F, 3) + return FaceGaussians( + vertices = vertices, + faces = faces_t, + face_colors = face_colors, + normal_thin_factor = normal_thin_factor, + init_opacity = init_opacity, + init_scale_factor = init_scale_factor, + ) + + +def init_hand_face_gaussians( + rest_vertices: torch.Tensor, # (V, 3) MANO rest-pose vertices + faces: "np.ndarray | torch.Tensor", # (F, 3) MANO faces + is_right: bool, + skin_tone: tuple[float, float, float] = (0.72, 0.55, 0.45), + normal_thin_factor: float = 0.25, + hand_scale_init: float = 1.0, + init_opacity: float = 0.9, + init_scale_factor: float = 1.0, + device: str | torch.device = "cuda", + subsample_face_indices: torch.Tensor | None = None, +) -> HandFaceGaussians: + import numpy as np + if isinstance(faces, np.ndarray): + faces_t = torch.from_numpy(faces.astype(np.int64)) + else: + faces_t = faces.to(dtype=torch.long) + init_color = torch.tensor(skin_tone, dtype=torch.float32) + # If hand_scale enlarges the mesh, the face frame's edge_len enlarges too — + # _faces_to_centroid_and_tbn reads scaled vertices, so pre-scale them here. + rest_scaled = rest_vertices * float(hand_scale_init) + return HandFaceGaussians( + rest_vertices = rest_scaled, + faces = faces_t, + is_right = is_right, + init_color = init_color, + normal_thin_factor = normal_thin_factor, + init_opacity = init_opacity, + init_scale_factor = init_scale_factor, + device = device, + subsample_face_indices = subsample_face_indices, + ) diff --git a/third-party/video_to_data/reconstruction/modules/v2d_gsplat_refinement/lib/io.py b/third-party/video_to_data/reconstruction/modules/v2d_gsplat_refinement/lib/io.py new file mode 100644 index 0000000000000000000000000000000000000000..2f71a42798d319d4650b07fab7a52ed1540b6abf --- /dev/null +++ b/third-party/video_to_data/reconstruction/modules/v2d_gsplat_refinement/lib/io.py @@ -0,0 +1,429 @@ +# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 +"""I/O for the gsplat-refinement optimizer. + +All loaders return torch tensors on a target device so the optimizer can +keep everything on GPU. All savers write back the same on-disk formats the +upstream pipeline produces (Transform3d JSON for object poses, HaMeR +aligned-style JSON for hands), so refined outputs slot into existing +downstream renderers without changes. +""" +from __future__ import annotations + +import glob +import json +import os +from dataclasses import dataclass + +import numpy as np +import torch +import trimesh +from PIL import Image + +from v2d.common.datatypes import CameraIntrinsics, Mask, Transform3d + + +# --------------------------------------------------------------------------- +# Paths +# --------------------------------------------------------------------------- + +def _frame_idx(path: str) -> int: + return int(os.path.splitext(os.path.basename(path))[0]) + + +def list_frame_indices(directory: str, ext: str = ".png") -> list[int]: + files = sorted(glob.glob(os.path.join(directory, f"*{ext}"))) + return [_frame_idx(f) for f in files] + + +# --------------------------------------------------------------------------- +# Per-frame raster inputs +# --------------------------------------------------------------------------- + +def load_rgb(path: str, device: str) -> torch.Tensor: + """Load an RGB frame as a (H, W, 3) float32 tensor in [0, 1].""" + img = np.asarray(Image.open(path).convert("RGB"), dtype=np.float32) / 255.0 + return torch.from_numpy(img).to(device) + + +def load_mask(path: str, device: str) -> torch.Tensor: + """Load a binary mask as a (H, W) float32 tensor in {0, 1}.""" + m = Mask.load(path).mask.astype(np.float32) + if m.ndim == 3: + m = m[..., 0] + m = (m > 0.5).astype(np.float32) + return torch.from_numpy(m).to(device) + + +def load_depth(path: str, device: str) -> torch.Tensor: + """Load MoGe inverse-depth PNG as a (H, W) float32 metric depth tensor. + + Pixels at infinity (inverse_depth == 0) become +inf; callers should mask + them out before computing losses. + """ + px = np.asarray(Image.open(path)).astype(np.float32) + with np.errstate(divide="ignore"): + depth = 1.0 / (px / 65535.0) - 1.0 + return torch.from_numpy(depth).to(device) + + +# --------------------------------------------------------------------------- +# Camera intrinsics +# --------------------------------------------------------------------------- + +def load_intrinsics(path: str, device: str) -> tuple[torch.Tensor, int, int]: + """Return ((3, 3) K tensor, width, height).""" + intr = CameraIntrinsics.load(path) + K = torch.tensor(intr.to_matrix(), dtype=torch.float32, device=device) + return K, int(intr.width), int(intr.height) + + +# --------------------------------------------------------------------------- +# Object poses (Transform3d JSON, object-to-camera) +# --------------------------------------------------------------------------- + +@dataclass +class ObjectPoseTrack: + """Per-frame object→camera transforms, stacked as torch tensors. + + rotations: (T, 4) quaternion (w, x, y, z) + translations: (T, 3) + scales: (T, 3) -- usually [1, 1, 1] post-FoundationPose + frame_indices: list[int] + """ + rotations: torch.Tensor + translations: torch.Tensor + scales: torch.Tensor + frame_indices: list[int] + + +def load_object_poses(poses_dir: str, device: str) -> ObjectPoseTrack: + files = sorted(glob.glob(os.path.join(poses_dir, "*.json"))) + if not files: + raise FileNotFoundError(f"No Transform3d JSONs in {poses_dir}") + rots, trans, scls, idxs = [], [], [], [] + for f in files: + t = Transform3d.load(f) + rots.append(t.rotation) + trans.append(t.translation) + scls.append(t.scale) + idxs.append(_frame_idx(f)) + return ObjectPoseTrack( + rotations = torch.tensor(rots, dtype=torch.float32, device=device), + translations = torch.tensor(trans, dtype=torch.float32, device=device), + scales = torch.tensor(scls, dtype=torch.float32, device=device), + frame_indices= idxs, + ) + + +def save_object_poses(track: ObjectPoseTrack, poses_dir: str) -> None: + os.makedirs(poses_dir, exist_ok=True) + rots = track.rotations.detach().cpu().tolist() + trans = track.translations.detach().cpu().tolist() + scls = track.scales.detach().cpu().tolist() + for i, fidx in enumerate(track.frame_indices): + Transform3d( + rotation = rots[i], + translation = trans[i], + scale = scls[i], + ).save(os.path.join(poses_dir, f"{fidx:06d}.json")) + + +# --------------------------------------------------------------------------- +# Hand poses (HaMeR aligned-style JSON, per-frame in a single track dir) +# --------------------------------------------------------------------------- + +@dataclass +class HandPoseTrack: + """Per-frame MANO params + cam_t in real intrinsics for a single hand. + + global_orient: (T, 3) axis-angle (root) + hand_pose: (T, 45) axis-angle (15 finger joints x 3) + betas: (T, 10) + cam_t: (T, 3) translation in real-camera frame + is_right: bool + frame_indices: list[int] + raw_records: list[dict] -- preserved verbatim so we can round-trip + non-optimized fields (intrinsics, image_size, + diagnostics, track_id, hand_scale) on save. + hand_scale: float -- per-track multiplicative depth correction + emitted by align_hands. cam_t carries the + additive (dz) shift; hand_scale corrects + multiplicative depth mismatch by scaling + the MANO mesh around its centroid. + Defaults to 1.0 when absent. + """ + global_orient: torch.Tensor + hand_pose: torch.Tensor + betas: torch.Tensor + cam_t: torch.Tensor + is_right: bool + frame_indices: list[int] + raw_records: list[dict] + hand_scale: float = 1.0 + + +def load_hand_poses(track_dir: str, device: str) -> HandPoseTrack: + files = sorted(glob.glob(os.path.join(track_dir, "*.json"))) + if not files: + raise FileNotFoundError(f"No hand JSONs in {track_dir}") + go, hp, be, ct, idxs, recs = [], [], [], [], [], [] + is_right = None + hand_scale: float | None = None + for f in files: + with open(f) as fh: + r = json.load(fh) + if is_right is None: + is_right = bool(r["is_right"]) + elif bool(r["is_right"]) != is_right: + raise ValueError(f"Mixed handedness in {track_dir}") + # hand_scale is per-track-constant; first non-default record wins. + if hand_scale is None and "hand_scale" in r: + hand_scale = float(r["hand_scale"]) + go.append(r["mano"]["global_orient"]) + hp.append(r["mano"]["hand_pose"]) + be.append(r["mano"]["betas"]) + ct.append(r["cam_t"]) + idxs.append(_frame_idx(f)) + recs.append(r) + return HandPoseTrack( + global_orient = torch.tensor(go, dtype=torch.float32, device=device), + hand_pose = torch.tensor(hp, dtype=torch.float32, device=device), + betas = torch.tensor(be, dtype=torch.float32, device=device), + cam_t = torch.tensor(ct, dtype=torch.float32, device=device), + is_right = bool(is_right), + frame_indices = idxs, + raw_records = recs, + hand_scale = float(hand_scale) if hand_scale is not None else 1.0, + ) + + +def save_hand_poses(track: HandPoseTrack, track_dir: str) -> None: + os.makedirs(track_dir, exist_ok=True) + go = track.global_orient.detach().cpu().tolist() + hp = track.hand_pose.detach().cpu().tolist() + be = track.betas.detach().cpu().tolist() + ct = track.cam_t.detach().cpu().tolist() + hand_scale = float(track.hand_scale) + for i, fidx in enumerate(track.frame_indices): + rec = dict(track.raw_records[i]) # shallow copy preserves diagnostics etc. + rec["mano"] = { + "global_orient": go[i], + "hand_pose": hp[i], + "betas": be[i], + } + rec["cam_t"] = ct[i] + rec["hand_scale"] = hand_scale + with open(os.path.join(track_dir, f"{fidx:06d}.json"), "w") as fh: + json.dump(rec, fh, indent=2) + + +# --------------------------------------------------------------------------- +# Object mesh (anchor positions for object Gaussians) +# --------------------------------------------------------------------------- + +# --------------------------------------------------------------------------- +# Frame-level supervision cache (RGB + masks + depth) +# --------------------------------------------------------------------------- + +class FrameCache: + """Pre-loaded RGB / mask / depth tensors for the whole sequence. + + All channels are stacked into single contiguous tensors of shape (T, ...) + held on CPU. Per-step access is a tensor index + ``.to(device)`` — no PNG + decode, no disk I/O after construction. + + Memory cost (T frames at HxW): + rgb: T * H * W * 3 * 4 bytes + each mask: T * H * W * 4 bytes + depth: T * H * W * 4 bytes (only if depth_dir provided) + + So a 500-frame 720x720 clip with object mask + 2 hand masks + depth uses + ~7 GB of CPU RAM. This is a deliberate tradeoff vs. lazy loading: a + typical refinement run iterates each frame dozens of times, so the + upfront one-shot decode pays for itself within the first epoch. + """ + + def __init__( + self, + frame_indices: list[int], + frames_dir: str, + object_mask_dir: str, + hand_mask_dirs: list[str], + depth_dir: str | None, + height: int, + width: int, + valid_mask_threshold: float = 0.04, + valid_mask_erode_iters: int = 2, + ) -> None: + from tqdm import tqdm + + n = len(frame_indices) + self.frame_indices = list(frame_indices) + self.height = height + self.width = width + self.has_depth = depth_dir is not None + + self.rgb = torch.zeros((n, height, width, 3), dtype=torch.float32) + self.obj_mask = torch.zeros((n, height, width), dtype=torch.float32) + self.hand_masks = [ + torch.zeros((n, height, width), dtype=torch.float32) + for _ in hand_mask_dirs + ] + self.depth = ( + torch.zeros((n, height, width), dtype=torch.float32) + if self.has_depth else None + ) + + for t, fidx in enumerate(tqdm(frame_indices, ncols=80, + desc="caching frames", unit="frame")): + # RGB. Resize during load (PIL) if source resolution differs + # from the cache target (height, width). PIL.size is (W, H). + rgb_path = _find_frame_file(frames_dir, fidx) + img = Image.open(rgb_path).convert("RGB") + if img.size != (width, height): + img = img.resize((width, height), Image.BILINEAR) + arr = np.asarray(img, dtype=np.float32) / 255.0 + self.rgb[t] = torch.from_numpy(arr) + + # Object mask (zero if missing or wrong-shape). + self.obj_mask[t] = _load_mask_or_zero( + object_mask_dir, fidx, height, width) + + # Per-hand masks. + for k, mdir in enumerate(hand_mask_dirs): + self.hand_masks[k][t] = _load_mask_or_zero( + mdir, fidx, height, width) + + # Optional depth (infinity-fills propagate into the loss mask). + # Resize via PIL bilinear before decoding inverse-depth — the + # tiny smoothing introduced by interpolating raw uint16 values + # is fine for our soft depth prior. + if self.has_depth: + dpath = os.path.join(depth_dir, f"{fidx:06d}.png") + if os.path.exists(dpath): + img_d = Image.open(dpath) + if img_d.size != (width, height): + img_d = img_d.resize((width, height), Image.BILINEAR) + px = np.asarray(img_d).astype(np.float32) + with np.errstate(divide="ignore"): + d = 1.0 / (px / 65535.0) - 1.0 + self.depth[t] = torch.from_numpy(d) + else: + self.depth[t].fill_(float("inf")) + + # Static valid-pixel mask derived from the input video itself. + # Detects fixed black regions (fisheye crop, vignette, dead border) + # by checking the per-pixel max brightness across all frames: any + # pixel that never exceeds ``valid_mask_threshold`` is treated as + # invalid and excluded from photometric / depth / SuGaR supervision. + # Eroded by ``valid_mask_erode_iters`` 3x3 steps to peel back the + # soft transition at the boundary. + # + # Single static mask (shape (H, W)), shared across all frames — + # the artifact is image-space-fixed, so cross-frame consistency is + # automatic and there's no per-frame degeneracy. + max_brightness = self.rgb.amax(dim=0).amax(dim=-1) # (H, W) + valid = (max_brightness > float(valid_mask_threshold)).float() + if valid_mask_erode_iters > 0: + m = valid.unsqueeze(0).unsqueeze(0) + for _ in range(int(valid_mask_erode_iters)): + m = 1.0 - torch.nn.functional.max_pool2d( + 1.0 - m, kernel_size=3, stride=1, padding=1, + ) + valid = m.squeeze(0).squeeze(0) + self.valid_mask = valid # (H, W) + n_valid = int(self.valid_mask.sum().item()) + n_total = height * width + print(f" Valid-pixel mask: {n_valid}/{n_total} pixels " + f"({100.0 * n_valid / n_total:.1f}%) " + f"(threshold={valid_mask_threshold:.3f}, " + f"erode_iters={valid_mask_erode_iters})") + + # Pin memory for async H2D transfers under non_blocking=True. + # Pinning can fail on systems with low locked-memory limits — fall + # back silently if so; transfers still work, just slightly slower. + try: + self.rgb = self.rgb.pin_memory() + self.obj_mask = self.obj_mask.pin_memory() + self.hand_masks = [m.pin_memory() for m in self.hand_masks] + if self.depth is not None: + self.depth = self.depth.pin_memory() + self.valid_mask = self.valid_mask.pin_memory() + except RuntimeError: + pass + + def get(self, t: int, device) -> dict: + return { + "rgb": self.rgb[t].to(device, non_blocking=True), + "obj_mask": self.obj_mask[t].to(device, non_blocking=True), + "hand_masks":[m[t].to(device, non_blocking=True) for m in self.hand_masks], + "depth": (self.depth[t].to(device, non_blocking=True) + if self.depth is not None else None), + } + + +def _find_frame_file(frames_dir: str, fidx: int) -> str: + for ext in (".png", ".jpg"): + p = os.path.join(frames_dir, f"{fidx:06d}{ext}") + if os.path.exists(p): + return p + raise FileNotFoundError(f"Frame {fidx:06d} not found in {frames_dir}") + + +def _load_mask_or_zero(mask_dir: str, fidx: int, H: int, W: int) -> torch.Tensor: + p = os.path.join(mask_dir, f"{fidx:06d}.png") + if not os.path.exists(p): + return torch.zeros((H, W), dtype=torch.float32) + # Resize via PIL nearest-neighbor before decoding so binary mask + # values stay {0, 1}. PIL.size is (W, H). + img = Image.open(p) + if img.size != (W, H): + img = img.resize((W, H), Image.NEAREST) + arr = np.asarray(img).astype(np.float32) + if arr.ndim == 3: + arr = arr[..., 0] + arr = arr / arr.max() if arr.max() > 1.0 else arr + return torch.from_numpy((arr > 0.5).astype(np.float32)) + + +# --------------------------------------------------------------------------- +# Object mesh +# --------------------------------------------------------------------------- + +def load_object_mesh( + mesh_path: str, device: str +) -> tuple[torch.Tensor, torch.Tensor, np.ndarray]: + """Load (N_vertices, 3) vertex positions, (N_vertices, 3) per-vertex + diffuse colors in [0, 1], and (N_faces, 3) face indices. + + Vertex positions are in the mesh's own (canonical / object) frame. + Faces are returned as a numpy array (consumed by trimesh-based SDF + construction, no need to live on GPU). + """ + scene = trimesh.load(mesh_path, force="mesh", process=False) + if isinstance(scene, trimesh.Scene): + scene = trimesh.util.concatenate(list(scene.geometry.values())) + verts = np.asarray(scene.vertices, dtype=np.float32) + faces = np.asarray(scene.faces, dtype=np.int64) + + colors = None + if hasattr(scene.visual, "vertex_colors") and scene.visual.vertex_colors is not None: + vc = np.asarray(scene.visual.vertex_colors, dtype=np.float32) + if vc.shape[0] == verts.shape[0] and vc.shape[1] >= 3: + colors = vc[:, :3] / 255.0 + if colors is None and hasattr(scene.visual, "to_color"): + try: + vc = np.asarray(scene.visual.to_color().vertex_colors, dtype=np.float32) + if vc.shape[0] == verts.shape[0] and vc.shape[1] >= 3: + colors = vc[:, :3] / 255.0 + except Exception: + pass + if colors is None: + colors = np.full((verts.shape[0], 3), 0.5, dtype=np.float32) + + return ( + torch.from_numpy(verts).to(device), + torch.from_numpy(colors).to(device), + faces, + ) diff --git a/third-party/video_to_data/reconstruction/modules/v2d_gsplat_refinement/lib/losses.py b/third-party/video_to_data/reconstruction/modules/v2d_gsplat_refinement/lib/losses.py new file mode 100644 index 0000000000000000000000000000000000000000..2b211496fca34456b89a813f9fc1831046992971 --- /dev/null +++ b/third-party/video_to_data/reconstruction/modules/v2d_gsplat_refinement/lib/losses.py @@ -0,0 +1,872 @@ +# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 +"""Losses for joint hand+object Gaussian refinement. + +Photometric: L1 between rendered RGB and image RGB, masked to the union + of hand+object SAM2 masks (background pixels are not + supervised — Gaussians don't have to explain them). + +Silhouette: BCE-ish L1 between per-set rendered alpha and the + corresponding SAM2 mask. Object alpha vs. object mask, each + hand alpha vs. its own SAM2 hand mask. + +Depth: Huber on rendered depth vs. MoGe depth, masked to the union + mask AND to pixels where MoGe is finite. Low default weight + (0.05) since MoGe depth is temporally jittery. + +Smoothness: Penalize first-difference of per-frame pose params (axis-angle + + translation for object; global_orient + hand_pose + cam_t + for hand). +""" +from __future__ import annotations + +import torch +import torch.nn.functional as F + + +# --------------------------------------------------------------------------- +# SSIM (Gaussian-window, masked). 11x11 σ=1.5 window, matching the 3DGS / +# original SSIM paper. Cached per (window_size, channels, device, dtype) so +# the window tensor is built once. +# --------------------------------------------------------------------------- + +_SSIM_WINDOW_CACHE: dict = {} + + +def _ssim_window(window_size: int, channels: int, device, dtype) -> torch.Tensor: + key = (window_size, channels, device, dtype) + win = _SSIM_WINDOW_CACHE.get(key) + if win is not None: + return win + sigma = 1.5 + coords = torch.arange(window_size, dtype=dtype, device=device) - window_size // 2 + g = torch.exp(-(coords ** 2) / (2.0 * sigma * sigma)) + g = g / g.sum() + w2d = g[:, None] * g[None, :] # (K, K) + win = w2d.expand(channels, 1, window_size, window_size).contiguous() + _SSIM_WINDOW_CACHE[key] = win + return win + + +def _ssim_map( + x: torch.Tensor, # (1, C, H, W) + y: torch.Tensor, # (1, C, H, W) + data_range: float, + window_size: int = 11, +) -> torch.Tensor: + """Per-pixel SSIM map, (1, C, H, W). Padding=window_size//2.""" + C = x.shape[1] + pad = window_size // 2 + win = _ssim_window(window_size, C, x.device, x.dtype) + mu_x = F.conv2d(x, win, padding=pad, groups=C) + mu_y = F.conv2d(y, win, padding=pad, groups=C) + mu_x2, mu_y2, mu_xy = mu_x * mu_x, mu_y * mu_y, mu_x * mu_y + sig_x2 = F.conv2d(x * x, win, padding=pad, groups=C) - mu_x2 + sig_y2 = F.conv2d(y * y, win, padding=pad, groups=C) - mu_y2 + sig_xy = F.conv2d(x * y, win, padding=pad, groups=C) - mu_xy + C1 = (0.01 * data_range) ** 2 + C2 = (0.03 * data_range) ** 2 + num = (2.0 * mu_xy + C1) * (2.0 * sig_xy + C2) + den = (mu_x2 + mu_y2 + C1) * (sig_x2 + sig_y2 + C2) + return num / den + + +def photometric_ssim_loss( + rendered_rgb: torch.Tensor, # (H, W, 3) + target_rgb: torch.Tensor, # (H, W, 3) + union_mask: torch.Tensor, # (H, W) in {0, 1} + window_size: int = 11, +) -> torch.Tensor: + """1 − SSIM between rendered and target RGB, masked to ``union_mask``. + + Standard 11x11 Gaussian-window SSIM (3DGS default). The per-pixel SSIM + map is computed over the full image and then masked — SSIM windows + straddling the mask boundary see some invalid content, but for typical + fg coverage this is a small artifact and matches the 3DGS reference + implementation. Data range fixed to 1.0 (RGB in [0, 1]). + """ + x = rendered_rgb.permute(2, 0, 1).unsqueeze(0) # (1, 3, H, W) + y = target_rgb .permute(2, 0, 1).unsqueeze(0) # (1, 3, H, W) + smap = _ssim_map(x, y, data_range=1.0, window_size=window_size) + per_pixel = smap.mean(dim=1).squeeze(0) # (H, W) + n = union_mask.sum().clamp_min(1.0) + return 1.0 - (per_pixel * union_mask).sum() / n + + +def depth_ssim_loss( + rendered_depth: torch.Tensor, # (H, W) + target_depth: torch.Tensor, # (H, W), may contain +inf + union_mask: torch.Tensor, # (H, W) in {0, 1} + window_size: int = 11, + eps: float = 1e-3, +) -> torch.Tensor: + """1 − SSIM on log-depth, masked and percentile-normalized. + + Depth is unbounded, so we (a) work in log space — same invariance to + multiplicative scaling as ``depth_gradient_loss`` — and (b) rescale to + roughly [0, 1] using the 5th/95th percentiles of the target's valid + region (detached, so the scaling itself doesn't get optimized). This + keeps SSIM's C1 / C2 constants (calibrated for data_range=1) in the + right regime regardless of scene scale. + + +inf target pixels are excluded via the mask and replaced with ``eps`` + inside log() so gradients stay finite. + """ + valid = union_mask * torch.isfinite(target_depth).float() + if float(valid.sum()) < 10.0: + return rendered_depth.sum() * 0.0 + + dp = torch.log(rendered_depth.clamp_min(eps)) + dt = torch.log(target_depth.nan_to_num(posinf=eps).clamp_min(eps)) + + with torch.no_grad(): + dt_v = dt[valid > 0.5] + lo = torch.quantile(dt_v, 0.05) + hi = torch.quantile(dt_v, 0.95) + rng = (hi - lo).clamp_min(1e-3) + dp_n = ((dp - lo) / rng).clamp(0.0, 1.0) + dt_n = ((dt - lo) / rng).clamp(0.0, 1.0) + + x = dp_n.unsqueeze(0).unsqueeze(0) # (1, 1, H, W) + y = dt_n.unsqueeze(0).unsqueeze(0) + smap = _ssim_map(x, y, data_range=1.0, window_size=window_size) + per_pixel = smap.squeeze(0).squeeze(0) # (H, W) + n = valid.sum().clamp_min(1.0) + return 1.0 - (per_pixel * valid).sum() / n + + +def photometric_loss( + rendered_rgb: torch.Tensor, # (H, W, 3) + target_rgb: torch.Tensor, # (H, W, 3) + union_mask: torch.Tensor, # (H, W) in {0, 1} + mask_background_to_black: bool = False, + use_l2: bool = False, +) -> torch.Tensor: + """Per-foreground-pixel L1 between rendered and target RGB. + + With ``mask_background_to_black=False`` (default): only foreground (mask) + pixels contribute — safer when the SAM2 masks are noisy, since wrong + mask pixels don't get a hard "match black" target imposed. + + With ``mask_background_to_black=True``: target's background is zeroed to + match the renderer's black BG and the L1 is summed over the whole image + (then normalized by foreground pixel count). Penalizes Gaussians that + leak outside the mask, but makes mask errors more costly. + + In both cases the normalization is ``sum / union_mask.sum()`` so per- + foreground-pixel gradient magnitude is image-size-invariant. + """ + n = union_mask.sum().clamp_min(1.0) + if mask_background_to_black: + target = target_rgb * union_mask.unsqueeze(-1) + d = rendered_rgb - target + else: + d = rendered_rgb - target_rgb + if use_l2: + per_pixel = (d * d).sum(dim=-1) # (H, W) + else: + per_pixel = d.abs().sum(dim=-1) + if mask_background_to_black: + return per_pixel.sum() / n + return (per_pixel * union_mask).sum() / n + + +def delta_p_regularizer(delta_p: torch.Tensor) -> torch.Tensor: + """Sum-squared L2 on per-Gaussian position offsets in canonical frame. + + Pulls Gaussians back toward their mesh-vertex anchor; without this the + optimizer is free to slide them anywhere photometrically convenient, + which manifests as Gaussians "scattering" off the mesh surface. + + Sum reduction (not mean) avoids the 1/N gradient dilution: with .mean() + over N=1000 Gaussians, each Δp_i gets ~1000× less gradient, so a + weight of 100 effectively acts like 0.1 — too weak to compete with + photometric pulls of ~0.1-1.0 magnitude. + """ + return (delta_p * delta_p).sum() + + +def depth_ordering_loss( + depth_fg: torch.Tensor, # (H, W) E[d] from foreground-only render + depth_bg: torch.Tensor, # (H, W) E[d] from background-only render + fg_mask: torch.Tensor, # (H, W) {0,1} foreground pixels + margin: float = 0.0, # require depth_fg ≤ depth_bg - margin +) -> torch.Tensor: + """Penetration penalty: foreground Gaussians should be in front of the + background at foreground-mask pixels. + + Per-pixel loss = max(0, depth_fg - depth_bg + margin), masked to the + foreground mask and averaged. Fires only when the optimizer pushes + hand or object Gaussians *behind* the background — exactly the + penetration mode for that pair. Background pixels (where fg_mask=0) + contribute zero. Units: [depth]. + + Differentiable through both depth maps and the mask is constant + (gradient flows back into the Gaussian centers). + """ + diff = (depth_fg - depth_bg + float(margin)).clamp(min=0.0) # (H, W) + n = fg_mask.sum().clamp_min(1.0) + return (diff * fg_mask).sum() / n + + +def depth_variance_loss( + depth_var: torch.Tensor, # (H, W) per-pixel E[d²] − E[d]², ≥ 0 + mask: torch.Tensor | None = None, # (H, W) {0,1} or None for all pixels +) -> torch.Tensor: + """Mean per-pixel alpha-weighted depth variance — depth-variance proxy + for Mip-NeRF 360 distortion loss. + + Penalizes the spread of compositing weights along the view ray: when a + pixel sums contributions from Gaussians at different depths, the + variance grows. Minimizing it concentrates per-pixel mass at one + depth, killing "floater" Gaussians and producing a thin-shell surface. + + Units are [depth²]. If your scene scale is ~0.1 m, variance scales + are ~0.01, so a weight of ~1.0 gives a loss term of similar magnitude + to other regularizers; tune from there. + """ + if mask is None: + return depth_var.mean() + n = mask.sum().clamp_min(1.0) + return (depth_var * mask).sum() / n + + +def opacity_binary_loss(opacities: torch.Tensor) -> torch.Tensor: + """Sum of α(1 − α) — pushes each Gaussian's opacity toward 0 or 1. + + The product is zero at α = 0 and α = 1, peaks at 0.25 when α = 0.5, and + is smooth everywhere (gradient pushes away from 0.5 toward the nearer + extreme). Sum reduction matches ``delta_p_regularizer``: per-Gaussian + pressure doesn't get diluted by 1/N, so weights here are comparable to + the other sequence-wide regularizers. + + Pairs well with face-anchored Gaussians: low-opacity (invisible) + Gaussians "drop out" rather than stay as semi-transparent fog, which + tightens the rendered silhouette and lets the optimizer commit to which + faces actually contribute to the surface. + """ + return (opacities * (1.0 - opacities)).sum() + + +def face_delta_p_regularizer( + delta_p_local: torch.Tensor, # (F, 3) in face-local (T, B, N) coords + w_tangent: float = 1.0, # penalty on tangent + bitangent slide + w_normal_outward: float = 100.0, # penalty on Δp_N > 0 (leaks outside the mesh) + w_normal_inward: float = 0.0, # penalty on Δp_N < 0 (sinks into the volume) +) -> torch.Tensor: + """Asymmetric sum-squared regularizer on face-anchored Gaussian offsets. + + Used in place of ``delta_p_regularizer`` for ``FaceGaussians`` / + ``HandFaceGaussians``, whose ``_delta_p`` is in face-local (T, B, N) + coordinates rather than canonical world coordinates. + + The three components have distinct meanings: + - tangent + bitangent (axes 0, 1): Δp slides the Gaussian across the + face, parallel to the surface. Light penalty — we want Gaussians to + slide freely to wherever the photometric signal is best. + - normal outward (axis 2, positive): Δp pushes the Gaussian out + through the surface, away from the mesh interior. Heavy penalty — + this is the "stay inside the volume" constraint. + - normal inward (axis 2, negative): Δp sinks the Gaussian into the + volume. Default zero (free) — combined with the outward penalty, + this lets Gaussians populate the mesh interior under photometric + pull while never leaking outside. + + Sum reduction matches ``delta_p_regularizer`` so weight magnitudes are + comparable to the legacy regularizer. + """ + tb_sq = (delta_p_local[:, :2] ** 2).sum() + n = delta_p_local[:, 2] + n_out_sq = n.clamp(min=0.0).pow(2).sum() + n_in_sq = n.clamp(max=0.0).pow(2).sum() + return ( + w_tangent * tb_sq + + w_normal_outward * n_out_sq + + w_normal_inward * n_in_sq + ) + + +def silhouette_loss( + rendered_class_map: torch.Tensor, # (H, W, K) per-pixel class probabilities + target_class_map: torch.Tensor, # (H, W, K) one-hot per-pixel class targets + class_weights: torch.Tensor | None = None, # (K,) optional per-class weight + use_l2: bool = False, +) -> torch.Tensor: + """Per-pixel L1 between a composited class-label render and the SAM2 + one-hot class targets, with optional per-class weighting. + + Class-label rendering: each Gaussian carries a K-dim one-hot label + (object=class 0, hand_i=class i+1). All Gaussians render together with + proper depth ordering, so the gsplat rasterizer's alpha compositing + naturally accounts for occlusion: at a pixel where the hand is in + front of the object, the rendered class probability is dominated by + "hand" — exactly what SAM2 labels there. + + ``class_weights`` (shape (K,)) lets the caller weight different mask + sources differently, e.g. trust the SAM2 object mask more than the + hand masks when the latter are flickery. + """ + d = rendered_class_map - target_class_map # (H, W, K) + diff = (d * d) if use_l2 else d.abs() + if class_weights is not None: + diff = diff * class_weights # broadcast (K,) → (H, W, K) + return diff.mean() + + +def depth_loss( + rendered_depth: torch.Tensor, # (H, W) + target_depth: torch.Tensor, # (H, W) + union_mask: torch.Tensor, # (H, W) in {0, 1} + huber_delta: float = 0.05, +) -> torch.Tensor: + """Huber on depth difference, masked to union ∩ valid-target. + + ``target_depth`` may contain +inf (sky / no MoGe estimate) — those pixels + are excluded from the loss. + """ + valid = union_mask * torch.isfinite(target_depth).float() + diff = (rendered_depth - target_depth) * valid + abs_diff = diff.abs() + quad = 0.5 * diff * diff + lin = huber_delta * (abs_diff - 0.5 * huber_delta) + huber = torch.where(abs_diff <= huber_delta, quad, lin) + n = valid.sum().clamp_min(1.0) + return huber.sum() / n + + +def depth_gradient_loss( + rendered_depth: torch.Tensor, # (H, W) + target_depth: torch.Tensor, # (H, W) + union_mask: torch.Tensor, # (H, W) in {0, 1} + log_space: bool = True, + eps: float = 1e-3, +) -> torch.Tensor: + """L1 between per-pixel depth gradients of ``rendered`` and ``target``. + + Shape-only depth supervision: ``rendered`` only has to match the *slope* + of ``target``, not its absolute level. With ``log_space=True`` (default) + we differentiate ``log(d)`` instead of ``d`` itself, which makes the loss + invariant to a global multiplicative scaling of either map. That's the + right invariance for monocular depth like MoGe, whose dominant errors are + scale/offset rather than local shape. + + Notation: subscript x = horizontal finite difference, y = vertical. + ``union_mask`` and a finite-target check gate both endpoints of each + difference so we never compare across an invalid pixel. + """ + valid = union_mask * torch.isfinite(target_depth).float() + if log_space: + d_r = torch.log(rendered_depth.clamp_min(eps)) + d_t = torch.log(target_depth.clamp_min(eps)) + else: + d_r = rendered_depth + d_t = target_depth + + # Horizontal differences (between cols c and c+1). + gx_r = d_r[:, 1:] - d_r[:, :-1] + gx_t = d_t[:, 1:] - d_t[:, :-1] + mx = valid[:, 1:] * valid[:, :-1] + lx = (gx_r - gx_t).abs() * mx + + # Vertical differences (between rows r and r+1). + gy_r = d_r[1:, :] - d_r[:-1, :] + gy_t = d_t[1:, :] - d_t[:-1, :] + my = valid[1:, :] * valid[:-1, :] + ly = (gy_r - gy_t).abs() * my + + n = (mx.sum() + my.sum()).clamp_min(1.0) + return (lx.sum() + ly.sum()) / n + + +def temporal_smoothness(param: torch.Tensor) -> torch.Tensor: + """Sum-squared first-difference of a (T, D) parameter tensor. + + Sum reduction (not mean) keeps per-frame-pair gradient magnitude + independent of sequence length; with mean, a 500-frame clip dilutes + each pair's gradient by ~1/(3*(T-1)) ≈ 1/1500, which makes weights + in the 0.01-0.1 range effectively negligible. + + Use ``rotation_smoothness`` instead for axis-angle parameters — naive + L2 smoothness on axis-angle is broken near the |θ|=π boundary because + of the ±2π·n/‖n‖ representational ambiguity. + """ + if param.shape[0] < 2: + return param.new_zeros(()) + d = param[1:] - param[:-1] + return (d * d).sum() + + +def quat_smoothness(q: torch.Tensor) -> torch.Tensor: + """Sum-squared first-difference of unit quaternions with sign alignment. + + Same semantics as ``rotation_smoothness`` but takes quats directly + (T, ..., 4) — useful when the quat has been composed in quat space + (e.g. world-frame pose = q_bg⁻¹ ⊗ q_cam) and converting to axis-angle + would hit the wrap singularity at θ=π. + + Sign alignment uses the standard q ≡ −q double-cover: flip the sign + of any consecutive quat whose dot product with the previous is < 0. + """ + if q.shape[0] < 2: + return q.new_zeros(()) + q = q / q.norm(dim=-1, keepdim=True).clamp_min(1e-8) + dot = (q[1:] * q[:-1]).sum(dim=-1, keepdim=True) + q_aligned = torch.where(dot < 0, -q[1:], q[1:]) + d = q_aligned - q[:-1] + return (d * d).sum() + + +def rotation_smoothness(axis_angle: torch.Tensor) -> torch.Tensor: + """Sum-squared first-difference of axis-angle rotations, measured in + quaternion space with double-cover sign alignment. + + Why not L2 directly on axis-angle: the same rotation has two + representations across the |θ|=π boundary (``aa`` and + ``aa - 2π·aa/‖aa‖``). Per-frame regressors like FoundationPose / HaMeR + sometimes pick different representations for nearly-identical + rotations, so direct L2 smoothness sees a phantom huge difference and + pushes the optimizer to discontinuously flip — visible as sporadic + orientation flips in refined poses. + + Converting to unit quaternions and sign-aligning consecutive pairs + (q ≡ -q) makes wrap invisible to the loss. The squared-difference is + then proportional to ``1 - cos(θ_rel/2)``, a smooth function of the + relative rotation angle. + + Accepts (T, 3) for a single rotation per frame or (T, ..., 3) for + multiple (e.g. (T, 15, 3) for the 15-joint MANO ``hand_pose``). + """ + if axis_angle.shape[0] < 2: + return axis_angle.new_zeros(()) + + angle = axis_angle.norm(dim=-1, keepdim=True).clamp_min(1e-8) + half = angle * 0.5 + w = torch.cos(half) + xyz = axis_angle / angle * torch.sin(half) + q = torch.cat([w, xyz], dim=-1) # (T, ..., 4) + + dot = (q[1:] * q[:-1]).sum(dim=-1, keepdim=True) + q_aligned = torch.where(dot < 0, -q[1:], q[1:]) + d = q_aligned - q[:-1] + return (d * d).sum() + + +def balanced_photometric_loss( + rendered_rgb: torch.Tensor, # (H, W, 3) + target_rgb: torch.Tensor, # (H, W, 3) + obj_mask: torch.Tensor, # (H, W) in {0, 1} + hand_masks: list[torch.Tensor], # each (H, W) in {0, 1} + include_background: bool = True, + use_l2: bool = False, +) -> torch.Tensor: + """Per-pixel L1 weighted so each *entity* contributes equally, + regardless of how many pixels it covers. + + For each entity i (object, hand_0, hand_1, ..., optionally background), + every pixel in that entity's mask gets per-pixel weight 1 / N_i. The + integral of the weight over the entity's mask is therefore 1 — so a + 1%-coverage hand contributes the same total loss mass as a 10%-coverage + object or an 89%-coverage background. Without this rebalancing, a + full-image L1 is dominated by whatever covers the most pixels. + + Background, when included, is the complement of the union of all + foreground masks. + """ + d = rendered_rgb - target_rgb + if use_l2: + diff = (d * d).sum(dim=-1) # (H, W) + else: + diff = d.abs().sum(dim=-1) # (H, W) + weight_map = torch.zeros_like(diff) + weight_map = weight_map + obj_mask / obj_mask.sum().clamp_min(1.0) + + union = obj_mask.clone() + for hm in hand_masks: + weight_map = weight_map + hm / hm.sum().clamp_min(1.0) + union = torch.maximum(union, hm) + + if include_background: + bg_mask = 1.0 - union + weight_map = weight_map + bg_mask / bg_mask.sum().clamp_min(1.0) + + return (diff * weight_map).sum() + + +def pose_init_prior_loss( + axis_angle: torch.Tensor, # (T, 3) current + translation: torch.Tensor, # (T, 3) current + axis_angle_init: torch.Tensor, # (T, 3) frozen reference (FP/HaMeR) + translation_init: torch.Tensor, # (T, 3) frozen reference + per_frame_weights: torch.Tensor, # (T,) e.g. confidence +) -> torch.Tensor: + """Per-frame weighted squared distance from an initial pose. + + Rotation distance is measured in quaternion space with double-cover + sign alignment so axis-angle representation wraps don't appear as + huge phantom drift. Translation uses plain squared L2. + + Used to anchor high-confidence frames near their input poses while + leaving low-confidence frames (low ``per_frame_weights``) free to + move under photometric pull. + """ + # axis-angle → unit quaternion. + a = axis_angle.norm(dim=-1, keepdim=True).clamp_min(1e-8) + q = torch.cat([ + torch.cos(a * 0.5), + axis_angle / a * torch.sin(a * 0.5), + ], dim=-1) + a0 = axis_angle_init.norm(dim=-1, keepdim=True).clamp_min(1e-8) + q0 = torch.cat([ + torch.cos(a0 * 0.5), + axis_angle_init / a0 * torch.sin(a0 * 0.5), + ], dim=-1) + dot = (q * q0).sum(dim=-1, keepdim=True) + q0_aligned = torch.where(dot < 0, -q0, q0) + rot_diff_sq = ((q - q0_aligned) ** 2).sum(dim=-1) # (T,) + + trans_diff_sq = ((translation - translation_init) ** 2).sum(dim=-1) + return (per_frame_weights * (rot_diff_sq + trans_diff_sq)).sum() + + +def beta_prior_loss(beta: torch.Tensor, beta_init: torch.Tensor) -> torch.Tensor: + """Sum-squared deviation of MANO shape from its initialization. + + ``beta`` and ``beta_init`` are (10,). Sum (not mean) so each individual + component is penalized at full weight — keeps the prior tight regardless + of the 10-dim normalization. + """ + d = beta - beta_init + return (d * d).sum() + + +def intrinsics_prior_loss( + fx: torch.Tensor, fy: torch.Tensor, cx: torch.Tensor, cy: torch.Tensor, + fx_init: torch.Tensor, fy_init: torch.Tensor, + cx_init: torch.Tensor, cy_init: torch.Tensor, +) -> torch.Tensor: + """Sum-squared deviation of intrinsics from their calibrated init. + + Anchors fx/fy/cx/cy to the input JSON values. Without this, fx is + degenerate with global scene scale on no-depth runs and will wander. + Tight default weight (~1e3) keeps K close to init while still letting + it absorb small calibration drift. + """ + return ((fx - fx_init) ** 2 + + (fy - fy_init) ** 2 + + (cx - cx_init) ** 2 + + (cy - cy_init) ** 2) + + +def hand_scale_prior_loss( + scale: torch.Tensor, scale_init: torch.Tensor, +) -> torch.Tensor: + """Squared deviation of per-track hand_scale from its initialization. + + Both are scalar tensors. The init comes from align_hands' n_pixels- + weighted median (a strong estimator); the prior keeps the learned value + from drifting if photometric signal is weak (e.g. small hand silhouettes). + """ + d = scale - scale_init + return d * d + + +# --------------------------------------------------------------------------- +# SuGaR-style surface-alignment regularizers. +# +# Pure 3D losses on the Gaussian field — no depth-image supervision is used. +# Two pieces, following Guédon & Lepetit 2023: +# * scale anisotropy: push each Gaussian toward a flat disk (one scale +# much smaller than the others). +# * density regularizer: at sampled probes drawn along each Gaussian's +# normal at ±s_min, compare the local mixture +# density to the ideal thin-shell density exp(-½). +# +# Notes on scope: SuGaR was originally formulated for an unconstrained set +# of free Gaussians. In our pipeline hand + object Gaussians are anchored +# to mesh / MANO vertices and don't strictly need these losses (the anchor +# spring already pins them to a surface). The bg Gaussians are anchored +# to a noisy depth-unprojected point cloud and are the primary target for +# SuGaR regularization. +# --------------------------------------------------------------------------- + + +def scale_anisotropy_loss(scales: torch.Tensor) -> torch.Tensor: + """Per-Gaussian flatness penalty — rewards *disk* shape only. + + ``scales`` is ``(N, 3)`` (already exponentiated, not log). Sorted ascending: + ``s_min ≤ s_med ≤ s_max``. Loss is:: + + L = mean(s_min / s_med) + mean(1 − s_med / s_max) + + The first term encourages a single very thin axis (``s_min`` ≪ the + others); the second pins the remaining two axes to be similar. Both are + near zero only when ``(s_min, s_med, s_max) ≈ (ε, S, S)`` — a flat disk. + Needle / spike shapes ``(ε, ε, S)`` keep the first term at ~1 and are + properly penalized (which the older ``min/max``-only form did not do). + """ + if scales.shape[0] == 0: + return scales.sum() * 0.0 + s_sorted, _ = torch.sort(scales, dim=-1) # ascending + s_min = s_sorted[..., 0] + s_med = s_sorted[..., 1] + s_max = s_sorted[..., 2] + return ((s_min / s_med.clamp_min(1e-8)).mean() + + (1.0 - s_med / s_max.clamp_min(1e-8)).mean()) + + +def sugar_sdf_losses( + means: torch.Tensor, # (N, 3) Gaussian centers, world frame + quats: torch.Tensor, # (N, 4) (w, x, y, z) canonical rotation + scales: torch.Tensor, # (N, 3) per-axis sigmas (post-exp) + opacities: torch.Tensor, # (N,) + depth: torch.Tensor, # (H, W) MoGe depth in camera frame + K: torch.Tensor, # (3, 3) intrinsics + R_w2c: torch.Tensor, # (3, 3) world→camera rotation for this frame + t_w2c: torch.Tensor, # (3,) world→camera translation + union_mask: torch.Tensor, # (H, W) {0,1} valid pixels (e.g. bg) + n_samples: int = 1000, + n_neighbors: int = 8, + compute_normal: bool = True, + samples_on_surface_weight: float = 0.2, + sampling_scale_factor: float = 1.5, +) -> tuple[torch.Tensor, torch.Tensor]: + """SuGaR-paper density + normal regularization (Eqs. 5-10, Guédon & + Lepetit 2024). + + Operates on a single camera frame at a time so the caller can pick which + frame's depth to anchor against per step. World frame = whatever frame + the Gaussians live in (gsplat's "world", typically the ref-frame cam). + + Returns ``(sdf_loss, normal_loss)``. Both are scalars; ``normal_loss`` + is a zero tensor (still differentiable w.r.t. ``means``) when + ``compute_normal=False``. + + ``sdf_loss`` combines two terms (matching SuGaR's coarse-density trainer): + * SDF-match: ``|f̂(p) − f(p)|`` — depth-implied SDF should match the + Gaussian-mixture SDF. This is the Eq. 9 term. + * Samples-on-surface: ``|f̂(p)| / σ`` (weighted by + ``samples_on_surface_weight``, default 0.2 from the paper). This + directly pulls probe points — and therefore their anchor + Gaussians — toward the depth surface. Without it the SDF-match + term can be satisfied by Gaussians that drift away from the + surface together with a matching density profile. + + Theory in two lines: + * ``f̂(p)`` = signed distance from probe ``p`` to the depth-implied + surface along the camera's z axis, i.e. ``z_depth(u,v) − p_cam.z``. + * ``f(p)`` = ``sign(f̂) · sg* · √(−2 log d(p))`` where ``d`` is the + K-NN Gaussian-mixture density at ``p`` and ``sg*`` is the smallest + scale of the closest Gaussian. (Eq. 7-8.) + * Sample probes from each anchor Gaussian's distribution ``N(μ, Σ)`` + with spread ``sampling_scale_factor·s`` (Eq. 9; SuGaR uses 1.5 by + default). Density losses then encourage ``f`` and ``f̂`` to agree. + * Normal-consistency (Eq. 10): the *direction* of ``∇d`` (which is + parallel to ``∇f`` up to a scalar) should match the closest + Gaussian's smallest-scale axis ``ng*``. Computed analytically. + """ + from .gaussians import quat_to_rotmat + + N = means.shape[0] + if N == 0 or n_samples <= 0: + zero = means.sum() * 0.0 + return zero, zero + + # ---- 1. Pick anchors and sample probes from N(μ, Σ) ---- + n_probes = min(int(n_samples), N) + probe_idx = torch.randperm(N, device=means.device)[:n_probes] + R_anchors = quat_to_rotmat(quats[probe_idx]) # (P, 3, 3) + s_anchors = scales[probe_idx].clamp_min(1e-6) # (P, 3) + z = torch.randn(n_probes, 3, device=means.device) + # p = μ + R · diag(sampling_scale_factor · s) · z. SuGaR uses 1.5·s + # (sdf_sampling_scale_factor) — wider than the raw Gaussian so probes + # cover the off-surface region where the SDF has informative gradient. + local_offset = sampling_scale_factor * s_anchors * z + p = means[probe_idx] + torch.einsum("pij,pj->pi", R_anchors, local_offset) + + # ---- 2. f̂(p): depth-implied SDF along camera z ---- + p_cam = p @ R_w2c.T + t_w2c[None, :] # (P, 3) + fx = K[0, 0]; fy = K[1, 1]; cx = K[0, 2]; cy = K[1, 2] + z_c = p_cam[:, 2].clamp_min(1e-3) + u = fx * p_cam[:, 0] / z_c + cx + v = fy * p_cam[:, 1] / z_c + cy + + H, W = int(depth.shape[-2]), int(depth.shape[-1]) + iu = u.round().long().clamp(0, W - 1) + iv = v.round().long().clamp(0, H - 1) + + z_depth = depth[iv, iu] # (P,) + in_frame = (u >= 0) & (u < W) & (v >= 0) & (v < H) + valid = ( + in_frame + & (union_mask[iv, iu] > 0.5) + & torch.isfinite(z_depth) + & (z_depth > 0) + & (p_cam[:, 2] > 0) + ) + f_hat = z_depth - p_cam[:, 2] # (P,) + + # ---- 3. f(p): SDF from Gaussian-mixture density ---- + k = int(min(n_neighbors, N)) + # Chunked KNN: (P, N) cdist OOMs at P,N ~ 50k+. Same chunking pattern + # as density_regularizer_local — cap each chunk at ~1e8 float entries. + chunk = max(1, int(1e8 // max(N, 1))) + knn_idx_chunks: list[torch.Tensor] = [] + for s in range(0, n_probes, chunk): + e = min(s + chunk, n_probes) + d_chunk = torch.cdist(p[s:e], means) + _, ki = d_chunk.topk(k, dim=-1, largest=False) + knn_idx_chunks.append(ki) + knn_idx = torch.cat(knn_idx_chunks, dim=0) # (P, k) + + nbr_means = means [knn_idx] # (P, k, 3) + nbr_quats = quats [knn_idx] # (P, k, 4) + nbr_scales = scales [knn_idx].clamp_min(1e-6) # (P, k, 3) + nbr_opacities = opacities[knn_idx] # (P, k) + nbr_R = quat_to_rotmat(nbr_quats.reshape(-1, 4)).reshape(n_probes, k, 3, 3) + + delta = p[:, None, :] - nbr_means # (P, k, 3) + delta_local = torch.einsum("pkji,pkj->pki", nbr_R, delta) # R^T · delta + mahal_sq = (delta_local / nbr_scales).pow(2).sum(dim=-1) # (P, k) + contrib = nbr_opacities * torch.exp(-0.5 * mahal_sq) # (P, k) + d = contrib.sum(dim=-1).clamp(1e-8, 1.0 - 1e-8) # (P,) + + closest = knn_idx[:, 0] # (P,) + s_closest_min = scales[closest].min(dim=-1).values # (P,) + f_mag = s_closest_min * torch.sqrt(-2.0 * torch.log(d)) # (P,) + f = torch.sign(f_hat.detach()) * f_mag # (P,) + + valid_f = valid.to(f.dtype) + n_valid = valid.sum().clamp_min(1).to(f.dtype) + sdf_match = ((f_hat - f).abs() * valid_f).sum() / n_valid + + # Samples-on-surface (SuGaR coarse-density Eq. ~9 + samples_on_surface + # term in their trainer): penalize the signed depth distance directly, + # normalized by its (detached) scale so the loss is scale-invariant. + # This is the term that actually pulls Gaussian centers onto the + # depth-implied surface — without it the SDF-match loss can be + # satisfied by Gaussians sitting off-surface with a matching density + # profile around them. + f_hat_valid = f_hat[valid] + if f_hat_valid.numel() > 1: + sigma = f_hat_valid.detach().abs().mean().clamp_min(1e-6) + else: + sigma = torch.ones((), device=f_hat.device, dtype=f_hat.dtype) + samples_on_surface = (f_hat.abs() * valid_f).sum() / n_valid / sigma + sdf_loss = sdf_match + samples_on_surface_weight * samples_on_surface + + # ---- 4. Normal consistency (Eq. 10) ---- + # ∇d analytically: ∂d/∂p = -Σ_k contrib_k · Σ_k⁻¹ · (p − μ_k) + # = -Σ_k contrib_k · R_k · diag(1/s²) · R_k^T · (p − μ_k) + # = -Σ_k contrib_k · R_k · (delta_local_k / s_k²) + # ∇f is parallel to ∇d up to a positive scalar; use ∇d direction. + if not compute_normal: + zero = means.sum() * 0.0 + return sdf_loss, zero + + local_inv_s2 = delta_local / nbr_scales.pow(2) # (P, k, 3) + grad_world_per_k = torch.einsum("pkij,pkj->pki", nbr_R, local_inv_s2) + grad_d = -(contrib[..., None] * grad_world_per_k).sum(dim=1) # (P, 3) + grad_norm = grad_d.norm(dim=-1, keepdim=True).clamp_min(1e-8) + grad_unit = grad_d / grad_norm # (P, 3) + + # Closest Gaussian's smallest-scale axis (normal direction). + R_closest = quat_to_rotmat(quats[closest]) # (P, 3, 3) + s_min_axis = scales[closest].argmin(dim=-1) # (P,) + n_closest = torch.gather( + R_closest, dim=2, + index=s_min_axis[:, None, None].expand(-1, 3, 1), + ).squeeze(-1) # (P, 3) + n_closest = n_closest / n_closest.norm(dim=-1, keepdim=True).clamp_min(1e-8) + + # Sign-invariant alignment: 1 - ² is zero when parallel + # OR anti-parallel. Avoids the canonical-sign ambiguity of normals. + dot = (grad_unit * n_closest).sum(dim=-1) # (P,) + normal_loss = (1.0 - dot.pow(2)).mean() + + return sdf_loss, normal_loss + + +def density_regularizer_local( + means: torch.Tensor, # (N, 3) Gaussian centers (world frame) + quats: torch.Tensor, # (N, 4) (w, x, y, z) world-frame canonical rotation + scales: torch.Tensor, # (N, 3) per-axis sigmas (post-exp) + opacities: torch.Tensor, # (N,) + n_neighbors: int = 8, + subsample_frac: float = 0.2, +) -> torch.Tensor: + """SuGaR-style density loss on the Gaussian field. + + Per-step subsample: pick ``ceil(subsample_frac * N)`` Gaussians at random + as probe anchors. For each anchor: + * find its smallest-scale axis (the disk normal) by reading the column + of its rotation matrix that corresponds to the min(scales) index; + * sample 2 probe points at the center ± ``s_min`` along that normal; + * compute the K-nearest-neighbor mixture density at each probe, + using anisotropic Mahalanobis distance ``Σᵢ (R^T (p−μ))ᵢ² / sᵢ²``; + * compare to the ideal thin-shell density ``α · exp(-½)``. + + Returns ``mean |f_actual − f_ideal|``. Loss is bounded; magnitude depends + on opacity scale (typically O(0.1)–O(1)). Wire as ``w_density_bg``. + + No supervision from depth images. The Gaussian field is its own teacher. + """ + from .gaussians import quat_to_rotmat + + N = means.shape[0] + if N == 0 or subsample_frac <= 0: + return means.sum() * 0.0 + + n_probes = max(1, int(N * subsample_frac)) + probe_idx = torch.randperm(N, device=means.device)[:n_probes] + + p_centers = means [probe_idx] # (P, 3) + s_probe = scales [probe_idx] # (P, 3) + q_probe = quats [probe_idx] # (P, 4) + a_probe = opacities[probe_idx] # (P,) + + s_min, s_min_idx = s_probe.min(dim=-1) # (P,), (P,) + R = quat_to_rotmat(q_probe) # (P, 3, 3) + # The k-th column of R is the world direction of the local k-th axis. + normal = torch.gather( + R, dim=2, + index=s_min_idx[:, None, None].expand(-1, 3, 1), + ).squeeze(-1) # (P, 3) + normal = normal / normal.norm(dim=-1, keepdim=True).clamp_min(1e-8) + + probe_pos = torch.cat([ + p_centers + normal * s_min[:, None], + p_centers - normal * s_min[:, None], + ], dim=0) # (2P, 3) + + # Cap the number of neighbors at N (small scenes). + k = int(min(n_neighbors, N)) + + # KNN: compute pairwise distances probes vs all means, take top-k. + # Memory: (2P) * N floats. Chunked when 2P*N exceeds ~1e8 entries. + chunk = max(1, int(1e8 // max(N, 1))) + knn_idx_chunks: list[torch.Tensor] = [] + for s in range(0, probe_pos.shape[0], chunk): + e = min(s + chunk, probe_pos.shape[0]) + d = torch.cdist(probe_pos[s:e], means) + _, ki = d.topk(k, dim=-1, largest=False) + knn_idx_chunks.append(ki) + knn_idx = torch.cat(knn_idx_chunks, dim=0) # (2P, k) + + nbr_means = means [knn_idx] # (2P, k, 3) + nbr_quats = quats [knn_idx] # (2P, k, 4) + nbr_scales = scales [knn_idx] # (2P, k, 3) + nbr_opacities = opacities [knn_idx] # (2P, k) + + nbr_R = quat_to_rotmat(nbr_quats.reshape(-1, 4)).reshape( + probe_pos.shape[0], k, 3, 3, + ) # (2P, k, 3, 3) + delta = probe_pos[:, None, :] - nbr_means # (2P, k, 3) + # Local-frame delta: R^T @ (p − μ). + delta_local = torch.einsum("pkji,pkj->pki", nbr_R, delta) + mahal_sq = (delta_local / nbr_scales.clamp_min(1e-8)).pow(2).sum(dim=-1) + contrib = nbr_opacities * torch.exp(-0.5 * mahal_sq) + f_actual = contrib.sum(dim=-1) # (2P,) + + # Ideal thin-shell density at the ±s_min probes: opacity · exp(-½). + f_ideal = a_probe.repeat(2) * float(torch.exp(torch.tensor(-0.5))) + return (f_actual - f_ideal).abs().mean() diff --git a/third-party/video_to_data/reconstruction/modules/v2d_gsplat_refinement/lib/pose_fields.py b/third-party/video_to_data/reconstruction/modules/v2d_gsplat_refinement/lib/pose_fields.py new file mode 100644 index 0000000000000000000000000000000000000000..ad20f396aadc1628fb35a270be060021b89be60d --- /dev/null +++ b/third-party/video_to_data/reconstruction/modules/v2d_gsplat_refinement/lib/pose_fields.py @@ -0,0 +1,445 @@ +# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 +"""Per-frame learnable pose state. + +Two modules: + + ObjectPoseField -- (T, 6) of [axis-angle, translation] per frame; ``scale`` + is held as a buffer (carried through to output but not + optimized in the simplest setup, since post-FoundationPose + scales are [1, 1, 1] and we add no global scale param). + + HandPoseField -- (T, 3) global_orient axis-angle, (T, 45) hand_pose + axis-angle, (T, 3) cam_t. Owns a manotorch ``ManoLayer`` + and exposes ``posed_verts_camera(t)`` so the renderer + can pull world-frame MANO vertices each step. ``betas`` + is a buffer in this minimal version (per-identity but + not optimized). +""" +from __future__ import annotations + +import torch +import torch.nn as nn + +from .gaussians import axis_angle_to_quat, quat_to_rotmat +from .io import HandPoseTrack, ObjectPoseTrack + + +# --------------------------------------------------------------------------- +# Object pose field +# --------------------------------------------------------------------------- + +def _quat_to_axis_angle(q: torch.Tensor) -> torch.Tensor: + """(..., 4) (w, x, y, z) → (..., 3) axis-angle (canonical, |angle| ≤ π). + + Canonicalize first: the double-cover ``q ≡ −q`` represents the same + rotation, but ``2·acos(w)`` only returns the short-way form when + ``w ≥ 0``. Flip the sign of any quat with negative w so the resulting + axis-angle magnitude stays in [0, π] rather than the "long way around" + [π, 2π] band. + """ + q = q / q.norm(dim=-1, keepdim=True).clamp_min(1e-8) + # Canonical hemisphere: w ≥ 0. + q = torch.where(q[..., :1] < 0, -q, q) + w = q[..., 0].clamp(-1.0, 1.0) + angle = 2.0 * torch.acos(w) + s = torch.sqrt((1.0 - w * w).clamp_min(1e-12)) + axis = q[..., 1:] / s.unsqueeze(-1).clamp_min(1e-12) + # When angle is ~0, axis is undefined; safe to keep aa = 0 in that case. + aa = axis * angle.unsqueeze(-1) + aa = torch.where(angle.unsqueeze(-1) < 1e-6, + torch.zeros_like(aa), aa) + return aa + + +class ObjectPoseField(nn.Module): + """Per-frame object→camera pose, parameterized as axis-angle + translation.""" + + def __init__(self, track: ObjectPoseTrack) -> None: + super().__init__() + # Convert (T, 4) quats to axis-angle so we have a minimal, + # singularity-free parameterization for small updates. + aa = _quat_to_axis_angle(track.rotations) + self.axis_angle = nn.Parameter(aa.contiguous()) # (T, 3) + self.translation = nn.Parameter(track.translations.clone()) # (T, 3) + self.register_buffer("scale", track.scales.clone()) # (T, 3) + self.frame_indices = list(track.frame_indices) + + def num_frames(self) -> int: + return self.axis_angle.shape[0] + + def forward(self, t: int) -> tuple[torch.Tensor, torch.Tensor]: + """Return (R (3,3), t (3,)) for frame index ``t`` (positional, not frame_idx).""" + q = axis_angle_to_quat(self.axis_angle[t]) # (4,) + R = quat_to_rotmat(q) # (3, 3) + return R, self.translation[t] + + def batched_forward( + self, t_idx: torch.Tensor # (B,) long tensor of positional indices + ) -> tuple[torch.Tensor, torch.Tensor]: + """Batched version of forward — returns ((B, 3, 3), (B, 3)).""" + aa = self.axis_angle[t_idx] # (B, 3) + q = axis_angle_to_quat(aa) # (B, 4) + R = quat_to_rotmat(q) # (B, 3, 3) + return R, self.translation[t_idx] + + def export_track(self) -> ObjectPoseTrack: + """Return the optimized state as an ObjectPoseTrack (for I/O).""" + q = axis_angle_to_quat(self.axis_angle) # (T, 4) + return ObjectPoseTrack( + rotations = q.detach(), + translations = self.translation.detach(), + scales = self.scale.detach(), + frame_indices = list(self.frame_indices), + ) + + +# --------------------------------------------------------------------------- +# Hand pose field (wraps manotorch.ManoLayer) +# --------------------------------------------------------------------------- + +class IntrinsicsField(nn.Module): + """Learnable camera intrinsics (fx, fy, cx, cy). + + Stores each component as a scalar ``nn.Parameter`` and exposes a + ``K()`` method that assembles the (3, 3) intrinsics matrix on demand + so downstream renderers see a fresh tensor with current values. + + Per-component ``register_buffer`` copies of the init values anchor the + L2 prior — without it, the focal length can drift along the + focal/depth degeneracy (doubling fx is photometrically equivalent to + halving every scene-z, when depth supervision is absent). + + Each parameter independently controls its ``requires_grad`` via the + ``learn_focal`` / ``learn_principal_point`` constructor flags, so the + optimizer can refine principal point alone (safer) while keeping + focal length pinned to the calibrated input. + """ + + def __init__( + self, + K: torch.Tensor, # (3, 3) input intrinsics + learn_focal: bool = False, + learn_principal_point: bool = False, + ) -> None: + super().__init__() + device = K.device + # Parameters: split per-component so each is independently learnable. + self.fx = nn.Parameter( + K[0, 0].detach().clone().to(device, dtype=torch.float32), + requires_grad=bool(learn_focal), + ) + self.fy = nn.Parameter( + K[1, 1].detach().clone().to(device, dtype=torch.float32), + requires_grad=bool(learn_focal), + ) + self.cx = nn.Parameter( + K[0, 2].detach().clone().to(device, dtype=torch.float32), + requires_grad=bool(learn_principal_point), + ) + self.cy = nn.Parameter( + K[1, 2].detach().clone().to(device, dtype=torch.float32), + requires_grad=bool(learn_principal_point), + ) + # Init buffers — fixed reference for the prior loss. + self.register_buffer("fx_init", self.fx.detach().clone()) + self.register_buffer("fy_init", self.fy.detach().clone()) + self.register_buffer("cx_init", self.cx.detach().clone()) + self.register_buffer("cy_init", self.cy.detach().clone()) + + def K(self) -> torch.Tensor: + """Assemble the (3, 3) intrinsics tensor from the four scalars. + + Differentiable w.r.t. fx / fy / cx / cy. Constructed fresh each + call so downstream consumers always see current values. + """ + zero = self.fx.new_zeros(()) + one = self.fx.new_ones(()) + return torch.stack([ + torch.stack([self.fx, zero, self.cx]), + torch.stack([zero, self.fy, self.cy]), + torch.stack([zero, zero, one]), + ], dim=0) + + def has_learnable(self) -> bool: + return any(p.requires_grad for p in (self.fx, self.fy, self.cx, self.cy)) + + +class HandPoseField(nn.Module): + """Per-frame MANO global_orient + hand_pose + cam_t for a single hand, + plus a single shared per-identity ``betas`` (10,). + + ``betas`` is initialized from the mean of HaMeR's per-frame predictions + and optimized with a tight Gaussian prior pulling back to that init + (``betas_init`` is a buffer holding the prior mean). Per-frame β is + anatomically incorrect; one shared vector keeps hand size consistent + across the sequence while still allowing it to adapt globally. + + Left-hand mirroring follows ``align_hands.py``: negate vertex x after + the layer call. + """ + + def __init__( + self, + track: HandPoseTrack, + mano_assets_root: str, + device: str | torch.device = "cuda", + learn_hand_scale: bool = False, + ) -> None: + super().__init__() + # Lazy import so non-hand pipelines don't pay for manotorch. + from manotorch.manolayer import ManoLayer + + self.global_orient = nn.Parameter(track.global_orient.clone()) # (T, 3) + self.hand_pose = nn.Parameter(track.hand_pose.clone()) # (T, 45) + self.cam_t = nn.Parameter(track.cam_t.clone()) # (T, 3) + + # Shared β: mean of HaMeR's per-frame estimates → (10,). Optimized + # softly via beta_prior_loss(self.betas, self.betas_init). + beta_init = track.betas.mean(dim=0).clone() # (10,) + self.betas = nn.Parameter(beta_init.clone()) # (10,) + self.register_buffer("betas_init", beta_init.clone()) # (10,) + + self.is_right = bool(track.is_right) + self.frame_indices = list(track.frame_indices) + + # Per-track multiplicative depth correction from align_hands. The + # MANO mesh is rescaled around its centroid (in MANO/rest frame, + # before adding cam_t) so the projected silhouette matches the + # image. cam_t carries the additive (dz) shift; together they + # correct both modes of depth mismatch. + # + # Stored as a Parameter so refine can optimize it when + # ``learn_hand_scale=True``; otherwise ``requires_grad=False`` and + # the parameter is excluded from optimizer param groups (functions + # as a fixed buffer). ``hand_scale_init`` is kept as a buffer to + # anchor the soft prior pulling the learned value back to the + # align_hands estimate. + scale_init = float(getattr(track, "hand_scale", 1.0) or 1.0) + self.hand_scale = nn.Parameter( + torch.tensor(scale_init, device=device, dtype=torch.float32), + requires_grad=bool(learn_hand_scale), + ) + self.register_buffer( + "hand_scale_init", + torch.tensor(scale_init, device=device, dtype=torch.float32), + ) + + # ManoLayer always produces right-hand vertices in its own frame; we + # mirror x for left hands at output (matches v2d_hamer/align_hands.py). + self.mano = ManoLayer( + rot_mode = "axisang", + use_pca = False, + side = "right", + center_idx = None, + mano_assets_root = mano_assets_root, + ).to(device) + + # Per-vertex LBS rotation requires subtracting the rest-pose joint + # rotation from each frame's joint rotation: R_def_j = R_j @ R_j_rest^T. + # Cache the rest-pose rotation inverses (a fixed buffer) so we can + # compute deformation rotations on the fly. + with torch.no_grad(): + zero_pose = torch.zeros(1, 48, device=device) + zero_betas = torch.zeros(1, 10, device=device) + out_rest = self.mano(zero_pose, zero_betas) + if hasattr(out_rest, "transforms_abs"): + R_rest = out_rest.transforms_abs[0, :, :3, :3].detach() # (J, 3, 3) + else: + # Older manotorch builds expose this as a positional output; + # fall back to identity (rest joint orientations are identity at + # zero pose for MANO's kinematic tree, so this is correct). + R_rest = torch.eye(3, device=device).unsqueeze(0).repeat(16, 1, 1) + # Inverse of a rotation is its transpose. + self.register_buffer("_R_joints_rest_inv", R_rest.transpose(-1, -2).contiguous()) + + # Skinning weights: shape (1, N, J) or (N, J) depending on manotorch + # version. Normalize to (N, J) and stash as a non-learnable buffer. + W = self.mano.th_weights + if W.ndim == 3: + W = W.squeeze(0) + self.register_buffer("_skin_weights", W.detach().clone()) + + def num_frames(self) -> int: + return self.global_orient.shape[0] + + def num_verts(self) -> int: + return int(self.mano.th_v_template.shape[1]) if hasattr(self.mano, "th_v_template") else 778 + + def posed_verts_and_rotmats_camera( + self, t: int + ) -> tuple[torch.Tensor, torch.Tensor]: + """Return MANO vertices and per-vertex LBS rotation matrices in + camera frame for frame ``t`` (positional index, not frame_idx). + + Pipeline: + 1. ManoLayer forward → posed verts (N, 3) in MANO local frame and + absolute joint transforms (J, 4, 4), with global_orient applied + via the root joint. + 2. Per-joint deformation rotation: R_def_j = R_j @ R_j_rest^T. + 3. Per-vertex rotation: R_v = sum_j W[v, j] * R_def_j (LBS). + 4. Mirror x for left hand: verts[:, 0] *= -1, and conjugate the + rotation by M = diag(-1, 1, 1) → R' = M R M. + 5. Translate verts by cam_t (rotation unaffected). + """ + pose_aa = torch.cat([self.global_orient[t], self.hand_pose[t]], dim=-1) # (48,) + out = self.mano(pose_aa.unsqueeze(0), self.betas.unsqueeze(0)) + verts = out.verts[0] # (N, 3) + + # Per-joint deformation rotation. transforms_abs is (B, J, 4, 4). + if hasattr(out, "transforms_abs"): + R_joints = out.transforms_abs[0, :, :3, :3] # (J, 3, 3) + else: + # Should not occur with current manotorch — fall back to identity. + R_joints = torch.eye(3, device=verts.device).unsqueeze(0).expand(16, -1, -1) + R_def = R_joints @ self._R_joints_rest_inv # (J, 3, 3) + + # LBS skinning: R_v = sum_j W[v, j] * R_def[j]. + R_per_vert = torch.einsum("vj,jik->vik", self._skin_weights, R_def) # (N, 3, 3) + + if not self.is_right: + mirror = verts.new_tensor([-1.0, 1.0, 1.0]) + verts = verts * mirror + M = torch.diag(mirror) + R_per_vert = M @ R_per_vert @ M + + # Multiplicative depth correction (hand_scale) — applied around the + # mesh centroid in MANO frame, before cam_t. Rotations untouched + # (uniform isotropic scale). Skipped only when scale is exactly 1 + # AND not learnable (avoids killing gradient flow when learnable + # happens to start at 1.0). + if self.hand_scale.requires_grad or float(self.hand_scale) != 1.0: + c = verts.mean(dim=0, keepdim=True) # (1, 3) + verts = (verts - c) * self.hand_scale + c + + verts = verts + self.cam_t[t] # (N, 3) + return verts, R_per_vert + + def batched_posed_verts_and_rotmats_camera( + self, t_idx: torch.Tensor # (B,) long tensor of positional indices + ) -> tuple[torch.Tensor, torch.Tensor]: + """Batched version of ``posed_verts_and_rotmats_camera``. + + Returns: + verts: (B, N_verts, 3) MANO vertices in camera frame. + R_per_vert: (B, N_verts, 3, 3) per-vertex LBS deformation + rotation in camera frame. + + Single MANO forward over the whole batch (replaces B per-frame + calls); LBS skinning is one big einsum. The biggest speedup of + this whole change comes from this method — at batch=1 ManoLayer + is mostly kernel-launch overhead. + """ + B = int(t_idx.shape[0]) + pose_aa_b = torch.cat( + [self.global_orient[t_idx], self.hand_pose[t_idx]], dim=-1 + ) # (B, 48) + betas_b = self.betas.unsqueeze(0).expand(B, -1) # (B, 10) + out = self.mano(pose_aa_b, betas_b) + verts = out.verts # (B, N, 3) + + if hasattr(out, "transforms_abs"): + R_joints = out.transforms_abs[:, :, :3, :3] # (B, J, 3, 3) + else: + R_joints = torch.eye(3, device=verts.device).expand(B, 16, 3, 3).contiguous() + # Per-joint deformation rotation: R_def = R_current @ R_rest^T. + R_def = R_joints @ self._R_joints_rest_inv.unsqueeze(0) # (B, J, 3, 3) + + # Per-vertex LBS skinning: R_v = sum_j W[v, j] * R_def[b, j]. + R_per_vert = torch.einsum( + "vj,bjik->bvik", self._skin_weights, R_def + ) # (B, N, 3, 3) + + if not self.is_right: + mirror = verts.new_tensor([-1.0, 1.0, 1.0]) + verts = verts * mirror # broadcast over (B, N, 3) + M = torch.diag(mirror) + # M @ R @ M for every (b, v); contract via broadcasting. + R_per_vert = M @ R_per_vert @ M + + # Multiplicative depth correction (hand_scale), per-batch-elt-centred. + # Skip only when fixed-at-1.0 (preserves gradient flow when learnable). + if self.hand_scale.requires_grad or float(self.hand_scale) != 1.0: + c = verts.mean(dim=1, keepdim=True) # (B, 1, 3) + verts = (verts - c) * self.hand_scale + c + + verts = verts + self.cam_t[t_idx].unsqueeze(1) # (B, 1, 3) → (B, N, 3) + return verts, R_per_vert + + def wrist_pose_camera( + self, t: int + ) -> tuple[torch.Tensor, torch.Tensor]: + """Single-frame wrapper around ``batched_wrist_pose_camera``.""" + t_idx = torch.as_tensor([int(t)], device=self.cam_t.device, dtype=torch.long) + R, tt = self.batched_wrist_pose_camera(t_idx) + return R[0], tt[0] + + def batched_wrist_pose_camera( + self, t_idx: torch.Tensor # (B,) long + ) -> tuple[torch.Tensor, torch.Tensor]: + """Return per-frame wrist (joint 0) cam-frame pose. + + Returns ((B, 3, 3), (B, 3)) — rotation and translation of the wrist + joint in camera frame. Includes left/right mirror conjugation and + the centroid-based hand_scale + cam_t offsets used by the vertex + path, so the wrist transform is consistent with the rendered hand. + + The wrist orientation is MANO joint 0's absolute rotation (which + equals the root rotation, ``global_orient``, up to mirror). The + wrist position is MANO joint 0's absolute translation after the + same centroid-scale + cam_t transforms applied to vertices. + + Used by ``WristAttachedGaussians`` to attach rigid arm Gaussians + to the hand without distorting MANO. + """ + B = int(t_idx.shape[0]) + pose_aa_b = torch.cat( + [self.global_orient[t_idx], self.hand_pose[t_idx]], dim=-1 + ) # (B, 48) + betas_b = self.betas.unsqueeze(0).expand(B, -1) # (B, 10) + out = self.mano(pose_aa_b, betas_b) + verts = out.verts # (B, N, 3) + + if hasattr(out, "transforms_abs"): + R_wrist = out.transforms_abs[:, 0, :3, :3] # (B, 3, 3) + t_wrist = out.transforms_abs[:, 0, :3, 3] # (B, 3) + else: + R_wrist = torch.eye(3, device=verts.device).expand(B, 3, 3).contiguous() + # Fallback: joint 0 ≈ origin in MANO local frame. + t_wrist = torch.zeros(B, 3, device=verts.device) + + if not self.is_right: + mirror = verts.new_tensor([-1.0, 1.0, 1.0]) + verts = verts * mirror + t_wrist = t_wrist * mirror + M = torch.diag(mirror) + R_wrist = M @ R_wrist @ M + + # Apply centroid-based hand_scale to the wrist translation (same + # transform applied to verts). hand_scale is uniform → no effect on + # rotation. + if self.hand_scale.requires_grad or float(self.hand_scale) != 1.0: + c = verts.mean(dim=1) # (B, 3) + t_wrist = (t_wrist - c) * self.hand_scale + c + + t_wrist = t_wrist + self.cam_t[t_idx] # (B, 3) + return R_wrist, t_wrist + + def export_track(self, raw_records: list[dict]) -> HandPoseTrack: + """Return the optimized state as a HandPoseTrack for I/O. + + ``self.betas`` is shared (10,); broadcast to (T, 10) so the on-disk + per-frame schema is preserved. + """ + T = self.global_orient.shape[0] + betas_per_frame = self.betas.detach().unsqueeze(0).expand(T, -1).contiguous() + return HandPoseTrack( + global_orient = self.global_orient.detach(), + hand_pose = self.hand_pose.detach(), + betas = betas_per_frame, + cam_t = self.cam_t.detach(), + is_right = self.is_right, + frame_indices = list(self.frame_indices), + raw_records = raw_records, + hand_scale = float(self.hand_scale.detach().cpu().item()), + ) diff --git a/third-party/video_to_data/reconstruction/modules/v2d_gsplat_refinement/lib/pyproject.toml b/third-party/video_to_data/reconstruction/modules/v2d_gsplat_refinement/lib/pyproject.toml new file mode 100644 index 0000000000000000000000000000000000000000..2c3d67c0cc0e231d63ba7d8645a4942dd836ba1d --- /dev/null +++ b/third-party/video_to_data/reconstruction/modules/v2d_gsplat_refinement/lib/pyproject.toml @@ -0,0 +1,27 @@ +# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 +[build-system] +requires = ["setuptools>=68.0", "wheel"] +build-backend = "setuptools.build_meta" + +[project] +name = "v2d-gsplat-refinement-lib" +version = "0.1.0" +description = "Joint hand+object pose refinement via Gaussian splatting" +requires-python = ">=3.10" +dependencies = [ + "numpy", + "Pillow", + "trimesh", + "rtree", + "imageio", + "imageio-ffmpeg", + "tqdm", + "v2d-common", +] + +[tool.setuptools] +packages = ["v2d.gsplat_refinement.lib"] + +[tool.setuptools.package-dir] +"v2d.gsplat_refinement.lib" = "." diff --git a/third-party/video_to_data/reconstruction/modules/v2d_gsplat_refinement/lib/refine.py b/third-party/video_to_data/reconstruction/modules/v2d_gsplat_refinement/lib/refine.py new file mode 100644 index 0000000000000000000000000000000000000000..ed8de42fd7f48ae5533cf2f6906de8d7121e0b70 --- /dev/null +++ b/third-party/video_to_data/reconstruction/modules/v2d_gsplat_refinement/lib/refine.py @@ -0,0 +1,3465 @@ +# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 +"""Joint hand+object Gaussian-splatting refinement. + +Optimizes: + Globals (shared across all frames): + - Object Gaussian attributes (Δp, q, log-scale, opacity, color) + - Per-hand Gaussian attributes (isotropic log-scale, opacity, color) + + Per-frame: + - Object pose (axis-angle, translation) + - MANO global_orient, hand_pose, cam_t for each hand track + +Losses (all jointly, no warmup): + - Masked photometric L1 (combined render vs. image, in union mask) + - Per-set silhouette L1 (object alpha vs. object mask; each hand alpha + vs. that hand's mask) + - Optional MoGe depth Huber (when ``depth_dir`` is provided) + - Temporal smoothness on per-frame pose params + +Inputs are loaded with ``v2d.gsplat_refinement.lib.io`` and outputs are +written back in the same on-disk formats so existing renderers (e.g. +``v2d.hamer.docker.run_render_hands_aligned_video``) work unchanged on the +refined data. + +Usage: + python -m v2d.gsplat_refinement.lib.refine \\ + --frames_dir /data/frames \\ + --intrinsics_path /data/intrinsics.json \\ + --object_mesh_path /data/mesh.obj \\ + --object_poses_dir /data/poses_smoothed \\ + --object_mask_dir /data/object_masks \\ + --right_hand_pose_dir /data/hamer_aligned/2 \\ + --right_hand_mask_dir /data/masks/2 \\ + --mano_assets_root /data/weights/hamer/_DATA/data \\ + --refined_object_poses_dir /data/refined_poses \\ + --refined_right_hand_pose_dir /data/refined_hamer/2 \\ + --overlay_path /data/refined_overlay.mp4 +""" +from __future__ import annotations + +import argparse +import dataclasses +import math +import os +import subprocess +import tempfile +from dataclasses import dataclass + +import numpy as np +import torch +from PIL import Image, ImageDraw, ImageFont +from tqdm import tqdm + +from .background import ( + BackgroundGaussians, + BackgroundPoseField, + init_background_from_depth, + init_background_multiframe, +) +from .gaussians import ( + concat_frames, + init_hand_face_gaussians, + init_hand_gaussians, + init_object_face_gaussians_from_mesh, + init_object_gaussians_from_mesh, + init_wrist_attached_gaussians, + resample_mesh_surface, +) +from .io import ( + FrameCache, + HandPoseTrack, + ObjectPoseTrack, + list_frame_indices, + load_hand_poses, + load_intrinsics, + load_object_mesh, + load_object_poses, + load_rgb, + save_hand_poses, + save_object_poses, +) +from .losses import ( + balanced_photometric_loss, + beta_prior_loss, + delta_p_regularizer, + density_regularizer_local, + depth_gradient_loss, + depth_loss, + depth_ordering_loss, + depth_ssim_loss, + depth_variance_loss, + face_delta_p_regularizer, + intrinsics_prior_loss, + opacity_binary_loss, + sugar_sdf_losses, + hand_scale_prior_loss, + photometric_loss, + photometric_ssim_loss, + pose_init_prior_loss, + quat_smoothness, + rotation_smoothness, + scale_anisotropy_loss, + silhouette_loss, + temporal_smoothness, +) +from .pose_fields import HandPoseField, IntrinsicsField, ObjectPoseField +from .render import render_rgb_depth + + +# --------------------------------------------------------------------------- +# Background pose seeding (external VO/SfM init) +# --------------------------------------------------------------------------- + + +def _load_relative_w2c_poses( + poses_dir: str, + frame_indices: list[int], + ref_t: int, +) -> dict[int, np.ndarray]: + """Load per-frame Transform3d JSONs and return relative world→camera SE(3). + + gsplat's "world" is the reference frame's camera frame, so we rebase the + DROID/COLMAP cam-to-world poses against the reference frame: + + T_w2c_gsplat(t) = T_cw(t)^-1 @ T_cw(ref) + + Returns a dict mapping ``positional index t`` → 4×4 ``np.float64`` matrix. + The ref frame is always present and set to identity. Frames whose JSON + is missing OR whose ``Transform3d.scale`` differs from 1 are omitted from + the result (caller can treat them as "no SLAM info"). + """ + from v2d.common.datatypes import Transform3d + + ref_fidx = frame_indices[ref_t] + ref_path = os.path.join(poses_dir, f"{ref_fidx:06d}.json") + if not os.path.exists(ref_path): + raise FileNotFoundError( + f"background_pose_init_dir is set but reference-frame pose " + f"{ref_path} does not exist. The relative-pose composition needs " + f"the reference frame to anchor the gsplat world frame." + ) + M_ref = Transform3d.load(ref_path).to_matrix() # cam→world (DROID) + + out: dict[int, np.ndarray] = {ref_t: np.eye(4)} + for t, fidx in enumerate(frame_indices): + if t == ref_t: + continue + path = os.path.join(poses_dir, f"{fidx:06d}.json") + if not os.path.exists(path): + continue + tf = Transform3d.load(path) + if any(abs(s - 1.0) > 1e-3 for s in tf.scale): + continue + M_cw_t = tf.to_matrix() + out[t] = np.linalg.inv(M_cw_t) @ M_ref + return out + + +def _seed_background_pose_field( + bg_pose_field, # BackgroundPoseField + poses: dict[int, np.ndarray], +) -> tuple[int, int]: + """Overwrite bg_pose_field.{axis_angle, translation} from a pre-loaded + dict of positional index → T_w2c_gsplat 4×4 matrix. + + Missing positions keep the identity (zeros) init that BackgroundPoseField + starts with. + """ + from .gaussians import rotmat_to_quat + from .pose_fields import _quat_to_axis_angle + + device = bg_pose_field.axis_angle.device + aa_init = bg_pose_field.axis_angle.detach().clone() + tr_init = bg_pose_field.translation.detach().clone() + + T = aa_init.shape[0] + n_loaded = 0 + n_missing = 0 + for t in range(T): + if t not in poses: + n_missing += 1 + continue + M = poses[t] + R = torch.from_numpy(M[:3, :3]).to(device, dtype=torch.float32) + t_vec = torch.from_numpy(M[:3, 3]).to(device, dtype=torch.float32) + q = rotmat_to_quat(R) + aa = _quat_to_axis_angle(q) + aa_init[t] = aa + tr_init[t] = t_vec + n_loaded += 1 + + with torch.no_grad(): + bg_pose_field.axis_angle.data.copy_(aa_init) + bg_pose_field.translation.data.copy_(tr_init) + return n_loaded, n_missing + + +# --------------------------------------------------------------------------- +# Containers +# --------------------------------------------------------------------------- + +@dataclass +class HandSlot: + """All per-hand state bundled together: input data + learnable modules.""" + side: str # "left" or "right" + track: HandPoseTrack + pose_field: HandPoseField + gaussians: object # HandGaussians (avoid circular import in type) + mask_dir: str + output_pose_dir: str | None + # Optional WristAttachedGaussians: free 3D Gaussians rigidly attached + # to the wrist 6DOF pose, for arm geometry. None when disabled. + wrist_gaussians: object | None = None + + +@dataclass +class LossWeights: + photometric: float = 1.0 + silhouette: float = 0.5 + # Per-class relative weights inside the silhouette loss. When SAM2 + # hand masks are noisier than the object mask (typical), drop + # silhouette_hand to e.g. 0.3 to trust object more without changing + # the overall silhouette/photometric balance. + silhouette_obj: float = 1.0 + silhouette_hand: float = 1.0 + depth: float = 0.05 + # Shape-only depth prior: L1 between log-depth gradients of rendered vs + # MoGe target. Scale-invariant, so it tolerates MoGe's bias and only + # penalizes wrong local geometry. Default off; use in addition to + # ``depth`` (which provides the absolute-scale anchor). + log_depth_grad: float = 0.0 + # SSIM losses (1 - SSIM) on RGB and (log-)depth. Captures local + # structure / texture that pixel-wise L1 misses. 3DGS pairs L1+SSIM + # at ratio ~0.8 / 0.2 — same default here (photometric=1.0, ssim=0.2). + photometric_ssim: float = 0.0 + depth_ssim: float = 0.0 + # Smoothness terms use .sum() reduction in losses.py — gradients are + # length-invariant, so weights here are much smaller than under the + # old .mean() formulation. Rotation and translation are split so + # either can be disabled or weighted independently (e.g. set + # smooth_obj_rot=0 to allow free per-frame rotation while still + # smoothing translation). + smooth_obj_rot: float = 0.01 + smooth_obj_trans: float = 0.01 + # Hand rotation is split into global vs finger because finger joints + # carry much weaker photometric signal per joint (a fingertip covers + # ~10 pixels vs. the whole hand orientation affecting hundreds), so a + # smoothness that's right for global_orient over-smooths fingers and + # kills articulation. Default finger weight is 10× smaller. + smooth_hand_rot: float = 0.01 # global_orient (T, 3) + smooth_hand_finger: float = 0.001 # hand_pose (T, 15, 3) — 15 joints + smooth_hand_trans: float = 0.01 # cam_t (T, 3) + # Background camera motion is usually slow and continuous; tighter + # smoothness than foreground keeps the optimizer from absorbing + # photometric noise as fake camera jitter. + smooth_bg_rot: float = 0.1 + smooth_bg_trans: float = 0.1 + beta_prior: float = 10.0 # tight; keeps β from absorbing per-frame photometric noise + hand_scale_prior: float = 10.0 # tight by default — align_hands' median is a good init + # Δp regularizer uses .sum() — per-Gaussian gradient is no longer + # divided by N. Default 1.0 with N≈1000 gives a comparable pull to a + # photometric loss of ~0.1 magnitude. Split per category so the user + # can let bg breathe (e.g. set delta_p_reg_bg=1) while keeping obj/hand + # tightly mesh-anchored (delta_p_reg_obj=100, delta_p_reg_hand=100). + delta_p_reg_obj: float = 1.0 + delta_p_reg_hand: float = 1.0 + delta_p_reg_bg: float = 1.0 + # Face-anchored regularization (used in place of delta_p_reg_{obj,hand} + # when the corresponding anchor mode is "face"). Δp is in face-local + # (T, B, N) coords. Defaults express "stay inside the volume": light + # surface slide, heavy outward leak, free inward sink. See + # losses.face_delta_p_regularizer. + face_delta_p_tangent_obj: float = 1.0 + face_delta_p_normal_outward_obj: float = 100.0 + face_delta_p_normal_inward_obj: float = 0.0 + face_delta_p_tangent_hand: float = 1.0 + face_delta_p_normal_outward_hand: float = 100.0 + face_delta_p_normal_inward_hand: float = 0.0 + # Opacity binarization (α(1−α) summed, per set). Pushes each Gaussian + # toward fully opaque or fully transparent — invisible Gaussians "drop + # out" rather than persisting as semi-transparent fog. Default 0 + # (disabled). Sum reduction matches delta_p_regularizer. + opacity_binary_obj: float = 0.0 + opacity_binary_hand: float = 0.0 + opacity_binary_bg: float = 0.0 + # Depth-variance distortion loss (gsplat 3DGS has no native distloss; + # this is the depth-variance proxy to Mip-NeRF 360's distortion term). + # Single weight; loss is the mean per-pixel variance, masked to the + # union-of-foreground (or to the full image when bg Gaussians are on). + # Default 0 (disabled). Units: [depth²]. + depth_variance: float = 0.0 + # Foreground / background penetration loss. Penalizes + # relu(depth_fg − depth_bg) at foreground-mask pixels, so hand / + # object Gaussians stay in front of the background. Active only when + # both ``with_background=True`` AND this weight > 0 (renders bg-only + # and fg-only depth as extra passes — see ``depth_ordering_margin`` + # for slack). Default 0. Units: [depth]. + depth_ordering: float = 0.0 + # Slack (meters) in the depth-ordering inequality: + # require depth_fg ≤ depth_bg − margin. Positive margin enforces a + # gap, zero allows touching. + depth_ordering_margin: float = 0.0 + # Tight Gaussian prior on log_scale_global (pulls global object scale + # toward 1.0). Drop to ~0 if you want unrestricted scale; raise to + # freeze it near init. Default is moderate — prior is observable enough + # via background depth / hand size to converge without tight pinning. + obj_scale_prior: float = 1.0 + # SuGaR-style surface-alignment regularizers (bg only for now). All + # default to zero — pure drop-in. See losses.scale_anisotropy_loss / + # density_regularizer_local / sugar_sdf_losses. + scale_aniso_bg: float = 0.0 + density_bg: float = 0.0 # our local proxy (no depth anchor) + # Paper-faithful SuGaR losses (Guédon & Lepetit 2024). Connect Gaussians + # to MoGe depth via the implicit-SDF formulation. ``sdf_density_bg`` + # weights the L1 between f̂ (depth-implied SDF) and f (Gaussian-mixture + # SDF, Eq. 7-8); ``normal_consistency_bg`` weights the alignment of the + # field gradient with the closest Gaussian's normal (Eq. 10). + sdf_density_bg: float = 0.0 + normal_consistency_bg: float = 0.0 + + +# --------------------------------------------------------------------------- +# Frame index alignment +# --------------------------------------------------------------------------- + +def _common_frame_indices(*lists: list[int]) -> list[int]: + """Intersection of multiple frame-index lists, preserving order.""" + common = set(lists[0]) + for lst in lists[1:]: + common &= set(lst) + return sorted(common) + + +def _restrict_object_track(track: ObjectPoseTrack, keep: set[int]) -> ObjectPoseTrack: + idxs = [i for i, fi in enumerate(track.frame_indices) if fi in keep] + return ObjectPoseTrack( + rotations = track.rotations[idxs], + translations = track.translations[idxs], + scales = track.scales[idxs], + frame_indices= [track.frame_indices[i] for i in idxs], + ) + + +def _restrict_hand_track(track: HandPoseTrack, keep: set[int]) -> HandPoseTrack: + idxs = [i for i, fi in enumerate(track.frame_indices) if fi in keep] + return HandPoseTrack( + global_orient = track.global_orient[idxs], + hand_pose = track.hand_pose[idxs], + betas = track.betas[idxs], + cam_t = track.cam_t[idxs], + is_right = track.is_right, + frame_indices = [track.frame_indices[i] for i in idxs], + raw_records = [track.raw_records[i] for i in idxs], + hand_scale = track.hand_scale, + ) + + +# --------------------------------------------------------------------------- +# Overlay rendering +# --------------------------------------------------------------------------- + +def _save_overlay_video( + overlay_frames: list[np.ndarray], # list of (H, W, 3) uint8 + output_path: str, + fps: float = 30.0, +) -> None: + if not overlay_frames: + return + os.makedirs(os.path.dirname(os.path.abspath(output_path)) or ".", exist_ok=True) + with tempfile.TemporaryDirectory() as tmp: + for i, fr in enumerate(overlay_frames): + Image.fromarray(fr).save(os.path.join(tmp, f"{i:06d}.png")) + subprocess.run([ + "ffmpeg", "-y", "-loglevel", "error", + "-r", str(fps), + "-i", os.path.join(tmp, "%06d.png"), + "-c:v", "libx264", "-pix_fmt", "yuv420p", "-crf", "20", + output_path, + ], check=True) + + +# --------------------------------------------------------------------------- +# Checkpoint write — atomic via tmp + rename so a live reader (the viewer's +# hot-reload) never sees a half-written file. +# --------------------------------------------------------------------------- + +def _write_refine_checkpoint( + *, + checkpoint_path: str, + obj_gaussians, obj_pose_field, hand_slots, + bg_gaussians, bg_pose_field, + intrinsics_field, + optimizer, lr_scheduler, + init_obj_axis_angle: torch.Tensor, + init_obj_translation: torch.Tensor, + frame_indices: list[int], + step_count: int, + s_obj_learned: float, +) -> None: + os.makedirs( + os.path.dirname(os.path.abspath(checkpoint_path)) or ".", + exist_ok=True, + ) + ckpt_save = { + "obj_gaussians": obj_gaussians.state_dict(), + "obj_pose_field": obj_pose_field.state_dict(), + "hand_gaussians": [s.gaussians.state_dict() for s in hand_slots], + "hand_pose_fields": [s.pose_field.state_dict() for s in hand_slots], + "hand_sides": [s.side for s in hand_slots], + "intrinsics_field": intrinsics_field.state_dict(), + # Wrist-attached "arm" Gaussians per hand: None entries for hands + # that don't have them. Visualizer/resume rebuild from these. + "wrist_gaussians": [ + (s.wrist_gaussians.state_dict() if s.wrist_gaussians is not None else None) + for s in hand_slots + ], + "optimizer": optimizer.state_dict(), + "init_obj_axis_angle": init_obj_axis_angle.detach().cpu(), + "init_obj_translation": init_obj_translation.detach().cpu(), + "step_count": step_count, + "frame_indices": list(frame_indices), + "s_obj_learned": s_obj_learned, + } + if bg_gaussians is not None: + ckpt_save["bg_gaussians"] = bg_gaussians.state_dict() + ckpt_save["bg_pose_field"] = bg_pose_field.state_dict() + if lr_scheduler is not None: + ckpt_save["lr_scheduler"] = lr_scheduler.state_dict() + + def _exp_avg_sq(p): + v = optimizer.state.get(p, {}).get("exp_avg_sq") + return v.detach().cpu() if v is not None else None + ckpt_save["pose_grad_state"] = { + "obj_axis_angle": _exp_avg_sq(obj_pose_field.axis_angle), + "obj_translation": _exp_avg_sq(obj_pose_field.translation), + "hands": [ + { + "side": slot.side, + "global_orient": _exp_avg_sq(slot.pose_field.global_orient), + "hand_pose": _exp_avg_sq(slot.pose_field.hand_pose), + "cam_t": _exp_avg_sq(slot.pose_field.cam_t), + } + for slot in hand_slots + ], + } + tmp_path = checkpoint_path + ".tmp" + torch.save(ckpt_save, tmp_path) + os.replace(tmp_path, checkpoint_path) + + +# --------------------------------------------------------------------------- +# Main entry +# --------------------------------------------------------------------------- + +def refine( + frames_dir: str, + intrinsics_path: str, + object_mesh_path: str, + object_poses_dir: str, + object_mask_dir: str, + refined_object_poses_dir: str, + overlay_path: str, + # Learned global object scale: when provided, written as a JSON file + # ``{"scale": float}``. Per-frame Transform3d scales are then left + # untouched (passthrough of input). When None, falls back to baking + # the learned scale into each frame's Transform3d.scale (legacy). + refined_object_scale_path: str | None = None, + left_hand_pose_dir: str | None = None, + left_hand_mask_dir: str | None = None, + right_hand_pose_dir: str | None = None, + right_hand_mask_dir: str | None = None, + refined_left_hand_pose_dir: str | None = None, + refined_right_hand_pose_dir: str | None = None, + depth_dir: str | None = None, + mano_assets_root: str | None = None, + n_epochs: int = 30, + n_gaussian_only_epochs: int = 5, # epochs at the start with poses frozen + batch_size: int = 4, + lr_gaussians: float = 1e-2, + lr_hand_gaussians: float | None = None, # defaults to lr_gaussians if None + # Per-attribute LR multipliers applied on top of the per-set base LR + # (lr_gaussians / lr_hand_gaussians / lr_bg_gaussians). Defaults to 1.0 + # everywhere preserves the old single-LR behavior; standard 3DGS uses + # very different ratios (e.g. opacity ~300x position) — see docstrings + # on the CLI flags for typical settings. + lr_mul_delta_p: float = 1.0, + lr_mul_quat: float = 1.0, + lr_mul_scale: float = 1.0, + lr_mul_opacity: float = 1.0, + lr_mul_color: float = 1.0, + lr_mul_obj_global_scale: float = 1.0, + lr_object_pose: float = 1e-3, # legacy: applies to both rot+trans if specifics are None + lr_object_rot: float | None = None, # axis_angle; falls back to lr_object_pose + lr_object_trans: float | None = None, # translation; falls back to lr_object_pose + lr_hand_pose: float = 1e-3, # legacy: applies to global_orient + hand_pose + cam_t if specifics are None + lr_hand_global_orient: float | None = None, # MANO root rotation; falls back to lr_hand_pose + lr_hand_finger: float | None = None, # MANO hand_pose (15 joint axis-angles); falls back to lr_hand_pose + lr_hand_trans: float | None = None, # MANO cam_t; falls back to lr_hand_pose + lr_betas: float = 1e-4, + # Optional optimization of per-track hand_scale (init from align_hands). + # When False (default), hand_scale stays fixed at the align-hands estimate + # and is excluded from the optimizer. Prior weight lives on LossWeights + # (``hand_scale_prior``), wired through the lib CLI. + learn_hand_scale: bool = False, + lr_hand_scale: float = 1e-3, + render_every: int = 0, + progress_dir: str | None = None, + debug_frame_idx: int | None = None, + mask_background_to_black: bool = False, + balance_photometric_by_mask: bool = False, + freeze_object_rot: bool = False, + freeze_object_trans: bool = False, + freeze_object_scale: bool = False, + freeze_hand_rot: bool = False, + freeze_hand_trans: bool = False, + with_background: bool = False, + bg_ref_frame: int | None = None, # ref frame index; defaults to debug_frame_idx or first frame + lr_bg_gaussians: float | None = None, # defaults to lr_gaussians + lr_bg_pose: float = 1e-3, # legacy: applies to both rot+trans if specifics are None + lr_bg_rot: float | None = None, # axis_angle; falls back to lr_bg_pose + lr_bg_trans: float | None = None, # translation; falls back to lr_bg_pose + bg_max_points: int = 50000, + # SuGaR-style background regularization (kicks in when the corresponding + # LossWeights field is > 0 via the CLI; these knobs control sampling cost). + n_density_neighbors: int = 8, + density_subsample_frac_bg: float = 0.2, + # Paper-faithful SuGaR knobs. + n_sdf_samples_bg: int = 1000, + n_sdf_neighbors_bg: int = 8, + # Static valid-pixel mask derived from the input video — detects fixed + # black regions (fisheye crop, vignette, dead border) so they're + # excluded from all photometric / depth / SuGaR supervision. A pixel + # is invalid if its max brightness across all frames is below + # ``valid_mask_threshold`` (in [0,1] image scale). Erosion peels back + # the soft transition at the boundary. Set threshold to 0 to disable. + valid_mask_threshold: float = 0.04, + valid_mask_erode_iters: int = 2, + # Optional: seed the background pose field with an external VO/SfM solution + # (e.g. DROID-SLAM). Folder of per-frame `Transform3d` JSONs encoding + # camera-to-world SE(3) (DROID/COLMAP convention). When set, after + # BackgroundPoseField construction we replace the identity init with + # T_w2c_gsplat(t) = T_cw(t)^-1 @ T_cw(ref) so the ref frame stays identity + # and other frames carry the relative motion. Missing/unreadable frames + # fall back to identity. Frames whose `Transform3d.scale` differs from 1 + # are ignored — pass a scale-aligned trajectory (e.g. via DROID's + # --align_to_depth_folder). + background_pose_init_dir: str | None = None, + # Multi-frame BG point-cloud init (only effective when + # background_pose_init_dir is also set, since we need per-frame poses to + # compose unprojections into a common world frame). When stride > 1, the + # BG anchor cloud is fused from MoGe depth at frame indices [ref, ref+s, + # ref+2s, ...] ∪ [ref-s, ref-2s, ...] using each frame's own SAM2 + # foreground mask. Voxel-downsampled to bg_voxel_size before final + # random subsample to bg_max_points. Stride=1 or =0 → single-frame init. + bg_init_stride: int = 10, + bg_voxel_size: float = 0.005, + n_obj_gaussians: int | None = None, # None = use mesh vertex count as-is + n_hand_gaussians: int | None = None, # None = use 778 (full MANO verts); + # smaller subsamples; >778 ignored + # (would require barycentric LBS). + # Anchor mode for object / hand Gaussians: "vertex" (legacy, one Gaussian + # per mesh vertex) or "face" (one Gaussian per mesh face, anchored at the + # face centroid with orientation derived from the face's TBN frame and Δp + # parameterized in face-local coords). Set independently per set. + # + # In "face" mode the corresponding ``n_*_gaussians`` knob is ignored — + # Gaussian count equals face count (1538 for MANO, mesh face count for + # object). The delta-p regularizer also switches: legacy + # ``delta_p_reg_{obj,hand}`` is replaced by the asymmetric per-axis trio + # ``face_delta_p_{tangent,normal_outward,normal_inward}_{obj,hand}``. + object_anchor_mode: str = "vertex", # "vertex" | "face" + hand_anchor_mode: str = "vertex", # "vertex" | "face" + # Per-axis thin-slab init for face Gaussians: normal-axis sigma = + # face_normal_thin_factor * tangent sigma. Smaller → flatter disks. + face_normal_thin_factor_obj: float = 0.25, + face_normal_thin_factor_hand: float = 0.25, + init_opacity_obj: float = 0.9, + init_opacity_hand: float = 0.9, + init_opacity_bg: float = 0.9, + init_opacity_wrist: float = 0.5, + init_gaussian_scale_factor: float = 1.0, + # Hand Gaussian color init: when True (default), overwrite each hand + # Gaussian's color with the mean RGB inside its SAM2 mask at the + # reference frame (bg_ref_frame → debug_frame_idx → 0). Falls back to + # the default skin tone if the ref-frame mask is empty. + init_hand_color_from_mask: bool = True, + # When True, compute object/hand rotation+translation smoothness in + # *world frame* rather than camera frame, using bg_pose_field to invert + # the per-frame camera motion. This separates "the camera moved" from + # "the object moved" — without it, smoothness fights a moving camera. + # Only effective when bg_pose_field is constructed (--with_background). + # Hand finger articulation (hand_pose 15-joint) is intrinsic to the + # hand and is *not* re-expressed in world frame — its smoothness term + # stays unchanged. + smooth_obj_in_world: bool = False, + smooth_hand_in_world: bool = False, + # Wrist-attached "arm" Gaussians per hand. 0 disables. When > 0, + # constructs a set of free 3D Gaussians rigidly attached to each + # hand's wrist 6DOF pose, initialized at the wrist origin with the + # specified scale. Δp is loosely regularized so they can drift to + # fill the arm volume. No silhouette supervision (zero class labels). + n_wrist_gaussians: int = 0, + wrist_init_scale: float = 0.03, # ~3 cm — arm-sized blobs + wrist_init_radius: float = 0.0, # uniform-in-ball spread; 0 = all at origin + lr_wrist_gaussians: float | None = None, # defaults to lr_hand_gaussians + w_delta_p_reg_wrist: float = 0.01, # light by default — let them drift + # Learnable camera intrinsics. Both default off. + # learn_focal: refine fx, fy. CAUTION — degenerate with global scene + # scale when there's no depth supervision (doubling fx ≡ halving + # every Gaussian's z photometrically). Only safe with --w_depth > 0. + # learn_principal_point: refine cx, cy. Lower-risk — it's a 2D + # image-plane shift, not coupled to z. Safe to enable even without + # depth supervision. + learn_focal: bool = False, + learn_principal_point: bool = False, + lr_intrinsics: float = 1e-4, + w_intrinsics_prior: float = 1e3, # tight by default — K shouldn't wander far + # Rotation outlier median-snap. Periodically detect frames whose + # rotation is far from the quat-aligned median of a temporal window + # and replace them with the median (resetting Adam moments at that + # frame). 0 disables. Recommended pairing: enable after the first + # epoch when initial flips have stabilized. + snap_rotation_outliers_every: int = 0, # measured in optimizer steps; 0 disables + snap_rotation_threshold: float = 1.0, # quat-distance threshold (~85°) + snap_rotation_window: int = 3, # half-window (full window = 2*w + 1) + snap_rotation_targets: str = "obj,hand_wrist", # comma-sep subset of {obj, hand_wrist, hand_finger} + snap_rotation_verbose: bool = False, + use_cosine_lr_schedule: bool = False, + cosine_lr_min_ratio: float = 0.0, # final LR / initial LR (per group) + # Coarse-to-fine scale annealing: at training start, multiply every + # Gaussian's render-time scale by this factor; decay log-linearly to + # 1.0 over ``coarse_decay_epochs`` (defaults to n_epochs). 1.0 disables. + # Wider Gaussians mean even a far-off pose has photometric overlap + # with the target — helps recover outlier frames that would otherwise + # be stuck in flat regions of the loss. + coarse_init_scale_factor: float = 1.0, + coarse_decay_epochs: int | None = None, + # Distance-from-reference per-frame pose confidence. c_t scales + # per-frame photometric/silhouette/depth (high-c frames contribute + # more to Gaussian appearance) AND modulates a pose-init prior + # (high-c frames are pinned near input pose). 0 disables. + pose_confidence_decay: float = 0.0, # τ in frames; 0 disables (static c) + pose_confidence_ref_frame: int | None = None, # fidx; falls back to bg_ref_frame, then first frame + # Dynamic per-frame confidence based on quaternion-aligned distance + # to neighbor frames' rotations, recomputed every batch from the + # current pose state. Multiplies into the per-frame loss together + # with the static confidence: c_total[t] = c_static[t] * c_dynamic[t]. + # Set the static decay to 0 to use ONLY dynamic (uniform static = 1). + pose_confidence_dynamic_tau: float = 0.0, # quat-distance² scale; 0 disables + w_pose_init_prior: float = 0.0, # weight for the c_t-scaled pose-init prior + # Per-frame discrete rotation search for the object pose. For each + # frame, render the current Gaussian set at N candidate rotations + # (batched as multiple viewmats in a single gsplat call), score by + # photometric + silhouette IoU vs the SAM2 target, snap the frame's + # axis_angle to the best candidate. Handles rotation errors that are + # too large for the photometric basin to recover via gradient. + rotation_search_n_candidates: int = 0, # 0 disables + rotation_search_period: int = 0, # 0 = run once at start; >0 = also every K epochs + rotation_search_local_frac: float = 0.5, # fraction of candidates as local perturbations (rest are global SO(3)) + rotation_search_local_max_deg: float = 30.0, # max angle for local perturbations + rotation_search_silhouette_weight: float = 1.0, # IoU weight in scoring (photometric weight is 1.0) + rotation_search_smoothness_weight: float = 1.0, # causal smoothness weight: penalize candidates far from previous frame's rotation (in quat-aligned space). Forward sweep is implicit; t=0 has no penalty. + use_l2_photometric: bool = False, # squared error instead of L1 for the photometric loss + use_l2_silhouette: bool = False, # squared error instead of L1 for the class-label silhouette loss + # Train at lower resolution for speed. 1.0 = native; 0.5 ≈ 4x faster + # rendering (gsplat is ~linear in pixel count). Cache, intrinsics, + # and all downstream renders use the scaled dimensions; the final + # overlay video is also at the scaled resolution. + train_resolution_scale: float = 1.0, + multiview_include_background: bool = False, # include bg Gaussians in the final multi-view grid + # Checkpointing: save a single .pt with all module state_dicts + + # optimizer + LR scheduler + init pose snapshot + step counter, so + # a follow-up run can resume from exactly this state and run more + # epochs. ``checkpoint_path`` controls where to save (None disables); + # ``resume_from_checkpoint`` loads such a file at startup before the + # epoch loop. + checkpoint_path: str | None = None, + resume_from_checkpoint: str | None = None, + # If >0 and ``checkpoint_path`` is set, write the checkpoint every N + # optimizer steps in addition to the final write. Writes go through a + # ``.tmp`` rename so the file is never read mid-write — safe to + # tail with the live viewer's hot-reload. + checkpoint_every: int = 0, + ignore_optimizer_state: bool = False, # when resuming, skip optimizer/scheduler state load + freeze_gaussians: bool = False, # freeze ALL Gaussian attrs (obj + hand + bg) + random_init_obj_pose: bool = False, # randomize obj pose after build (uniform rot, σ=0.1 trans) + random_init_obj_pose_trans_std: float = 0.1, + freeze_bg_rot: bool = False, + freeze_bg_trans: bool = False, + weights: LossWeights | None = None, + device: str = "cuda", + seed: int = 0, +) -> None: + if weights is None: + weights = LossWeights() + if lr_hand_gaussians is None: + lr_hand_gaussians = lr_gaussians + if lr_bg_gaussians is None: + lr_bg_gaussians = lr_gaussians + if lr_wrist_gaussians is None: + lr_wrist_gaussians = lr_hand_gaussians + # Resolve per-DOF pose LR overrides; default to the lumped legacy LR. + if lr_object_rot is None: lr_object_rot = lr_object_pose + if lr_object_trans is None: lr_object_trans = lr_object_pose + if lr_hand_global_orient is None: lr_hand_global_orient = lr_hand_pose + if lr_hand_finger is None: lr_hand_finger = lr_hand_pose + if lr_hand_trans is None: lr_hand_trans = lr_hand_pose + if lr_bg_rot is None: lr_bg_rot = lr_bg_pose + if lr_bg_trans is None: lr_bg_trans = lr_bg_pose + if (left_hand_pose_dir is not None or right_hand_pose_dir is not None) and \ + mano_assets_root is None: + raise ValueError("mano_assets_root is required when any hand pose dir is set") + if with_background and depth_dir is None: + raise ValueError( + "with_background=True requires depth_dir for reference-frame " + "depth unprojection. Pass --depth_dir." + ) + + torch.manual_seed(seed) + device = torch.device(device) + + # ----- intrinsics, frames, masks ---------------------------------------- + K_init, W, H = load_intrinsics(intrinsics_path, str(device)) + if train_resolution_scale != 1.0: + s = float(train_resolution_scale) + K_init = K_init.clone() + K_init[0, 0] *= s # fx + K_init[1, 1] *= s # fy + K_init[0, 2] *= s # cx + K_init[1, 2] *= s # cy + W_scaled = max(1, int(round(W * s))) + H_scaled = max(1, int(round(H * s))) + print(f"Training resolution: {W}x{H} → {W_scaled}x{H_scaled} " + f"(scale={s:.3f}); render time ≈ {s*s:.3f}× of native.") + W, H = W_scaled, H_scaled + # Learnable intrinsics field. ``K`` below is a property-style getter + # that assembles a fresh (3,3) tensor on each call — when neither + # learn_* flag is set, all four params have requires_grad=False so + # this is equivalent to a constant tensor with negligible overhead. + intrinsics_field = IntrinsicsField( + K_init, + learn_focal = learn_focal, + learn_principal_point = learn_principal_point, + ).to(device) + if learn_focal or learn_principal_point: + flags = [] + if learn_focal: flags.append("focal (fx, fy)") + if learn_principal_point: flags.append("principal point (cx, cy)") + print(f"Learning intrinsics: {' + '.join(flags)}.") + if learn_focal and depth_dir is None: + print(" WARNING: --learn_focal without depth supervision is " + "degenerate with global scene scale; expect drift unless " + "--w_intrinsics_prior is tight.") + # Default K (no grad) for one-time / outside-training-loop uses. The + # training loop overwrites this per step with a fresh gradient-bearing + # assembly. Detach so the "outer" K doesn't carry stale grads when + # learning is on but the consumer doesn't need gradient. + K = intrinsics_field.K().detach() + + object_track = load_object_poses(object_poses_dir, str(device)) + hand_tracks: list[tuple[str, HandPoseTrack, str, str | None]] = [] + if right_hand_pose_dir is not None: + if right_hand_mask_dir is None: + raise ValueError("right_hand_mask_dir is required with right_hand_pose_dir") + hand_tracks.append(("right", load_hand_poses(right_hand_pose_dir, str(device)), + right_hand_mask_dir, refined_right_hand_pose_dir)) + if left_hand_pose_dir is not None: + if left_hand_mask_dir is None: + raise ValueError("left_hand_mask_dir is required with left_hand_pose_dir") + hand_tracks.append(("left", load_hand_poses(left_hand_pose_dir, str(device)), + left_hand_mask_dir, refined_left_hand_pose_dir)) + + # Restrict everything to frames present in *all* sources (frames + object + # poses + every hand pose). Mask dirs aren't required to be complete; a + # missing per-frame mask is treated as zero supervision for that frame. + all_idx_sets: list[list[int]] = [ + list_frame_indices(frames_dir, ".png") or list_frame_indices(frames_dir, ".jpg"), + object_track.frame_indices, + ] + for _, ht, _, _ in hand_tracks: + all_idx_sets.append(ht.frame_indices) + frame_indices = _common_frame_indices(*all_idx_sets) + if not frame_indices: + raise RuntimeError("No frames common to all input sources") + print(f"Refining over {len(frame_indices)} frames " + f"(intersection of {len(all_idx_sets)} sources)") + + object_track = _restrict_object_track(object_track, set(frame_indices)) + hand_tracks = [ + (side, _restrict_hand_track(ht, set(frame_indices)), md, out) + for side, ht, md, out in hand_tracks + ] + + # ----- learnable state -------------------------------------------------- + obj_verts, obj_colors, _obj_faces = load_object_mesh(object_mesh_path, str(device)) + if object_anchor_mode == "face": + if n_obj_gaussians is not None: + print(f"Object: anchor mode 'face' — ignoring n_obj_gaussians=" + f"{n_obj_gaussians} (count fixed at {_obj_faces.shape[0]} " + f"faces).") + obj_gaussians = init_object_face_gaussians_from_mesh( + obj_verts, _obj_faces, obj_colors, + normal_thin_factor = face_normal_thin_factor_obj, + init_opacity = init_opacity_obj, + init_scale_factor = init_gaussian_scale_factor, + ).to(device) + elif object_anchor_mode == "vertex": + if n_obj_gaussians is not None and n_obj_gaussians != obj_verts.shape[0]: + print(f"Object: resampling mesh surface to {n_obj_gaussians} " + f"Gaussians (mesh has {obj_verts.shape[0]} verts).") + obj_verts, obj_colors = resample_mesh_surface( + obj_verts, obj_colors, _obj_faces, n_obj_gaussians, + ) + obj_gaussians = init_object_gaussians_from_mesh( + obj_verts, obj_colors, + scale_factor=init_gaussian_scale_factor, + init_opacity=init_opacity_obj, + ).to(device) + else: + raise ValueError( + f"object_anchor_mode must be 'vertex' or 'face' (got {object_anchor_mode!r})" + ) + obj_pose_field = ObjectPoseField(object_track).to(device) + + if random_init_obj_pose: + with torch.no_grad(): + n = obj_pose_field.axis_angle.shape[0] + # Uniform random unit quaternion → axis_angle for each frame. + q = torch.randn(n, 4, device=device) + q = q / q.norm(dim=-1, keepdim=True).clamp_min(1e-8) + from .pose_fields import _quat_to_axis_angle + obj_pose_field.axis_angle.data = _quat_to_axis_angle(q) + # Translation: add Gaussian noise to the input. Default std + # is 0.1 m, typically the order of object size for HOI. + noise = torch.randn_like(obj_pose_field.translation) * float(random_init_obj_pose_trans_std) + obj_pose_field.translation.data = obj_pose_field.translation.data + noise + print(f"Randomized object pose: uniform SO(3) rotation, " + f"translation += N(0, {random_init_obj_pose_trans_std:.3f} m).") + + hand_slots: list[HandSlot] = [] + for side, ht, md, out_pose in hand_tracks: + pf = HandPoseField( + ht, mano_assets_root, device=device, + learn_hand_scale=learn_hand_scale, + ).to(device) + # Scale the per-Gaussian init footprint by the per-track hand_scale + # from align_hands. MANO native vertex spacing is ~5 mm, but + # hand_scale enlarges the mesh around its centroid by that factor; + # the Gaussian extents must match or the splat is sparse and the + # rendered hand appears smaller / hollow than the mesh overlay. + hand_scale_init = float(getattr(ht, "hand_scale", 1.0) or 1.0) + if hand_anchor_mode == "face": + if n_hand_gaussians is not None: + print(f"Hand ({side}): anchor mode 'face' — ignoring " + f"n_hand_gaussians={n_hand_gaussians} (count fixed at " + f"MANO face count).") + # Rest-pose MANO verts in the MANO local frame (no global_orient, + # no cam_t, zero pose / zero betas). + with torch.no_grad(): + _zero_pose = torch.zeros(1, 48, device=device) + _zero_betas = torch.zeros(1, 10, device=device) + _rest_out = pf.mano(_zero_pose, _zero_betas) + rest_verts = _rest_out.verts[0].detach().clone() # (V, 3) + if not ht.is_right: + # Mirror so the rest mesh used for face init matches the + # mirrored convention applied at runtime. + rest_verts = rest_verts * rest_verts.new_tensor([-1.0, 1.0, 1.0]) + faces_np = pf.mano.th_faces.detach().cpu().numpy() + hg = init_hand_face_gaussians( + rest_vertices = rest_verts, + faces = faces_np, + is_right = ht.is_right, + normal_thin_factor = face_normal_thin_factor_hand, + hand_scale_init = hand_scale_init, + init_opacity = init_opacity_hand, + init_scale_factor = init_gaussian_scale_factor, + device = device, + subsample_face_indices = None, + ) + elif hand_anchor_mode == "vertex": + # Optionally subsample the MANO vertex set to reduce hand Gaussian + # count. Larger-than-778 not supported here (would require + # barycentric LBS skinning). + sub_idx: torch.Tensor | None = None + if n_hand_gaussians is not None and n_hand_gaussians < pf.num_verts(): + g = torch.Generator(device="cpu").manual_seed(seed) + sub_idx = torch.randperm(pf.num_verts(), generator=g)[:n_hand_gaussians] + print(f"Hand ({side}): subsampling MANO verts " + f"{pf.num_verts()} → {n_hand_gaussians}.") + elif n_hand_gaussians is not None and n_hand_gaussians > pf.num_verts(): + print(f"Hand ({side}): n_hand_gaussians={n_hand_gaussians} > " + f"{pf.num_verts()} MANO verts; using all 778. " + f"(Supersampling would require barycentric LBS.)") + hg = init_hand_gaussians( + n_verts = pf.num_verts(), + is_right = ht.is_right, + init_scale = 0.005 * hand_scale_init, + init_opacity = init_opacity_hand, + init_scale_factor = init_gaussian_scale_factor, + device = device, + subsample_indices = sub_idx, + ) + else: + raise ValueError( + f"hand_anchor_mode must be 'vertex' or 'face' (got {hand_anchor_mode!r})" + ) + # Optional wrist-attached "arm" Gaussians. Initialized at the wrist + # origin (or in a small ball of init_radius) with large per-Gaussian + # scale; Δp is loosely regularized so they drift to fill the arm. + wrist_g = None + if n_wrist_gaussians > 0: + wrist_g = init_wrist_attached_gaussians( + n = int(n_wrist_gaussians), + init_scale = float(wrist_init_scale) * hand_scale_init, + init_radius = float(wrist_init_radius), + init_opacity = init_opacity_wrist, + init_scale_factor = init_gaussian_scale_factor, + device = device, + seed = seed + (1 if ht.is_right else 2), + ) + print(f"Hand ({side}): added {n_wrist_gaussians} wrist-attached " + f"Gaussians (init_scale={wrist_init_scale * hand_scale_init:.3f}, " + f"radius={wrist_init_radius:.3f}).") + hand_slots.append(HandSlot( + side = side, + track = ht, + pose_field = pf, + gaussians = hg, + mask_dir = md, + output_pose_dir = out_pose, + wrist_gaussians = wrist_g, + )) + + # ----- preload supervision into a CPU cache ----------------------------- + # Built before the optimizer because the optional background init needs + # ref-frame RGB / depth / masks from this cache. + cache = FrameCache( + frame_indices = frame_indices, + frames_dir = frames_dir, + object_mask_dir = object_mask_dir, + hand_mask_dirs = [s.mask_dir for s in hand_slots], + depth_dir = depth_dir, + height = H, + width = W, + valid_mask_threshold = valid_mask_threshold, + valid_mask_erode_iters = valid_mask_erode_iters, + ) + # Static valid-pixel mask on device — used by bg init, the training + # loop's batch_union, and the SuGaR bg_pixel_mask. Single (H, W) tensor + # shared across all frames (the artifact is image-space-fixed, so + # cross-frame consistency is automatic and there's no per-frame + # degeneracy). + valid_pixel_mask = cache.valid_mask.to(device, non_blocking=True) + + # Debug dump: write the mask + a blended overlay next to the output + # overlay video so you can eyeball what got excluded. Cheap — two PNGs + # written once. + debug_dir = os.path.dirname(os.path.abspath(overlay_path)) or "." + os.makedirs(debug_dir, exist_ok=True) + vm_np = (cache.valid_mask.cpu().numpy() * 255).astype(np.uint8) # (H, W) + Image.fromarray(vm_np, mode="L").save( + os.path.join(debug_dir, "valid_pixel_mask.png")) + ref_rgb_np = (cache.rgb[0].cpu().numpy() * 255).astype(np.uint8) # (H, W, 3) + blend = ref_rgb_np.astype(np.float32) * cache.valid_mask.cpu().numpy()[..., None] + blend += (1.0 - cache.valid_mask.cpu().numpy()[..., None]) * np.array( + [255, 0, 0], dtype=np.float32, + ) + Image.fromarray(blend.clip(0, 255).astype(np.uint8)).save( + os.path.join(debug_dir, "valid_pixel_mask_overlay.png")) + print(f" Valid-pixel mask dumped to {debug_dir}/valid_pixel_mask{{,_overlay}}.png") + + # ----- hand Gaussian color init from reference-frame mask -------------- + if init_hand_color_from_mask and hand_slots: + # Same ref-frame precedence as the bg init below: explicit + # bg_ref_frame → debug_frame_idx → first frame. + if bg_ref_frame is not None: + try: + _color_ref_t = frame_indices.index(int(bg_ref_frame)) + except ValueError: + _color_ref_t = 0 + elif debug_frame_idx is not None: + try: + _color_ref_t = frame_indices.index(int(debug_frame_idx)) + except ValueError: + _color_ref_t = 0 + else: + _color_ref_t = 0 + _ref_rgb = cache.rgb[_color_ref_t].to(device) # (H, W, 3) in [0,1] + for slot_i, slot in enumerate(hand_slots): + mask = cache.hand_masks[slot_i][_color_ref_t].to(device) # (H, W) in {0,1} + mass = float(mask.sum()) + if mass < 1.0: + print(f"Hand ({slot.side}): ref-frame mask empty — keeping " + f"default skin-tone init color.") + continue + mean_rgb = (_ref_rgb * mask.unsqueeze(-1)).sum(dim=(0, 1)) / mass # (3,) + mean_rgb = mean_rgb.clamp(0.0, 1.0) + with torch.no_grad(): + slot.gaussians._color.data.copy_( + mean_rgb.to(slot.gaussians._color) + .expand_as(slot.gaussians._color) + ) + # Wrist (arm) Gaussians: also start with the hand's skin color. + # Photometric will pull them toward the actual arm color once + # they drift into the arm region. + if slot.wrist_gaussians is not None: + slot.wrist_gaussians._color.data.copy_( + mean_rgb.to(slot.wrist_gaussians._color) + .expand_as(slot.wrist_gaussians._color) + ) + print(f"Hand ({slot.side}): init color from frame " + f"{frame_indices[_color_ref_t]:06d} mask mean = " + f"({mean_rgb[0]:.3f}, {mean_rgb[1]:.3f}, {mean_rgb[2]:.3f}).") + + # ----- optional background Gaussians + pose field ----------------------- + bg_gaussians: BackgroundGaussians | None = None + bg_pose_field: BackgroundPoseField | None = None + if with_background: + # Resolve reference frame: prefer explicit bg_ref_frame, fall back + # to debug_frame_idx (already validated to be in the sequence), then + # to the first frame. + if bg_ref_frame is not None: + try: + ref_t = frame_indices.index(int(bg_ref_frame)) + except ValueError: + print(f"Warning: bg_ref_frame={bg_ref_frame} not in sequence; " + f"falling back to first frame.") + ref_t = 0 + elif debug_frame_idx is not None: + try: + ref_t = frame_indices.index(int(debug_frame_idx)) + except ValueError: + ref_t = 0 + else: + ref_t = 0 + ref_fidx = frame_indices[ref_t] + print(f"Initializing background from reference frame {ref_fidx:06d} " + f"(positional t={ref_t})...") + + # Decide single-frame vs multi-frame init. Multi-frame requires + # per-frame world→camera poses (= SLAM seeding) to compose + # unprojections into a shared gsplat world. Without SLAM we can only + # trust the reference frame. + slam_poses: dict[int, np.ndarray] | None = None + if background_pose_init_dir is not None: + slam_poses = _load_relative_w2c_poses( + background_pose_init_dir, frame_indices, ref_t, + ) + + def _union_mask_at(t: int) -> torch.Tensor: + m = cache.obj_mask[t].to(device).clone() + for hm in cache.hand_masks: + m = torch.maximum(m, hm[t].to(device)) + # Treat invalid (black-border) pixels as if they were foreground + # so init_background_from_depth excludes them from the bg point + # cloud — those pixels have no real depth signal. + m = torch.maximum(m, 1.0 - valid_pixel_mask) + return m + + K_intr = K + use_multiframe = ( + slam_poses is not None + and bg_init_stride is not None + and bg_init_stride > 1 + ) + if use_multiframe: + # Frames included: ref_t + every stride'th position before/after ref, + # intersected with frames that have a valid SLAM pose. + positions = sorted({ref_t} | set(range(0, len(frame_indices), bg_init_stride))) + positions = [t for t in positions if t in slam_poses] + print(f"Initializing background from {len(positions)} frames " + f"(ref t={ref_t}, stride={bg_init_stride}, voxel={bg_voxel_size} m)...") + rgbs = [cache.rgb[t].to(device) for t in positions] + depths = [cache.depth[t].to(device) for t in positions] + masks = [_union_mask_at(t) for t in positions] + T_w2c_list = [ + torch.from_numpy(slam_poses[t]).to(device, dtype=torch.float32) + for t in positions + ] + anchors, colors, init_scales = init_background_multiframe( + rgbs = rgbs, + depths = depths, + union_masks = masks, + T_w2c_list = T_w2c_list, + K = K_intr, + voxel_size = bg_voxel_size, + max_points = bg_max_points, + ) + else: + ref_fidx = frame_indices[ref_t] + print(f"Initializing background from reference frame {ref_fidx:06d} " + f"(positional t={ref_t})...") + anchors, colors, init_scales = init_background_from_depth( + rgb = cache.rgb[ref_t].to(device), + depth = cache.depth[ref_t].to(device), + union_mask = _union_mask_at(ref_t), + K = K_intr, + max_points = bg_max_points, + ) + print(f"Background: {anchors.shape[0]} Gaussians initialized.") + + bg_gaussians = BackgroundGaussians( + anchors, colors, init_scales, + init_opacity=init_opacity_bg, + init_scale_factor=init_gaussian_scale_factor, + ).to(device) + bg_pose_field = BackgroundPoseField( + n_frames=len(frame_indices), device=device, ref_frame_t=ref_t + ).to(device) + + if slam_poses is not None: + n_loaded, n_missing = _seed_background_pose_field(bg_pose_field, slam_poses) + print(f"Background pose seeded from {background_pose_init_dir}: " + f"{n_loaded} frames loaded, {n_missing} fell back to identity.") + + # ----- optimizer -------------------------------------------------------- + # Per-attribute LR groups (multipliers shared across object / hand / bg + # Gaussian sets — only the per-set base LR differs). Standard 3DGS uses + # very different per-attribute ratios; making them user-tunable lets the + # caller mimic those without touching the base LRs. + def _gaussian_groups(gaussians, base_lr: float) -> list[dict]: + groups = [ + {"params": [gaussians._delta_p], "lr": base_lr * lr_mul_delta_p}, + {"params": [gaussians._quat_canon], "lr": base_lr * lr_mul_quat}, + {"params": [gaussians._log_scale], "lr": base_lr * lr_mul_scale}, + {"params": [gaussians._opacity_logit], "lr": base_lr * lr_mul_opacity}, + {"params": [gaussians._color], "lr": base_lr * lr_mul_color}, + ] + if hasattr(gaussians, "_log_scale_global"): + groups.append({ + "params": [gaussians._log_scale_global], + "lr": base_lr * lr_mul_obj_global_scale, + }) + return groups + + # Per-DOF param groups so rotation, translation, and (for hands) finger + # articulation can have independent learning rates. Adam's normalization + # mostly compensates for gradient-magnitude differences, but rotation + # needs many more steps per "physical unit" of motion than translation + # — separate LRs let you boost rotation explicitly when poses are + # converging slowly there. + param_groups: list[dict] = [] + param_groups += _gaussian_groups(obj_gaussians, lr_gaussians) + param_groups.append({"params": [obj_pose_field.axis_angle], "lr": lr_object_rot}) + param_groups.append({"params": [obj_pose_field.translation], "lr": lr_object_trans}) + for slot in hand_slots: + # Hand Gaussians get their own base LR knob — they typically need a bump + # over the object's because the hand covers fewer pixels in image and + # gradient signal per-Gaussian is correspondingly diluted. + param_groups += _gaussian_groups(slot.gaussians, lr_hand_gaussians) + if slot.wrist_gaussians is not None: + param_groups += _gaussian_groups(slot.wrist_gaussians, lr_wrist_gaussians) + param_groups.append({"params": [slot.pose_field.global_orient], "lr": lr_hand_global_orient}) + param_groups.append({"params": [slot.pose_field.hand_pose], "lr": lr_hand_finger}) + param_groups.append({"params": [slot.pose_field.cam_t], "lr": lr_hand_trans}) + param_groups.append({"params": [slot.pose_field.betas], "lr": lr_betas}) + if learn_hand_scale: + param_groups.append({"params": [slot.pose_field.hand_scale], "lr": lr_hand_scale}) + if bg_gaussians is not None: + param_groups += _gaussian_groups(bg_gaussians, lr_bg_gaussians) + param_groups.append({"params": [bg_pose_field.axis_angle], "lr": lr_bg_rot}) + param_groups.append({"params": [bg_pose_field.translation], "lr": lr_bg_trans}) + # Learnable intrinsics. Skip the param group entirely when no component + # is learnable — keeps the optimizer state clean and avoids a no-op group. + if intrinsics_field.has_learnable(): + intr_params = [ + p for p in ( + intrinsics_field.fx, intrinsics_field.fy, + intrinsics_field.cx, intrinsics_field.cy, + ) if p.requires_grad + ] + param_groups.append({"params": intr_params, "lr": lr_intrinsics}) + optimizer = torch.optim.Adam(param_groups) + + # Optional cosine LR schedule. LambdaLR multiplies each param group's + # *initial* LR by the same scalar each step, so per-attribute / per-set + # LR ratios are preserved as the global scale decays. + lr_scheduler: torch.optim.lr_scheduler.LRScheduler | None = None + if use_cosine_lr_schedule: + import math + steps_per_epoch_local = (len(frame_indices) + batch_size - 1) // batch_size + total_steps_local = max(1, n_epochs * steps_per_epoch_local) + + def _cosine_lambda(step: int) -> float: + progress = min(step / max(1, total_steps_local - 1), 1.0) + cos_factor = 0.5 * (1.0 + math.cos(math.pi * progress)) + return cosine_lr_min_ratio + (1.0 - cosine_lr_min_ratio) * cos_factor + + lr_scheduler = torch.optim.lr_scheduler.LambdaLR(optimizer, _cosine_lambda) + print(f"Cosine LR schedule: decay over {total_steps_local} steps " + f"to {cosine_lr_min_ratio:.2%} of initial LR.") + + # Per-class silhouette weights (allocated once, reused per step). + silhouette_class_weights = torch.tensor( + [weights.silhouette_obj] + [weights.silhouette_hand] * len(hand_slots), + dtype=torch.float32, device=device, + ) + + # Parse the rotation-snap target list once at startup. + _snap_targets = { + s.strip().lower() + for s in (snap_rotation_targets or "").split(",") + if s.strip() + } + _snap_unknown = _snap_targets - {"obj", "hand_wrist", "hand_finger"} + if _snap_unknown: + raise ValueError( + f"snap_rotation_targets contains unknown entries: {sorted(_snap_unknown)}. " + f"Valid: obj, hand_wrist, hand_finger.") + if snap_rotation_outliers_every > 0 and _snap_targets: + print(f"Rotation outlier median-snap: every {snap_rotation_outliers_every} " + f"steps, targets {sorted(_snap_targets)}, " + f"threshold {snap_rotation_threshold:.2f}, window ±{snap_rotation_window}.") + + # ----- pre-allocate static class-label tensor -------------------------- + # The per-Gaussian one-hot labels depend only on Gaussian counts, not + # on per-frame state, so we build them once and reuse every step. + # Layout matches concat_frames([obj] + hands + [bg]): block-diagonal + # one-hots, with bg's block all zeros. + K_classes_static = 1 + len(hand_slots) + obj_n_static = obj_gaussians.num_gaussians() + hand_n_static = [s.gaussians.num_gaussians() for s in hand_slots] + bg_n_static = bg_gaussians.num_gaussians() if bg_gaussians is not None else 0 + wrist_n_static = [ + (s.wrist_gaussians.num_gaussians() if s.wrist_gaussians is not None else 0) + for s in hand_slots + ] + _label_chunks: list[torch.Tensor] = [] + obj_label = torch.zeros(obj_n_static, K_classes_static, device=device) + obj_label[:, 0] = 1.0 + _label_chunks.append(obj_label) + # Concat order matches the per-frame render: obj + hands + wrist + bg. + for i, n in enumerate(hand_n_static): + h_label = torch.zeros(n, K_classes_static, device=device) + h_label[:, i + 1] = 1.0 + _label_chunks.append(h_label) + # Wrist-attached "arm" Gaussians: zero-class — silhouette loss treats + # them as "no target", so they only get photometric supervision. If a + # wrist Gaussian sits in front of a hand pixel it occludes the hand's + # class probability, which the silhouette loss correctly penalizes. + for n_w in wrist_n_static: + if n_w > 0: + _label_chunks.append(torch.zeros(n_w, K_classes_static, device=device)) + if bg_n_static > 0: + _label_chunks.append(torch.zeros(bg_n_static, K_classes_static, device=device)) + labels_static = torch.cat(_label_chunks, dim=0).contiguous() # (sum_N, K) + + # ----- per-frame pose confidence ---------------------------------------- + n_frames_local = len(frame_indices) + if pose_confidence_decay > 0.0: + # Resolve reference frame: explicit → bg_ref_frame → first frame. + ref_t_pose = 0 + for cand in (pose_confidence_ref_frame, bg_ref_frame): + if cand is None: + continue + try: + ref_t_pose = frame_indices.index(int(cand)) + break + except ValueError: + continue + t_arr = torch.arange(n_frames_local, device=device, dtype=torch.float32) + pose_confidence = torch.exp( + -(t_arr - float(ref_t_pose)).abs() / float(pose_confidence_decay) + ) + print(f"Pose confidence: ref t={ref_t_pose} " + f"(frame {frame_indices[ref_t_pose]:06d}), " + f"τ={pose_confidence_decay} frames; " + f"c range [{pose_confidence.min().item():.3f}, " + f"{pose_confidence.max().item():.3f}].") + else: + pose_confidence = torch.ones(n_frames_local, device=device) + + # Snapshot of the initial object pose (frozen reference for the prior). + init_obj_axis_angle = obj_pose_field.axis_angle.detach().clone() + init_obj_translation = obj_pose_field.translation.detach().clone() + + # Helper for dynamic pose confidence: per-frame quat-aligned distance + # to neighbors → exp(-dist² / τ). Recomputed each batch. + def _compute_dynamic_pose_confidence() -> torch.Tensor: + with torch.no_grad(): + aa = obj_pose_field.axis_angle # (T, 3) + T = aa.shape[0] + ang = aa.norm(dim=-1, keepdim=True).clamp_min(1e-8) + q = torch.cat([torch.cos(ang * 0.5), + aa / ang * torch.sin(ang * 0.5)], dim=-1) # (T, 4) + # Sign-aligned squared distance to prev (T-1 entries). + dot = (q[1:] * q[:-1]).sum(dim=-1, keepdim=True) + q_prev_aligned = torch.where(dot < 0, -q[:-1], q[:-1]) + d_prev = ((q[1:] - q_prev_aligned) ** 2).sum(dim=-1) # (T-1,) + # Build per-frame mean of available neighbor distances. + zero = aa.new_zeros(1) + d_to_prev = torch.cat([zero, d_prev]) # (T,) — d to t-1 + d_to_next = torch.cat([d_prev, zero]) # (T,) — d to t+1 + counts = torch.full((T,), 2.0, device=aa.device) + counts[0] = 1.0 + counts[-1] = 1.0 + mean_dist = (d_to_prev + d_to_next) / counts + return torch.exp(-mean_dist / float(pose_confidence_dynamic_tau)) + + # ----- training loop (epochs × random permutation × batched accumulation) + n_frames = len(frame_indices) + rng = np.random.default_rng(seed) + steps_per_epoch = (n_frames + batch_size - 1) // batch_size + total_steps = n_epochs * steps_per_epoch + # Coarse-to-fine scale anneal setup: log-linear decay from + # coarse_init_scale_factor → 1.0 over coarse_decay_steps. + coarse_decay_steps = ( + (coarse_decay_epochs if coarse_decay_epochs is not None else n_epochs) + * steps_per_epoch + ) + if coarse_init_scale_factor != 1.0: + print(f"Coarse-to-fine scale anneal: factor " + f"{coarse_init_scale_factor:.2f} → 1.0 over " + f"{coarse_decay_steps} steps.") + print(f"Refining: {n_epochs} epochs x {steps_per_epoch} steps " + f"(batch_size={batch_size}, n_frames={n_frames}, " + f"~{n_epochs} updates/frame)") + + # ----- progress-render setup ------------------------------------------- + # When render_every > 0, dump an overlay PNG of a single fixed reference + # frame to progress_dir at every Nth optimizer step. Cheap (one frame's + # render) and lets you watch poses converge step-by-step. + if render_every > 0: + if progress_dir is None: + progress_dir = os.path.join( + os.path.dirname(os.path.abspath(overlay_path)) or ".", "progress" + ) + os.makedirs(progress_dir, exist_ok=True) + if debug_frame_idx is None: + debug_frame_t = 0 + else: + try: + debug_frame_t = frame_indices.index(int(debug_frame_idx)) + except ValueError: + debug_frame_t = 0 + print(f"Warning: debug_frame_idx={debug_frame_idx} not in " + f"the refined sequence; falling back to t=0 " + f"(frame {frame_indices[0]:06d}).") + debug_fidx = frame_indices[debug_frame_t] + print(f"Progress dumps every {render_every} steps → " + f"{progress_dir} (reference frame {debug_fidx:06d})") + else: + progress_dir = None + debug_frame_t = None + + pbar = tqdm(total=total_steps, ncols=100, desc="refine") + step_count = 0 + + # ----- optional resume from checkpoint --------------------------------- + # Loads after all modules + optimizer + scheduler are built, so + # state_dict shapes are guaranteed to exist on the target side. + if resume_from_checkpoint is not None: + ckpt = torch.load(resume_from_checkpoint, map_location=device) + if len(ckpt.get("hand_sides", [])) != len(hand_slots): + raise ValueError( + f"Checkpoint has {len(ckpt.get('hand_sides', []))} hand " + f"slots; current run has {len(hand_slots)}." + ) + ck_frames = ckpt.get("frame_indices") + if ck_frames is not None and list(ck_frames) != list(frame_indices): + print("Warning: checkpoint frame_indices differ from current " + "run — proceeding but state may not align.") + + obj_gaussians.load_state_dict(ckpt["obj_gaussians"]) + obj_pose_field.load_state_dict(ckpt["obj_pose_field"]) + for slot, hg, hp in zip(hand_slots, + ckpt["hand_gaussians"], + ckpt["hand_pose_fields"]): + slot.gaussians.load_state_dict(hg) + slot.pose_field.load_state_dict(hp) + # Learnable intrinsics — older checkpoints won't have this key. + if "intrinsics_field" in ckpt: + intrinsics_field.load_state_dict(ckpt["intrinsics_field"]) + # Wrist-attached Gaussians: only load when both checkpoint and slot + # have them. Older checkpoints (pre-wrist) carry no "wrist_gaussians" + # key — gracefully skip. + ckpt_wrist = ckpt.get("wrist_gaussians") + if ckpt_wrist is not None: + for slot, wg_state in zip(hand_slots, ckpt_wrist): + if slot.wrist_gaussians is not None and wg_state is not None: + slot.wrist_gaussians.load_state_dict(wg_state) + if bg_gaussians is not None and ckpt.get("bg_gaussians") is not None: + bg_gaussians.load_state_dict(ckpt["bg_gaussians"]) + bg_pose_field.load_state_dict(ckpt["bg_pose_field"]) + if ignore_optimizer_state: + print("Skipping optimizer/scheduler state on resume " + "(--ignore_optimizer_state); Adam will reinit lazily.") + else: + optimizer.load_state_dict(ckpt["optimizer"]) + if lr_scheduler is not None and ckpt.get("lr_scheduler") is not None: + lr_scheduler.load_state_dict(ckpt["lr_scheduler"]) + if "init_obj_axis_angle" in ckpt: + init_obj_axis_angle = ckpt["init_obj_axis_angle"].to(device) + init_obj_translation = ckpt["init_obj_translation"].to(device) + step_count = int(ckpt.get("step_count", 0)) + print(f"Resumed from {resume_from_checkpoint} (step {step_count}).") + + # Dump a "step 0" frame so you can visually confirm the starting state + # (FP/HaMeR init or resumed checkpoint state) before optimization moves + # things. Filename suffix marks resume to avoid overwriting the prior + # run's 000000.png when extending training. + if render_every > 0: + start_step = step_count if resume_from_checkpoint is not None else 0 + _dump_progress_frame( + progress_dir, start_step, debug_frame_t, cache, + K, W, H, device, + obj_gaussians, obj_pose_field, hand_slots, + bg_gaussians=bg_gaussians, bg_pose_field=bg_pose_field, + labels_static=labels_static, + ) + + # Pose-param requires_grad is toggled per-epoch by two independent + # gates: + # - the Gaussian-only warmup (first N epochs): freezes everything. + # - explicit freeze_* user flags: hold for the entire run. + # Both work via toggling requires_grad rather than excluding params + # from the optimizer, so Adam's running moments aren't corrupted by + # stale state when params are re-enabled at the warmup boundary. + def _set_pose_grad_state(epoch: int) -> None: + in_warmup = epoch < n_gaussian_only_epochs + # Whole-Gaussian freeze: pins every Gaussian-attribute parameter + # (obj + hand + bg) for the entire run. Combine with freeze_hand_* + # and freeze_bg_* to do "object-pose-only" optimization while + # everything else stays exactly as the (possibly resumed) state + # left it. + if freeze_gaussians: + for p in obj_gaussians.parameters(): + p.requires_grad_(False) + for slot in hand_slots: + for p in slot.gaussians.parameters(): + p.requires_grad_(False) + if bg_gaussians is not None: + for p in bg_gaussians.parameters(): + p.requires_grad_(False) + obj_pose_field.axis_angle.requires_grad_( + not in_warmup and not freeze_object_rot) + obj_pose_field.translation.requires_grad_( + not in_warmup and not freeze_object_trans) + # Global object scale: lives on ObjectGaussians, not pose field; + # toggle the same way to keep behavior consistent across the run. + obj_gaussians._log_scale_global.requires_grad_( + not in_warmup and not freeze_object_scale) + for slot in hand_slots: + slot.pose_field.global_orient.requires_grad_( + not in_warmup and not freeze_hand_rot) + slot.pose_field.hand_pose.requires_grad_( + not in_warmup and not freeze_hand_rot) + slot.pose_field.cam_t.requires_grad_( + not in_warmup and not freeze_hand_trans) + # Betas only frozen during warmup; no user-level freeze knob. + slot.pose_field.betas.requires_grad_(not in_warmup) + # hand_scale gated on both --learn_hand_scale (user opt-in) AND + # warmup. Outside warmup with the flag set, the prior loss + # also activates. + slot.pose_field.hand_scale.requires_grad_( + learn_hand_scale and not in_warmup) + if bg_pose_field is not None: + bg_pose_field.axis_angle.requires_grad_( + not in_warmup and not freeze_bg_rot) + bg_pose_field.translation.requires_grad_( + not in_warmup and not freeze_bg_trans) + + if any([freeze_object_rot, freeze_object_trans, + freeze_hand_rot, freeze_hand_trans]): + flags = [] + if freeze_object_rot: flags.append("object rot") + if freeze_object_trans: flags.append("object trans") + if freeze_hand_rot: flags.append("hand rot") + if freeze_hand_trans: flags.append("hand trans") + print(f"Frozen for the entire run: {', '.join(flags)}") + + for epoch in range(n_epochs): + _set_pose_grad_state(epoch) + if epoch == 0 and n_gaussian_only_epochs > 0: + print(f"Epochs 0..{n_gaussian_only_epochs - 1}: all poses " + f"frozen (Gaussian-only warmup).") + if epoch == n_gaussian_only_epochs: + print(f"Epoch {epoch}: warmup over; pose optimization on " + f"(per freeze_* flags).") + + # Discrete rotation search: runs at the warmup boundary (when + # poses unfreeze for the first time, Gaussians are settled enough + # to score candidates well) and optionally every K epochs after. + if rotation_search_n_candidates > 0 and not freeze_object_rot: + do_search = (epoch == n_gaussian_only_epochs) + if rotation_search_period > 0 and epoch >= n_gaussian_only_epochs: + do_search = do_search or ( + (epoch - n_gaussian_only_epochs) % rotation_search_period == 0 + ) + if do_search: + pbar.set_description(f"refine (rot search at epoch {epoch})") + n_upd = _discrete_rotation_search( + obj_gaussians = obj_gaussians, + obj_pose_field = obj_pose_field, + optimizer = optimizer, + cache = cache, + K=K, W=W, H=H, device=device, + n_candidates = rotation_search_n_candidates, + local_frac = rotation_search_local_frac, + local_max_deg = rotation_search_local_max_deg, + silhouette_weight = rotation_search_silhouette_weight, + smoothness_weight = rotation_search_smoothness_weight, + seed = seed + epoch, + ) + print(f"Rotation search updated {n_upd}/{n_frames} frames.") + pbar.set_description("refine") + + order = rng.permutation(n_frames) # frame visit order + for batch_start in range(0, n_frames, batch_size): + batch_ts = order[batch_start : batch_start + batch_size] + + optimizer.zero_grad(set_to_none=True) + total = 0.0 + + # Coarse-to-fine multiplier on Gaussian render-scales for this batch. + # Constant within the batch so all sampled frames see the same blur. + if coarse_init_scale_factor != 1.0: + anneal_progress = min( + step_count / max(1, coarse_decay_steps - 1), 1.0 + ) + coarse_scale_mul = math.exp( + math.log(coarse_init_scale_factor) * (1.0 - anneal_progress) + ) + else: + coarse_scale_mul = 1.0 + + # Dynamic per-frame confidence (recomputed each batch from + # current pose state). Multiplies with the static confidence. + if pose_confidence_dynamic_tau > 0.0: + pose_confidence_dyn = _compute_dynamic_pose_confidence() + else: + pose_confidence_dyn = None + + # ---- batched per-frame compute (cache + poses) ---------------- + # Single-pass index tensor for the batch. All per-frame quantities + # that don't depend on Gaussian rasterization (MANO LBS, object + # pose, bg pose, cache fetches) are computed in one big tensor op + # here, instead of B small ops in the per-frame loop below. The + # ManoLayer call alone goes from ~B kernel-launch-bound batch=1 + # invocations to a single batch=B invocation — biggest single win. + batch_ts_t = torch.as_tensor( + [int(x) for x in batch_ts], device=device, dtype=torch.long + ) + B = int(batch_ts_t.shape[0]) + + # Cache fetch — single H2D transfer per buffer instead of B. + batch_rgb = cache.rgb[batch_ts_t.cpu()].to(device, non_blocking=True) # (B, H, W, 3) + batch_obj_mask = cache.obj_mask[batch_ts_t.cpu()].to(device, non_blocking=True) # (B, H, W) + batch_hand_msks = [ + m[batch_ts_t.cpu()].to(device, non_blocking=True) for m in cache.hand_masks + ] # list of (B, H, W) + batch_depth = ( + cache.depth[batch_ts_t.cpu()].to(device, non_blocking=True) + if cache.depth is not None else None + ) # (B, H, W) or None + # Union mask per batch member (vectorized). Gated by the static + # ``valid_pixel`` mask so fisheye black corners / dead-border + # pixels never enter photometric / depth / SuGaR supervision, + # even if a SAM2 mask spuriously leaked into them. + batch_union = batch_obj_mask.clone() + for hm in batch_hand_msks: + batch_union = torch.maximum(batch_union, hm) + batch_union = batch_union * valid_pixel_mask # (B, H, W) * (H, W) + + # Fresh intrinsics K per step. When neither learn_focal nor + # learn_principal_point is set, this returns a tensor with + # requires_grad=False, so no autograd cost. + K = intrinsics_field.K() + + # Poses, batched. + R_obj_b, t_obj_b = obj_pose_field.batched_forward(batch_ts_t) # (B, 3, 3), (B, 3) + hand_batched: list[tuple[torch.Tensor, torch.Tensor]] = [] + wrist_batched: list[tuple[torch.Tensor, torch.Tensor] | None] = [] + for slot in hand_slots: + hv, hr = slot.pose_field.batched_posed_verts_and_rotmats_camera(batch_ts_t) + hand_batched.append((hv, hr)) # (B, V, 3), (B, V, 3, 3) + if slot.wrist_gaussians is not None: + Rw, tw = slot.pose_field.batched_wrist_pose_camera(batch_ts_t) # (B, 3, 3), (B, 3) + wrist_batched.append((Rw, tw)) + else: + wrist_batched.append(None) + if bg_gaussians is not None: + R_bg_b, t_bg_b = bg_pose_field.batched_forward(batch_ts_t) # (B, 3, 3), (B, 3) + + # Per-frame losses, summed across the batch then backward once. + for i, t in enumerate(batch_ts): + t = int(t) + obj_mask = batch_obj_mask[i] + hand_msks = [hm[i] for hm in batch_hand_msks] + union_mask = batch_union[i] + target_rgb_t = batch_rgb[i] + + obj_frame = obj_gaussians(R_obj_b[i], t_obj_b[i]) + hand_frames = [ + slot.gaussians(hv[i], hr[i]) + for slot, (hv, hr) in zip(hand_slots, hand_batched) + ] + # Wrist-attached arm Gaussians (one per slot, may be None). + # Concat order must match labels_static: obj + hands + wrist + bg. + wrist_frames = [] + for slot, wb in zip(hand_slots, wrist_batched): + if slot.wrist_gaussians is not None and wb is not None: + Rw, tw = wb + wrist_frames.append(slot.wrist_gaussians(Rw[i], tw[i])) + bg_frame = None + if bg_gaussians is not None: + bg_frame = bg_gaussians(R_bg_b[i], t_bg_b[i]) + + all_frames = [obj_frame] + hand_frames + wrist_frames + if bg_frame is not None: + all_frames.append(bg_frame) + combined = concat_frames(all_frames) + if coarse_scale_mul != 1.0: + combined = dataclasses.replace( + combined, scales=combined.scales * coarse_scale_mul + ) + + # Class labels are static (depend only on Gaussian counts); + # built once at startup as ``labels_static``. + _compute_dvar = weights.depth_variance > 0.0 + rgb_pred, depth_pred, _, class_pred, depth_var_pred = render_rgb_depth( + combined, K, W, H, + extra_features=labels_static, + compute_depth_variance=_compute_dvar, + ) + + # Photometric: + # - balance_photometric_by_mask: per-entity inverse-area + # weighting so each entity contributes equally. + # - else if bg_gaussians: full-image L1. + # - else: foreground-only L1 (or black-bg masked variant). + if balance_photometric_by_mask: + fl = weights.photometric * balanced_photometric_loss( + rgb_pred, target_rgb_t, + obj_mask, hand_msks, + include_background=(bg_gaussians is not None), + use_l2=use_l2_photometric, + ) + elif bg_gaussians is not None: + diff_full = rgb_pred - target_rgb_t + if use_l2_photometric: + fl = weights.photometric * (diff_full * diff_full).mean() + else: + fl = weights.photometric * diff_full.abs().mean() + else: + fl = weights.photometric * photometric_loss( + rgb_pred, target_rgb_t, union_mask, + mask_background_to_black=mask_background_to_black, + use_l2=use_l2_photometric, + ) + + # SSIM photometric — captures local structure (textures / + # edges) that pixel-wise L1 ignores. Mask choice mirrors the + # L1 path: full valid-pixel image when bg Gaussians explain + # the whole scene, foreground-only otherwise. + if weights.photometric_ssim > 0: + ssim_mask = ( + valid_pixel_mask if bg_gaussians is not None + else union_mask + ) + fl = fl + weights.photometric_ssim * photometric_ssim_loss( + rgb_pred, target_rgb_t, ssim_mask, + ) + + # Class-label silhouette target. + target_class = obj_mask.new_zeros((H, W, K_classes_static)) + target_class[..., 0] = obj_mask + for k_h, hmask in enumerate(hand_msks): + target_class[..., k_h + 1] = hmask + fl = fl + weights.silhouette * silhouette_loss( + class_pred, target_class, + class_weights=silhouette_class_weights, + use_l2=use_l2_silhouette, + ) + + if batch_depth is not None: + fl = fl + weights.depth * depth_loss( + depth_pred, batch_depth[i], union_mask) + if weights.log_depth_grad > 0: + # Shape-only depth prior. Gated on > 0 so the + # graph stays the same shape (no inf log) when off. + fl = fl + weights.log_depth_grad * depth_gradient_loss( + depth_pred, batch_depth[i], union_mask, + log_space=True, + ) + if weights.depth_ssim > 0: + # SSIM on log-depth — captures local depth structure + # (edges, plane orientation) that pointwise depth L1 + # misses. Percentile-normalized internally. + fl = fl + weights.depth_ssim * depth_ssim_loss( + depth_pred, batch_depth[i], union_mask, + ) + + # Depth-variance distortion (Mip-NeRF 360 distloss proxy). + # Mask choice mirrors the depth loss: foreground-only by + # default, full image when bg Gaussians explain the scene. + if depth_var_pred is not None: + _dvar_mask = ( + valid_pixel_mask if bg_gaussians is not None + else union_mask + ) + fl = fl + weights.depth_variance * depth_variance_loss( + depth_var_pred, _dvar_mask, + ) + + # FG/BG penetration: foreground Gaussians should sit in + # front of the background at every foreground pixel. Only + # active when bg exists and weight > 0; pays two extra + # render passes (fg-only and bg-only depth). Without this + # term, a misregistered hand or object can sink behind the + # bg cloud and the photometric loss won't see it. + if (bg_frame is not None + and weights.depth_ordering > 0 + and union_mask.sum() > 0): + fg_combined = concat_frames([obj_frame] + hand_frames) + _, depth_fg, _, _, _ = render_rgb_depth(fg_combined, K, W, H) + _, depth_bg, _, _, _ = render_rgb_depth(bg_frame, K, W, H) + fl = fl + weights.depth_ordering * depth_ordering_loss( + depth_fg, depth_bg, union_mask, + margin=weights.depth_ordering_margin, + ) + + # Confidence weighting (static × dynamic). + c_t = pose_confidence[t] + if pose_confidence_dyn is not None: + c_t = c_t * pose_confidence_dyn[t] + fl = fl * c_t + + total = total + fl + + # Average per-frame losses so loss magnitude is independent of B. + loss = total / float(len(batch_ts)) + + # Sequence-wide regularizers (computed once per step, not per-frame). + if getattr(obj_gaussians, "is_face_anchored", False): + # Face-anchored: Δp is in face-local (T, B, N) coords — + # asymmetric per-axis regularizer expresses "stay inside + # the volume" (heavy outward, free inward, light surface + # slide). Legacy delta_p_reg_obj weight is ignored here. + loss = loss + face_delta_p_regularizer( + obj_gaussians._delta_p, + w_tangent = weights.face_delta_p_tangent_obj, + w_normal_outward = weights.face_delta_p_normal_outward_obj, + w_normal_inward = weights.face_delta_p_normal_inward_obj, + ) + else: + loss = loss + weights.delta_p_reg_obj * delta_p_regularizer( + obj_gaussians._delta_p + ) + if weights.opacity_binary_obj > 0.0: + loss = loss + weights.opacity_binary_obj * opacity_binary_loss( + torch.sigmoid(obj_gaussians._opacity_logit) + ) + # Rotations get quat-aligned smoothness so axis-angle + # double-cover wraps don't induce phantom large differences. + # With smooth_obj_in_world + bg pose field, the smoothness is + # measured in *world frame* — the obj→cam pose is composed + # with bg's world→cam to express obj→world, so a moving camera + # doesn't drag the regularizer. + if smooth_obj_in_world and bg_pose_field is not None: + from .gaussians import axis_angle_to_quat, quat_mul, quat_to_rotmat + q_bg = axis_angle_to_quat(bg_pose_field.axis_angle) # (T, 4) + q_bg_inv = torch.cat([q_bg[..., :1], -q_bg[..., 1:]], dim=-1) # conjugate + q_oc = axis_angle_to_quat(obj_pose_field.axis_angle) # (T, 4) + q_ow = quat_mul(q_bg_inv, q_oc) # obj→world quat + R_bg_T = quat_to_rotmat(q_bg).transpose(-1, -2) # cam→world rot + t_ow = torch.einsum( + "tij,tj->ti", R_bg_T, + obj_pose_field.translation - bg_pose_field.translation, + ) + loss = loss + ( + weights.smooth_obj_rot * quat_smoothness(q_ow) + + weights.smooth_obj_trans * temporal_smoothness(t_ow) + ) + else: + loss = loss + ( + weights.smooth_obj_rot * rotation_smoothness(obj_pose_field.axis_angle) + + weights.smooth_obj_trans * temporal_smoothness(obj_pose_field.translation) + ) + # Tight prior on global object scale (log = 0 → s = 1). + loss = loss + weights.obj_scale_prior * ( + obj_gaussians._log_scale_global ** 2 + ) + # Intrinsics prior — only fires when any component is learnable. + # Without this, fx is degenerate with global scene scale on + # no-depth runs and will wander. + if intrinsics_field.has_learnable(): + loss = loss + w_intrinsics_prior * intrinsics_prior_loss( + intrinsics_field.fx, intrinsics_field.fy, + intrinsics_field.cx, intrinsics_field.cy, + intrinsics_field.fx_init, intrinsics_field.fy_init, + intrinsics_field.cx_init, intrinsics_field.cy_init, + ) + # Per-frame pose-init prior weighted by confidence: pulls + # high-confidence frames toward FoundationPose's input pose, + # leaves low-confidence frames free. + if w_pose_init_prior > 0.0: + loss = loss + w_pose_init_prior * pose_init_prior_loss( + obj_pose_field.axis_angle, + obj_pose_field.translation, + init_obj_axis_angle, + init_obj_translation, + pose_confidence, + ) + if bg_gaussians is not None: + loss = loss + weights.delta_p_reg_bg * delta_p_regularizer( + bg_gaussians._delta_p + ) + if weights.opacity_binary_bg > 0.0: + loss = loss + weights.opacity_binary_bg * opacity_binary_loss( + torch.sigmoid(bg_gaussians._opacity_logit) + ) + loss = loss + ( + weights.smooth_bg_rot * rotation_smoothness(bg_pose_field.axis_angle) + + weights.smooth_bg_trans * temporal_smoothness(bg_pose_field.translation) + ) + for slot in hand_slots: + if getattr(slot.gaussians, "is_face_anchored", False): + loss = loss + face_delta_p_regularizer( + slot.gaussians._delta_p, + w_tangent = weights.face_delta_p_tangent_hand, + w_normal_outward = weights.face_delta_p_normal_outward_hand, + w_normal_inward = weights.face_delta_p_normal_inward_hand, + ) + else: + loss = loss + weights.delta_p_reg_hand * delta_p_regularizer( + slot.gaussians._delta_p + ) + if weights.opacity_binary_hand > 0.0: + loss = loss + weights.opacity_binary_hand * opacity_binary_loss( + torch.sigmoid(slot.gaussians._opacity_logit) + ) + # Wrist-attached "arm" Gaussians: very loose Δp regularizer + # (they need to drift far from the wrist origin to fill the + # arm volume) and opacity binarization reuses the hand weight. + if slot.wrist_gaussians is not None: + loss = loss + w_delta_p_reg_wrist * delta_p_regularizer( + slot.wrist_gaussians._delta_p + ) + if weights.opacity_binary_hand > 0.0: + loss = loss + weights.opacity_binary_hand * opacity_binary_loss( + torch.sigmoid(slot.wrist_gaussians._opacity_logit) + ) + T_h = slot.pose_field.hand_pose.shape[0] + # Finger articulation is intrinsic to the hand, so its + # smoothness stays in cam frame regardless of the world-frame + # toggle. Only wrist rotation + translation are re-expressed. + if smooth_hand_in_world and bg_pose_field is not None: + from .gaussians import axis_angle_to_quat, quat_mul, quat_to_rotmat + q_bg = axis_angle_to_quat(bg_pose_field.axis_angle) + q_bg_inv = torch.cat([q_bg[..., :1], -q_bg[..., 1:]], dim=-1) + q_hc = axis_angle_to_quat(slot.pose_field.global_orient) + q_hw = quat_mul(q_bg_inv, q_hc) + R_bg_T = quat_to_rotmat(q_bg).transpose(-1, -2) + t_hw = torch.einsum( + "tij,tj->ti", R_bg_T, + slot.pose_field.cam_t - bg_pose_field.translation, + ) + loss = loss + ( + weights.smooth_hand_rot * quat_smoothness(q_hw) + + weights.smooth_hand_finger * rotation_smoothness(slot.pose_field.hand_pose.view(T_h, 15, 3)) + + weights.smooth_hand_trans * temporal_smoothness(t_hw) + ) + else: + loss = loss + ( + weights.smooth_hand_rot * rotation_smoothness(slot.pose_field.global_orient) + + weights.smooth_hand_finger * rotation_smoothness(slot.pose_field.hand_pose.view(T_h, 15, 3)) + + weights.smooth_hand_trans * temporal_smoothness(slot.pose_field.cam_t) + ) + loss = loss + weights.beta_prior * beta_prior_loss( + slot.pose_field.betas, slot.pose_field.betas_init + ) + if slot.pose_field.hand_scale.requires_grad: + loss = loss + weights.hand_scale_prior * hand_scale_prior_loss( + slot.pose_field.hand_scale, slot.pose_field.hand_scale_init + ) + + # SuGaR-style background regularization (bg only). All weights + # default to 0. The local proxy + scale anisotropy are + # pose-invariant so they run once per step against the world-frame + # bg. The paper-faithful SDF / normal losses need depth + a + # camera pose, so they pick a random frame from the batch. + sugar_active = ( + bg_gaussians is not None + and (weights.scale_aniso_bg > 0 or weights.density_bg > 0 + or weights.sdf_density_bg > 0 + or weights.normal_consistency_bg > 0) + ) + if sugar_active: + I3 = torch.eye(3, device=device) + z3 = torch.zeros(3, device=device) + bg_world = bg_gaussians(I3, z3) # GaussianFrame in world frame + if weights.scale_aniso_bg > 0: + loss = loss + weights.scale_aniso_bg * scale_anisotropy_loss(bg_world.scales) + if weights.density_bg > 0: + loss = loss + weights.density_bg * density_regularizer_local( + means = bg_world.means, + quats = bg_world.quats, + scales = bg_world.scales, + opacities = bg_world.opacities, + n_neighbors = n_density_neighbors, + subsample_frac = density_subsample_frac_bg, + ) + # Paper-faithful SDF + normal-consistency loss. Tie the + # Gaussian field to MoGe depth: pick a random batch frame + # to anchor against, evaluate ``sugar_sdf_losses``. + if (weights.sdf_density_bg > 0 or weights.normal_consistency_bg > 0) \ + and batch_depth is not None: + pick = int(torch.randint(0, B, (1,), device=device).item()) + R_bg_pick, t_bg_pick = bg_pose_field(int(batch_ts[pick])) + # bg pixels (not in object mask, not in any hand mask), + # additionally gated by the static valid-pixel mask so + # fisheye black corners / dead-border pixels don't + # pollute the SuGaR depth anchor. + bg_pixel_mask = ( + (1.0 - batch_union[pick].clamp(0.0, 1.0)) + * valid_pixel_mask + ) + sdf_loss, normal_loss = sugar_sdf_losses( + means = bg_world.means, + quats = bg_world.quats, + scales = bg_world.scales, + opacities = bg_world.opacities, + depth = batch_depth[pick], + K = K, + R_w2c = R_bg_pick, + t_w2c = t_bg_pick, + union_mask = bg_pixel_mask, + n_samples = n_sdf_samples_bg, + n_neighbors = n_sdf_neighbors_bg, + compute_normal = weights.normal_consistency_bg > 0, + ) + if weights.sdf_density_bg > 0: + loss = loss + weights.sdf_density_bg * sdf_loss + if weights.normal_consistency_bg > 0: + loss = loss + weights.normal_consistency_bg * normal_loss + + loss.backward() + optimizer.step() + if lr_scheduler is not None: + lr_scheduler.step() + step_count += 1 + pbar.update(1) + pbar.set_postfix(loss=f"{float(loss):.4f}", epoch=epoch) + + # Rotation outlier median-snap. Runs after optimizer.step() so + # the Adam-moment reset has its intended effect on the next + # step. Disabled when ``snap_rotation_outliers_every == 0``. + if (snap_rotation_outliers_every > 0 + and _snap_targets + and step_count % snap_rotation_outliers_every == 0): + with torch.no_grad(): + if "obj" in _snap_targets: + _snap_rotation_outliers( + obj_pose_field.axis_angle, optimizer, + window=snap_rotation_window, + threshold=snap_rotation_threshold, + verbose=snap_rotation_verbose, + label="obj", + ) + for slot in hand_slots: + if "hand_wrist" in _snap_targets: + _snap_rotation_outliers( + slot.pose_field.global_orient, optimizer, + window=snap_rotation_window, + threshold=snap_rotation_threshold, + verbose=snap_rotation_verbose, + label=f"hand-{slot.side}-wrist", + ) + if "hand_finger" in _snap_targets: + _snap_rotation_outliers( + slot.pose_field.hand_pose, optimizer, + window=snap_rotation_window, + threshold=snap_rotation_threshold, + verbose=snap_rotation_verbose, + label=f"hand-{slot.side}-finger", + ) + + if render_every > 0 and step_count % render_every == 0: + _dump_progress_frame( + progress_dir, step_count, debug_frame_t, cache, + K, W, H, device, + obj_gaussians, obj_pose_field, hand_slots, + bg_gaussians=bg_gaussians, bg_pose_field=bg_pose_field, + labels_static=labels_static, + ) + + if (checkpoint_every > 0 + and checkpoint_path is not None + and step_count % checkpoint_every == 0): + _write_refine_checkpoint( + checkpoint_path = checkpoint_path, + obj_gaussians = obj_gaussians, + obj_pose_field = obj_pose_field, + hand_slots = hand_slots, + bg_gaussians = bg_gaussians, + bg_pose_field = bg_pose_field, + intrinsics_field = intrinsics_field, + optimizer = optimizer, + lr_scheduler = lr_scheduler, + init_obj_axis_angle = init_obj_axis_angle, + init_obj_translation = init_obj_translation, + frame_indices = frame_indices, + step_count = step_count, + s_obj_learned = float(obj_gaussians.object_scale().detach()), + ) + + pbar.close() + + # Stitch progress frames into a video for easy review. + if render_every > 0 and progress_dir is not None: + _stitch_progress_video(progress_dir) + + # ----- save outputs ----------------------------------------------------- + s_obj_learned = float(obj_gaussians.object_scale().detach()) + print(f"Learned object scale: {s_obj_learned:.4f}") + refined_obj_track = obj_pose_field.export_track() + if refined_object_scale_path is None: + # Legacy path: bake the learned global scale into the per-frame + # Transform3d.scale so downstream renderers that read pd["scale"] + # see the correct size without needing to know about s_obj. + refined_obj_track.scales = refined_obj_track.scales * s_obj_learned + else: + # Clean path: keep per-frame scales as input, save the learned + # scale to its own JSON for explicit consumption by the renderer. + os.makedirs( + os.path.dirname(os.path.abspath(refined_object_scale_path)) or ".", + exist_ok=True, + ) + import json as _json + with open(refined_object_scale_path, "w") as f: + _json.dump({"scale": s_obj_learned}, f, indent=2) + print(f"Wrote learned object scale → {refined_object_scale_path}") + save_object_poses(refined_obj_track, refined_object_poses_dir) + print(f"Wrote refined object poses → {refined_object_poses_dir}") + for slot in hand_slots: + if slot.output_pose_dir is None: + continue + save_hand_poses(slot.pose_field.export_track(slot.track.raw_records), + slot.output_pose_dir) + print(f"Wrote refined {slot.side}-hand poses → {slot.output_pose_dir}") + + # ----- optional checkpoint save ---------------------------------------- + if checkpoint_path is not None: + s_obj_for_ckpt = float(obj_gaussians.object_scale().detach()) + _write_refine_checkpoint( + checkpoint_path = checkpoint_path, + obj_gaussians = obj_gaussians, + obj_pose_field = obj_pose_field, + hand_slots = hand_slots, + bg_gaussians = bg_gaussians, + bg_pose_field = bg_pose_field, + optimizer = optimizer, + lr_scheduler = lr_scheduler, + init_obj_axis_angle = init_obj_axis_angle, + init_obj_translation = init_obj_translation, + frame_indices = frame_indices, + step_count = step_count, + s_obj_learned = s_obj_for_ckpt, + ) + print(f"Wrote checkpoint → {checkpoint_path}") + + # Final overlay video — streamed render + ffmpeg encode in one pass. + _render_overlay_video_streaming( + cache, frame_indices, K, W, H, device, + obj_gaussians, obj_pose_field, hand_slots, + output_path=overlay_path, + bg_gaussians=bg_gaussians, bg_pose_field=bg_pose_field, + include_background=multiview_include_background, + ) + + +# --------------------------------------------------------------------------- +# Helpers +# --------------------------------------------------------------------------- + +def _find_frame_path(frames_dir: str, fidx: int) -> str: + for ext in (".png", ".jpg"): + p = os.path.join(frames_dir, f"{fidx:06d}{ext}") + if os.path.exists(p): + return p + raise FileNotFoundError(f"Frame {fidx:06d} not found in {frames_dir}") + + +_SEG_PALETTE = torch.tensor([ + [1.00, 0.00, 0.00], # class 0 (object) → red + [0.00, 1.00, 0.00], # class 1 (hand 0) → green + [0.20, 0.40, 1.00], # class 2 (hand 1) → blue + [1.00, 1.00, 0.00], # class 3 (extra hand) → yellow + [1.00, 0.00, 1.00], # class 4 → magenta + [0.00, 1.00, 1.00], # class 5 → cyan +], dtype=torch.float32) + + +def _dump_progress_frame( + progress_dir: str, + step: int, + t: int, + cache, + K, W: int, H: int, device, + obj_gaussians, obj_pose_field, hand_slots, + bg_gaussians=None, bg_pose_field=None, + labels_static: torch.Tensor | None = None, +) -> None: + """Render a single reference frame's overlay, segmentation, and depth. + + Cheap: one combined gsplat rasterization (with class labels packed as + extra features when ``labels_static`` is provided), so RGB + seg + depth + all come from the same pass. PNG outputs land in: + + progress_dir/{step:06d}.png - RGB overlay (legacy) + progress_dir/seg/{step:06d}.png - per-class color-coded mask + progress_dir/depth/{step:06d}.png - grayscale depth, percentile-normalized + """ + seg_dir = os.path.join(progress_dir, "seg") + depth_dir = os.path.join(progress_dir, "depth") + os.makedirs(seg_dir, exist_ok=True) + os.makedirs(depth_dir, exist_ok=True) + + with torch.no_grad(): + rgb = cache.rgb[t].to(device, non_blocking=True) + R_obj, t_obj = obj_pose_field(t) + obj_frame = obj_gaussians(R_obj, t_obj) + hand_frames = [] + wrist_frames = [] + for s in hand_slots: + v, R = s.pose_field.posed_verts_and_rotmats_camera(t) + hand_frames.append(s.gaussians(v, R)) + if s.wrist_gaussians is not None: + Rw, tw = s.pose_field.wrist_pose_camera(t) + wrist_frames.append(s.wrist_gaussians(Rw, tw)) + all_frames = [obj_frame] + hand_frames + wrist_frames + if bg_gaussians is not None: + R_bg, t_bg = bg_pose_field(t) + all_frames.append(bg_gaussians(R_bg, t_bg)) + combined = concat_frames(all_frames) + rgb_pred, depth_pred, alpha, class_pred, _ = render_rgb_depth( + combined, K, W, H, extra_features=labels_static, + ) + # ---- RGB overlay (legacy path) ---------------------------------- + if bg_gaussians is not None: + mix = rgb_pred + else: + mix = rgb * (1.0 - alpha.unsqueeze(-1)) + rgb_pred * alpha.unsqueeze(-1) + rgb_arr = (mix.clamp(0, 1) * 255).to(torch.uint8).cpu().numpy() + + # ---- Segmentation ----------------------------------------------- + # class_pred is (H, W, K) of compositd class probabilities. Pick a + # palette color per channel and blend by channel weight so the + # output also looks reasonable on pixels with multi-class overlap. + if class_pred is not None and class_pred.shape[-1] > 0: + K_classes = int(class_pred.shape[-1]) + palette = _SEG_PALETTE[:K_classes].to(device=device, dtype=class_pred.dtype) + if palette.shape[0] < K_classes: + # Extend with light gray for any classes beyond the palette. + pad = torch.full( + (K_classes - palette.shape[0], 3), 0.5, + dtype=palette.dtype, device=device, + ) + palette = torch.cat([palette, pad], dim=0) + seg_rgb = class_pred @ palette # (H, W, 3) + seg_arr = (seg_rgb.clamp(0, 1) * 255).to(torch.uint8).cpu().numpy() + else: + seg_arr = np.zeros((H, W, 3), dtype=np.uint8) + + # ---- Depth (percentile-normalized grayscale) -------------------- + d = depth_pred + valid = (d > 0) & torch.isfinite(d) + if valid.any(): + d_valid = d[valid] + lo = torch.quantile(d_valid, 0.05) + hi = torch.quantile(d_valid, 0.95) + rng = (hi - lo).clamp_min(1e-6) + d_norm = ((d - lo) / rng).clamp(0.0, 1.0) + d_norm = torch.where(valid, d_norm, torch.zeros_like(d_norm)) + else: + d_norm = torch.zeros_like(d) + depth_arr = (d_norm * 255).to(torch.uint8).cpu().numpy() + + Image.fromarray(rgb_arr).save(os.path.join(progress_dir, f"{step:06d}.png")) + Image.fromarray(seg_arr).save(os.path.join(seg_dir, f"{step:06d}.png")) + Image.fromarray(depth_arr, mode="L").save( + os.path.join(depth_dir, f"{step:06d}.png")) + + +def _stitch_progress_video(progress_dir: str, fps: float = 30.0) -> None: + """Stitch progress PNG sets into companion mp4s. + + Inputs (any may be absent): + progress_dir/*.png → progress_dir/../progress.mp4 + progress_dir/seg/*.png → progress_dir/../progress_seg.mp4 + progress_dir/depth/*.png → progress_dir/../progress_depth.mp4 + """ + parent = os.path.dirname(progress_dir.rstrip("/")) or "." + targets = [ + (progress_dir, "progress.mp4"), + (os.path.join(progress_dir, "seg"), "progress_seg.mp4"), + (os.path.join(progress_dir, "depth"), "progress_depth.mp4"), + ] + for src_dir, name in targets: + if not os.path.isdir(src_dir): + continue + pngs = [p for p in os.listdir(src_dir) if p.endswith(".png")] + if not pngs: + continue + out_path = os.path.join(parent, name) + # ffmpeg's -pattern_type glob handles non-contiguous step numbers cleanly. + try: + subprocess.run([ + "ffmpeg", "-y", "-loglevel", "error", + "-r", str(fps), + "-pattern_type", "glob", + "-i", os.path.join(src_dir, "*.png"), + "-c:v", "libx264", "-pix_fmt", "yuv420p", "-crf", "20", + out_path, + ], check=True) + print(f"Wrote progress video → {out_path}") + except subprocess.CalledProcessError: + print(f"Warning: failed to stitch progress video from {src_dir}") + + +def _snap_rotation_outliers( + axis_angle: torch.nn.Parameter, # (T, ..., 3) + optimizer: "torch.optim.Optimizer | None", + window: int = 3, + threshold: float = 1.0, + verbose: bool = False, + label: str = "", +) -> int: + """Detect-and-replace outlier rotations with the temporal median. + + For each (frame, joint) cell whose quat-distance from the quat-aligned + median of a (2*window+1)-frame window exceeds ``threshold``, overwrite + the cell's axis-angle with the median and reset Adam moments for that + cell so the optimizer doesn't immediately fight the snap with stale + momentum. + + Operates in-place on the parameter and the optimizer state. Returns + the count of (frame, joint) cells snapped. + + ``axis_angle`` can be (T, 3) — single rotation per frame, e.g. obj + axis_angle / hand global_orient — or (T, K, 3) / (T, K*3) — multiple + independent rotations per frame, e.g. hand_pose's 15 joints. Each + joint is processed independently so a single fingerstipping out + doesn't drag the whole hand_pose with it. + + Threshold of 1.0 in quat-distance corresponds to ~85° rotation, well + above any plausible single-frame motion (~5°→0.04, fast 30°→0.26). + """ + from .gaussians import axis_angle_to_quat + from .pose_fields import _quat_to_axis_angle + + shape = axis_angle.shape + T = int(shape[0]) + if T < 2: + return 0 + + # Normalize shape to (T, K, 3) where K = number of independent + # rotations per frame. (T, 3) → K=1; (T, 15, 3) → K=15; (T, 45) → K=15. + if len(shape) == 2 and shape[-1] == 3: + aa = axis_angle.detach().reshape(T, 1, 3) + elif len(shape) == 2 and shape[-1] % 3 == 0: + aa = axis_angle.detach().reshape(T, shape[-1] // 3, 3) + elif len(shape) == 3 and shape[-1] == 3: + aa = axis_angle.detach().reshape(T, shape[1], 3) + else: + raise ValueError( + f"_snap_rotation_outliers: unsupported axis_angle shape {tuple(shape)}; " + f"expected (T, 3), (T, K, 3), or (T, K*3)." + ) + K = aa.shape[1] + + # Convert all to quats up front (T, K, 4). + q_all = axis_angle_to_quat(aa) + new_aa = aa.clone() + snapped: list[tuple[int, int]] = [] + for t in range(T): + lo = max(0, t - window) + hi = min(T, t + window + 1) + if hi - lo < 2: + continue + for k in range(K): + q_t = q_all[t, k] # (4,) + q_win = q_all[lo:hi, k] # (W, 4) + # Sign-align all window quats with q_t (handles ±q double cover). + dot = (q_win * q_t).sum(dim=-1, keepdim=True) + q_aligned = torch.where(dot < 0, -q_win, q_win) + # Per-component median, then re-normalize. (Median isn't strictly + # a quat operation but is robust to one outlier and produces a + # near-unit quat when the window is mostly consistent.) + q_med = q_aligned.median(dim=0).values # (4,) + q_med = q_med / q_med.norm().clamp_min(1e-8) + d = (q_t - q_med).norm() + if float(d) > threshold: + aa_med = _quat_to_axis_angle(q_med) + new_aa[t, k] = aa_med + snapped.append((t, k)) + + if not snapped: + return 0 + + with torch.no_grad(): + axis_angle.copy_(new_aa.reshape(shape)) + if optimizer is not None: + state = optimizer.state.get(axis_angle, {}) + ea = state.get("exp_avg") + es = state.get("exp_avg_sq") + if ea is not None and es is not None: + ea_view = ea.reshape(T, K, 3) + es_view = es.reshape(T, K, 3) + for t, k in snapped: + ea_view[t, k].zero_() + es_view[t, k].zero_() + if verbose: + # Aggregate: list unique frame indices, joint count per frame. + per_frame: dict[int, int] = {} + for t, _ in snapped: + per_frame[t] = per_frame.get(t, 0) + 1 + details = ", ".join( + f"t={t}({per_frame[t]})" if K > 1 else f"t={t}" + for t in sorted(per_frame) + ) + print(f"[snap{':'+label if label else ''}] snapped {len(snapped)} " + f"cells over {len(per_frame)} frames: {details}") + return len(snapped) + + +def _generate_rotation_candidates( + current_rotmat: torch.Tensor, # (3, 3) + n_candidates: int, + n_local: int, + local_max_rad: float, + seed: int, +) -> torch.Tensor: + """Return (n_candidates, 3, 3) rotation matrices. + + Layout: + idx 0 — current rotation (so the search never regresses) + idx 1..n_local — local perturbations of current (axis-angle within + ±local_max_rad on a random axis) + idx n_local+1.. — global uniform-on-SO(3) rotations + """ + from .gaussians import axis_angle_to_quat, quat_to_rotmat + + device = current_rotmat.device + rots = [current_rotmat] + g = torch.Generator(device="cpu").manual_seed(seed) + + if n_local > 0: + axes = torch.randn(n_local, 3, generator=g) + axes = axes / axes.norm(dim=-1, keepdim=True).clamp_min(1e-8) + angles = torch.rand(n_local, generator=g) * local_max_rad + aa = (axes * angles.unsqueeze(-1)).to(device) + q_perturb = axis_angle_to_quat(aa) # (n_local, 4) + R_perturb = quat_to_rotmat(q_perturb) # (n_local, 3, 3) + # Apply perturbation in current frame: R = R_perturb @ R_current. + rots.append((R_perturb @ current_rotmat.unsqueeze(0)).reshape(-1, 3, 3)) + + n_global = n_candidates - 1 - n_local + if n_global > 0: + # Uniform on SO(3) via random unit quaternions. + q_rand = torch.randn(n_global, 4, generator=g) + q_rand = q_rand / q_rand.norm(dim=-1, keepdim=True).clamp_min(1e-8) + # Convert (x,y,z,w) order doesn't matter here since we feed straight + # to quat_to_rotmat which expects (w,x,y,z) — randn samples are + # rotation-isotropic either way. + R_global = quat_to_rotmat(q_rand.to(device)) # (n_global, 3, 3) + rots.append(R_global) + + out = torch.cat([r if r.dim() == 3 else r.unsqueeze(0) for r in rots], dim=0) + return out + + +def _discrete_rotation_search( + obj_gaussians, + obj_pose_field, + optimizer, + cache, + K, W: int, H: int, device, + n_candidates: int, + local_frac: float, + local_max_deg: float, + silhouette_weight: float, + smoothness_weight: float, + seed: int, +) -> int: + """Per-frame batched rotation hypothesis search for the object pose. + + For each frame, render all N candidate rotations in a *single* gsplat + call (each candidate is a different viewmat sharing the same Gaussian + set in canonical frame), score by photometric L1 + silhouette IoU + against the SAM2 target, and snap the frame's axis_angle to the best + candidate. Optimizer state for the axis_angle parameter is cleared so + Adam's running moments don't fight the snap. + + Returns the number of frames whose pose was updated. + """ + from .gaussians import axis_angle_to_quat, quat_to_rotmat, rotmat_to_quat + from .pose_fields import _quat_to_axis_angle + from gsplat.rendering import rasterization + + n_frames = obj_pose_field.axis_angle.shape[0] + n_local = max(1, int(local_frac * (n_candidates - 1))) + n_local = min(n_local, n_candidates - 1) + + # Canonical Gaussians (object frame, with global object scale baked in). + # Calling forward(I, 0) gives positions in object frame. + with torch.no_grad(): + canon = obj_gaussians( + torch.eye(3, device=device), + torch.zeros(3, device=device), + ) + + n_updated = 0 + pbar = tqdm(range(n_frames), ncols=80, desc="rotation search") + with torch.no_grad(): + for t in pbar: + current_aa = obj_pose_field.axis_angle[t] + current_rot = quat_to_rotmat(axis_angle_to_quat(current_aa)) # (3, 3) + current_t = obj_pose_field.translation[t] # (3,) + + candidates = _generate_rotation_candidates( + current_rotmat=current_rot, + n_candidates=n_candidates, + n_local=n_local, + local_max_rad=float(local_max_deg) * 3.141592653589793 / 180.0, + seed=seed + t, + ) # (N, 3, 3) + N = candidates.shape[0] + + # Build (N, 4, 4) viewmats with same translation, varying rotation. + viewmats = torch.eye(4, device=device).unsqueeze(0).repeat(N, 1, 1) + viewmats[:, :3, :3] = candidates + viewmats[:, :3, 3] = current_t + + Ks = K.unsqueeze(0).expand(N, 3, 3).contiguous() + out, alphas, _ = rasterization( + means = canon.means, + quats = canon.quats, + scales = canon.scales, + opacities = canon.opacities, + colors = canon.colors, + viewmats = viewmats, + Ks = Ks, + width = W, + height = H, + render_mode = "RGB", + ) + # out: (N, H, W, 3); alphas: (N, H, W, 1) + + target_rgb = cache.rgb[t].to(device, non_blocking=True) # (H, W, 3) + target_mask = cache.obj_mask[t].to(device, non_blocking=True) # (H, W) + + photo = (out - target_rgb.unsqueeze(0)).abs().mean(dim=(1, 2, 3)) # (N,) + alpha = alphas[..., 0] # (N, H, W) + inter = (alpha * target_mask.unsqueeze(0)).sum(dim=(1, 2)) + denom = (alpha.sum(dim=(1, 2)) + target_mask.sum() - inter).clamp_min(1e-6) + iou = inter / denom + + score = -photo + silhouette_weight * iou # (N,) + + # Causal smoothness: penalize candidates that diverge from the + # previous (already-snapped) frame's rotation. Forward sweep is + # implicit in the for-t loop: by the time we score frame t, + # frame t-1 has its final snapped axis_angle. Quat-aligned + # squared distance handles the q ≡ -q double cover. + if t > 0 and smoothness_weight > 0.0: + q_cand = rotmat_to_quat(candidates) # (N, 4) + q_prev = axis_angle_to_quat( + obj_pose_field.axis_angle[t - 1].unsqueeze(0) + )[0] # (4,) + dot = (q_cand * q_prev.unsqueeze(0)).sum(dim=-1, keepdim=True) + q_prev_aligned = torch.where( + dot < 0, + -q_prev.unsqueeze(0).expand_as(q_cand), + q_prev.unsqueeze(0).expand_as(q_cand), + ) + smooth_pen = ((q_cand - q_prev_aligned) ** 2).sum(dim=-1) # (N,) + score = score - smoothness_weight * smooth_pen + + best = int(score.argmax()) + + if best != 0: + best_R = candidates[best] + # rotmat → quat → axis-angle. + best_q = rotmat_to_quat(best_R) + best_aa = _quat_to_axis_angle(best_q.unsqueeze(0))[0] + obj_pose_field.axis_angle.data[t] = best_aa + n_updated += 1 + + # Clear Adam state for the snapped parameter so running moments don't + # fight the new init. State will be lazily re-initialized on the next + # optimizer.step() call. + if obj_pose_field.axis_angle in optimizer.state: + optimizer.state[obj_pose_field.axis_angle] = {} + + return n_updated + + +def _render_overlay_sequence( + frames_dir, frame_indices, K, W, H, device, + obj_gaussians, obj_pose_field, hand_slots, + bg_gaussians=None, bg_pose_field=None, +) -> list[np.ndarray]: + """Render every frame as image * (1 - α) + render * α and return uint8 RGBs. + + Disk-reads source RGB per frame and accumulates into a list. Slow; kept + only for completeness. Production path is + ``_render_overlay_video_streaming`` which streams cache→render→ffmpeg + without materializing the full sequence in memory. + """ + out = [] + with torch.no_grad(): + for t, fidx in enumerate(frame_indices): + rgb = load_rgb(_find_frame_path(frames_dir, fidx), str(device)) + R_obj, t_obj = obj_pose_field(t) + obj_frame = obj_gaussians(R_obj, t_obj) + hand_frames = [] + wrist_frames = [] + for s in hand_slots: + v, R = s.pose_field.posed_verts_and_rotmats_camera(t) + hand_frames.append(s.gaussians(v, R)) + if s.wrist_gaussians is not None: + Rw, tw = s.pose_field.wrist_pose_camera(t) + wrist_frames.append(s.wrist_gaussians(Rw, tw)) + all_frames = [obj_frame] + hand_frames + wrist_frames + if bg_gaussians is not None: + R_bg, t_bg = bg_pose_field(t) + all_frames.append(bg_gaussians(R_bg, t_bg)) + combined = concat_frames(all_frames) + rgb_pred, _, alpha, _, _ = render_rgb_depth(combined, K, W, H) + if bg_gaussians is not None: + mix = rgb_pred + else: + mix = rgb * (1.0 - alpha.unsqueeze(-1)) + rgb_pred * alpha.unsqueeze(-1) + out.append((mix.clamp(0, 1) * 255).to(torch.uint8).cpu().numpy()) + return out + + +def _orbit_viewmat_cv(eye: np.ndarray, target: np.ndarray, up: np.ndarray) -> np.ndarray: + """world→camera (4, 4) in CV convention (cam +Z forward, +Y down).""" + fwd = target - eye + fwd = fwd / max(np.linalg.norm(fwd), 1e-8) + x = np.cross(up, fwd) + nx = np.linalg.norm(x) + if nx < 1e-6: + # up ∥ fwd: pick a fallback up perpendicular to fwd. + alt = np.array([1.0, 0.0, 0.0]) if abs(fwd[0]) < 0.9 else np.array([0.0, 1.0, 0.0]) + x = np.cross(alt, fwd) + nx = np.linalg.norm(x) + x = x / nx + y = np.cross(fwd, x) + R = np.stack([x, y, fwd], axis=0) # rows = world→cam basis + M = np.eye(4) + M[:3, :3] = R + M[:3, 3] = -R @ eye + return M + + +def _render_overlay_video_streaming( + cache, frame_indices, K, W, H, device, + obj_gaussians, obj_pose_field, hand_slots, + output_path: str, + bg_gaussians=None, bg_pose_field=None, + fps: float = 30.0, + include_background: bool = False, +) -> None: + """Multi-viewpoint overlay video, streamed render+ffmpeg in one pass. + + Per frame we render four panels in a single batched gsplat call (one + rasterization, four viewmats): + + [ src cam (image underlay) ] [ world top ] + [ world side ] [ world back ] + + World cameras orbit the *current frame's* object centroid, so each + frame is independently centered (matches the mesh-render grid in + v2d_hamer/render_hands_aligned_video.py — "world" is just whatever + coordinate frame the Gaussians live in for that frame, which is the + camera frame at time t). + + Cost: one rasterization at 4× viewmats per frame (gsplat handles the + 4-camera batch natively with shared Gaussians), plus PIL grid stitch. + """ + os.makedirs(os.path.dirname(os.path.abspath(output_path)) or ".", exist_ok=True) + + # Each panel is half resolution; the full 2x2 grid output is W × H. + pw = max(2, (W // 2) & ~1) # even, ≥ 2 + ph = max(2, (H // 2) & ~1) + grid_W = 2 * pw + grid_H = 2 * ph + + # Intrinsics for half-resolution panels. + K_panel = K.clone() + K_panel[0, 0] *= pw / W + K_panel[1, 1] *= ph / H + K_panel[0, 2] *= pw / W + K_panel[1, 2] *= ph / H + + from gsplat.rendering import rasterization + panel_labels = ["src cam", "top", "side", "behind"] + + proc = subprocess.Popen( + [ + "ffmpeg", "-y", "-loglevel", "error", + "-f", "rawvideo", + "-pixel_format", "rgb24", + "-video_size", f"{grid_W}x{grid_H}", + "-framerate", str(fps), + "-i", "pipe:0", + "-c:v", "libx264", "-pix_fmt", "yuv420p", "-crf", "20", + output_path, + ], + stdin=subprocess.PIPE, + ) + + pbar = tqdm(total=len(frame_indices), ncols=80, desc="overlay video") + try: + with torch.no_grad(): + bg_zeros = torch.zeros(4, 3, device=device, dtype=torch.float32) + for t, _fidx in enumerate(frame_indices): + # Source image at panel resolution. + src_rgb_full = cache.rgb[t].to(device, non_blocking=True) # (H, W, 3) + src_rgb_panel = torch.nn.functional.interpolate( + src_rgb_full.permute(2, 0, 1).unsqueeze(0), + size=(ph, pw), mode="bilinear", align_corners=False, + ).squeeze(0).permute(1, 2, 0).contiguous() # (ph, pw, 3) + + # Build per-frame Gaussian set in current cam frame. + # By default we exclude the background Gaussians so the + # orbit panels show only the trained foreground (object + + # hands) — easier to read shape/pose quality. The src-cam + # panel uses the same foreground-only render and gets + # composited over the source image, recovering the + # "scene with foreground overlay" look. + R_obj, t_obj = obj_pose_field(t) + obj_frame = obj_gaussians(R_obj, t_obj) + hand_frames = [] + wrist_frames = [] + for s in hand_slots: + v, R = s.pose_field.posed_verts_and_rotmats_camera(t) + hand_frames.append(s.gaussians(v, R)) + if s.wrist_gaussians is not None: + Rw, tw = s.pose_field.wrist_pose_camera(t) + wrist_frames.append(s.wrist_gaussians(Rw, tw)) + all_frames = [obj_frame] + hand_frames + wrist_frames + if include_background and bg_gaussians is not None: + R_bg, t_bg = bg_pose_field(t) + all_frames.append(bg_gaussians(R_bg, t_bg)) + combined = concat_frames(all_frames) + + # Object centroid + radius in current cam frame (used for orbit). + obj_means = obj_frame.means + centroid_t = obj_means.mean(dim=0) + radius_t = (obj_means - centroid_t).norm(dim=-1).max().clamp_min(0.05) + centroid = centroid_t.cpu().numpy() + r = float(radius_t) * 2.5 + + # Four viewmats: + # 0: src cam (identity — Gaussians already in cam frame). + # 1: top — eye above (-Y), looking down; image-up = +Z (forward). + # 2: side — eye to the right (+X), looking inward. + # 3: behind — eye in +Z (further than centroid), looking back. + viewmats_np = np.stack([ + np.eye(4), + _orbit_viewmat_cv(centroid + np.array([0.0, -r, 0.0]), + centroid, up=np.array([0.0, 0.0, 1.0])), + _orbit_viewmat_cv(centroid + np.array([ r, 0.0, 0.0]), + centroid, up=np.array([0.0, -1.0, 0.0])), + _orbit_viewmat_cv(centroid + np.array([0.0, 0.0, r]), + centroid, up=np.array([0.0, -1.0, 0.0])), + ], axis=0) + viewmats = torch.from_numpy(viewmats_np).to(device, dtype=torch.float32) + Ks_4 = K_panel.unsqueeze(0).expand(4, 3, 3).contiguous() + + out, alphas, _ = rasterization( + means=combined.means, + quats=combined.quats, + scales=combined.scales, + opacities=combined.opacities, + colors=combined.colors, + viewmats=viewmats, + Ks=Ks_4, + width=pw, height=ph, + near_plane=0.01, + far_plane=100.0, + render_mode="RGB", + backgrounds=bg_zeros, + ) + rgb_pred = out[..., :3].clamp(0, 1) # (4, ph, pw, 3) + a0 = alphas[0, ..., 0].unsqueeze(-1) # (ph, pw, 1) + + # Panel 0: blend over source image. Panels 1-3: just the render + # (against black bg, or full scene if bg gaussians active). + panel_0 = src_rgb_panel * (1.0 - a0) + rgb_pred[0] * a0 + + grid = torch.zeros(grid_H, grid_W, 3, device=device) + grid[:ph, :pw] = panel_0 + grid[:ph, pw:] = rgb_pred[1] + grid[ph:, :pw] = rgb_pred[2] + grid[ph:, pw:] = rgb_pred[3] + + arr = (grid * 255).clamp(0, 255).to(torch.uint8).cpu().numpy() + arr = np.ascontiguousarray(arr) + + # Panel labels via PIL (cheap — adds ~1 ms/frame). + img = Image.fromarray(arr) + draw = ImageDraw.Draw(img) + font = _font_cached() + for i, label in enumerate(panel_labels): + x0 = (i % 2) * pw + 6 + y0 = (i // 2) * ph + 6 + tw = draw.textlength(label, font=font) + draw.rectangle([x0, y0, x0 + tw + 8, y0 + 22], fill=(0, 0, 0)) + draw.text((x0 + 4, y0 + 3), label, fill=(255, 255, 255), font=font) + arr = np.ascontiguousarray(np.asarray(img, dtype=np.uint8)) + + proc.stdin.write(arr.tobytes()) + pbar.update(1) + finally: + try: + proc.stdin.close() + except BrokenPipeError: + pass + proc.wait() + pbar.close() + print(f"Wrote multi-view overlay video → {output_path}") + + +def _font_cached(): + """Lazy small bitmap font for grid labels.""" + try: + return ImageFont.truetype( + "/usr/share/fonts/truetype/dejavu/DejaVuSans-Bold.ttf", 16, + ) + except OSError: + return ImageFont.load_default() + + +# --------------------------------------------------------------------------- +# CLI +# --------------------------------------------------------------------------- + +def main() -> None: + p = argparse.ArgumentParser(description=__doc__) + p.add_argument("--frames_dir", required=True) + p.add_argument("--intrinsics_path", required=True) + p.add_argument("--object_mesh_path", required=True) + p.add_argument("--object_poses_dir", required=True) + p.add_argument("--object_mask_dir", required=True) + p.add_argument("--refined_object_poses_dir", required=True) + p.add_argument("--overlay_path", required=True) + p.add_argument("--refined_object_scale_path", default=None, + help="Optional path to write the learned global object " + "scale as a JSON file ``{\"scale\": float}``. When " + "set, per-frame Transform3d.scale is left as input " + "(scale is exported separately for the renderer).") + p.add_argument("--left_hand_pose_dir", default=None) + p.add_argument("--left_hand_mask_dir", default=None) + p.add_argument("--right_hand_pose_dir", default=None) + p.add_argument("--right_hand_mask_dir", default=None) + p.add_argument("--refined_left_hand_pose_dir", default=None) + p.add_argument("--refined_right_hand_pose_dir", default=None) + p.add_argument("--depth_dir", default=None) + p.add_argument("--mano_assets_root", default=None) + p.add_argument("--n_epochs", type=int, default=30, + help="Number of full passes over the sequence. Each " + "epoch visits every frame once in random order.") + p.add_argument("--n_gaussian_only_epochs", type=int, default=5, + help="Number of initial epochs with pose params frozen " + "(only Gaussian attributes update). Lets appearance " + "settle before poses start moving.") + p.add_argument("--batch_size", type=int, default=4, + help="Frames per optimizer step. Per-frame losses are " + "averaged; sequence-wide regularizers (smoothness, " + "beta prior) are applied once per step.") + p.add_argument("--lr_gaussians", type=float, default=1e-2, + help="LR for object Gaussian attributes.") + p.add_argument("--lr_hand_gaussians", type=float, default=None, + help="LR for hand Gaussian attributes (defaults to " + "--lr_gaussians). Bump up to compensate for the " + "smaller image area covered by hands.") + # Per-attribute LR multipliers — shared across object/hand/bg Gaussian + # sets, multiplied by their per-set base LR. Defaults of 1.0 preserve + # old single-LR behavior. Standard 3DGS-ish ratios (relative to base + # LR of 1e-2): delta_p≈0.016, quat≈0.1, scale≈0.5, opacity≈5, color≈0.25. + p.add_argument("--lr_mul_delta_p", type=float, default=1.0, + help="LR multiplier for Gaussian Δp (positions).") + p.add_argument("--lr_mul_quat", type=float, default=1.0, + help="LR multiplier for Gaussian quaternion.") + p.add_argument("--lr_mul_scale", type=float, default=1.0, + help="LR multiplier for Gaussian per-axis log-scale.") + p.add_argument("--lr_mul_opacity", type=float, default=1.0, + help="LR multiplier for Gaussian opacity logit.") + p.add_argument("--lr_mul_color", type=float, default=1.0, + help="LR multiplier for Gaussian color.") + p.add_argument("--lr_mul_obj_global_scale", type=float, default=1.0, + help="LR multiplier for the global object-scale scalar.") + p.add_argument("--lr_object_pose", type=float, default=1e-3, + help="Legacy lumped LR for object pose (axis_angle + " + "translation). Overridden by --lr_object_rot / " + "--lr_object_trans if those are set.") + p.add_argument("--lr_object_rot", type=float, default=None, + help="Object rotation LR; defaults to --lr_object_pose. " + "Bump (e.g. 3-5x trans) if rotation converges slowly.") + p.add_argument("--lr_object_trans", type=float, default=None, + help="Object translation LR; defaults to --lr_object_pose.") + p.add_argument("--lr_hand_pose", type=float, default=1e-3, + help="Legacy lumped LR for hand pose; overridden by " + "--lr_hand_global_orient / --lr_hand_finger / " + "--lr_hand_trans if those are set.") + p.add_argument("--lr_hand_global_orient", type=float, default=None, + help="Hand wrist/root rotation LR.") + p.add_argument("--lr_hand_finger", type=float, default=None, + help="Hand finger articulation LR (15 joint axis-angles). " + "Often kept lower than global_orient/trans because " + "fingers tend to oscillate under photometric pull.") + p.add_argument("--lr_hand_trans", type=float, default=None, + help="Hand cam_t LR.") + p.add_argument("--lr_betas", type=float, default=1e-4) + p.add_argument("--render_every", type=int, default=0, + help="Every N optimizer steps, dump an overlay PNG of " + "the reference frame to --progress_dir. Stitched " + "into progress.mp4 at the end. 0 disables.") + p.add_argument("--progress_dir", default=None, + help="Directory for per-step progress PNGs. Defaults " + "to /progress/.") + p.add_argument("--debug_frame_idx", type=int, default=None, + help="Reference frame index for progress dumps " + "(defaults to the first frame in the sequence).") + p.add_argument("--w_photometric", type=float, default=1.0) + p.add_argument("--w_silhouette", type=float, default=0.5) + p.add_argument("--w_silhouette_obj", type=float, default=1.0, + help="Per-class relative weight for the object mask.") + p.add_argument("--w_silhouette_hand", type=float, default=1.0, + help="Per-class relative weight for hand masks. " + "Drop below 1.0 (e.g. 0.3) when SAM2 hand masks " + "are noisier than the object mask.") + p.add_argument("--w_depth", type=float, default=0.05) + p.add_argument("--w_log_depth_grad", type=float, default=0.0, + help="L1 on the gradient of log(depth) — scale-invariant " + "shape prior that complements --w_depth. Tolerates " + "MoGe's scale/offset bias by only penalizing wrong " + "local geometry. Try ~0.1× of w_depth as a start.") + p.add_argument("--w_photometric_ssim", type=float, default=0.0, + help="SSIM photometric loss weight (1 - SSIM, 11x11 " + "Gaussian window). Captures local texture/edge " + "structure that pixel-wise L1 misses. 3DGS default " + "pairs at ~0.2 (with w_photometric=1.0).") + p.add_argument("--w_depth_ssim", type=float, default=0.0, + help="SSIM depth loss weight (1 - SSIM on log-depth, " + "percentile-normalized). Captures local depth " + "structure (edges, plane orientation) that " + "pointwise depth L1 misses. Try ~0.1.") + p.add_argument("--w_smooth_obj_rot", type=float, default=0.01, + help="Smoothness weight for object rotation (axis-angle, " + "in quat space). Set to 0 to disable rotation " + "smoothness while keeping translation smoothness.") + p.add_argument("--w_smooth_obj_trans", type=float, default=0.01) + p.add_argument("--w_smooth_hand_rot", type=float, default=0.01, + help="Smoothness weight for hand global_orient.") + p.add_argument("--w_smooth_hand_finger", type=float, default=0.001, + help="Smoothness weight for finger articulation " + "(hand_pose, 15 joints). Default is 10x smaller " + "than --w_smooth_hand_rot since each finger joint " + "carries much weaker photometric signal — keeping " + "this low lets fingers articulate freely.") + p.add_argument("--w_smooth_hand_trans", type=float, default=0.01) + p.add_argument("--w_beta_prior", type=float, default=10.0) + p.add_argument("--learn_hand_scale", action="store_true", + help="Optimize the per-track hand_scale buffer (init from " + "align_hands' n_pixels-weighted median). Off by " + "default; the init is usually already good and " + "betas covers the same DoF.") + p.add_argument("--lr_hand_scale", type=float, default=1e-3, + help="LR for hand_scale when --learn_hand_scale is set.") + p.add_argument("--w_hand_scale_prior", type=float, default=10.0, + help="Tight prior pulling hand_scale back to the " + "align_hands estimate (only active when " + "--learn_hand_scale).") + p.add_argument("--w_delta_p_reg", type=float, default=100.0, + help="Fallback L2 penalty on Gaussian Δp. Applied to " + "object + hand + bg unless overridden by " + "--w_delta_p_reg_{obj,hand,bg}.") + p.add_argument("--w_delta_p_reg_obj", type=float, default=None, + help="Override Δp penalty for object Gaussians " + "(falls back to --w_delta_p_reg when unset).") + p.add_argument("--w_delta_p_reg_hand", type=float, default=None, + help="Override Δp penalty for hand Gaussians " + "(falls back to --w_delta_p_reg when unset).") + p.add_argument("--w_delta_p_reg_bg", type=float, default=None, + help="Override Δp penalty for background Gaussians " + "(falls back to --w_delta_p_reg when unset). " + "Lower this (e.g. 1.0–10.0) to let bg breathe.") + # ---- Face-anchored Gaussian options -------------------------------------- + p.add_argument("--object_anchor_mode", choices=["vertex", "face"], + default="vertex", + help="How object Gaussians are anchored to the mesh. " + "'vertex' (legacy): one Gaussian per mesh vertex with " + "free Δp. 'face': one Gaussian per mesh face, anchored " + "at the centroid with orientation from the face TBN " + "frame and Δp in face-local (T, B, N) coords. " + "In 'face' mode the asymmetric per-axis regularizer " + "(--w_face_delta_p_*_obj) replaces --w_delta_p_reg_obj, " + "and --n_obj_gaussians is ignored.") + p.add_argument("--hand_anchor_mode", choices=["vertex", "face"], + default="vertex", + help="Same as --object_anchor_mode, for hand Gaussians. " + "'face' mode uses one Gaussian per MANO face (1538). " + "Per-frame TBN is recomputed from the deformed face " + "vertices — no LBS weight inheritance approximation. " + "--n_hand_gaussians is ignored in this mode.") + p.add_argument("--face_normal_thin_factor_obj", type=float, default=0.25, + help="Init thinness of object face Gaussians along the " + "face normal: normal sigma = factor * tangent sigma. " + "Default 0.25 gives a disk shape; lower values flatter.") + p.add_argument("--face_normal_thin_factor_hand", type=float, default=0.25, + help="Init thinness of hand face Gaussians (see above).") + p.add_argument("--w_face_delta_p_tangent_obj", type=float, default=1.0, + help="Object face-anchor Δp penalty along tangent + " + "bitangent (surface slide). Light by default.") + p.add_argument("--w_face_delta_p_normal_outward_obj", type=float, default=100.0, + help="Object face-anchor Δp penalty along outward normal " + "(Δp_N > 0). Heavy by default — this is the " + "'stay inside the mesh volume' constraint.") + p.add_argument("--w_face_delta_p_normal_inward_obj", type=float, default=0.0, + help="Object face-anchor Δp penalty along inward normal " + "(Δp_N < 0). Free by default — Gaussians may sink " + "into the volume under photometric pull.") + p.add_argument("--w_face_delta_p_tangent_hand", type=float, default=1.0, + help="Hand face-anchor Δp penalty along tangent + bitangent.") + p.add_argument("--w_face_delta_p_normal_outward_hand", type=float, default=100.0, + help="Hand face-anchor Δp penalty along outward normal.") + p.add_argument("--w_face_delta_p_normal_inward_hand", type=float, default=0.0, + help="Hand face-anchor Δp penalty along inward normal.") + # ---- Opacity binarization ------------------------------------------------ + p.add_argument("--w_opacity_binary", type=float, default=0.0, + help="Fallback weight for the α(1-α) opacity binarization " + "penalty. Applied to object + hand + bg unless overridden " + "by --w_opacity_binary_{obj,hand,bg}. 0 disables. " + "Pushes each Gaussian's opacity toward 0 or 1; " + "low-opacity Gaussians effectively drop out.") + p.add_argument("--w_opacity_binary_obj", type=float, default=None, + help="Override opacity binarization weight for object Gaussians " + "(falls back to --w_opacity_binary).") + p.add_argument("--w_opacity_binary_hand", type=float, default=None, + help="Override opacity binarization weight for hand Gaussians " + "(falls back to --w_opacity_binary).") + p.add_argument("--w_opacity_binary_bg", type=float, default=None, + help="Override opacity binarization weight for background " + "Gaussians (falls back to --w_opacity_binary).") + p.add_argument("--w_depth_variance", type=float, default=0.0, + help="Depth-variance distortion loss weight (Mip-NeRF 360 " + "distloss proxy). Penalizes the alpha-weighted " + "variance of depth at each pixel, killing floaters " + "and compacting the surface along the view ray. " + "Units are [depth²] — for ~0.1 m scenes, variance " + "is ~0.01, so weight ~1.0 is comparable to other " + "regularizers. 0 disables.") + p.add_argument("--w_depth_ordering", type=float, default=0.0, + help="Foreground/background depth-ordering penetration " + "weight. Penalizes relu(depth_fg - depth_bg) at " + "foreground-mask pixels — discourages hand/object " + "Gaussians from sinking behind the background. " + "Active only when --with_background is set and " + "weight > 0 (pays two extra render passes per " + "frame). Units: [depth]. 0 disables.") + p.add_argument("--depth_ordering_margin", type=float, default=0.0, + help="Slack (m) in the depth-ordering inequality: " + "require depth_fg ≤ depth_bg - margin. Positive " + "margin enforces a gap, zero allows touching.") + p.add_argument("--w_obj_scale_prior", type=float, default=1.0, + help="Tight Gaussian prior on log(global object scale). " + "Pulls scale toward 1.0; raise to freeze, lower to " + "let scale move freely.") + # SuGaR-style background surface alignment (bg only). 0 = disabled. + p.add_argument("--w_scale_aniso_bg", type=float, default=0.0, + help="Background Gaussian flatness penalty " + "(mean min/max scale). Push toward thin-disk shape. " + "0 disables.") + p.add_argument("--w_density_bg", type=float, default=0.0, + help="SuGaR density regularizer for background. Probes " + "Gaussian field density at +/- s_min along each " + "anchor's normal and pulls toward thin-shell ideal. " + "0 disables.") + p.add_argument("--w_sdf_density_bg", type=float, default=0.0, + help="Paper-faithful SuGaR SDF loss for bg (Eq. 7-8). " + "Anchors Gaussians to MoGe depth via |f̂(p) − f(p)|. " + "0 disables. Typical range 0.01-0.5.") + p.add_argument("--w_normal_consistency_bg", type=float, default=0.0, + help="Paper-faithful SuGaR normal-consistency loss for bg " + "(Eq. 10). Aligns the implicit field's gradient with " + "the closest Gaussian's smallest-scale axis. 0 " + "disables. Typical range 0.01-0.5.") + p.add_argument("--n_sdf_samples_bg", type=int, default=1000, + help="Number of probe points per step for the SuGaR SDF " + "loss (paper samples ~10K; we default to 1K for " + "tractability).") + p.add_argument("--n_sdf_neighbors_bg", type=int, default=8, + help="K for the SDF loss's KNN mixture sum.") + p.add_argument("--valid_mask_threshold", type=float, default=0.04, + help="Max-brightness threshold (in [0,1] image scale) for " + "the static valid-pixel mask derived from the input " + "video. Pixels whose max brightness across all frames " + "is below this are treated as fixed dead/black " + "regions (fisheye crop, vignette) and excluded from " + "photometric / depth / SuGaR supervision. 0 disables.") + p.add_argument("--valid_mask_erode_iters", type=int, default=2, + help="3x3 erosion passes on the valid-pixel mask, to peel " + "back the soft boundary transition.") + p.add_argument("--n_density_neighbors", type=int, default=8, + help="K for the density-regularizer's KNN mixture sum.") + p.add_argument("--density_subsample_frac_bg", type=float, default=0.2, + help="Fraction of bg Gaussians sampled as probe anchors " + "each step. 1.0 = all (slow on large scenes); 0.2 " + "is the default cost/quality balance.") + p.add_argument("--mask_background_to_black", action="store_true", + help="Zero target's background and compute photometric " + "L1 over all pixels. Penalizes Gaussian leaks " + "outside the mask but makes mask errors costly.") + p.add_argument("--balance_photometric_by_mask", action="store_true", + help="Per-pixel weight = 1/N_entity so object, each " + "hand, and (when --with_background) background " + "contribute equally to the photometric loss " + "regardless of pixel count. Prevents the largest " + "region from dominating the loss.") + p.add_argument("--freeze_object_rot", action="store_true", + help="Hold object rotation at its input value for the " + "entire run.") + p.add_argument("--freeze_object_trans", action="store_true", + help="Hold object translation at its input value.") + p.add_argument("--freeze_object_scale", action="store_true", + help="Hold global object scale at 1.0.") + p.add_argument("--freeze_hand_rot", action="store_true", + help="Hold hand rotations (global_orient + hand_pose) " + "at their input values for the entire run.") + p.add_argument("--freeze_hand_trans", action="store_true", + help="Hold hand cam_t at its input value.") + p.add_argument("--with_background", action="store_true", + help="Add background Gaussians (initialized from MoGe " + "depth at the reference frame) and a per-frame " + "rigid background→camera pose. Switches photometric " + "to a full-image L1.") + p.add_argument("--bg_ref_frame", type=int, default=None, + help="Reference frame index for background init. " + "Defaults to --debug_frame_idx, then frame 0.") + p.add_argument("--lr_bg_gaussians", type=float, default=None, + help="LR for background Gaussian attributes " + "(defaults to --lr_gaussians).") + p.add_argument("--lr_bg_pose", type=float, default=1e-3, + help="Legacy lumped LR for background pose; overridden " + "by --lr_bg_rot / --lr_bg_trans if those are set.") + p.add_argument("--lr_bg_rot", type=float, default=None) + p.add_argument("--lr_bg_trans", type=float, default=None) + p.add_argument("--bg_max_points", type=int, default=50000, + help="Subsample background point cloud to this size.") + p.add_argument("--background_pose_init_dir", default=None, + help="Optional folder of per-frame `Transform3d` JSONs " + "(camera-to-world; DROID/COLMAP convention) used " + "to seed the background pose field. With this set, " + "non-reference frames start at the relative pose " + "implied by the VO/SfM solution instead of identity, " + "which is the right basin for moving/egocentric " + "cameras.") + p.add_argument("--bg_init_stride", type=int, default=10, + help="When background_pose_init_dir is set, fuse the BG " + "point cloud from MoGe depth at every Nth frame " + "(in addition to ref). 1 or 0 forces single-frame " + "(ref-only) init.") + p.add_argument("--bg_voxel_size", type=float, default=0.005, + help="Voxel size (metres) used to dedup the fused BG " + "point cloud before the final random subsample. " + "Smaller = denser; 0 disables voxel dedup.") + p.add_argument("--n_obj_gaussians", type=int, default=None, + help="Resample the object mesh surface to exactly this " + "many Gaussians. Default uses the mesh's vertex " + "count; useful for high-poly meshes (decimate) " + "or low-poly (densify on the surface).") + p.add_argument("--n_hand_gaussians", type=int, default=None, + help="Subsample the 778 MANO vertices down to this " + "many Gaussians per hand. Default uses all 778. " + "Values > 778 are clipped (supersampling would " + "require barycentric LBS).") + p.add_argument("--use_cosine_lr_schedule", action="store_true", + help="Apply a cosine LR decay across all param groups " + "over the full run. Per-group LR ratios are " + "preserved (each group's initial LR is multiplied " + "by the same cosine factor).") + p.add_argument("--cosine_lr_min_ratio", type=float, default=0.0, + help="Final LR as a fraction of initial LR when cosine " + "schedule is on (e.g. 0.1 = decays to 10%% of " + "initial; 0.0 decays all the way to zero).") + p.add_argument("--coarse_init_scale_factor", type=float, default=1.0, + help="Multiplier applied to all Gaussian render-scales " + "at training start. Decays log-linearly to 1.0 " + "over --coarse_decay_epochs. >1.0 widens the " + "photometric basin so outlier-pose frames have " + "gradient signal to be pulled in. 1.0 disables.") + p.add_argument("--coarse_decay_epochs", type=int, default=None, + help="Epochs over which to anneal the coarse scale " + "factor back to 1.0 (default: full n_epochs).") + p.add_argument("--pose_confidence_decay", type=float, default=0.0, + help="Per-frame pose confidence τ (in frames) for " + "exp(-|t-ref|/τ) decay from the reference frame. " + "Scales per-frame photometric/silhouette/depth " + "and modulates the pose-init prior. 0 disables " + "(uniform confidence).") + p.add_argument("--pose_confidence_ref_frame", type=int, default=None, + help="Reference frame index (frame_idx, not positional) " + "for confidence decay. Falls back to " + "--bg_ref_frame, then 0.") + p.add_argument("--pose_confidence_dynamic_tau", type=float, default=0.0, + help="Dynamic per-frame confidence based on quat-aligned " + "distance to neighbor frames' rotations, recomputed " + "each batch. c_dyn[t] = exp(-mean_neighbor_dist² / τ). " + "Multiplies with the static distance-from-ref " + "confidence. Set --pose_confidence_decay 0 to use " + "ONLY the dynamic confidence. 0 disables.") + p.add_argument("--w_pose_init_prior", type=float, default=0.0, + help="Weight of the c_t-scaled pose-init prior. Pulls " + "high-confidence object poses back toward " + "FoundationPose input. 0 disables.") + p.add_argument("--rotation_search_n_candidates", type=int, default=0, + help="Per-frame discrete rotation hypothesis search. " + "Render N candidate rotations in one batched gsplat " + "call, snap the frame's axis_angle to the best. " + "0 disables. 32-64 is typical.") + p.add_argument("--rotation_search_period", type=int, default=0, + help="If >0, run rotation search every K epochs (after " + "the warmup boundary). 0 = run only once at the " + "warmup boundary.") + p.add_argument("--rotation_search_local_frac", type=float, default=0.5, + help="Fraction of search candidates that are local " + "perturbations of the current rotation; the rest " + "are global uniform-on-SO(3) rotations.") + p.add_argument("--rotation_search_local_max_deg", type=float, default=30.0, + help="Max angle (deg) for local perturbations.") + p.add_argument("--rotation_search_silhouette_weight", type=float, default=1.0, + help="Silhouette IoU weight in candidate scoring " + "(photometric L1 weight is fixed at 1.0).") + p.add_argument("--rotation_search_smoothness_weight", type=float, default=1.0, + help="Causal smoothness weight in candidate scoring. " + "Each candidate is penalized by its quat-aligned " + "squared distance to the previous (already-snapped) " + "frame's rotation. 0 disables, biasing only toward " + "image fit. The frame at t=0 has no penalty.") + p.add_argument("--use_l2_photometric", action="store_true", + help="Use squared error (L2) for the photometric loss " + "instead of L1. Smoother gradient near the optimum, " + "less robust to outliers.") + p.add_argument("--use_l2_silhouette", action="store_true", + help="Use squared error (L2) for the class-label " + "silhouette loss instead of L1.") + p.add_argument("--train_resolution_scale", type=float, default=1.0, + help="Render at this scale of native resolution. " + "Cache, intrinsics, and renders all use the " + "scaled dimensions. 0.5 ≈ 4x faster rendering " + "with negligible accuracy hit. 1.0 = native.") + p.add_argument("--multiview_include_background", action="store_true", + help="Include background Gaussians in the final multi-" + "view overlay grid. Default off — orbit panels " + "show only the trained foreground (object + " + "hands) for cleaner shape/pose QA.") + p.add_argument("--checkpoint_path", default=None, + help="If set, save a .pt with full state (Gaussians + " + "poses + optimizer + LR scheduler + step counter) " + "at the end of training.") + p.add_argument("--checkpoint_every", type=int, default=0, + help="If >0 and --checkpoint_path is set, also write the " + "checkpoint every N optimizer steps. Atomic via " + "tmp+rename so the viewer's hot-reload never reads " + "a half-written file.") + p.add_argument("--resume_from_checkpoint", default=None, + help="If set, load a previously-saved checkpoint before " + "the training loop. Module sizes must match (same " + "n_obj_gaussians / n_hand_gaussians / " + "bg_max_points / inputs).") + p.add_argument("--ignore_optimizer_state", action="store_true", + help="When resuming, skip the optimizer (and LR " + "scheduler) state load — Adam moments reinit " + "lazily on the next step. Useful when changing " + "LRs / weights between runs.") + p.add_argument("--freeze_gaussians", action="store_true", + help="Freeze ALL Gaussian-attribute parameters (object " + "+ hands + background) for the entire run. " + "Combine with --freeze_hand_rot / --freeze_hand_trans " + "/ --freeze_bg_rot / --freeze_bg_trans to leave " + "object pose as the only thing that updates.") + p.add_argument("--random_init_obj_pose", action="store_true", + help="Randomize the per-frame object pose at startup " + "(uniform SO(3) rotation, translation += " + "N(0, σ²)) before training begins.") + p.add_argument("--random_init_obj_pose_trans_std", type=float, default=0.1, + help="Stddev (m) of the per-frame translation noise " + "added when --random_init_obj_pose is set.") + p.add_argument("--init_opacity_obj", type=float, default=0.9, + help="Initial opacity for object Gaussians before sigmoid-logit optimization.") + p.add_argument("--init_opacity_hand", type=float, default=0.9, + help="Initial opacity for hand Gaussians before sigmoid-logit optimization.") + p.add_argument("--init_opacity_bg", type=float, default=0.9, + help="Initial opacity for background Gaussians before sigmoid-logit optimization.") + p.add_argument("--init_opacity_wrist", type=float, default=0.5, + help="Initial opacity for optional wrist-attached Gaussians.") + p.add_argument("--init_gaussian_scale_factor", type=float, default=1.0, + help="Multiplier on initial Gaussian scales/radii for object, hand, background, and wrist Gaussians.") + p.add_argument("--no_init_hand_color_from_mask", + dest="init_hand_color_from_mask", + action="store_false", + help="Disable per-hand Gaussian color init from the " + "reference-frame SAM2 mask mean. By default the hand " + "color is set to the average RGB inside the hand " + "mask at the ref frame (bg_ref_frame → debug_frame_idx " + "→ 0). Disable to use the fixed default skin tone.") + p.set_defaults(init_hand_color_from_mask=True) + p.add_argument("--smooth_obj_in_world", action="store_true", + help="Measure object pose smoothness in world frame " + "(composed via bg_pose_field) rather than camera " + "frame. Requires --with_background. Recommended " + "for moving-camera scenes — separates 'the object " + "moved' from 'the camera moved'.") + p.add_argument("--smooth_hand_in_world", action="store_true", + help="Measure hand global_orient + cam_t smoothness in " + "world frame. Finger (hand_pose) smoothness stays " + "in cam frame either way (it's joint-relative). " + "Requires --with_background.") + p.add_argument("--n_wrist_gaussians", type=int, default=0, + help="Per-hand count of free Gaussians rigidly attached " + "to the MANO wrist 6DOF pose, used to model the " + "arm without distorting MANO. 0 disables. ") + p.add_argument("--wrist_init_scale", type=float, default=0.03, + help="Initial per-Gaussian scale (m) for wrist-attached " + "Gaussians. Large by default (~3 cm) — these are " + "arm-sized blobs.") + p.add_argument("--wrist_init_radius", type=float, default=0.0, + help="Init scatter radius (m) around the wrist origin. " + "0 puts every Gaussian at the wrist; >0 samples " + "uniformly in a ball of that radius.") + p.add_argument("--lr_wrist_gaussians", type=float, default=None, + help="LR for wrist-attached Gaussians (falls back to " + "--lr_hand_gaussians).") + p.add_argument("--w_delta_p_reg_wrist", type=float, default=0.01, + help="Δp penalty for wrist-attached Gaussians. Light " + "(0.01) by default — they need to drift far from " + "the wrist origin to fill the arm volume.") + p.add_argument("--learn_focal", action="store_true", + help="Refine fx, fy of the camera intrinsics. CAUTION: " + "without depth supervision (--w_depth > 0 and " + "--depth_dir set), fx is degenerate with global " + "scene scale and will drift. Pair with a tight " + "--w_intrinsics_prior, or only enable when depth " + "supervision is on.") + p.add_argument("--learn_principal_point", action="store_true", + help="Refine cx, cy of the camera intrinsics. Safer " + "than --learn_focal — it's a 2D image-plane shift, " + "not coupled to z. Use to absorb sub-pixel " + "calibration drift.") + p.add_argument("--lr_intrinsics", type=float, default=1e-4, + help="LR for the four intrinsics scalars when " + "--learn_focal or --learn_principal_point is set. " + "Default 1e-4 keeps motion slow relative to poses.") + p.add_argument("--w_intrinsics_prior", type=float, default=1e3, + help="L2 anchor of (fx, fy, cx, cy) to their JSON " + "init values. Tight (1e3) by default — K shouldn't " + "wander far. Lower (e.g. 1.0) if you want more " + "freedom.") + p.add_argument("--snap_rotation_outliers_every", type=int, default=0, + help="Periodicity (in optimizer steps) of the rotation " + "outlier median-snap pass. 0 disables. Detects " + "frames whose rotation is far from the local median " + "and replaces them; resets Adam moments at the " + "snapped frame. Useful for popping single-frame " + "wrist flips that the smoothness loss spreads into " + "smeared multi-frame rotations.") + p.add_argument("--snap_rotation_threshold", type=float, default=1.0, + help="Quat-distance threshold above which a frame is " + "considered an outlier. 1.0 ≈ 85° rotation; " + "well above normal frame-to-frame motion (~0.04 " + "per 5°). Lower for more aggressive snapping.") + p.add_argument("--snap_rotation_window", type=int, default=3, + help="Half-window for median (full window = 2*w + 1 = 7 " + "frames by default).") + p.add_argument("--snap_rotation_targets", type=str, + default="obj,hand_wrist", + help="Comma-sep subset of {obj, hand_wrist, hand_finger} " + "to apply the snap to. Defaults to object axis_angle " + "+ hand global_orient. Add 'hand_finger' to also " + "snap individual finger joints (15 per hand, each " + "treated independently).") + p.add_argument("--snap_rotation_verbose", action="store_true", + help="Print which frames got snapped at each pass.") + p.add_argument("--freeze_bg_rot", action="store_true", + help="Hold background rotation at identity.") + p.add_argument("--freeze_bg_trans", action="store_true", + help="Hold background translation at zero.") + p.add_argument("--w_smooth_bg_rot", type=float, default=0.1) + p.add_argument("--w_smooth_bg_trans", type=float, default=0.1) + p.add_argument("--device", default="cuda") + p.add_argument("--seed", type=int, default=0) + args = p.parse_args() + refine( + frames_dir = args.frames_dir, + intrinsics_path = args.intrinsics_path, + object_mesh_path = args.object_mesh_path, + object_poses_dir = args.object_poses_dir, + object_mask_dir = args.object_mask_dir, + refined_object_poses_dir = args.refined_object_poses_dir, + refined_object_scale_path = args.refined_object_scale_path, + overlay_path = args.overlay_path, + left_hand_pose_dir = args.left_hand_pose_dir, + left_hand_mask_dir = args.left_hand_mask_dir, + right_hand_pose_dir = args.right_hand_pose_dir, + right_hand_mask_dir = args.right_hand_mask_dir, + refined_left_hand_pose_dir = args.refined_left_hand_pose_dir, + refined_right_hand_pose_dir = args.refined_right_hand_pose_dir, + depth_dir = args.depth_dir, + mano_assets_root = args.mano_assets_root, + n_epochs = args.n_epochs, + n_gaussian_only_epochs = args.n_gaussian_only_epochs, + batch_size = args.batch_size, + lr_gaussians = args.lr_gaussians, + lr_hand_gaussians = args.lr_hand_gaussians, + lr_mul_delta_p = args.lr_mul_delta_p, + lr_mul_quat = args.lr_mul_quat, + lr_mul_scale = args.lr_mul_scale, + lr_mul_opacity = args.lr_mul_opacity, + lr_mul_color = args.lr_mul_color, + lr_mul_obj_global_scale = args.lr_mul_obj_global_scale, + lr_object_pose = args.lr_object_pose, + lr_object_rot = args.lr_object_rot, + lr_object_trans = args.lr_object_trans, + lr_hand_pose = args.lr_hand_pose, + lr_hand_global_orient = args.lr_hand_global_orient, + lr_hand_finger = args.lr_hand_finger, + lr_hand_trans = args.lr_hand_trans, + lr_betas = args.lr_betas, + learn_hand_scale = args.learn_hand_scale, + lr_hand_scale = args.lr_hand_scale, + render_every = args.render_every, + progress_dir = args.progress_dir, + debug_frame_idx = args.debug_frame_idx, + mask_background_to_black = args.mask_background_to_black, + balance_photometric_by_mask = args.balance_photometric_by_mask, + freeze_object_rot = args.freeze_object_rot, + freeze_object_trans = args.freeze_object_trans, + freeze_object_scale = args.freeze_object_scale, + freeze_hand_rot = args.freeze_hand_rot, + freeze_hand_trans = args.freeze_hand_trans, + with_background = args.with_background, + bg_ref_frame = args.bg_ref_frame, + lr_bg_gaussians = args.lr_bg_gaussians, + lr_bg_pose = args.lr_bg_pose, + lr_bg_rot = args.lr_bg_rot, + lr_bg_trans = args.lr_bg_trans, + bg_max_points = args.bg_max_points, + background_pose_init_dir = args.background_pose_init_dir, + bg_init_stride = args.bg_init_stride, + bg_voxel_size = args.bg_voxel_size, + n_density_neighbors = args.n_density_neighbors, + density_subsample_frac_bg = args.density_subsample_frac_bg, + n_sdf_samples_bg = args.n_sdf_samples_bg, + n_sdf_neighbors_bg = args.n_sdf_neighbors_bg, + valid_mask_threshold = args.valid_mask_threshold, + valid_mask_erode_iters = args.valid_mask_erode_iters, + n_obj_gaussians = args.n_obj_gaussians, + n_hand_gaussians = args.n_hand_gaussians, + object_anchor_mode = args.object_anchor_mode, + hand_anchor_mode = args.hand_anchor_mode, + face_normal_thin_factor_obj = args.face_normal_thin_factor_obj, + face_normal_thin_factor_hand = args.face_normal_thin_factor_hand, + init_opacity_obj = args.init_opacity_obj, + init_opacity_hand = args.init_opacity_hand, + init_opacity_bg = args.init_opacity_bg, + init_opacity_wrist = args.init_opacity_wrist, + init_gaussian_scale_factor = args.init_gaussian_scale_factor, + init_hand_color_from_mask = args.init_hand_color_from_mask, + smooth_obj_in_world = args.smooth_obj_in_world, + smooth_hand_in_world = args.smooth_hand_in_world, + n_wrist_gaussians = args.n_wrist_gaussians, + wrist_init_scale = args.wrist_init_scale, + wrist_init_radius = args.wrist_init_radius, + lr_wrist_gaussians = args.lr_wrist_gaussians, + w_delta_p_reg_wrist = args.w_delta_p_reg_wrist, + learn_focal = args.learn_focal, + learn_principal_point = args.learn_principal_point, + lr_intrinsics = args.lr_intrinsics, + w_intrinsics_prior = args.w_intrinsics_prior, + snap_rotation_outliers_every = args.snap_rotation_outliers_every, + snap_rotation_threshold = args.snap_rotation_threshold, + snap_rotation_window = args.snap_rotation_window, + snap_rotation_targets = args.snap_rotation_targets, + snap_rotation_verbose = args.snap_rotation_verbose, + use_cosine_lr_schedule = args.use_cosine_lr_schedule, + cosine_lr_min_ratio = args.cosine_lr_min_ratio, + coarse_init_scale_factor = args.coarse_init_scale_factor, + coarse_decay_epochs = args.coarse_decay_epochs, + pose_confidence_decay = args.pose_confidence_decay, + pose_confidence_ref_frame = args.pose_confidence_ref_frame, + pose_confidence_dynamic_tau = args.pose_confidence_dynamic_tau, + w_pose_init_prior = args.w_pose_init_prior, + rotation_search_n_candidates= args.rotation_search_n_candidates, + rotation_search_period = args.rotation_search_period, + rotation_search_local_frac = args.rotation_search_local_frac, + rotation_search_local_max_deg = args.rotation_search_local_max_deg, + rotation_search_silhouette_weight = args.rotation_search_silhouette_weight, + rotation_search_smoothness_weight = args.rotation_search_smoothness_weight, + use_l2_photometric = args.use_l2_photometric, + use_l2_silhouette = args.use_l2_silhouette, + train_resolution_scale = args.train_resolution_scale, + multiview_include_background = args.multiview_include_background, + checkpoint_path = args.checkpoint_path, + checkpoint_every = args.checkpoint_every, + resume_from_checkpoint = args.resume_from_checkpoint, + ignore_optimizer_state = args.ignore_optimizer_state, + freeze_gaussians = args.freeze_gaussians, + random_init_obj_pose = args.random_init_obj_pose, + random_init_obj_pose_trans_std = args.random_init_obj_pose_trans_std, + freeze_bg_rot = args.freeze_bg_rot, + freeze_bg_trans = args.freeze_bg_trans, + weights = LossWeights( + photometric = args.w_photometric, + silhouette = args.w_silhouette, + silhouette_obj = args.w_silhouette_obj, + silhouette_hand = args.w_silhouette_hand, + depth = args.w_depth, + log_depth_grad = args.w_log_depth_grad, + photometric_ssim = args.w_photometric_ssim, + depth_ssim = args.w_depth_ssim, + smooth_obj_rot = args.w_smooth_obj_rot, + smooth_obj_trans = args.w_smooth_obj_trans, + smooth_hand_rot = args.w_smooth_hand_rot, + smooth_hand_finger = args.w_smooth_hand_finger, + smooth_hand_trans = args.w_smooth_hand_trans, + smooth_bg_rot = args.w_smooth_bg_rot, + smooth_bg_trans = args.w_smooth_bg_trans, + beta_prior = args.w_beta_prior, + hand_scale_prior = args.w_hand_scale_prior, + delta_p_reg_obj = (args.w_delta_p_reg_obj if args.w_delta_p_reg_obj is not None else args.w_delta_p_reg), + delta_p_reg_hand = (args.w_delta_p_reg_hand if args.w_delta_p_reg_hand is not None else args.w_delta_p_reg), + delta_p_reg_bg = (args.w_delta_p_reg_bg if args.w_delta_p_reg_bg is not None else args.w_delta_p_reg), + face_delta_p_tangent_obj = args.w_face_delta_p_tangent_obj, + face_delta_p_normal_outward_obj = args.w_face_delta_p_normal_outward_obj, + face_delta_p_normal_inward_obj = args.w_face_delta_p_normal_inward_obj, + face_delta_p_tangent_hand = args.w_face_delta_p_tangent_hand, + face_delta_p_normal_outward_hand = args.w_face_delta_p_normal_outward_hand, + face_delta_p_normal_inward_hand = args.w_face_delta_p_normal_inward_hand, + opacity_binary_obj = (args.w_opacity_binary_obj if args.w_opacity_binary_obj is not None else args.w_opacity_binary), + opacity_binary_hand = (args.w_opacity_binary_hand if args.w_opacity_binary_hand is not None else args.w_opacity_binary), + opacity_binary_bg = (args.w_opacity_binary_bg if args.w_opacity_binary_bg is not None else args.w_opacity_binary), + depth_variance = args.w_depth_variance, + depth_ordering = args.w_depth_ordering, + depth_ordering_margin = args.depth_ordering_margin, + obj_scale_prior = args.w_obj_scale_prior, + scale_aniso_bg = args.w_scale_aniso_bg, + density_bg = args.w_density_bg, + sdf_density_bg = args.w_sdf_density_bg, + normal_consistency_bg = args.w_normal_consistency_bg, + ), + device = args.device, + seed = args.seed, + ) + + +if __name__ == "__main__": + main() diff --git a/third-party/video_to_data/reconstruction/modules/v2d_gsplat_refinement/lib/refine_simple.py b/third-party/video_to_data/reconstruction/modules/v2d_gsplat_refinement/lib/refine_simple.py new file mode 100644 index 0000000000000000000000000000000000000000..26b229854eca1c8944625c8c08066a00a0366bc2 --- /dev/null +++ b/third-party/video_to_data/reconstruction/modules/v2d_gsplat_refinement/lib/refine_simple.py @@ -0,0 +1,1698 @@ +# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 +"""Minimal 2DGS hand/object/camera refinement. + +This is intentionally much smaller than ``refine.py``. It optimizes only: + - static Gaussian appearance params: scale, color, opacity; + - per-frame object root pose; + - optional global object scale; + - per-frame hand wrist/root pose (MANO global_orient + cam_t only); + - per-frame background/camera pose for the static depth-initialized scene. + +It does not optimize Gaussian offsets or Gaussian orientation. MANO finger +pose, MANO shape, hand scale, and object scale are optional via their LR flags. +Image losses are full-frame +L1 photometric error plus optional L1 segmentation-mask supervision, with +optional relative depth-gradient supervision from MoGe depth, and with +optional temporal smoothness on the absolute and hand/object-relative dynamic +poses. + +Run inside the gsplat refinement environment, for example: + + python -m v2d.gsplat_refinement.lib.refine_simple \ + --frames_dir data/outputs/clip/frames \ + --depth_dir data/outputs/clip/depth \ + --intrinsics_path data/outputs/clip/intrinsics_stable.json \ + --object_mesh_path data/outputs/clip/mesh_scaled.obj \ + --object_poses_dir data/outputs/clip/poses \ + --object_mask_dir data/outputs/clip/masks/1 \ + --right_hand_pose_dir data/outputs/clip/hamer_aligned_filled/2 \ + --right_hand_mask_dir data/outputs/clip/masks/2 \ + --mano_assets_root data/weights/hamer/_DATA/data \ + --refined_object_poses_dir data/outputs/clip/poses_refined_simple \ + --refined_right_hand_pose_dir data/outputs/clip/hamer_refined_simple/2 \ + --refined_camera_poses_dir data/outputs/clip/camera_refined_simple \ + --overlay_path data/outputs/clip/refined_simple.mp4 +""" +from __future__ import annotations + +import argparse +import glob +import math +import os +import subprocess +import tempfile +from dataclasses import dataclass, replace + +import numpy as np +import torch +import torch.nn.functional as F +from PIL import Image +from tqdm import tqdm + +from v2d.common.datatypes import Transform3d + +from .background import ( + BackgroundGaussians, + BackgroundPoseField, + init_background_from_depth, + init_background_multiframe, +) +from .gaussians import ( + GaussianFrame, + axis_angle_to_quat, + concat_frames, + init_hand_face_gaussians, + init_object_face_gaussians_from_mesh, + quat_mul, +) +from .io import ( + HandPoseTrack, + ObjectPoseTrack, + load_hand_poses, + load_intrinsics, + load_object_mesh, + load_object_poses, + save_hand_poses, + save_object_poses, +) +from .losses import ( + depth_gradient_loss, + quat_smoothness, + rotation_smoothness, + temporal_smoothness, +) +from .pose_fields import HandPoseField, ObjectPoseField, _quat_to_axis_angle + + +@dataclass +class HandSlot: + side: str + track: HandPoseTrack + pose_field: HandPoseField + gaussians: torch.nn.Module + mask_dir: str + output_pose_dir: str | None + frame_to_pos: dict[int, int] + + +class SimpleFrameCache: + """CPU cache for the small set of supervision this script uses.""" + + def __init__( + self, + frame_indices: list[int], + frames_dir: str, + depth_dir: str | None, + object_mask_dir: str, + hand_mask_dirs: list[str], + height: int, + width: int, + valid_mask_threshold: float = 0.04, + valid_mask_erode_iters: int = 2, + ) -> None: + self.frame_indices = list(frame_indices) + self.height = int(height) + self.width = int(width) + n = len(frame_indices) + self.rgb = torch.zeros((n, height, width, 3), dtype=torch.float32) + self.depth = ( + torch.empty((n, height, width), dtype=torch.float32) + if depth_dir is not None else None + ) + self.obj_mask = torch.zeros((n, height, width), dtype=torch.float32) + self.hand_masks = [ + torch.zeros((n, height, width), dtype=torch.float32) + for _ in hand_mask_dirs + ] + + for t, fidx in enumerate(tqdm(frame_indices, ncols=80, desc="caching", unit="frame")): + self.rgb[t] = _load_rgb_resized(_find_frame_file(frames_dir, fidx), width, height) + if self.depth is not None and depth_dir is not None: + self.depth[t] = _load_depth_resized(os.path.join(depth_dir, f"{fidx:06d}.png"), width, height) + self.obj_mask[t] = _load_mask_or_zero(object_mask_dir, fidx, width, height) + for k, mask_dir in enumerate(hand_mask_dirs): + self.hand_masks[k][t] = _load_mask_or_zero(mask_dir, fidx, width, height) + + if valid_mask_threshold <= 0: + valid = torch.ones((height, width), dtype=torch.float32) + else: + max_brightness = self.rgb.amax(dim=0).amax(dim=-1) + valid = (max_brightness > float(valid_mask_threshold)).float() + if valid_mask_erode_iters > 0: + m = valid.unsqueeze(0).unsqueeze(0) + for _ in range(int(valid_mask_erode_iters)): + m = 1.0 - F.max_pool2d(1.0 - m, kernel_size=3, stride=1, padding=1) + valid = m.squeeze(0).squeeze(0) + self.valid_mask = valid + + try: + self.rgb = self.rgb.pin_memory() + if self.depth is not None: + self.depth = self.depth.pin_memory() + self.obj_mask = self.obj_mask.pin_memory() + self.hand_masks = [m.pin_memory() for m in self.hand_masks] + self.valid_mask = self.valid_mask.pin_memory() + except RuntimeError: + pass + + def union_mask(self, t: int, device: torch.device | str) -> torch.Tensor: + m = self.obj_mask[t].to(device, non_blocking=True).clone() + for hm in self.hand_masks: + m = torch.maximum(m, hm[t].to(device, non_blocking=True)) + return m + + +def _target_rgb( + cache: SimpleFrameCache, + t: int, + device: torch.device | str, + mask_background: bool, +) -> torch.Tensor: + target = cache.rgb[t].to(device, non_blocking=True) + if mask_background: + target = target * cache.union_mask(t, device).unsqueeze(-1) + return target + + +def _find_frame_file(frames_dir: str, fidx: int) -> str: + for ext in (".png", ".jpg", ".jpeg"): + p = os.path.join(frames_dir, f"{fidx:06d}{ext}") + if os.path.exists(p): + return p + raise FileNotFoundError(f"Frame {fidx:06d} not found in {frames_dir}") + + +def _list_frame_indices(frames_dir: str) -> set[int]: + out: set[int] = set() + for path in glob.glob(os.path.join(frames_dir, "*.png")) + glob.glob(os.path.join(frames_dir, "*.jpg")): + try: + out.add(int(os.path.splitext(os.path.basename(path))[0])) + except ValueError: + continue + return out + + +def _load_rgb_resized(path: str, width: int, height: int) -> torch.Tensor: + img = Image.open(path).convert("RGB") + if img.size != (width, height): + img = img.resize((width, height), Image.BILINEAR) + arr = np.asarray(img, dtype=np.float32) / 255.0 + return torch.from_numpy(arr) + + +def _load_depth_resized(path: str, width: int, height: int) -> torch.Tensor: + if not os.path.exists(path): + raise FileNotFoundError(f"Depth frame not found: {path}") + img = Image.open(path) + if img.size != (width, height): + img = img.resize((width, height), Image.BILINEAR) + px = np.asarray(img).astype(np.float32) + with np.errstate(divide="ignore"): + depth = 1.0 / (px / 65535.0) - 1.0 + return torch.from_numpy(depth) + + +def _load_mask_or_zero(mask_dir: str, fidx: int, width: int, height: int) -> torch.Tensor: + path = os.path.join(mask_dir, f"{fidx:06d}.png") + if not os.path.exists(path): + return torch.zeros((height, width), dtype=torch.float32) + img = Image.open(path) + if img.size != (width, height): + img = img.resize((width, height), Image.NEAREST) + arr = np.asarray(img).astype(np.float32) + if arr.ndim == 3: + arr = arr[..., 0] + if arr.max() > 1.0: + arr = arr / 255.0 + return torch.from_numpy((arr > 0.5).astype(np.float32)) + + +def _restrict_object_track(track: ObjectPoseTrack, keep: set[int]) -> ObjectPoseTrack: + idxs = [i for i, fidx in enumerate(track.frame_indices) if fidx in keep] + if not idxs: + raise RuntimeError("No object pose frames overlap the available RGB frames.") + return ObjectPoseTrack( + rotations=track.rotations[idxs], + translations=track.translations[idxs], + scales=track.scales[idxs], + frame_indices=[track.frame_indices[i] for i in idxs], + ) + + +def _restrict_hand_track(track: HandPoseTrack, keep: set[int]) -> HandPoseTrack: + idxs = [i for i, fidx in enumerate(track.frame_indices) if fidx in keep] + if not idxs: + raise RuntimeError("A hand pose track has no frames overlapping the training frames.") + return HandPoseTrack( + global_orient=track.global_orient[idxs], + hand_pose=track.hand_pose[idxs], + betas=track.betas[idxs], + cam_t=track.cam_t[idxs], + is_right=track.is_right, + frame_indices=[track.frame_indices[i] for i in idxs], + raw_records=[track.raw_records[i] for i in idxs], + hand_scale=track.hand_scale, + ) + + +def _freeze_all(module: torch.nn.Module) -> None: + for p in module.parameters(): + p.requires_grad_(False) + + +def _enable(module: torch.nn.Module, names: list[str]) -> list[torch.nn.Parameter]: + params: list[torch.nn.Parameter] = [] + for name in names: + value = getattr(module, name, None) + if isinstance(value, torch.nn.Parameter): + value.requires_grad_(True) + params.append(value) + return params + + +def _trainable_gaussian_params(module: torch.nn.Module) -> list[torch.nn.Parameter]: + _freeze_all(module) + return _enable(module, ["_log_scale", "_opacity_logit", "_color"]) + + +def _load_relative_w2c_poses( + poses_dir: str, + frame_indices: list[int], + ref_t: int, +) -> dict[int, np.ndarray]: + ref_fidx = frame_indices[ref_t] + ref_path = os.path.join(poses_dir, f"{ref_fidx:06d}.json") + if not os.path.exists(ref_path): + raise FileNotFoundError( + f"background_pose_init_dir is set but reference pose {ref_path} is missing." + ) + M_ref = Transform3d.load(ref_path).to_matrix() + out: dict[int, np.ndarray] = {ref_t: np.eye(4)} + for t, fidx in enumerate(frame_indices): + if t == ref_t: + continue + path = os.path.join(poses_dir, f"{fidx:06d}.json") + if not os.path.exists(path): + continue + tf = Transform3d.load(path) + if any(abs(s - 1.0) > 1e-3 for s in tf.scale): + continue + out[t] = np.linalg.inv(tf.to_matrix()) @ M_ref + return out + + +def _seed_background_pose_field( + bg_pose_field: BackgroundPoseField, + poses: dict[int, np.ndarray], +) -> tuple[int, int]: + device = bg_pose_field.axis_angle.device + aa = bg_pose_field.axis_angle.detach().clone() + tr = bg_pose_field.translation.detach().clone() + loaded = missing = 0 + for t in range(aa.shape[0]): + if t not in poses: + missing += 1 + continue + M = poses[t] + R = torch.from_numpy(M[:3, :3]).to(device=device, dtype=torch.float32) + q = _rotmat_to_quat(R) + aa[t] = _quat_to_axis_angle(q) + tr[t] = torch.from_numpy(M[:3, 3]).to(device=device, dtype=torch.float32) + loaded += 1 + with torch.no_grad(): + bg_pose_field.axis_angle.copy_(aa) + bg_pose_field.translation.copy_(tr) + return loaded, missing + + +def _rotmat_to_quat(R: torch.Tensor) -> torch.Tensor: + import roma + + q_xyzw = roma.rotmat_to_unitquat(R) + return torch.cat([q_xyzw[..., 3:4], q_xyzw[..., :3]], dim=-1) + + +def _anchor_camera_reference(bg_pose_field: BackgroundPoseField) -> None: + ref_t = int(bg_pose_field.ref_frame_t) + with torch.no_grad(): + bg_pose_field.axis_angle[ref_t].zero_() + bg_pose_field.translation[ref_t].zero_() + + +@dataclass +class ObjectSDFGrid: + """Differentiable object-space SDF grid. + + ``values`` stores signed distance with positive outside the object and + negative inside. Trimesh uses the opposite sign convention, so construction + flips the sign once. Querying uses ``grid_sample`` so gradients flow to the + queried points, hence to hand/object pose and scale parameters. + """ + + values: torch.Tensor # (1, 1, D, H, W), D=z, H=y, W=x + bounds_min: torch.Tensor # (3,) object-frame xyz + bounds_max: torch.Tensor # (3,) object-frame xyz + + def query(self, points_obj: torch.Tensor) -> torch.Tensor: + if points_obj.numel() == 0: + return points_obj.new_zeros((0,)) + span = (self.bounds_max - self.bounds_min).clamp_min(1e-8) + coords = 2.0 * (points_obj - self.bounds_min) / span - 1.0 + grid = coords.view(1, -1, 1, 1, 3) + sampled = F.grid_sample( + self.values.to(device=points_obj.device, dtype=points_obj.dtype), + grid, + mode="bilinear", + padding_mode="border", + align_corners=True, + ) + return sampled.view(-1) + + +def _build_object_sdf_grid( + vertices: torch.Tensor, + faces: np.ndarray, + resolution: int, + margin: float, + device: torch.device, +) -> ObjectSDFGrid: + res = int(resolution) + if res < 8: + raise ValueError("object_sdf_resolution must be >= 8") + verts_np = vertices.detach().cpu().numpy().astype(np.float64) + faces_np = np.asarray(faces, dtype=np.int64) + try: + import trimesh + from trimesh.proximity import signed_distance + except ImportError as exc: + raise RuntimeError( + "Hand/object penetration loss requires trimesh and its proximity dependencies." + ) from exc + + mesh = trimesh.Trimesh(vertices=verts_np, faces=faces_np, process=False) + if not bool(getattr(mesh, "is_watertight", False)): + print("Warning: object mesh is not watertight; hand/object SDF signs may be approximate.") + + bounds_min_np = verts_np.min(axis=0) + bounds_max_np = verts_np.max(axis=0) + extent = bounds_max_np - bounds_min_np + pad = max(float(margin) * 4.0, float(extent.max()) * 0.05, 1e-3) + bounds_min_np = bounds_min_np - pad + bounds_max_np = bounds_max_np + pad + + xs = np.linspace(bounds_min_np[0], bounds_max_np[0], res, dtype=np.float32) + ys = np.linspace(bounds_min_np[1], bounds_max_np[1], res, dtype=np.float32) + zs = np.linspace(bounds_min_np[2], bounds_max_np[2], res, dtype=np.float32) + gx, gy, gz = np.meshgrid(xs, ys, zs, indexing="ij") + points = np.stack([gx.reshape(-1), gy.reshape(-1), gz.reshape(-1)], axis=-1) + + sdf = np.empty((points.shape[0],), dtype=np.float32) + chunk = 200_000 + print(f"Building object SDF grid: resolution={res}, points={points.shape[0]}, padding={pad:.4g}") + try: + for start in tqdm(range(0, points.shape[0], chunk), ncols=80, desc="object_sdf", unit="chunk"): + end = min(start + chunk, points.shape[0]) + # trimesh signed_distance is positive inside, negative outside. + sdf[start:end] = -signed_distance(mesh, points[start:end]).astype(np.float32) + except BaseException as exc: + raise RuntimeError( + "Failed to build object SDF grid for hand/object penetration. " + "This usually means trimesh's optional rtree dependency is missing " + "or the object mesh is invalid." + ) from exc + + sdf_xyz = torch.from_numpy(sdf.reshape(res, res, res)) + values = sdf_xyz.permute(2, 1, 0).contiguous().view(1, 1, res, res, res).to(device) + bounds_min = torch.tensor(bounds_min_np, dtype=torch.float32, device=device) + bounds_max = torch.tensor(bounds_max_np, dtype=torch.float32, device=device) + return ObjectSDFGrid(values=values, bounds_min=bounds_min, bounds_max=bounds_max) + + +def _hand_object_penetration_loss( + t: int, + fidx: int, + obj_pose_field: ObjectPoseField, + obj_gaussians: torch.nn.Module, + hand_slots: list[HandSlot], + object_sdf: ObjectSDFGrid, + margin: float, + max_hand_verts: int, +) -> torch.Tensor: + R_obj, t_obj = obj_pose_field(t) + if hasattr(obj_gaussians, "object_scale"): + s_obj = obj_gaussians.object_scale().clamp_min(1e-6) + else: + s_obj = R_obj.new_ones(()) + losses: list[torch.Tensor] = [] + for slot in hand_slots: + local_t = slot.frame_to_pos.get(fidx) + if local_t is None: + continue + verts_cam, _ = slot.pose_field.posed_verts_and_rotmats_camera(local_t) + if max_hand_verts > 0 and verts_cam.shape[0] > int(max_hand_verts): + idx = torch.linspace( + 0, + verts_cam.shape[0] - 1, + int(max_hand_verts), + device=verts_cam.device, + ).round().to(torch.long) + verts_cam = verts_cam[idx] + verts_obj = ((verts_cam - t_obj) @ R_obj) / s_obj + sdf_metric = object_sdf.query(verts_obj) * s_obj + penetration = (float(margin) - sdf_metric).clamp_min(0.0) + losses.append(penetration.square().mean()) + if not losses: + return R_obj.sum() * 0.0 + return torch.stack(losses).mean() + + +class VGG16PerceptualLoss(torch.nn.Module): + """VGG16 feature-space L1 loss for RGB images in [0, 1].""" + + def __init__( + self, + weights_path: str | None = None, + resize: int = 224, + layer_indices: tuple[int, ...] = (3, 8, 15, 22), + ) -> None: + super().__init__() + try: + from torchvision.models import VGG16_Weights, vgg16 + except ImportError as exc: + raise RuntimeError( + "VGG perceptual loss requires torchvision in the gsplat refinement environment." + ) from exc + + self.layer_indices = set(int(i) for i in layer_indices) + self.resize = int(resize) + if weights_path is not None: + weights_path = os.path.abspath(os.path.expanduser(weights_path)) + model = vgg16(weights=None) + if not os.path.exists(weights_path): + weights = VGG16_Weights.IMAGENET1K_V1 + os.makedirs(os.path.dirname(weights_path) or ".", exist_ok=True) + print(f"Downloading VGG16 ImageNet weights -> {weights_path}") + try: + state = torch.hub.load_state_dict_from_url( + weights.url, + model_dir=os.path.dirname(weights_path) or ".", + file_name=os.path.basename(weights_path), + map_location="cpu", + progress=True, + ) + except Exception as exc: + raise RuntimeError( + f"Failed to download torchvision VGG16 ImageNet weights to {weights_path}." + ) from exc + else: + state = torch.load(weights_path, map_location="cpu") + if isinstance(state, dict) and "state_dict" in state: + state = state["state_dict"] + model.load_state_dict(state) + else: + try: + model = vgg16(weights=VGG16_Weights.IMAGENET1K_V1) + except Exception as exc: + raise RuntimeError( + "Failed to load torchvision VGG16 ImageNet weights. " + "Provide --vgg_weights_path with a local vgg16 state_dict, " + "or ensure torchvision's weight cache/network access is available." + ) from exc + self.features = model.features[: max(self.layer_indices) + 1].eval() + for param in self.features.parameters(): + param.requires_grad_(False) + self.register_buffer( + "mean", torch.tensor([0.485, 0.456, 0.406], dtype=torch.float32).view(1, 3, 1, 1) + ) + self.register_buffer( + "std", torch.tensor([0.229, 0.224, 0.225], dtype=torch.float32).view(1, 3, 1, 1) + ) + + def _preprocess( + self, + image: torch.Tensor, + valid_mask: torch.Tensor | None = None, + ) -> torch.Tensor: + x = image.clamp(0.0, 1.0).permute(2, 0, 1).unsqueeze(0) + if valid_mask is not None: + x = x * valid_mask.to(device=x.device, dtype=x.dtype).unsqueeze(0).unsqueeze(0) + if self.resize > 0 and (x.shape[-2] != self.resize or x.shape[-1] != self.resize): + x = F.interpolate(x, size=(self.resize, self.resize), mode="bilinear", align_corners=False) + return (x - self.mean.to(x.device, x.dtype)) / self.std.to(x.device, x.dtype) + + def _features(self, x: torch.Tensor) -> list[torch.Tensor]: + outputs: list[torch.Tensor] = [] + for i, layer in enumerate(self.features): + x = layer(x) + if i in self.layer_indices: + outputs.append(x) + return outputs + + def forward( + self, + pred_rgb: torch.Tensor, + target_rgb: torch.Tensor, + valid_mask: torch.Tensor | None = None, + ) -> torch.Tensor: + pred_features = self._features(self._preprocess(pred_rgb, valid_mask)) + with torch.no_grad(): + target_features = self._features(self._preprocess(target_rgb, valid_mask)) + loss = pred_rgb.new_zeros(()) + for pred_f, target_f in zip(pred_features, target_features): + loss = loss + F.l1_loss(pred_f, target_f) + return loss / float(max(len(pred_features), 1)) + + +def _render_2dgs_features( + frame: GaussianFrame, + K: torch.Tensor, + width: int, + height: int, + near_plane: float = 0.01, + far_plane: float = 100.0, + colors: torch.Tensor | None = None, + clamp_colors: bool = True, +) -> torch.Tensor: + try: + from gsplat.rendering import rasterization_2dgs + except ImportError as exc: + raise RuntimeError( + "refine_simple.py requires gsplat.rendering.rasterization_2dgs. " + "Install/run in the gsplat refinement Docker image with gsplat>=1.4." + ) from exc + + device = frame.means.device + render_colors = frame.colors if colors is None else colors + if clamp_colors: + render_colors = render_colors.clamp(0.0, 1.0) + n_channels = int(render_colors.shape[-1]) + viewmats = torch.eye(4, device=device, dtype=torch.float32).unsqueeze(0) + kwargs = dict( + means=frame.means, + quats=frame.quats, + scales=frame.scales, + opacities=frame.opacities, + colors=render_colors, + viewmats=viewmats, + Ks=K.unsqueeze(0), + width=int(width), + height=int(height), + near_plane=float(near_plane), + far_plane=float(far_plane), + render_mode="RGB", + backgrounds=torch.zeros(1, n_channels, device=device, dtype=torch.float32), + ) + try: + result = rasterization_2dgs(**kwargs) + except TypeError: + # Some gsplat builds expose a narrower 2DGS signature. Retry with the + # universally required raster inputs before surfacing the error. + kwargs.pop("render_mode", None) + result = rasterization_2dgs(**kwargs) + + colors = result[0] if isinstance(result, tuple) else result + if colors.ndim == 4: + colors = colors[0] + return colors + + +def _render_2dgs_rgb( + frame: GaussianFrame, + K: torch.Tensor, + width: int, + height: int, + near_plane: float = 0.01, + far_plane: float = 100.0, +) -> torch.Tensor: + colors = _render_2dgs_features(frame, K, width, height, near_plane, far_plane) + return colors[..., :3] + + +def _render_2dgs_depth( + frame: GaussianFrame, + K: torch.Tensor, + width: int, + height: int, + near_plane: float = 0.01, + far_plane: float = 100.0, +) -> tuple[torch.Tensor, torch.Tensor]: + depth_feature = frame.means[:, 2:3].clamp_min(float(near_plane)) + alpha_feature = torch.ones_like(depth_feature) + rendered = _render_2dgs_features( + frame, + K, + width, + height, + near_plane=near_plane, + far_plane=far_plane, + colors=torch.cat([depth_feature, alpha_feature], dim=-1), + clamp_colors=False, + ) + depth_accum = rendered[..., 0] + alpha = rendered[..., 1].clamp(0.0, 1.0) + depth = depth_accum / alpha.clamp_min(1e-4) + return depth, alpha + + +def _current_frame( + t: int, + fidx: int, + obj_gaussians: torch.nn.Module, + obj_pose_field: ObjectPoseField, + hand_slots: list[HandSlot], + bg_gaussians: BackgroundGaussians | None, + bg_pose_field: BackgroundPoseField | None, +) -> GaussianFrame: + R_obj, t_obj = obj_pose_field(t) + frames = [obj_gaussians(R_obj, t_obj)] + for slot in hand_slots: + local_t = slot.frame_to_pos.get(fidx) + if local_t is None: + continue + verts, Rv = slot.pose_field.posed_verts_and_rotmats_camera(local_t) + frames.append(slot.gaussians(verts, Rv)) + if bg_gaussians is not None and bg_pose_field is not None: + R_bg, t_bg = bg_pose_field(t) + frames.append(bg_gaussians(R_bg, t_bg)) + return concat_frames(frames) + + +def _label_block( + n: int, + n_classes: int, + class_idx: int | None, + device: torch.device, +) -> torch.Tensor: + labels = torch.zeros((int(n), int(n_classes)), device=device, dtype=torch.float32) + if class_idx is not None and n > 0: + labels[:, int(class_idx)] = 1.0 + return labels + + +def _current_frame_with_labels( + t: int, + fidx: int, + obj_gaussians: torch.nn.Module, + obj_pose_field: ObjectPoseField, + hand_slots: list[HandSlot], + bg_gaussians: BackgroundGaussians | None, + bg_pose_field: BackgroundPoseField | None, + n_classes: int, +) -> tuple[GaussianFrame, torch.Tensor]: + R_obj, t_obj = obj_pose_field(t) + obj_frame = obj_gaussians(R_obj, t_obj) + frames = [obj_frame] + labels = [_label_block(obj_frame.means.shape[0], n_classes, 0, obj_frame.means.device)] + + for slot_i, slot in enumerate(hand_slots): + local_t = slot.frame_to_pos.get(fidx) + if local_t is None: + continue + verts, Rv = slot.pose_field.posed_verts_and_rotmats_camera(local_t) + hand_frame = slot.gaussians(verts, Rv) + frames.append(hand_frame) + labels.append(_label_block( + hand_frame.means.shape[0], n_classes, slot_i + 1, hand_frame.means.device + )) + + if bg_gaussians is not None and bg_pose_field is not None: + R_bg, t_bg = bg_pose_field(t) + bg_frame = bg_gaussians(R_bg, t_bg) + frames.append(bg_frame) + labels.append(_label_block(bg_frame.means.shape[0], n_classes, None, bg_frame.means.device)) + + return concat_frames(frames), torch.cat(labels, dim=0).contiguous() + + +def _segmentation_mask_loss( + rendered_class: torch.Tensor, + cache: SimpleFrameCache, + t: int, + valid_mask: torch.Tensor, + valid_denom: torch.Tensor, +) -> torch.Tensor: + n_classes = int(rendered_class.shape[-1]) + target = rendered_class.new_zeros(rendered_class.shape) + target[..., 0] = cache.obj_mask[t].to(rendered_class.device, non_blocking=True) + for slot_i, hand_mask in enumerate(cache.hand_masks): + if slot_i + 1 >= n_classes: + break + target[..., slot_i + 1] = hand_mask[t].to(rendered_class.device, non_blocking=True) + diff = (rendered_class - target).abs() + return (diff * valid_mask.unsqueeze(-1)).sum() / ( + valid_denom * float(max(n_classes, 1)) + ) + + +def _normalized_smooth(loss: torch.Tensor, n: int) -> torch.Tensor: + return loss / float(max(n - 1, 1)) + + +def _cosine_lr_scale(step: int, total_steps: int, min_factor: float) -> float: + if total_steps <= 1: + return float(min_factor) + progress = min(max(int(step), 0), int(total_steps) - 1) / float(int(total_steps) - 1) + return float(min_factor) + 0.5 * (1.0 - float(min_factor)) * (1.0 + math.cos(math.pi * progress)) + + +def _first_nonfinite_tensor( + tensors: list[tuple[str, torch.Tensor | None]], +) -> str | None: + """Return the first named tensor containing NaN or Inf, if any.""" + for name, tensor in tensors: + if tensor is not None and not bool(torch.isfinite(tensor).all()): + return name + return None + + +def _quat_conj(q: torch.Tensor) -> torch.Tensor: + return torch.cat([q[..., :1], -q[..., 1:]], dim=-1) + + +def _hand_root_quats_camera(slot: HandSlot, t_idx: torch.Tensor) -> torch.Tensor: + q_hand = axis_angle_to_quat(slot.pose_field.global_orient[t_idx]) + if not slot.pose_field.is_right: + q_hand = torch.cat([q_hand[..., :2], -q_hand[..., 2:]], dim=-1) + return q_hand + + +def _hand_object_relative_smoothness( + obj_pose_field: ObjectPoseField, + slot: HandSlot, + w_smooth_hand_object_relative_rot: float, + w_smooth_hand_object_relative_trans: float, +) -> torch.Tensor: + loss = obj_pose_field.axis_angle.new_zeros(()) + if ( + float(w_smooth_hand_object_relative_rot) <= 0.0 + and float(w_smooth_hand_object_relative_trans) <= 0.0 + ): + return loss + + object_frame_to_pos = {fidx: i for i, fidx in enumerate(obj_pose_field.frame_indices)} + paired: list[tuple[int, int]] = [] + for hand_t, fidx in enumerate(slot.pose_field.frame_indices): + obj_t = object_frame_to_pos.get(fidx) + if obj_t is not None: + paired.append((hand_t, obj_t)) + if len(paired) < 2: + return loss + + device = obj_pose_field.axis_angle.device + hand_idx = torch.tensor([h for h, _ in paired], device=device, dtype=torch.long) + obj_idx = torch.tensor([o for _, o in paired], device=device, dtype=torch.long) + + R_obj, t_obj = obj_pose_field.batched_forward(obj_idx) + q_obj = axis_angle_to_quat(obj_pose_field.axis_angle[obj_idx]) + q_hand = _hand_root_quats_camera(slot, hand_idx) + t_hand = slot.pose_field.cam_t[hand_idx] + + if float(w_smooth_hand_object_relative_rot) > 0.0: + q_rel = quat_mul(_quat_conj(q_obj), q_hand) + loss = loss + float(w_smooth_hand_object_relative_rot) * _normalized_smooth( + quat_smoothness(q_rel), + len(paired), + ) + if float(w_smooth_hand_object_relative_trans) > 0.0: + # Express hand root translation in the object frame, removing common + # camera-frame motion before applying temporal smoothness. + t_rel = torch.matmul((t_hand - t_obj).unsqueeze(1), R_obj).squeeze(1) + loss = loss + float(w_smooth_hand_object_relative_trans) * _normalized_smooth( + temporal_smoothness(t_rel), + len(paired), + ) + return loss + + +def _pose_smoothness( + obj_pose_field: ObjectPoseField, + hand_slots: list[HandSlot], + bg_pose_field: BackgroundPoseField | None, + w_smooth_object_rot: float, + w_smooth_object_trans: float, + w_smooth_hand_rot: float, + w_smooth_hand_articulation: float, + w_smooth_hand_trans: float, + w_smooth_hand_object_relative_rot: float, + w_smooth_hand_object_relative_trans: float, + w_smooth_camera_rot: float, + w_smooth_camera_trans: float, +) -> torch.Tensor: + loss = obj_pose_field.axis_angle.new_zeros(()) + T = obj_pose_field.num_frames() + loss = loss + float(w_smooth_object_rot) * _normalized_smooth( + rotation_smoothness(obj_pose_field.axis_angle), T + ) + loss = loss + float(w_smooth_object_trans) * _normalized_smooth( + temporal_smoothness(obj_pose_field.translation), T + ) + if bg_pose_field is not None: + loss = loss + float(w_smooth_camera_rot) * _normalized_smooth( + rotation_smoothness(bg_pose_field.axis_angle), T + ) + loss = loss + float(w_smooth_camera_trans) * _normalized_smooth( + temporal_smoothness(bg_pose_field.translation), T + ) + for slot in hand_slots: + n = slot.pose_field.num_frames() + loss = loss + float(w_smooth_hand_rot) * _normalized_smooth( + rotation_smoothness(slot.pose_field.global_orient), n + ) + loss = loss + float(w_smooth_hand_articulation) * _normalized_smooth( + rotation_smoothness(slot.pose_field.hand_pose.view(n, 15, 3)), n + ) + loss = loss + float(w_smooth_hand_trans) * _normalized_smooth( + temporal_smoothness(slot.pose_field.cam_t), n + ) + loss = loss + _hand_object_relative_smoothness( + obj_pose_field, + slot, + w_smooth_hand_object_relative_rot, + w_smooth_hand_object_relative_trans, + ) + return loss + + +def _save_camera_poses( + bg_pose_field: BackgroundPoseField, + frame_indices: list[int], + output_dir: str, +) -> None: + os.makedirs(output_dir, exist_ok=True) + q = axis_angle_to_quat(bg_pose_field.axis_angle.detach()).cpu().tolist() + tr = bg_pose_field.translation.detach().cpu().tolist() + for t, fidx in enumerate(frame_indices): + Transform3d(rotation=q[t], translation=tr[t], scale=[1.0, 1.0, 1.0]).save( + os.path.join(output_dir, f"{fidx:06d}.json") + ) + + +def _write_overlay_video( + output_path: str, + cache: SimpleFrameCache, + K: torch.Tensor, + width: int, + height: int, + device: torch.device, + obj_gaussians: torch.nn.Module, + obj_pose_field: ObjectPoseField, + hand_slots: list[HandSlot], + bg_gaussians: BackgroundGaussians | None, + bg_pose_field: BackgroundPoseField | None, + fps: float = 30.0, +) -> None: + os.makedirs(os.path.dirname(os.path.abspath(output_path)) or ".", exist_ok=True) + with tempfile.TemporaryDirectory() as tmp: + with torch.no_grad(): + for t, fidx in enumerate(tqdm(cache.frame_indices, desc="render overlay", ncols=80)): + frame = _current_frame( + t, fidx, obj_gaussians, obj_pose_field, hand_slots, + bg_gaussians, bg_pose_field, + ) + rgb = _render_2dgs_rgb(frame, K, width, height) + arr = (rgb.clamp(0.0, 1.0) * 255).to(torch.uint8).cpu().numpy() + Image.fromarray(arr).save(os.path.join(tmp, f"{t:06d}.png")) + subprocess.run([ + "ffmpeg", "-y", "-loglevel", "error", + "-r", str(fps), + "-i", os.path.join(tmp, "%06d.png"), + "-c:v", "libx264", "-pix_fmt", "yuv420p", "-crf", "20", + output_path, + ], check=True) + + +def _class_render_to_rgb(rendered_class: torch.Tensor) -> torch.Tensor: + """Colorize alpha-composited class channels for progress visualization.""" + if rendered_class.numel() == 0 or rendered_class.shape[-1] == 0: + h, w = rendered_class.shape[:2] + return rendered_class.new_zeros((h, w, 3)) + palette = rendered_class.new_tensor([ + [1.00, 0.24, 0.12], # object + [0.10, 0.76, 1.00], # hand slot 0 + [1.00, 0.22, 0.86], # hand slot 1 + [0.70, 1.00, 0.18], + [1.00, 0.78, 0.12], + ]) + n_classes = int(rendered_class.shape[-1]) + if n_classes > palette.shape[0]: + repeats = (n_classes + palette.shape[0] - 1) // palette.shape[0] + palette = palette.repeat(repeats, 1) + return (rendered_class.clamp(0.0, 1.0) @ palette[:n_classes]).clamp(0.0, 1.0) + + +def _dump_progress_frame( + progress_dir: str, + step: int, + t: int, + cache: SimpleFrameCache, + K: torch.Tensor, + width: int, + height: int, + device: torch.device, + obj_gaussians: torch.nn.Module, + obj_pose_field: ObjectPoseField, + hand_slots: list[HandSlot], + bg_gaussians: BackgroundGaussians | None, + bg_pose_field: BackgroundPoseField | None, + mask_background: bool = False, +) -> None: + os.makedirs(progress_dir, exist_ok=True) + with torch.no_grad(): + fidx = cache.frame_indices[t] + target = _target_rgb(cache, t, device, mask_background) + n_mask_classes = 1 + len(hand_slots) + frame, labels = _current_frame_with_labels( + t, fidx, obj_gaussians, obj_pose_field, hand_slots, + bg_gaussians, bg_pose_field, n_mask_classes, + ) + render_frame = replace( + frame, + colors=torch.cat([frame.colors, labels.to(frame.colors.dtype)], dim=-1), + ) + rendered = _render_2dgs_features(render_frame, K, width, height) + pred = rendered[..., :3].clamp(0.0, 1.0) + rendered_mask = _class_render_to_rgb(rendered[..., 3:]) + err = (pred - target).abs().mul(4.0).clamp(0.0, 1.0) + panel = torch.cat([target, pred, rendered_mask, err], dim=1) + arr = (panel * 255).to(torch.uint8).cpu().numpy() + Image.fromarray(arr).save(os.path.join(progress_dir, f"{step:06d}.png")) + + +def _stitch_progress_video(progress_dir: str, fps: float = 12.0) -> None: + if not os.path.isdir(progress_dir): + return + pngs = [p for p in os.listdir(progress_dir) if p.endswith(".png")] + if not pngs: + return + out_path = os.path.join(os.path.dirname(progress_dir.rstrip("/")), "progress_simple.mp4") + subprocess.run([ + "ffmpeg", "-y", "-loglevel", "error", + "-r", str(fps), + "-pattern_type", "glob", + "-i", os.path.join(progress_dir, "*.png"), + "-c:v", "libx264", "-pix_fmt", "yuv420p", "-crf", "20", + out_path, + ], check=True) + print(f"Wrote simple-refinement progress video -> {out_path}") + + +def refine_simple( + frames_dir: str, + depth_dir: str | None, + intrinsics_path: str, + object_mesh_path: str, + object_poses_dir: str, + object_mask_dir: str, + refined_object_poses_dir: str, + overlay_path: str, + left_hand_pose_dir: str | None = None, + left_hand_mask_dir: str | None = None, + right_hand_pose_dir: str | None = None, + right_hand_mask_dir: str | None = None, + refined_left_hand_pose_dir: str | None = None, + refined_right_hand_pose_dir: str | None = None, + refined_camera_poses_dir: str | None = None, + mano_assets_root: str | None = None, + background_pose_init_dir: str | None = None, + n_epochs: int = 20, + batch_size: int = 4, + train_resolution_scale: float = 0.5, + lr_gaussians: float = 1e-2, + lr_object_pose: float = 1e-3, + lr_object_scale: float = 0.0, + lr_hand_pose: float = 1e-3, + lr_hand_articulation: float = 0.0, + lr_hand_shape: float = 0.0, + lr_hand_scale: float = 0.0, + lr_camera_pose: float = 1e-4, + lr_schedule: str = "constant", + lr_cosine_min_factor: float = 0.0, + w_smooth_object_rot: float = 0.01, + w_smooth_object_trans: float = 0.01, + w_smooth_hand_rot: float = 0.01, + w_smooth_hand_articulation: float = 0.01, + w_smooth_hand_trans: float = 0.01, + w_smooth_hand_object_relative_rot: float = 0.0, + w_smooth_hand_object_relative_trans: float = 0.0, + w_smooth_camera_rot: float = 0.01, + w_smooth_camera_trans: float = 0.01, + w_mask: float = 1.0, + w_relative_depth: float = 0.0, + w_perceptual: float = 0.0, + vgg_weights_path: str | None = None, + perceptual_resize: int = 224, + w_hand_object_penetration: float = 0.0, + hand_object_penetration_margin: float = 0.003, + object_sdf_resolution: int = 96, + hand_object_penetration_max_verts: int = 0, + mask_background: bool = False, + bg_ref_frame: int | None = None, + bg_init_stride: int = 10, + bg_voxel_size: float = 0.005, + bg_max_points: int = 50000, + valid_mask_threshold: float = 0.04, + valid_mask_erode_iters: int = 2, + face_normal_thin_factor_obj: float = 0.25, + face_normal_thin_factor_hand: float = 0.25, + init_opacity_obj: float = 0.9, + init_opacity_hand: float = 0.9, + init_opacity_bg: float = 0.9, + init_gaussian_scale_factor: float = 1.0, + render_every: int = 25, + progress_dir: str | None = None, + debug_frame_idx: int | None = None, + fps: float = 30.0, + seed: int = 0, + device: str = "cuda", +) -> None: + if (left_hand_pose_dir or right_hand_pose_dir) and mano_assets_root is None: + raise ValueError("mano_assets_root is required when refining hand tracks") + if left_hand_pose_dir and left_hand_mask_dir is None: + raise ValueError("left_hand_mask_dir is required with left_hand_pose_dir") + if right_hand_pose_dir and right_hand_mask_dir is None: + raise ValueError("right_hand_mask_dir is required with right_hand_pose_dir") + if not mask_background and depth_dir is None: + raise ValueError("depth_dir is required unless --mask-background is set") + if float(w_relative_depth) > 0.0 and depth_dir is None: + raise ValueError("depth_dir is required when --w_relative_depth is nonzero") + lr_schedule = str(lr_schedule).lower() + if lr_schedule not in {"constant", "cosine"}: + raise ValueError("lr_schedule must be 'constant' or 'cosine'") + lr_cosine_min_factor = float(lr_cosine_min_factor) + if lr_cosine_min_factor < 0.0 or lr_cosine_min_factor > 1.0: + raise ValueError("lr_cosine_min_factor must be in [0, 1]") + + torch.manual_seed(seed) + device_t = torch.device(device) + + K, width, height = load_intrinsics(intrinsics_path, str(device_t)) + if train_resolution_scale != 1.0: + s = float(train_resolution_scale) + K = K.clone() + K[0, 0] *= s + K[1, 1] *= s + K[0, 2] *= s + K[1, 2] *= s + width = max(1, int(round(width * s))) + height = max(1, int(round(height * s))) + print(f"Training/render resolution: {width}x{height} (scale={s:.3f})") + + available_frames = _list_frame_indices(frames_dir) + object_track = _restrict_object_track(load_object_poses(object_poses_dir, str(device_t)), available_frames) + frame_indices = list(object_track.frame_indices) + keep = set(frame_indices) + + raw_hand_specs: list[tuple[str, str, str, str | None]] = [] + if left_hand_pose_dir is not None: + raw_hand_specs.append(("left", left_hand_pose_dir, left_hand_mask_dir, refined_left_hand_pose_dir)) + if right_hand_pose_dir is not None: + raw_hand_specs.append(("right", right_hand_pose_dir, right_hand_mask_dir, refined_right_hand_pose_dir)) + + hand_tracks: list[tuple[str, HandPoseTrack, str, str | None]] = [] + for side, pose_dir, mask_dir, out_dir in raw_hand_specs: + ht = _restrict_hand_track(load_hand_poses(pose_dir, str(device_t)), keep) + hand_tracks.append((side, ht, mask_dir, out_dir)) + + cache = SimpleFrameCache( + frame_indices=frame_indices, + frames_dir=frames_dir, + depth_dir=depth_dir if (not mask_background or float(w_relative_depth) > 0.0) else None, + object_mask_dir=object_mask_dir, + hand_mask_dirs=[h[2] for h in hand_tracks], + height=height, + width=width, + valid_mask_threshold=valid_mask_threshold, + valid_mask_erode_iters=valid_mask_erode_iters, + ) + valid_mask = cache.valid_mask.to(device_t, non_blocking=True) + valid_denom = valid_mask.sum().clamp_min(1.0) + + obj_pose_field = ObjectPoseField(object_track).to(device_t) + obj_verts, obj_colors, obj_faces = load_object_mesh(object_mesh_path, str(device_t)) + obj_gaussians = init_object_face_gaussians_from_mesh( + obj_verts, obj_faces, obj_colors, + normal_thin_factor=face_normal_thin_factor_obj, + init_opacity=init_opacity_obj, + init_scale_factor=init_gaussian_scale_factor, + ).to(device_t) + obj_g_params = _trainable_gaussian_params(obj_gaussians) + if float(lr_object_scale) > 0.0 and hasattr(obj_gaussians, "_log_scale_global"): + obj_gaussians._log_scale_global.requires_grad_(True) + object_trainable = "appearance" + if getattr(obj_gaussians, "_log_scale_global", None) is not None and obj_gaussians._log_scale_global.requires_grad: + object_trainable += ", global scale" + print(f"Object: {obj_gaussians.num_gaussians()} face-anchored Gaussians " + f"(trainable: {object_trainable})") + + hand_slots: list[HandSlot] = [] + for slot_i, (side, ht, mask_dir, out_dir) in enumerate(hand_tracks): + pf = HandPoseField( + ht, + mano_assets_root, + device=device_t, + learn_hand_scale=float(lr_hand_scale) > 0.0, + ).to(device_t) + _freeze_all(pf) + if float(lr_hand_pose) > 0.0: + pf.global_orient.requires_grad_(True) + pf.cam_t.requires_grad_(True) + if float(lr_hand_articulation) > 0.0: + pf.hand_pose.requires_grad_(True) + if float(lr_hand_shape) > 0.0: + pf.betas.requires_grad_(True) + if float(lr_hand_scale) > 0.0: + pf.hand_scale.requires_grad_(True) + with torch.no_grad(): + zero_pose = torch.zeros(1, 48, device=device_t) + zero_betas = torch.zeros(1, 10, device=device_t) + rest = pf.mano(zero_pose, zero_betas).verts[0].detach().clone() + if not ht.is_right: + rest = rest * rest.new_tensor([-1.0, 1.0, 1.0]) + faces_np = pf.mano.th_faces.detach().cpu().numpy() + hg = init_hand_face_gaussians( + rest_vertices=rest, + faces=faces_np, + is_right=ht.is_right, + normal_thin_factor=face_normal_thin_factor_hand, + hand_scale_init=float(getattr(ht, "hand_scale", 1.0) or 1.0), + init_opacity=init_opacity_hand, + init_scale_factor=init_gaussian_scale_factor, + device=device_t, + ).to(device_t) + if cache.hand_masks[slot_i].sum() > 0: + mask_sum = cache.hand_masks[slot_i].sum().clamp_min(1.0) + mean_rgb = (cache.rgb * cache.hand_masks[slot_i].unsqueeze(-1)).sum(dim=(0, 1, 2)) / mask_sum + with torch.no_grad(): + hg._color.copy_(mean_rgb.to(device_t).expand_as(hg._color)) + hg_params = _trainable_gaussian_params(hg) + trainable_hand = [] + if pf.global_orient.requires_grad or pf.cam_t.requires_grad: + trainable_hand.append("root") + if pf.hand_pose.requires_grad: + trainable_hand.append("fingers") + if pf.betas.requires_grad: + trainable_hand.append("shape") + if pf.hand_scale.requires_grad: + trainable_hand.append("scale") + trainable_desc = ", ".join(trainable_hand) if trainable_hand else "none" + print(f"Hand {side}: {hg.num_gaussians()} face-anchored Gaussians " + f"(trainable: {trainable_desc})") + hand_slots.append(HandSlot( + side=side, + track=ht, + pose_field=pf, + gaussians=hg, + mask_dir=mask_dir, + output_pose_dir=out_dir, + frame_to_pos={fidx: i for i, fidx in enumerate(ht.frame_indices)}, + )) + del hg_params # collected below by module reference + + if bg_ref_frame is not None and int(bg_ref_frame) in frame_indices: + ref_t = frame_indices.index(int(bg_ref_frame)) + else: + ref_t = 0 + bg_gaussians: BackgroundGaussians | None = None + bg_pose_field: BackgroundPoseField | None = None + bg_g_params: list[torch.nn.Parameter] = [] + if mask_background: + if background_pose_init_dir is not None: + print("Ignoring background_pose_init_dir because --mask-background omits background Gaussians.") + if refined_camera_poses_dir is not None: + print("Ignoring refined_camera_poses_dir because --mask-background omits camera/background pose refinement.") + print("Mask background: target background is black and no background Gaussians are rendered.") + else: + if cache.depth is None: + raise RuntimeError("Depth cache is missing; depth_dir is required for background refinement.") + slam_poses = None + if background_pose_init_dir is not None: + slam_poses = _load_relative_w2c_poses(background_pose_init_dir, frame_indices, ref_t) + + def union_for_bg(t: int) -> torch.Tensor: + m = cache.union_mask(t, device_t) + m = torch.maximum(m, 1.0 - valid_mask) + return m + + if slam_poses is not None and bg_init_stride > 1: + positions = sorted({ref_t} | set(range(0, len(frame_indices), int(bg_init_stride)))) + positions = [t for t in positions if t in slam_poses] + T_w2c_list = [torch.from_numpy(slam_poses[t]).to(device_t, dtype=torch.float32) for t in positions] + anchors, colors, init_scales = init_background_multiframe( + rgbs=[cache.rgb[t].to(device_t) for t in positions], + depths=[cache.depth[t].to(device_t) for t in positions], + union_masks=[union_for_bg(t) for t in positions], + T_w2c_list=T_w2c_list, + K=K, + voxel_size=bg_voxel_size, + max_points=bg_max_points, + ) + print(f"Background: initialized from {len(positions)} frames") + else: + anchors, colors, init_scales = init_background_from_depth( + rgb=cache.rgb[ref_t].to(device_t), + depth=cache.depth[ref_t].to(device_t), + union_mask=union_for_bg(ref_t), + K=K, + max_points=bg_max_points, + ) + print(f"Background: initialized from frame {frame_indices[ref_t]:06d}") + bg_gaussians = BackgroundGaussians( + anchors, colors, init_scales, + init_opacity=init_opacity_bg, + init_scale_factor=init_gaussian_scale_factor, + ).to(device_t) + bg_g_params = _trainable_gaussian_params(bg_gaussians) + bg_pose_field = BackgroundPoseField(len(frame_indices), device=device_t, ref_frame_t=ref_t).to(device_t) + if slam_poses is not None: + loaded, missing = _seed_background_pose_field(bg_pose_field, slam_poses) + print(f"Camera/background pose seed: loaded {loaded}, missing {missing}") + _anchor_camera_reference(bg_pose_field) + print(f"Background: {bg_gaussians.num_gaussians()} depth-initialized Gaussians") + + use_mask_loss = float(w_mask) > 0.0 + n_mask_classes = 1 + len(hand_slots) + if use_mask_loss: + print(f"Segmentation mask L1: weight={float(w_mask):.4g}, classes={n_mask_classes}") + + use_relative_depth_loss = float(w_relative_depth) > 0.0 + if use_relative_depth_loss: + if cache.depth is None: + raise RuntimeError("Depth cache is missing; depth_dir is required for relative depth loss.") + region = "foreground masks" if mask_background else "valid image region" + print(f"Relative MoGe depth-gradient loss: weight={float(w_relative_depth):.4g}, " + f"region={region}") + + if ( + float(w_smooth_hand_object_relative_rot) > 0.0 + or float(w_smooth_hand_object_relative_trans) > 0.0 + ): + if hand_slots: + print( + "Hand/object relative smoothness: " + f"rot={float(w_smooth_hand_object_relative_rot):.4g}, " + f"trans={float(w_smooth_hand_object_relative_trans):.4g}" + ) + else: + print("Ignoring hand/object relative smoothness because no hand tracks are present.") + + use_perceptual_loss = float(w_perceptual) > 0.0 + perceptual_loss_fn: VGG16PerceptualLoss | None = None + if use_perceptual_loss: + perceptual_loss_fn = VGG16PerceptualLoss( + weights_path=vgg_weights_path, + resize=perceptual_resize, + ).to(device_t) + print(f"VGG16 perceptual L1: weight={float(w_perceptual):.4g}, " + f"resize={int(perceptual_resize)}") + + object_sdf: ObjectSDFGrid | None = None + if float(w_hand_object_penetration) > 0.0: + if hand_slots: + object_sdf = _build_object_sdf_grid( + obj_verts, + obj_faces, + object_sdf_resolution, + hand_object_penetration_margin, + device_t, + ) + print( + f"Hand/object penetration: weight={float(w_hand_object_penetration):.4g}, " + f"margin={float(hand_object_penetration_margin):.4g}, " + f"sdf_res={int(object_sdf_resolution)}" + ) + else: + print("Ignoring hand/object penetration loss because no hand tracks are present.") + + progress_t = ref_t + if debug_frame_idx is not None: + try: + progress_t = frame_indices.index(int(debug_frame_idx)) + except ValueError: + print(f"Warning: debug_frame_idx={debug_frame_idx} not in sequence; " + f"using frame {frame_indices[progress_t]:06d} for progress.") + if render_every > 0 and progress_dir is None: + progress_dir = os.path.join( + os.path.dirname(os.path.abspath(overlay_path)) or ".", + "refined_simple_progress", + ) + if render_every > 0 and progress_dir is not None: + print(f"Simple-refinement progress frames -> {progress_dir} " + f"(frame {frame_indices[progress_t]:06d}, every {render_every} steps)") + _dump_progress_frame( + progress_dir, 0, progress_t, cache, K, width, height, device_t, + obj_gaussians, obj_pose_field, hand_slots, bg_gaussians, bg_pose_field, + mask_background=mask_background, + ) + + param_groups: list[dict] = [] + if obj_g_params: + param_groups.append({"params": obj_g_params, "lr": lr_gaussians}) + for slot in hand_slots: + params = [p for p in (slot.gaussians._log_scale, slot.gaussians._opacity_logit, slot.gaussians._color) if p.requires_grad] + if params: + param_groups.append({"params": params, "lr": lr_gaussians}) + if bg_g_params: + param_groups.append({"params": bg_g_params, "lr": lr_gaussians}) + if float(lr_object_scale) > 0.0 and hasattr(obj_gaussians, "_log_scale_global"): + param_groups.append({"params": [obj_gaussians._log_scale_global], "lr": lr_object_scale}) + param_groups.extend([ + {"params": [obj_pose_field.axis_angle], "lr": lr_object_pose}, + {"params": [obj_pose_field.translation], "lr": lr_object_pose}, + ]) + if bg_pose_field is not None: + param_groups.extend([ + {"params": [bg_pose_field.axis_angle], "lr": lr_camera_pose}, + {"params": [bg_pose_field.translation], "lr": lr_camera_pose}, + ]) + for slot in hand_slots: + if float(lr_hand_pose) > 0.0: + param_groups.append({"params": [slot.pose_field.global_orient], "lr": lr_hand_pose}) + param_groups.append({"params": [slot.pose_field.cam_t], "lr": lr_hand_pose}) + if float(lr_hand_articulation) > 0.0: + param_groups.append({"params": [slot.pose_field.hand_pose], "lr": lr_hand_articulation}) + if float(lr_hand_shape) > 0.0: + param_groups.append({"params": [slot.pose_field.betas], "lr": lr_hand_shape}) + if float(lr_hand_scale) > 0.0: + param_groups.append({"params": [slot.pose_field.hand_scale], "lr": lr_hand_scale}) + + optimizer = torch.optim.Adam(param_groups) + # The rasterizer can occasionally emit an invalid backward value for a + # plausible initial trajectory. Keep that one mini-batch from poisoning + # every pose through the sequence-wide smoothness terms. + trainable_params = [ + param for group in optimizer.param_groups for param in group["params"] + ] + max_grad_norm = 1.0 + print(f"Gradient clipping: global norm <= {max_grad_norm:g}") + base_lrs = [float(group["lr"]) for group in optimizer.param_groups] + T = len(frame_indices) + n_batches = max(1, (T + int(batch_size) - 1) // int(batch_size)) + total_steps = int(n_epochs) * n_batches + lr_scale = 1.0 + if lr_schedule == "cosine": + print(f"LR schedule: cosine, min_factor={lr_cosine_min_factor:.4g}, steps={total_steps}") + pbar = tqdm(total=total_steps, ncols=100, desc="refine_simple") + step = 0 + for _epoch in range(int(n_epochs)): + order = torch.randperm(T).tolist() + for start in range(0, T, int(batch_size)): + batch = order[start:start + int(batch_size)] + if lr_schedule == "cosine": + lr_scale = _cosine_lr_scale(step, total_steps, lr_cosine_min_factor) + for group, base_lr in zip(optimizer.param_groups, base_lrs): + group["lr"] = base_lr * lr_scale + optimizer.zero_grad(set_to_none=True) + photo = obj_pose_field.axis_angle.new_zeros(()) + mask_l1 = obj_pose_field.axis_angle.new_zeros(()) + relative_depth = obj_pose_field.axis_angle.new_zeros(()) + perceptual = obj_pose_field.axis_angle.new_zeros(()) + penetration = obj_pose_field.axis_angle.new_zeros(()) + for t in batch: + fidx = frame_indices[t] + target = _target_rgb(cache, t, device_t, mask_background) + if use_mask_loss: + frame, labels = _current_frame_with_labels( + t, fidx, obj_gaussians, obj_pose_field, hand_slots, + bg_gaussians, bg_pose_field, n_mask_classes, + ) + render_frame = replace( + frame, + colors=torch.cat([frame.colors, labels.to(frame.colors.dtype)], dim=-1), + ) + rendered = _render_2dgs_features(render_frame, K, width, height) + pred = rendered[..., :3] + class_pred = rendered[..., 3:] + mask_l1 = mask_l1 + _segmentation_mask_loss( + class_pred, cache, t, valid_mask, valid_denom, + ) + else: + frame = _current_frame( + t, fidx, obj_gaussians, obj_pose_field, hand_slots, + bg_gaussians, bg_pose_field, + ) + pred = _render_2dgs_rgb(frame, K, width, height) + per_pixel = (pred - target).abs().sum(dim=-1) + photo = photo + (per_pixel * valid_mask).sum() / valid_denom + if perceptual_loss_fn is not None: + perceptual = perceptual + perceptual_loss_fn(pred, target, valid_mask) + if use_relative_depth_loss: + rendered_depth, rendered_alpha = _render_2dgs_depth(frame, K, width, height) + target_depth = cache.depth[t].to(device_t, non_blocking=True) + depth_mask = ( + cache.union_mask(t, device_t) + if mask_background else valid_mask + ) + depth_mask = depth_mask * (rendered_alpha > 1e-3).to(depth_mask.dtype) + relative_depth = relative_depth + depth_gradient_loss( + rendered_depth, + target_depth, + depth_mask, + ) + if object_sdf is not None: + penetration = penetration + _hand_object_penetration_loss( + t, + fidx, + obj_pose_field, + obj_gaussians, + hand_slots, + object_sdf, + hand_object_penetration_margin, + hand_object_penetration_max_verts, + ) + photo = photo / float(max(len(batch), 1)) + mask_l1 = mask_l1 / float(max(len(batch), 1)) + relative_depth = relative_depth / float(max(len(batch), 1)) + perceptual = perceptual / float(max(len(batch), 1)) + penetration = penetration / float(max(len(batch), 1)) + smooth = _pose_smoothness( + obj_pose_field, hand_slots, bg_pose_field, + w_smooth_object_rot, w_smooth_object_trans, + w_smooth_hand_rot, w_smooth_hand_articulation, w_smooth_hand_trans, + w_smooth_hand_object_relative_rot, w_smooth_hand_object_relative_trans, + w_smooth_camera_rot, w_smooth_camera_trans, + ) / float(n_batches) + loss = ( + photo + + float(w_mask) * mask_l1 + + float(w_relative_depth) * relative_depth + + float(w_perceptual) * perceptual + + float(w_hand_object_penetration) * penetration + + smooth + ) + if not bool(torch.isfinite(loss)): + print( + f"WARNING: skipping non-finite refinement loss at step={step}, " + f"frames={[frame_indices[t] for t in batch]}" + ) + optimizer.zero_grad(set_to_none=True) + step += 1 + pbar.update(1) + continue + + loss.backward() + bad_gradient = _first_nonfinite_tensor([ + (f"gradient for group={group_i} param={param_i} shape={tuple(param.shape)}", param.grad) + for group_i, group in enumerate(optimizer.param_groups) + for param_i, param in enumerate(group["params"]) + ]) + if bad_gradient is not None: + print( + f"WARNING: skipping non-finite refinement gradient at step={step}, " + f"frames={[frame_indices[t] for t in batch]}: {bad_gradient}" + ) + optimizer.zero_grad(set_to_none=True) + step += 1 + pbar.update(1) + continue + + grad_norm = torch.nn.utils.clip_grad_norm_( + trainable_params, max_norm=max_grad_norm, error_if_nonfinite=False + ) + if not bool(torch.isfinite(grad_norm)): + print( + f"WARNING: skipping non-finite gradient norm at step={step}, " + f"frames={[frame_indices[t] for t in batch]}" + ) + optimizer.zero_grad(set_to_none=True) + step += 1 + pbar.update(1) + continue + + optimizer.step() + bad_parameter = _first_nonfinite_tensor([ + (f"group={group_i} param={param_i} shape={tuple(param.shape)}", param) + for group_i, group in enumerate(optimizer.param_groups) + for param_i, param in enumerate(group["params"]) + ]) + if bad_parameter is not None: + raise FloatingPointError( + f"Non-finite refinement parameter after optimizer step {step}, " + f"frames={[frame_indices[t] for t in batch]}: {bad_parameter}" + ) + if bg_pose_field is not None: + _anchor_camera_reference(bg_pose_field) + step += 1 + if render_every > 0 and progress_dir is not None and step % int(render_every) == 0: + _dump_progress_frame( + progress_dir, step, progress_t, cache, K, width, height, device_t, + obj_gaussians, obj_pose_field, hand_slots, bg_gaussians, bg_pose_field, + mask_background=mask_background, + ) + pbar.update(1) + pbar.set_postfix( + photo=f"{float(photo.detach()):.4f}", + mask=f"{float(mask_l1.detach()):.4f}", + rdepth=f"{float(relative_depth.detach()):.4f}", + perc=f"{float(perceptual.detach()):.4f}", + pen=f"{float(penetration.detach()):.4f}", + lr=f"{lr_scale:.3g}", + smooth=f"{float(smooth.detach()):.4f}", + ) + pbar.close() + if render_every > 0 and progress_dir is not None: + _dump_progress_frame( + progress_dir, step, progress_t, cache, K, width, height, device_t, + obj_gaussians, obj_pose_field, hand_slots, bg_gaussians, bg_pose_field, + mask_background=mask_background, + ) + _stitch_progress_video(progress_dir) + + refined_obj_track = obj_pose_field.export_track() + s_obj_learned = float(obj_gaussians.object_scale().detach()) + refined_obj_track.scales = refined_obj_track.scales * s_obj_learned + if float(lr_object_scale) > 0.0: + print(f"Learned object scale: {s_obj_learned:.4f}") + save_object_poses(refined_obj_track, refined_object_poses_dir) + print(f"Wrote refined object poses -> {refined_object_poses_dir}") + for slot in hand_slots: + if slot.output_pose_dir is None: + continue + save_hand_poses(slot.pose_field.export_track(slot.track.raw_records), slot.output_pose_dir) + print(f"Wrote refined {slot.side} hand poses -> {slot.output_pose_dir}") + if refined_camera_poses_dir is not None and bg_pose_field is not None: + _save_camera_poses(bg_pose_field, frame_indices, refined_camera_poses_dir) + print(f"Wrote refined camera/background poses -> {refined_camera_poses_dir}") + + _write_overlay_video( + output_path=overlay_path, + cache=cache, + K=K, + width=width, + height=height, + device=device_t, + obj_gaussians=obj_gaussians, + obj_pose_field=obj_pose_field, + hand_slots=hand_slots, + bg_gaussians=bg_gaussians, + bg_pose_field=bg_pose_field, + fps=fps, + ) + print(f"Wrote overlay -> {overlay_path}") + + +def parse_args() -> argparse.Namespace: + p = argparse.ArgumentParser(description=__doc__) + p.add_argument("--frames_dir", required=True) + p.add_argument("--depth_dir", default=None, + help="Depth frames for background initialization. Required unless --mask-background is set.") + p.add_argument("--intrinsics_path", required=True) + p.add_argument("--object_mesh_path", required=True) + p.add_argument("--object_poses_dir", required=True) + p.add_argument("--object_mask_dir", required=True) + p.add_argument("--refined_object_poses_dir", required=True) + p.add_argument("--overlay_path", required=True) + p.add_argument("--left_hand_pose_dir", default=None) + p.add_argument("--left_hand_mask_dir", default=None) + p.add_argument("--right_hand_pose_dir", default=None) + p.add_argument("--right_hand_mask_dir", default=None) + p.add_argument("--refined_left_hand_pose_dir", default=None) + p.add_argument("--refined_right_hand_pose_dir", default=None) + p.add_argument("--refined_camera_poses_dir", default=None) + p.add_argument("--mano_assets_root", default=None) + p.add_argument("--background_pose_init_dir", default=None) + p.add_argument("--n_epochs", type=int, default=20) + p.add_argument("--batch_size", type=int, default=4) + p.add_argument("--train_resolution_scale", type=float, default=0.5) + p.add_argument("--lr_gaussians", type=float, default=1e-2) + p.add_argument("--lr_object_pose", type=float, default=1e-3) + p.add_argument("--lr_object_scale", type=float, default=0.0, + help="LR for global object scale. 0 disables.") + p.add_argument("--lr_hand_pose", type=float, default=1e-3, + help="LR for hand root global_orient and cam_t. 0 disables root pose refinement.") + p.add_argument("--lr_hand_articulation", type=float, default=0.0, + help="LR for MANO finger articulation hand_pose. 0 disables.") + p.add_argument("--lr_hand_shape", type=float, default=0.0, + help="LR for shared MANO betas/shape per hand track. 0 disables.") + p.add_argument("--lr_hand_scale", type=float, default=0.0, + help="LR for shared per-track hand_scale. 0 disables.") + p.add_argument("--lr_camera_pose", type=float, default=1e-4) + p.add_argument("--lr_schedule", choices=["constant", "cosine"], default="constant", + help="Learning-rate schedule for all optimizer groups.") + p.add_argument("--lr_cosine_min_factor", type=float, default=0.0, + help="Final LR multiplier for --lr_schedule cosine. 0 decays to zero.") + p.add_argument("--w_smooth_object_rot", type=float, default=0.01) + p.add_argument("--w_smooth_object_trans", type=float, default=0.01) + p.add_argument("--w_smooth_hand_rot", type=float, default=0.01) + p.add_argument("--w_smooth_hand_articulation", type=float, default=0.01, + help="Temporal rotation smoothness for MANO finger hand_pose.") + p.add_argument("--w_smooth_hand_trans", type=float, default=0.01) + p.add_argument("--w_smooth_hand_object_relative_rot", type=float, default=0.0, + help="Temporal smoothness for hand root rotation relative to object pose. 0 disables.") + p.add_argument("--w_smooth_hand_object_relative_trans", type=float, default=0.0, + help="Temporal smoothness for hand root translation in the object frame. " + "0 disables.") + p.add_argument("--w_smooth_camera_rot", type=float, default=0.01) + p.add_argument("--w_smooth_camera_trans", type=float, default=0.01) + p.add_argument("--w_mask", type=float, default=1.0, + help="Weight for L1 segmentation mask loss. 0 disables.") + p.add_argument("--w_relative_depth", type=float, default=0.0, + help="Weight for log-depth-gradient loss against MoGe depth. 0 disables.") + p.add_argument("--w_perceptual", type=float, default=0.0, + help="Weight for VGG16 perceptual feature L1 loss. 0 disables.") + p.add_argument("--vgg_weights_path", default=None, + help="Optional local VGG16 state_dict path. If missing, torchvision ImageNet weights are downloaded there.") + p.add_argument("--perceptual_resize", type=int, default=224, + help="Square resize for VGG perceptual loss. <=0 uses training resolution.") + p.add_argument("--w_hand_object_penetration", type=float, default=0.0, + help="Weight for 3D hand/object SDF penetration loss. 0 disables.") + p.add_argument("--hand_object_penetration_margin", type=float, default=0.003, + help="Signed-distance margin in meters/object units for hand/object separation.") + p.add_argument("--object_sdf_resolution", type=int, default=96, + help="Resolution per axis for the object SDF grid used by hand/object penetration.") + p.add_argument("--hand_object_penetration_max_verts", type=int, default=0, + help="Max MANO verts per hand for penetration loss. 0 uses all vertices.") + p.add_argument("--mask-background", "--mask_background", dest="mask_background", action="store_true", + help="Black out target background and omit background Gaussians/camera refinement.") + p.add_argument("--bg_ref_frame", type=int, default=None) + p.add_argument("--bg_init_stride", type=int, default=10) + p.add_argument("--bg_voxel_size", type=float, default=0.005) + p.add_argument("--bg_max_points", type=int, default=50000) + p.add_argument("--valid_mask_threshold", type=float, default=0.04) + p.add_argument("--valid_mask_erode_iters", type=int, default=2) + p.add_argument("--face_normal_thin_factor_obj", type=float, default=0.25) + p.add_argument("--face_normal_thin_factor_hand", type=float, default=0.25) + p.add_argument("--init_opacity_obj", type=float, default=0.9) + p.add_argument("--init_opacity_hand", type=float, default=0.9) + p.add_argument("--init_opacity_bg", type=float, default=0.9) + p.add_argument("--init_gaussian_scale_factor", type=float, default=1.0, + help="Multiplier for all initial Gaussian scales/radii.") + p.add_argument("--render_every", type=int, default=25, + help="Write a target/render/error progress panel every N optimizer steps. 0 disables.") + p.add_argument("--progress_dir", default=None, + help="Directory for simple-refinement progress PNGs. Defaults next to overlay_path.") + p.add_argument("--debug_frame_idx", type=int, default=None, + help="Frame index to use for intermediate progress visualizations.") + p.add_argument("--fps", type=float, default=30.0) + p.add_argument("--seed", type=int, default=0) + p.add_argument("--device", default="cuda") + return p.parse_args() + + +def main() -> None: + args = parse_args() + refine_simple(**vars(args)) + + +if __name__ == "__main__": + main() diff --git a/third-party/video_to_data/reconstruction/modules/v2d_gsplat_refinement/lib/render.py b/third-party/video_to_data/reconstruction/modules/v2d_gsplat_refinement/lib/render.py new file mode 100644 index 0000000000000000000000000000000000000000..dcc8c0ad21ea6de952e2bd751fd4d80b152fb8aa --- /dev/null +++ b/third-party/video_to_data/reconstruction/modules/v2d_gsplat_refinement/lib/render.py @@ -0,0 +1,172 @@ +# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 +"""gsplat render wrapper for the refinement loop. + +Renders Gaussian sets into the camera frame. We build everything already in +camera coords (object pose / MANO cam_t are applied by the pose fields), so +the view matrix passed to gsplat is identity and only the intrinsics matter. + +Three convenience entry points: + + render_rgb_depth(frame, K, H, W) -> (RGB, depth, alpha) + Single combined render of one ``GaussianFrame`` (typically the + concatenation of all sets) for the photometric + depth loss. + + render_alpha(frame, K, H, W) -> alpha + Cheaper render returning only the alpha channel; used per-set for the + silhouette loss. +""" +from __future__ import annotations + +import torch + +from .gaussians import GaussianFrame + + +# Lazy import to keep import-time light when only running tests on CPU +# without gsplat installed (e.g. unit tests of io.py). +def _rasterization(): + from gsplat.rendering import rasterization + return rasterization + + +_BG_BLACK = (0.0, 0.0, 0.0) + + +def _identity_viewmat(device: torch.device) -> torch.Tensor: + return torch.eye(4, device=device, dtype=torch.float32).unsqueeze(0) # (1, 4, 4) + + +def render_rgb_depth( + frame: GaussianFrame, + K: torch.Tensor, # (3, 3) + width: int, + height: int, + extra_features: torch.Tensor | None = None, # (N, F) extra per-Gaussian channels + near_plane: float = 0.01, + far_plane: float = 100.0, + compute_depth_variance: bool = False, +) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor, torch.Tensor | None, torch.Tensor | None]: + """Composite render of a Gaussian set in camera frame. + + If ``extra_features`` is provided, those per-Gaussian channels are + composited alongside RGB in a single pass (gsplat rasterizes any + feature dimension), and the corresponding (H, W, F) feature map is + returned. This is how the silhouette loss avoids needing N+1 separate + render passes: pack one-hot class labels into ``extra_features`` and + the same alpha compositing that produces RGB also gives a per-pixel + "front-most class" map that handles occlusion correctly. + + When ``compute_depth_variance=True``, an additional channel carrying + per-Gaussian ``d²`` (cam-frame z squared) is composited and the + function returns a per-pixel depth-variance map ``Var[d] = E[d²] − E[d]²``. + This is the depth-variance approximation to Mip-NeRF 360's distortion + loss (gsplat's mainline 3DGS rasterizer doesn't expose distloss; only + the 2DGS path does). The variance is alpha-normalized to match + ``depth = E[d]``, so it's a true variance with units of [depth²]. + + Returns: + rgb: (H, W, 3) + depth: (H, W) -- expected depth E[d] (alpha-weighted, normalized) + alpha: (H, W) -- accumulated opacity + features: (H, W, F) or None -- composited extra channels + depth_var: (H, W) or None -- E[d²] − E[d]², ≥ 0 (None when not requested) + """ + rasterization = _rasterization() + device = frame.means.device + viewmat = _identity_viewmat(device) + Ks = K.unsqueeze(0) + + # Pack channels: [user-extra | d² (optional)]. + extra_parts: list[torch.Tensor] = [] + if extra_features is not None: + extra_parts.append(extra_features) + F_user = extra_features.shape[-1] if extra_features is not None else 0 + if compute_depth_variance: + # Means live in cam frame here (viewmat is identity at this layer), + # so cam-z = means[:, 2]. Detach the centers? No — we *want* the + # gradient to push means toward smaller per-pixel variance. + d2 = (frame.means[:, 2] ** 2).unsqueeze(-1) # (N, 1) + extra_parts.append(d2) + + if extra_parts: + extra_all = torch.cat(extra_parts, dim=-1) # (N, F_user + (1?)) + colors = torch.cat([frame.colors, extra_all], dim=-1) # (N, 3 + F) + F_extra = extra_all.shape[-1] + else: + colors = frame.colors + F_extra = 0 + + bg = torch.zeros(3 + F_extra, device=device, dtype=torch.float32) + + out, alphas, _ = rasterization( + means = frame.means, + quats = frame.quats, + scales = frame.scales, + opacities = frame.opacities, + colors = colors, + viewmats = viewmat, + Ks = Ks, + width = width, + height = height, + near_plane = near_plane, + far_plane = far_plane, + render_mode= "RGB+ED", # ED = expected depth (alpha-weighted, normalized) + backgrounds= bg.unsqueeze(0), + ) + # out: (1, H, W, 3 + F_extra + 1) — last channel is depth. + rgb = out[0, ..., :3] + depth = out[0, ..., -1] # E[d], alpha-normalized + alpha = alphas[0, ..., 0] + + feats: torch.Tensor | None = None + if F_user > 0: + feats = out[0, ..., 3:3 + F_user] + + depth_var: torch.Tensor | None = None + if compute_depth_variance: + # Composited d² is NOT alpha-normalized by gsplat (extra features go + # through the standard sum_i T_i α_i x_i composite). Divide by alpha + # to get true E[d²], then variance = E[d²] − E[d]². Clamp alpha to + # avoid division by zero on empty pixels; clamp variance to ≥ 0 for + # float-precision safety (Jensen's inequality guarantees ≥ 0 in + # exact arithmetic). + d2_raw = out[0, ..., 3 + F_user] # (H, W) + e_d2 = d2_raw / alpha.clamp_min(1e-6) + depth_var = (e_d2 - depth * depth).clamp_min(0.0) + + return rgb, depth, alpha, feats, depth_var + + +def render_alpha( + frame: GaussianFrame, + K: torch.Tensor, + width: int, + height: int, + near_plane: float = 0.01, + far_plane: float = 100.0, +) -> torch.Tensor: + """Render only the accumulated opacity. (H, W).""" + rasterization = _rasterization() + device = frame.means.device + viewmat = _identity_viewmat(device) + Ks = K.unsqueeze(0) + # Use a 1-channel "color" of constant 1 so RGB is just alpha; we then + # take the alpha channel directly. Cheaper than dragging a 3-channel + # color through. + ones = torch.ones_like(frame.colors[..., :1]) + _, alphas, _ = rasterization( + means = frame.means, + quats = frame.quats, + scales = frame.scales, + opacities = frame.opacities, + colors = ones, + viewmats = viewmat, + Ks = Ks, + width = width, + height = height, + near_plane = near_plane, + far_plane = far_plane, + render_mode= "RGB", + ) + return alphas[0, ..., 0] diff --git a/third-party/video_to_data/reconstruction/modules/v2d_gsplat_refinement/lib/visualize.py b/third-party/video_to_data/reconstruction/modules/v2d_gsplat_refinement/lib/visualize.py new file mode 100644 index 0000000000000000000000000000000000000000..0eba336ec61a24fdb0c4e2c820d323fce4f74396 --- /dev/null +++ b/third-party/video_to_data/reconstruction/modules/v2d_gsplat_refinement/lib/visualize.py @@ -0,0 +1,957 @@ +# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 +"""Interactive OpenCV viewer for a v2d_gsplat_refinement checkpoint. + +Reconstructs the trained Gaussian sets + pose fields from a checkpoint and +shows them in a free-orbit camera. Controls: + + Mouse + LMB drag orbit around target + RMB drag pan target (in screen plane) + Wheel zoom (changes orbit distance) + + Keyboard + [ / ] previous / next frame + , / . previous / next 10 frames + space toggle play (auto-advance at --fps) + 1 toggle object visibility + 2 toggle hands visibility + 3 toggle background visibility + w toggle MANO wireframe overlay (per-hand color) + 0 reset to source-camera view (identity, frame intrinsics) + r reset orbit (target = current object centroid) + h print help to stdout + q / ESC quit + +The "world" coordinate frame is the *current* timestep's camera frame — +each Gaussian set produces its means already in that frame's camera coords, +matching the convention used by ``_render_overlay_video_streaming``. + +Usage: + python -m v2d.gsplat_refinement.lib.visualize \\ + --checkpoint /data/refine_checkpoint.pt \\ + --intrinsics_path /data/intrinsics_stable.json \\ + --mano_assets_root /data/weights/wilor/pretrained_models +""" +from __future__ import annotations + +import argparse +import json +import math +import os +import time + +os.environ.setdefault("PYOPENGL_PLATFORM", "egl") + +import cv2 +import numpy as np +import torch + +from .background import BackgroundGaussians, BackgroundPoseField +from .gaussians import ( + FaceGaussians, + GaussianFrame, + HandFaceGaussians, + HandGaussians, + ObjectGaussians, + WristAttachedGaussians, + concat_frames, + quat_mul, + rotmat_to_quat, +) +from .io import HandPoseTrack, ObjectPoseTrack +from .pose_fields import HandPoseField, IntrinsicsField, ObjectPoseField +from .refine import _orbit_viewmat_cv # already in CV convention + + +def _load_K(path: str) -> tuple[torch.Tensor, int, int]: + with open(path) as f: + d = json.load(f) + K = torch.tensor([ + [d["fx"], 0.0, d["cx"]], + [0.0, d["fy"], d["cy"]], + [0.0, 0.0, 1.0], + ], dtype=torch.float32) + return K, int(d["width"]), int(d["height"]) + + +def _scale_K(K: torch.Tensor, src_wh: tuple[int, int], dst_wh: tuple[int, int]) -> torch.Tensor: + sx = dst_wh[0] / src_wh[0] + sy = dst_wh[1] / src_wh[1] + K_out = K.clone() + K_out[0, 0] *= sx; K_out[0, 2] *= sx + K_out[1, 1] *= sy; K_out[1, 2] *= sy + return K_out + + +def _build_modules_from_ckpt( + ckpt: dict, mano_assets_root: str, device: torch.device, +) -> dict: + """Reconstruct trained modules from a checkpoint state_dict bundle. + + The checkpoint only stores state_dicts, so each module is built with + placeholder buffers of the right shape, then loaded. + """ + frame_indices: list[int] = list(ckpt["frame_indices"]) + T = len(frame_indices) + + # --- Object pose + Gaussians --------------------------------------- + # Detect anchor mode from state-dict keys: vertex-anchored has an + # "anchor" buffer; face-anchored has "centroid_canon" + "TBN_canon". + obj_state = ckpt["obj_gaussians"] + if "centroid_canon" in obj_state: + # Face-anchored object. Construct with a placeholder valid triangle + # mesh of the right face count; load_state_dict overwrites buffers. + obj_n = obj_state["centroid_canon"].shape[0] + placeholder_verts = torch.tensor( + [[0.0, 0.0, 0.0], [1.0, 0.0, 0.0], [0.0, 1.0, 0.0]], + dtype=torch.float32, device=device, + ) + placeholder_faces = torch.zeros(obj_n, 3, dtype=torch.long, device=device) + placeholder_faces[:, 1] = 1 + placeholder_faces[:, 2] = 2 + placeholder_face_colors = torch.full( + (obj_n, 3), 0.5, dtype=torch.float32, device=device, + ) + obj_gaussians = FaceGaussians( + vertices = placeholder_verts, + faces = placeholder_faces, + face_colors = placeholder_face_colors, + ).to(device) + else: + obj_n = obj_state["anchor"].shape[0] + placeholder_anchor = torch.zeros(obj_n, 3, dtype=torch.float32, device=device) + placeholder_color = torch.full((obj_n, 3), 0.5, dtype=torch.float32, device=device) + obj_gaussians = ObjectGaussians( + anchor_positions = placeholder_anchor, + init_color = placeholder_color, + init_scale = 0.01, + ).to(device) + obj_gaussians.load_state_dict(obj_state) + obj_gaussians.eval() + + obj_track = ObjectPoseTrack( + rotations = torch.tensor([[1.0, 0.0, 0.0, 0.0]] * T, dtype=torch.float32, device=device), + translations = torch.zeros(T, 3, dtype=torch.float32, device=device), + scales = torch.ones(T, 3, dtype=torch.float32, device=device), + frame_indices = frame_indices, + ) + obj_pose_field = ObjectPoseField(obj_track).to(device) + obj_pose_field.load_state_dict(ckpt["obj_pose_field"]) + obj_pose_field.eval() + + # --- Hands --------------------------------------------------------- + hand_sides: list[str] = list(ckpt.get("hand_sides", [])) + hand_pose_dicts: list[dict] = list(ckpt.get("hand_pose_fields", [])) + hand_gauss_dicts: list[dict] = list(ckpt.get("hand_gaussians", [])) + hand_gaussians_list: list = [] + hand_pose_fields_list: list[HandPoseField] = [] + for side, hp_state, hg_state in zip(hand_sides, hand_pose_dicts, hand_gauss_dicts): + # Pose field — dummy track of correct T then load. + ht = HandPoseTrack( + global_orient = torch.zeros(T, 3, dtype=torch.float32, device=device), + hand_pose = torch.zeros(T, 45, dtype=torch.float32, device=device), + betas = torch.zeros(T, 10, dtype=torch.float32, device=device), + cam_t = torch.zeros(T, 3, dtype=torch.float32, device=device), + is_right = (side == "right"), + frame_indices = frame_indices, + raw_records = [{} for _ in range(T)], + ) + hpf = HandPoseField(track=ht, mano_assets_root=mano_assets_root, device=device).to(device) + hpf.load_state_dict(hp_state) + hpf.eval() + hand_pose_fields_list.append(hpf) + + # Detect anchor mode: face-anchored hands have a "_faces" buffer. + if "_faces" in hg_state: + n_faces = hg_state["_faces"].shape[0] + # Placeholder rest mesh: non-degenerate triangle replicated for + # n_faces so the constructor's TBN math doesn't NaN. State-dict + # load then overwrites _faces / _log_scale / _delta_p / etc. + placeholder_verts = torch.tensor( + [[0.0, 0.0, 0.0], [1.0, 0.0, 0.0], [0.0, 1.0, 0.0]], + dtype=torch.float32, device=device, + ) + placeholder_faces = torch.zeros(n_faces, 3, dtype=torch.long, device=device) + placeholder_faces[:, 1] = 1 + placeholder_faces[:, 2] = 2 + hg = HandFaceGaussians( + rest_vertices = placeholder_verts, + faces = placeholder_faces, + is_right = (side == "right"), + init_color = torch.tensor( + [0.6, 0.45, 0.35], dtype=torch.float32, device=device, + ), + device = device, + ).to(device) + else: + subsample = hg_state.get("_subsample_idx", None) + hg = HandGaussians( + n_verts = 778, + is_right = (side == "right"), + init_scale = 0.005, + init_color = torch.tensor([0.6, 0.45, 0.35], dtype=torch.float32, device=device), + device = device, + subsample_indices = subsample if subsample is not None else None, + ).to(device) + # If shapes mismatch (e.g. checkpoint from a different anchor mode + # than expected), load_state_dict will raise — surfaces the issue + # cleanly rather than silently corrupting state. + hg.load_state_dict(hg_state) + hg.eval() + hand_gaussians_list.append(hg) + + # --- Background ---------------------------------------------------- + bg_gaussians = None + bg_pose_field = None + if "bg_gaussians" in ckpt: + bg_state = ckpt["bg_gaussians"] + bg_n = bg_state["anchor"].shape[0] + bg_gaussians = BackgroundGaussians( + anchor_positions = torch.zeros(bg_n, 3, dtype=torch.float32, device=device), + init_color = torch.full((bg_n, 3), 0.5, dtype=torch.float32, device=device), + init_scale = torch.full((bg_n,), 0.01, dtype=torch.float32, device=device), + ).to(device) + bg_gaussians.load_state_dict(bg_state) + bg_gaussians.eval() + + bg_pose_field = BackgroundPoseField(n_frames=T, device=device).to(device) + bg_pose_field.load_state_dict(ckpt["bg_pose_field"]) + bg_pose_field.eval() + + # Learnable intrinsics (optional). Build with a placeholder K — the + # state-dict load overwrites all four params + their init buffers, so + # the placeholder values never leak through. + intrinsics_field = None + if "intrinsics_field" in ckpt: + placeholder_K = torch.eye(3, dtype=torch.float32, device=device) + intrinsics_field = IntrinsicsField( + placeholder_K, learn_focal=False, learn_principal_point=False, + ).to(device) + intrinsics_field.load_state_dict(ckpt["intrinsics_field"]) + intrinsics_field.eval() + + # Wrist-attached Gaussians (optional, per-hand). Detect via checkpoint + # "wrist_gaussians" key; entries may be None for hands without them. + wrist_gaussians_list: list[WristAttachedGaussians | None] = [] + ckpt_wrist = ckpt.get("wrist_gaussians") + for slot_idx in range(len(hand_pose_fields_list)): + wg_state = None + if ckpt_wrist is not None and slot_idx < len(ckpt_wrist): + wg_state = ckpt_wrist[slot_idx] + if wg_state is None: + wrist_gaussians_list.append(None) + continue + n_wg = wg_state["anchor"].shape[0] + wrist_gaussians_list.append(WristAttachedGaussians( + anchor_positions = torch.zeros(n_wg, 3, dtype=torch.float32, device=device), + init_color = torch.full((n_wg, 3), 0.5, dtype=torch.float32, device=device), + init_scale = 0.03, + ).to(device)) + wrist_gaussians_list[-1].load_state_dict(wg_state) + wrist_gaussians_list[-1].eval() + + # Cache per-hand unique MANO edge list (for wireframe overlay). + # Build once at load: faces are static, so the edge set is too. + hand_edges_list: list[torch.Tensor] = [] + for hpf in hand_pose_fields_list: + faces = hpf.mano.th_faces.to(device=device, dtype=torch.long) # (F, 3) + edges = torch.cat([ + faces[:, [0, 1]], + faces[:, [1, 2]], + faces[:, [2, 0]], + ], dim=0) # (3F, 2) + edges, _ = torch.sort(edges, dim=1) # undirected + edges = torch.unique(edges, dim=0) # dedupe + hand_edges_list.append(edges) + + return { + "frame_indices": frame_indices, + "T": T, + "obj_gaussians": obj_gaussians, + "obj_pose_field": obj_pose_field, + "hand_gaussians": hand_gaussians_list, + "hand_pose_fields": hand_pose_fields_list, + "hand_edges": hand_edges_list, + "hand_sides": hand_sides, + "wrist_gaussians": wrist_gaussians_list, + "intrinsics_field": intrinsics_field, + "bg_gaussians": bg_gaussians, + "bg_pose_field": bg_pose_field, + "step_count": int(ckpt.get("step_count", 0)), + } + + +def _transform_frame_to_world( + frame: GaussianFrame, R_w2c: torch.Tensor, t_w2c: torch.Tensor, +) -> GaussianFrame: + """Pull a GaussianFrame from current-cam coords back into gsplat world. + + Object / hand gaussians always emit means in the current frame's camera + coords (they apply the per-frame pose internally). When rendering with a + static background, the world is the gsplat-world (reference-frame camera), + so we undo (R_w2c, t_w2c) on means and per-Gaussian quats. + """ + means_world = (frame.means - t_w2c) @ R_w2c # = R_w2c^T (x - t) + q_w2c = rotmat_to_quat(R_w2c) # (4,) wxyz unit + q_c2w = torch.stack([q_w2c[0], -q_w2c[1], -q_w2c[2], -q_w2c[3]]) + quats_world = quat_mul(q_c2w.expand_as(frame.quats), frame.quats) + return GaussianFrame( + means = means_world, + quats = quats_world, + scales = frame.scales, + opacities = frame.opacities, + colors = frame.colors, + ) + + +def _camera_frustum_segments_world( + R_w2c: np.ndarray, t_w2c: np.ndarray, K: np.ndarray, + W: int, H: int, depth: float = 0.1, +) -> tuple[np.ndarray, np.ndarray]: + """World-space line segments for a pyramid frustum at the given camera pose.""" + R_c2w = R_w2c.T + cam_center = -R_c2w @ t_w2c + fx, fy = K[0, 0], K[1, 1] + cx, cy = K[0, 2], K[1, 2] + z = depth + corners_cam = np.array([ + [(0 - cx) * z / fx, (0 - cy) * z / fy, z], + [(W - cx) * z / fx, (0 - cy) * z / fy, z], + [(W - cx) * z / fx, (H - cy) * z / fy, z], + [(0 - cx) * z / fx, (H - cy) * z / fy, z], + ], dtype=np.float64) + corners_world = corners_cam @ R_c2w.T + cam_center + starts, ends = [], [] + for c in corners_world: # pyramid edges + starts.append(cam_center); ends.append(c) + for i in range(4): # far-plane rect + starts.append(corners_world[i]); ends.append(corners_world[(i + 1) % 4]) + return np.array(starts), np.array(ends) + + +def _draw_world_segments( + img: np.ndarray, starts: np.ndarray, ends: np.ndarray, + viewmat: np.ndarray, K: np.ndarray, color: tuple[int, int, int], + thickness: int = 1, near: float = 0.01, +) -> np.ndarray: + """Project world-space segments through (viewmat, K) and draw with cv2.line. + + Each segment is clipped to z >= near in view space before projection so a + segment with one endpoint behind the camera still draws its visible part. + """ + out = img + R = viewmat[:3, :3]; t = viewmat[:3, 3] + fx, fy = K[0, 0], K[1, 1] + cx, cy = K[0, 2], K[1, 2] + for s, e in zip(starts, ends): + sc = R @ s + t + ec = R @ e + t + if sc[2] < near and ec[2] < near: + continue + if sc[2] < near: + alpha = (near - sc[2]) / (ec[2] - sc[2]) + sc = sc + alpha * (ec - sc) + elif ec[2] < near: + alpha = (near - ec[2]) / (sc[2] - ec[2]) + ec = ec + alpha * (sc - ec) + u0 = int(round(fx * sc[0] / sc[2] + cx)) + v0 = int(round(fy * sc[1] / sc[2] + cy)) + u1 = int(round(fx * ec[0] / ec[2] + cx)) + v1 = int(round(fy * ec[1] / ec[2] + cy)) + cv2.line(out, (u0, v0), (u1, v1), color, thickness, cv2.LINE_AA) + return out + + +def _draw_world_segments_batched( + img: np.ndarray, + starts_world: np.ndarray, # (E, 3) + ends_world: np.ndarray, # (E, 3) + viewmat: np.ndarray, # (4, 4) world→cam + K: np.ndarray, # (3, 3) + color: tuple[int, int, int], + thickness: int = 1, + near: float = 0.01, +) -> np.ndarray: + """Vectorized projection + per-edge cv2.line draw. + + Same semantics as ``_draw_world_segments`` but with all matrix math + done in numpy batches. Worth the rewrite when E is large (MANO has + ~2300 edges; the per-segment Python loop in the legacy helper would + cost ~50–200 ms per frame). + """ + if starts_world.shape[0] == 0: + return img + R = viewmat[:3, :3]; t = viewmat[:3, 3] + fx, fy = K[0, 0], K[1, 1] + cx, cy = K[0, 2], K[1, 2] + sc = starts_world @ R.T + t # (E, 3) + ec = ends_world @ R.T + t # (E, 3) + + keep = ~((sc[:, 2] < near) & (ec[:, 2] < near)) + sc = sc[keep]; ec = ec[keep] + if sc.shape[0] == 0: + return img + + # Clip endpoints that fall behind the near plane. + s_behind = sc[:, 2] < near + if s_behind.any(): + denom = (ec[s_behind, 2] - sc[s_behind, 2]) + alpha = ((near - sc[s_behind, 2]) / np.where(np.abs(denom) > 1e-6, denom, 1e-6))[:, None] + sc[s_behind] = sc[s_behind] + alpha * (ec[s_behind] - sc[s_behind]) + e_behind = ec[:, 2] < near + if e_behind.any(): + denom = (sc[e_behind, 2] - ec[e_behind, 2]) + alpha = ((near - ec[e_behind, 2]) / np.where(np.abs(denom) > 1e-6, denom, 1e-6))[:, None] + ec[e_behind] = ec[e_behind] + alpha * (sc[e_behind] - ec[e_behind]) + + u0 = np.rint(fx * sc[:, 0] / sc[:, 2] + cx).astype(np.int32) + v0 = np.rint(fy * sc[:, 1] / sc[:, 2] + cy).astype(np.int32) + u1 = np.rint(fx * ec[:, 0] / ec[:, 2] + cx).astype(np.int32) + v1 = np.rint(fy * ec[:, 1] / ec[:, 2] + cy).astype(np.int32) + + for x0, y0, x1, y1 in zip(u0.tolist(), v0.tolist(), u1.tolist(), v1.tolist()): + cv2.line(img, (x0, y0), (x1, y1), color, thickness, cv2.LINE_AA) + return img + + +# Per-hand-slot wireframe colors (BGR). Cycles for >2 hands. +_HAND_WIREFRAME_COLORS = [ + (80, 220, 80), # 0: green + (220, 120, 80), # 1: orange-ish + (80, 220, 220), # 2: yellow + (220, 80, 220), # 3: magenta +] + + +def _draw_hand_wireframes( + img_bgr: np.ndarray, + modules: dict, + t: int, + viewmat: np.ndarray, # (4, 4) world→cam in current view + K_np: np.ndarray, # (3, 3) + static_bg: bool, + device: torch.device, + thickness: int = 1, +) -> np.ndarray: + """Overlay each hand's MANO mesh as wireframe lines on ``img_bgr``. + + Verts come straight from ``posed_verts_and_rotmats_camera`` (per-frame + LBS + cam_t). When ``static_bg`` is on, they're transported into the + gsplat-world frame so the view matches the rendered Gaussians. + """ + with torch.no_grad(): + if static_bg and modules["bg_gaussians"] is not None: + R_bg, t_bg = modules["bg_pose_field"](t) + R_bg_np = R_bg.detach().cpu().numpy() + t_bg_np = t_bg.detach().cpu().numpy() + else: + R_bg_np = None + t_bg_np = None + + for i, (hpf, edges) in enumerate( + zip(modules["hand_pose_fields"], modules["hand_edges"]) + ): + v_cam, _ = hpf.posed_verts_and_rotmats_camera(t) # (N, 3) + v_cam_np = v_cam.detach().cpu().numpy() + if R_bg_np is not None: + # cam → world: v_world = R_bg.T @ (v_cam - t_bg). + v_world_np = (v_cam_np - t_bg_np) @ R_bg_np + else: + v_world_np = v_cam_np + edges_np = edges.detach().cpu().numpy() + starts = v_world_np[edges_np[:, 0]] + ends = v_world_np[edges_np[:, 1]] + color = _HAND_WIREFRAME_COLORS[i % len(_HAND_WIREFRAME_COLORS)] + img_bgr = _draw_world_segments_batched( + img_bgr, starts, ends, viewmat, K_np, + color=color, thickness=thickness, + ) + return img_bgr + + +def _build_per_frame_frames( + modules: dict, t: int, show_obj: bool, show_hands: bool, show_bg: bool, + static_bg: bool, +): + """Build the (possibly empty) list of GaussianFrames for the current view. + + When ``static_bg`` is True, the rendering world is the gsplat-world + (reference-frame camera) rather than the current frame's camera. The + background uses identity pose, and object/hand frames are pulled back into + world by inverting the current frame's background pose. + """ + frames = [] + R_bg = t_bg = None + if static_bg and modules["bg_gaussians"] is not None: + R_bg, t_bg = modules["bg_pose_field"](t) + if show_obj: + R, tt = modules["obj_pose_field"](t) + f = modules["obj_gaussians"](R, tt) + if R_bg is not None: + f = _transform_frame_to_world(f, R_bg, t_bg) + frames.append(f) + if show_hands: + for hpf, hg, wg in zip( + modules["hand_pose_fields"], + modules["hand_gaussians"], + modules.get("wrist_gaussians") or [None] * len(modules["hand_pose_fields"]), + ): + v, R = hpf.posed_verts_and_rotmats_camera(t) + f = hg(v, R) + if R_bg is not None: + f = _transform_frame_to_world(f, R_bg, t_bg) + frames.append(f) + # Wrist-attached arm Gaussians: ride along with hand visibility. + if wg is not None: + Rw, tw = hpf.wrist_pose_camera(t) + fw = wg(Rw, tw) + if R_bg is not None: + fw = _transform_frame_to_world(fw, R_bg, t_bg) + frames.append(fw) + if show_bg and modules["bg_gaussians"] is not None: + if static_bg: + R = torch.eye(3, dtype=torch.float32, device=modules["bg_gaussians"].anchor.device) + tt = torch.zeros(3, dtype=torch.float32, device=R.device) + else: + R, tt = modules["bg_pose_field"](t) + frames.append(modules["bg_gaussians"](R, tt)) + return frames + + +def _object_centroid(modules: dict, t: int, static_bg: bool) -> np.ndarray: + """Object centroid in the active world frame; used as orbit target.""" + R, tt = modules["obj_pose_field"](t) + f = modules["obj_gaussians"](R, tt) + if static_bg and modules["bg_gaussians"] is not None: + R_bg, t_bg = modules["bg_pose_field"](t) + f = _transform_frame_to_world(f, R_bg, t_bg) + return f.means.mean(dim=0).detach().cpu().numpy() + + +def _orbit_eye(target: np.ndarray, yaw: float, pitch: float, distance: float) -> np.ndarray: + """Spherical coords → eye position in the same frame as ``target``. + + Pitch and yaw are in the orbit's local frame: pitch=0 keeps the eye in the + target's horizontal plane (CV-cam's +X / +Z axes). pitch>0 lifts the eye + above the target. Yaw rotates around CV-cam's +Y (down) axis, so positive + yaw moves the eye to the target's right in screen space. + """ + cp = math.cos(pitch); sp = math.sin(pitch) + cy = math.cos(yaw); sy = math.sin(yaw) + # Local direction from target to eye (CV cam: +X right, +Y down, +Z fwd). + d = np.array([sy * cp, -sp, -cy * cp], dtype=np.float64) + return target + d * distance + + +def _render( + modules: dict, t: int, K: torch.Tensor, W: int, H: int, + viewmat: np.ndarray, # (4,4) world→camera + show_obj: bool, show_hands: bool, show_bg: bool, + static_bg: bool, + device: torch.device, +) -> np.ndarray: + """Single rasterization call → RGB uint8 (H, W, 3).""" + from gsplat.rendering import rasterization + + frames = _build_per_frame_frames( + modules, t, show_obj, show_hands, show_bg, static_bg, + ) + if not frames: + return np.zeros((H, W, 3), dtype=np.uint8) + combined = concat_frames(frames) + + Vt = torch.from_numpy(viewmat).to(device, dtype=torch.float32).unsqueeze(0) + Kt = K.to(device).unsqueeze(0) + with torch.no_grad(): + rgb, _, _ = rasterization( + means = combined.means, + quats = combined.quats, + scales = combined.scales, + opacities = combined.opacities, + colors = combined.colors, + viewmats = Vt, + Ks = Kt, + width = W, + height = H, + near_plane = 0.01, + far_plane = 100.0, + packed = False, + ) + img = rgb[0].clamp(0, 1).detach().cpu().numpy() + return (img * 255.0).astype(np.uint8) + + +def _annotate(img: np.ndarray, lines: list[str]) -> np.ndarray: + out = img.copy() + h, w = out.shape[:2] + pad = 8 + for i, line in enumerate(lines): + y = pad + 16 + i * 18 + cv2.putText(out, line, (pad + 1, y + 1), cv2.FONT_HERSHEY_SIMPLEX, + 0.5, (0, 0, 0), 2, cv2.LINE_AA) + cv2.putText(out, line, (pad, y), cv2.FONT_HERSHEY_SIMPLEX, + 0.5, (255, 255, 255), 1, cv2.LINE_AA) + return out + + +_HELP = """ +Mouse: + LMB drag orbit around target + RMB drag pan target (screen plane) + Wheel zoom +Keyboard: + [ / ] frame -1 / +1 + , / . frame -10 / +10 + space play / pause + 1 toggle object + 2 toggle hands + 3 toggle background + w toggle MANO wireframe overlay + s toggle static-background world (frustum overlay in orbit mode) + 0 source-camera view + r reset orbit (target = current obj centroid) + h this help + q / ESC quit +""" + + +def visualize( + checkpoint: str, + intrinsics_path: str, + mano_assets_root: str, + width: int | None = None, + height: int | None = None, + fps: float = 30.0, +) -> None: + device = torch.device("cuda" if torch.cuda.is_available() else "cpu") + print(f"[visualize] device = {device}") + + K_full, W_full, H_full = _load_K(intrinsics_path) + W = int(width) if width is not None else W_full + H = int(height) if height is not None else H_full + if (W, H) != (W_full, H_full): + K = _scale_K(K_full, (W_full, H_full), (W, H)) + else: + K = K_full + print(f"[visualize] render @ {W}×{H}") + + def _load_modules(path: str) -> tuple[dict, float]: + mtime = os.path.getmtime(path) + ckpt_local = torch.load(path, map_location=device, weights_only=False) + return _build_modules_from_ckpt(ckpt_local, mano_assets_root, device), mtime + + print(f"[visualize] loading checkpoint: {checkpoint}") + modules, ckpt_mtime = _load_modules(checkpoint) + print(f"[visualize] T = {modules['T']} frames, " + f"object N = {modules['obj_gaussians'].num_gaussians()}, " + f"hands = {len(modules['hand_sides'])} ({', '.join(modules['hand_sides']) or 'none'}), " + f"bg = {'yes' if modules['bg_gaussians'] is not None else 'no'}") + + # If the checkpoint carries refined intrinsics, override the JSON's K. + # The field's fx_init buffer equals JSON.fx × train_resolution_scale — + # we recover that scale to express the refined K at native resolution, + # then the existing _scale_K path scales to the visualizer's W/H. + if modules.get("intrinsics_field") is not None: + field = modules["intrinsics_field"] + train_scale = float(field.fx_init.detach().cpu() / K_full[0, 0]) + if abs(train_scale) < 1e-6: + print("[visualize] WARNING: intrinsics_field has fx_init~0; " + "skipping refined-K override.") + else: + K_trained = field.K().detach().cpu() # at training res + K_refined_native = K_trained.clone() + K_refined_native[0, 0] /= train_scale; K_refined_native[0, 2] /= train_scale + K_refined_native[1, 1] /= train_scale; K_refined_native[1, 2] /= train_scale + df = (K_refined_native - K_full).abs().max().item() + print(f"[visualize] using refined intrinsics from checkpoint " + f"(max Δ vs JSON: {df:.3f} px; train_resolution_scale ≈ " + f"{train_scale:.3f}).") + K_full = K_refined_native + # Re-apply the visualizer's resolution scaling now that K_full + # has been refreshed. + if (W, H) != (W_full, H_full): + K = _scale_K(K_full, (W_full, H_full), (W, H)) + else: + K = K_full + + has_bg = modules["bg_gaussians"] is not None + # --- Viewer state ------------------------------------------------------ + state = { + "t": 0, + "show_obj": True, + "show_hands": True, + "show_bg": has_bg, + "show_wireframe": False, + "static_bg": has_bg, # static-world mode (default on if bg) + "mode": "src", # 'src' or 'orbit' + # Orbit state (used only in 'orbit' mode) + "target": _object_centroid(modules, 0, has_bg), + "yaw": 0.0, + "pitch": 0.0, + "distance": 0.5, + # Mouse + "lmb": False, + "rmb": False, + "last_xy": (0, 0), + # Playback + "playing": False, + "last_advance": 0.0, + } + + def _reset_orbit_for_t(t: int) -> None: + state["target"] = _object_centroid(modules, t, state["static_bg"]) + # Initial distance: enough to comfortably see the object. + with torch.no_grad(): + R, tt = modules["obj_pose_field"](t) + f = modules["obj_gaussians"](R, tt) + if state["static_bg"] and modules["bg_gaussians"] is not None: + R_bg, t_bg = modules["bg_pose_field"](t) + f = _transform_frame_to_world(f, R_bg, t_bg) + r = (f.means - torch.from_numpy(state["target"]).to(device)).norm(dim=-1).max().item() + state["distance"] = max(0.2, r * 3.0) + state["yaw"] = 0.0 + state["pitch"] = 0.0 + + def on_mouse(event, x, y, flags, param): + if event == cv2.EVENT_LBUTTONDOWN: + state["lmb"] = True; state["last_xy"] = (x, y) + elif event == cv2.EVENT_LBUTTONUP: + state["lmb"] = False + elif event == cv2.EVENT_RBUTTONDOWN: + state["rmb"] = True; state["last_xy"] = (x, y) + elif event == cv2.EVENT_RBUTTONUP: + state["rmb"] = False + elif event == cv2.EVENT_MOUSEMOVE: + dx = x - state["last_xy"][0] + dy = y - state["last_xy"][1] + state["last_xy"] = (x, y) + if state["mode"] != "orbit": + # Any drag switches us into orbit mode for the current frame. + if state["lmb"] or state["rmb"]: + _reset_orbit_for_t(state["t"]) + state["mode"] = "orbit" + if state["lmb"]: + state["yaw"] += dx * 0.005 + state["pitch"] += dy * 0.005 + state["pitch"] = max(-1.4, min(1.4, state["pitch"])) + elif state["rmb"]: + # Pan in the orbit camera's screen plane. + # Approximate: move target in -x and +y by drag magnitude * distance scale. + scale = state["distance"] / float(W) + # Build right/up vectors of the current orbit cam. + eye = _orbit_eye(state["target"], state["yaw"], state["pitch"], state["distance"]) + fwd = state["target"] - eye + fwd /= max(np.linalg.norm(fwd), 1e-8) + world_up = np.array([0.0, -1.0, 0.0]) # CV-cam: +Y is down + right = np.cross(world_up, fwd) + rn = np.linalg.norm(right) + if rn > 1e-6: + right /= rn + up = np.cross(fwd, right) + state["target"] = state["target"] - dx * scale * right + dy * scale * up + elif event == cv2.EVENT_MOUSEWHEEL: + # OpenCV encodes wheel delta in the high 16 bits of flags. + delta = (flags >> 16) + sign = 1 if delta > 0 else -1 + if state["mode"] != "orbit": + _reset_orbit_for_t(state["t"]) + state["mode"] = "orbit" + state["distance"] *= 0.9 ** sign + state["distance"] = max(0.02, min(50.0, state["distance"])) + + win = "v2d gsplat viewer" + cv2.namedWindow(win, cv2.WINDOW_NORMAL) + cv2.resizeWindow(win, W, H) + cv2.setMouseCallback(win, on_mouse) + print(_HELP) + + # Track last successful mtime separately from the in-flight observation + # so a transient torch.load failure (e.g., we caught a rename mid-flight) + # only triggers a retry, not a state corruption. + last_loaded_mtime = ckpt_mtime + while True: + # --- hot-reload: poll checkpoint mtime each tick. The writer side + # uses tmp+rename, so a successful stat → torch.load on the same path + # is always self-consistent; we still try/except for robustness. + try: + new_mtime = os.path.getmtime(checkpoint) + except OSError: + new_mtime = last_loaded_mtime + if new_mtime > last_loaded_mtime + 1e-6: + try: + new_modules, new_mtime_loaded = _load_modules(checkpoint) + except Exception as e: + print(f"[visualize] hot-reload skipped (transient): {e}") + else: + modules = new_modules + last_loaded_mtime = new_mtime_loaded + # Frame count and bg-presence can in principle change between + # writes; clamp t and the bg toggles so the viewer stays sane. + if state["t"] >= modules["T"]: + state["t"] = modules["T"] - 1 + if modules["bg_gaussians"] is None: + state["show_bg"] = False + state["static_bg"] = False + print(f"[visualize] hot-reloaded checkpoint " + f"(T={modules['T']}, step=" + f"{modules.get('step_count', '?')})") + + t = state["t"] + + # In static-bg mode, the src view sits at the per-frame camera pose, + # so viewmat = world→cam_t from the background pose field. Otherwise + # the world IS the current cam, so identity reproduces the source. + if state["mode"] == "src": + if state["static_bg"] and modules["bg_gaussians"] is not None: + with torch.no_grad(): + R_bg, t_bg = modules["bg_pose_field"](t) + viewmat = np.eye(4) + viewmat[:3, :3] = R_bg.detach().cpu().numpy() + viewmat[:3, 3] = t_bg.detach().cpu().numpy() + else: + viewmat = np.eye(4) + else: + eye = _orbit_eye(state["target"], state["yaw"], state["pitch"], state["distance"]) + viewmat = _orbit_viewmat_cv(eye, state["target"], up=np.array([0.0, -1.0, 0.0])) + + img = _render( + modules, t, K, W, H, viewmat, + state["show_obj"], state["show_hands"], state["show_bg"], + state["static_bg"], + device, + ) + img_bgr = cv2.cvtColor(img, cv2.COLOR_RGB2BGR) + + # MANO wireframe overlay (under the frustum so it doesn't get hidden). + # Tied to hand visibility — hiding the Gaussians hides the wireframe too. + if (state["show_wireframe"] + and state["show_hands"] + and modules["hand_pose_fields"]): + K_np = K.detach().cpu().numpy() + img_bgr = _draw_hand_wireframes( + img_bgr, modules, t, viewmat, K_np, + state["static_bg"], device, + ) + + # Camera frustum overlay: only meaningful in orbit mode with a static + # world (in src mode the cam center is at the eye and degenerates; + # in non-static mode the cam is always at world origin). + if (state["static_bg"] + and state["mode"] == "orbit" + and modules["bg_gaussians"] is not None): + with torch.no_grad(): + R_bg, t_bg = modules["bg_pose_field"](t) + K_np = K.detach().cpu().numpy() + starts, ends = _camera_frustum_segments_world( + R_w2c=R_bg.detach().cpu().numpy(), + t_w2c=t_bg.detach().cpu().numpy(), + K=K_np, W=W, H=H, + depth=max(0.015, 0.05 * state["distance"]), + ) + img_bgr = _draw_world_segments( + img_bgr, starts, ends, viewmat, K_np, + color=(0, 220, 255), thickness=1, + ) + flags = (("O" if state["show_obj"] else "_") + + ("H" if state["show_hands"] else "_") + + ("B" if state["show_bg"] else "_") + + ("W" if state["show_wireframe"] else "_") + + ("S" if state["static_bg"] else "_")) + info = [ + f"frame {modules['frame_indices'][t]:06d} ({t+1}/{modules['T']}) step {modules.get('step_count', 0)}", + f"mode {state['mode']} visible {flags}" + + (f" yaw={state['yaw']:+.2f} pitch={state['pitch']:+.2f} d={state['distance']:.3f}" + if state["mode"] == "orbit" else ""), + "[/]=frame ,/.=10 space=play 1/2/3=obj/hands/bg w=wireframe s=static 0=src r=orbit h=help q=quit", + ] + cv2.imshow(win, _annotate(img_bgr, info)) + + # Playback: advance frames at fps when 'playing'. + wait_ms = 1 if state["playing"] else 30 + k = cv2.waitKey(wait_ms) & 0xFF + if state["playing"]: + now = time.monotonic() + if now - state["last_advance"] >= 1.0 / max(fps, 0.1): + state["t"] = (state["t"] + 1) % modules["T"] + state["last_advance"] = now + + if k == 255 or k == 0: + # No key — only the playback path drives advancement. + pass + elif k in (ord("q"), 27): + break + elif k == ord("["): + state["t"] = max(0, state["t"] - 1) + elif k == ord("]"): + state["t"] = min(modules["T"] - 1, state["t"] + 1) + elif k == ord(","): + state["t"] = max(0, state["t"] - 10) + elif k == ord("."): + state["t"] = min(modules["T"] - 1, state["t"] + 10) + elif k == ord(" "): + state["playing"] = not state["playing"] + state["last_advance"] = time.monotonic() + elif k == ord("1"): + state["show_obj"] = not state["show_obj"] + elif k == ord("2"): + state["show_hands"] = not state["show_hands"] + elif k == ord("3"): + if modules["bg_gaussians"] is None: + print("(no background in this checkpoint)") + else: + state["show_bg"] = not state["show_bg"] + elif k == ord("w"): + if not modules["hand_pose_fields"]: + print("(no hands in this checkpoint)") + else: + state["show_wireframe"] = not state["show_wireframe"] + elif k == ord("s"): + if modules["bg_gaussians"] is None: + print("(no background in this checkpoint — static mode requires bg)") + else: + state["static_bg"] = not state["static_bg"] + # Orbit target lived in the previous world frame; recenter so + # the view doesn't jump unexpectedly after the convention swap. + if state["mode"] == "orbit": + _reset_orbit_for_t(state["t"]) + elif k == ord("0"): + state["mode"] = "src" + elif k == ord("r"): + _reset_orbit_for_t(state["t"]) + state["mode"] = "orbit" + elif k == ord("h"): + print(_HELP) + + cv2.destroyAllWindows() + + +def main() -> None: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("--checkpoint", required=True) + parser.add_argument("--intrinsics_path", required=True, + help="JSON with {fx, fy, cx, cy, width, height} — " + "typically /intrinsics_stable.json.") + parser.add_argument("--mano_assets_root", required=True, + help="Dir whose models/MANO_RIGHT.pkl is readable by " + "manotorch (e.g. /pretrained_models " + "or /_DATA/data).") + parser.add_argument("--width", type=int, default=None, + help="Override render width (defaults to intrinsics' width).") + parser.add_argument("--height", type=int, default=None, + help="Override render height (defaults to intrinsics' height).") + parser.add_argument("--fps", type=float, default=30.0, + help="Playback FPS when space toggles play.") + args = parser.parse_args() + visualize( + checkpoint = args.checkpoint, + intrinsics_path = args.intrinsics_path, + mano_assets_root = args.mano_assets_root, + width = args.width, + height = args.height, + fps = args.fps, + ) + + +if __name__ == "__main__": + main() diff --git a/third-party/video_to_data/reconstruction/modules/v2d_hamer/LICENSE b/third-party/video_to_data/reconstruction/modules/v2d_hamer/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..10caffae439b956cdda2b1ded9ecbe51ac10befb --- /dev/null +++ b/third-party/video_to_data/reconstruction/modules/v2d_hamer/LICENSE @@ -0,0 +1,15 @@ +# Apache License 2.0 + +Copyright 2025 NVIDIA CORPORATION + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. diff --git a/third-party/video_to_data/reconstruction/modules/v2d_hamer/docker/Dockerfile b/third-party/video_to_data/reconstruction/modules/v2d_hamer/docker/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..57c758aeac70d5b084eabe7b4d563dac37485cac --- /dev/null +++ b/third-party/video_to_data/reconstruction/modules/v2d_hamer/docker/Dockerfile @@ -0,0 +1,47 @@ +FROM pytorch/pytorch:2.5.1-cuda12.4-cudnn9-devel +ENV DEBIAN_FRONTEND=noninteractive +ENV PYOPENGL_PLATFORM=egl +WORKDIR /app + +RUN apt-get update && apt-get install -y --no-install-recommends \ + git wget ffmpeg \ + libgl1 libegl1 libglib2.0-0 libxrender1 libsm6 libxext6 libglfw3 \ + fonts-dejavu-core \ + && rm -rf /var/lib/apt/lists/* + +# Vendor HaMeR at a pinned commit. We only need its hand-reconstruction code +# (models/, datasets/, utils/) — the demo-side detection chain (vitdet, +# vitpose) is intentionally NOT installed. +ARG HAMER_REPO=https://github.com/geopavlakos/hamer.git +ARG HAMER_COMMIT=3a01849f4148352e9260b69bf28b65d1671a4905 +RUN git clone --recursive ${HAMER_REPO} /opt/hamer && \ + cd /opt/hamer && git checkout ${HAMER_COMMIT} && \ + git submodule update --init --recursive + +RUN pip install --no-cache-dir \ + "numpy<2" \ + Pillow opencv-python tqdm \ + pyrender trimesh \ + smplx \ + yacs hydra-core omegaconf \ + pytorch-lightning \ + timm einops \ + webdataset braceexpand dill av joblib loguru \ + scikit-image + +# manotorch and chumpy aren't on PyPI for Python 3.11 — pull from git. +RUN pip install --no-cache-dir \ + git+https://github.com/lixiny/manotorch.git \ + git+https://github.com/mattloper/chumpy.git + +# Install HaMeR (skip its detector deps — we drive crops from SAM2 masks). +RUN pip install --no-deps -e /opt/hamer + +ENV PYTHONPATH=/opt/hamer + +COPY . /workspace +RUN pip install -e /workspace/v2d_common \ + -e /workspace/v2d_hamer/lib + +# Sanity-check imports at build time so a broken install fails the build. +RUN python -c "from hamer.models import load_hamer; from hamer.datasets.utils import generate_image_patch_cv2; print('hamer imports OK')" diff --git a/third-party/video_to_data/reconstruction/modules/v2d_hamer/docker/__init__.py b/third-party/video_to_data/reconstruction/modules/v2d_hamer/docker/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..52a7a9daf028f654d6a02f65c99cc609a57b492f --- /dev/null +++ b/third-party/video_to_data/reconstruction/modules/v2d_hamer/docker/__init__.py @@ -0,0 +1,2 @@ +# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 diff --git a/third-party/video_to_data/reconstruction/modules/v2d_hamer/docker/_config.py b/third-party/video_to_data/reconstruction/modules/v2d_hamer/docker/_config.py new file mode 100644 index 0000000000000000000000000000000000000000..3542c65e3d34176d190e995d7d778fab29ee776f --- /dev/null +++ b/third-party/video_to_data/reconstruction/modules/v2d_hamer/docker/_config.py @@ -0,0 +1,6 @@ +# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 +import os + +IMAGE_NAME = "v2d_hamer" +MODULES_DIR = os.path.abspath(os.path.join(os.path.dirname(os.path.abspath(__file__)), "..", "..")) diff --git a/third-party/video_to_data/reconstruction/modules/v2d_hamer/docker/build.py b/third-party/video_to_data/reconstruction/modules/v2d_hamer/docker/build.py new file mode 100644 index 0000000000000000000000000000000000000000..9b10f530258207b000790d9319fc585405860f83 --- /dev/null +++ b/third-party/video_to_data/reconstruction/modules/v2d_hamer/docker/build.py @@ -0,0 +1,19 @@ +# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 +import os +import subprocess + +IMAGE_NAME = "v2d_hamer" + +current_dir = os.path.dirname(os.path.abspath(__file__)) +module_dir = os.path.join(current_dir, "..") +root_dir = os.path.join(module_dir, "..") +dockerfile_path = os.path.join(current_dir, "Dockerfile") + + +def build_docker_image() -> None: + subprocess.run(["docker", "build", "-t", IMAGE_NAME, "-f", dockerfile_path, root_dir], check=True) + + +if __name__ == "__main__": + build_docker_image() diff --git a/third-party/video_to_data/reconstruction/modules/v2d_hamer/docker/pyproject.toml b/third-party/video_to_data/reconstruction/modules/v2d_hamer/docker/pyproject.toml new file mode 100644 index 0000000000000000000000000000000000000000..42d8a757b7914fbaface6308af0c869766390639 --- /dev/null +++ b/third-party/video_to_data/reconstruction/modules/v2d_hamer/docker/pyproject.toml @@ -0,0 +1,18 @@ +# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 +[build-system] +requires = ["setuptools>=68.0", "wheel"] +build-backend = "setuptools.build_meta" + +[project] +name = "v2d-hamer-docker" +version = "0.1.0" +description = "Docker orchestration for v2d_hamer" +requires-python = ">=3.10" +dependencies = ["v2d-docker"] + +[tool.setuptools] +packages = ["v2d.hamer.docker"] + +[tool.setuptools.package-dir] +"v2d.hamer.docker" = "." diff --git a/third-party/video_to_data/reconstruction/modules/v2d_hamer/docker/run_align_hands.py b/third-party/video_to_data/reconstruction/modules/v2d_hamer/docker/run_align_hands.py new file mode 100644 index 0000000000000000000000000000000000000000..8085293bed0f9f6f0c62c7f6b78b86b24820cf5f --- /dev/null +++ b/third-party/video_to_data/reconstruction/modules/v2d_hamer/docker/run_align_hands.py @@ -0,0 +1,64 @@ +# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 +from v2d.docker.container import run_in_container +from v2d.hamer.docker._config import IMAGE_NAME, MODULES_DIR + + +def run_align_hands( + hamer_dir: str, + depth_dir: str, + intrinsics_path: str, + mano_assets_root: str, + output_dir: str, + hand_masks_dir: str | None = None, + object_masks_dir: str | None = None, + mask_min_pixels: int = 256, + dev: bool = False, +) -> None: + inputs = { + "hamer_dir": hamer_dir, + "depth_dir": depth_dir, + "intrinsics_path": intrinsics_path, + "mano_assets_root": mano_assets_root, + } + if hand_masks_dir is not None: + inputs["hand_masks_dir"] = hand_masks_dir + if object_masks_dir is not None: + inputs["object_masks_dir"] = object_masks_dir + run_in_container( + image=IMAGE_NAME, + module="v2d.hamer.lib.align_hands", + inputs=inputs, + outputs={"output_dir": output_dir}, + extra_args={"mask_min_pixels": mask_min_pixels}, + dev=dev, + modules_dir=MODULES_DIR, + gpus=True, + ) + + +if __name__ == "__main__": + import argparse + + parser = argparse.ArgumentParser(description="Depth-align HaMeR per-frame outputs") + parser.add_argument("--hamer_dir", required=True) + parser.add_argument("--depth_dir", required=True) + parser.add_argument("--intrinsics_path", required=True) + parser.add_argument("--mano_assets_root", required=True) + parser.add_argument("--output_dir", required=True) + parser.add_argument("--hand_masks_dir", default=None) + parser.add_argument("--object_masks_dir", default=None) + parser.add_argument("--mask_min_pixels", type=int, default=256) + parser.add_argument("--dev", action="store_true") + args = parser.parse_args() + run_align_hands( + hamer_dir = args.hamer_dir, + depth_dir = args.depth_dir, + intrinsics_path = args.intrinsics_path, + mano_assets_root = args.mano_assets_root, + output_dir = args.output_dir, + hand_masks_dir = args.hand_masks_dir, + object_masks_dir = args.object_masks_dir, + mask_min_pixels = args.mask_min_pixels, + dev = args.dev, + ) diff --git a/third-party/video_to_data/reconstruction/modules/v2d_hamer/docker/run_download_weights.py b/third-party/video_to_data/reconstruction/modules/v2d_hamer/docker/run_download_weights.py new file mode 100644 index 0000000000000000000000000000000000000000..1015d5cbc199ca7c918b4f8609b0ac071d0c9a5e --- /dev/null +++ b/third-party/video_to_data/reconstruction/modules/v2d_hamer/docker/run_download_weights.py @@ -0,0 +1,26 @@ +# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 +from v2d.docker.container import run_in_container +from v2d.hamer.docker._config import IMAGE_NAME, MODULES_DIR + + +def run_download_weights(weights_dir: str, dev: bool = False) -> None: + run_in_container( + image=IMAGE_NAME, + module="v2d.hamer.lib.download_weights", + inputs={}, + outputs={"weights_dir": weights_dir}, + dev=dev, + modules_dir=MODULES_DIR, + gpus=False, + ) + + +if __name__ == "__main__": + import argparse + + parser = argparse.ArgumentParser(description="Download HaMeR demo data + checkpoint") + parser.add_argument("--weights_dir", required=True) + parser.add_argument("--dev", action="store_true") + args = parser.parse_args() + run_download_weights(weights_dir=args.weights_dir, dev=args.dev) diff --git a/third-party/video_to_data/reconstruction/modules/v2d_hamer/docker/run_masks_to_hands.py b/third-party/video_to_data/reconstruction/modules/v2d_hamer/docker/run_masks_to_hands.py new file mode 100644 index 0000000000000000000000000000000000000000..b5917c4ce4688c10be0342d03efd82c6083ab6ab --- /dev/null +++ b/third-party/video_to_data/reconstruction/modules/v2d_hamer/docker/run_masks_to_hands.py @@ -0,0 +1,59 @@ +# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 +from v2d.docker.container import run_in_container +from v2d.hamer.docker._config import IMAGE_NAME, MODULES_DIR + + +def run_masks_to_hands( + frames_dir: str, + masks_dir: str, + tracks_path: str, + output_dir: str, + weights_dir: str, + bbox_expansion: float = 1.7, + mask_min_pixels: int = 256, + dev: bool = False, +) -> None: + run_in_container( + image=IMAGE_NAME, + module="v2d.hamer.lib.masks_to_hands", + inputs={ + "frames_dir": frames_dir, + "masks_dir": masks_dir, + "tracks_path": tracks_path, + "weights_dir": weights_dir, + }, + outputs={"output_dir": output_dir}, + extra_args={ + "bbox_expansion": bbox_expansion, + "mask_min_pixels": mask_min_pixels, + }, + dev=dev, + modules_dir=MODULES_DIR, + gpus=True, + ) + + +if __name__ == "__main__": + import argparse + + parser = argparse.ArgumentParser(description="Run HaMeR per (track, frame) using SAM2 masks") + parser.add_argument("--frames_dir", required=True) + parser.add_argument("--masks_dir", required=True) + parser.add_argument("--tracks_path", required=True) + parser.add_argument("--output_dir", required=True) + parser.add_argument("--weights_dir", required=True) + parser.add_argument("--bbox_expansion", type=float, default=1.7) + parser.add_argument("--mask_min_pixels", type=int, default=256) + parser.add_argument("--dev", action="store_true") + args = parser.parse_args() + run_masks_to_hands( + frames_dir = args.frames_dir, + masks_dir = args.masks_dir, + tracks_path = args.tracks_path, + output_dir = args.output_dir, + weights_dir = args.weights_dir, + bbox_expansion = args.bbox_expansion, + mask_min_pixels = args.mask_min_pixels, + dev = args.dev, + ) diff --git a/third-party/video_to_data/reconstruction/modules/v2d_hamer/docker/run_render_hands_aligned_video.py b/third-party/video_to_data/reconstruction/modules/v2d_hamer/docker/run_render_hands_aligned_video.py new file mode 100644 index 0000000000000000000000000000000000000000..c0b0828433a75795133b8eb59e544534443bcb6a --- /dev/null +++ b/third-party/video_to_data/reconstruction/modules/v2d_hamer/docker/run_render_hands_aligned_video.py @@ -0,0 +1,72 @@ +# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 +from v2d.docker.container import run_in_container +from v2d.hamer.docker._config import IMAGE_NAME, MODULES_DIR + + +def run_render_hands_aligned_video( + frames_dir: str, + aligned_dir: str, + mano_assets_root: str, + output_path: str, + object_mesh_path: str | None = None, + object_poses_dir: str | None = None, + object_scale: float = 1.0, + fps: float = 30.0, + alpha: float = 0.55, + use_pre_dz_cam_t: bool = False, + dev: bool = False, +) -> None: + inputs = { + "frames_dir": frames_dir, + "aligned_dir": aligned_dir, + "mano_assets_root": mano_assets_root, + } + if object_mesh_path is not None: + inputs["object_mesh_path"] = object_mesh_path + if object_poses_dir is not None: + inputs["object_poses_dir"] = object_poses_dir + extra_args: dict = {"fps": fps, "alpha": alpha, "object_scale": object_scale} + if use_pre_dz_cam_t: + extra_args["use_pre_dz_cam_t"] = True + run_in_container( + image=IMAGE_NAME, + module="v2d.hamer.lib.render_hands_aligned_video", + inputs=inputs, + outputs={"output_path": output_path}, + extra_args=extra_args, + dev=dev, + modules_dir=MODULES_DIR, + gpus=True, + ) + + +if __name__ == "__main__": + import argparse + + parser = argparse.ArgumentParser(description="Render aligned MANO meshes onto video") + parser.add_argument("--frames_dir", required=True) + parser.add_argument("--aligned_dir", required=True) + parser.add_argument("--mano_assets_root", required=True) + parser.add_argument("--output_path", required=True) + parser.add_argument("--object_mesh_path", default=None) + parser.add_argument("--object_poses_dir", default=None) + parser.add_argument("--object_scale", type=float, default=1.0) + parser.add_argument("--fps", type=float, default=30.0) + parser.add_argument("--alpha", type=float, default=0.55) + parser.add_argument("--use_pre_dz_cam_t", action="store_true") + parser.add_argument("--dev", action="store_true") + args = parser.parse_args() + run_render_hands_aligned_video( + frames_dir = args.frames_dir, + aligned_dir = args.aligned_dir, + mano_assets_root = args.mano_assets_root, + output_path = args.output_path, + object_mesh_path = args.object_mesh_path, + object_poses_dir = args.object_poses_dir, + object_scale = args.object_scale, + fps = args.fps, + alpha = args.alpha, + use_pre_dz_cam_t = args.use_pre_dz_cam_t, + dev = args.dev, + ) diff --git a/third-party/video_to_data/reconstruction/modules/v2d_hamer/docker/run_render_hands_video.py b/third-party/video_to_data/reconstruction/modules/v2d_hamer/docker/run_render_hands_video.py new file mode 100644 index 0000000000000000000000000000000000000000..3ce493d541b3194fe7d705e0282e999fed6eecb9 --- /dev/null +++ b/third-party/video_to_data/reconstruction/modules/v2d_hamer/docker/run_render_hands_video.py @@ -0,0 +1,52 @@ +# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 +from v2d.docker.container import run_in_container +from v2d.hamer.docker._config import IMAGE_NAME, MODULES_DIR + + +def run_render_hands_video( + frames_dir: str, + hamer_dir: str, + mano_assets_root: str, + output_path: str, + fps: float = 30.0, + alpha: float = 0.55, + dev: bool = False, +) -> None: + run_in_container( + image=IMAGE_NAME, + module="v2d.hamer.lib.render_hands_video", + inputs={ + "frames_dir": frames_dir, + "hamer_dir": hamer_dir, + "mano_assets_root": mano_assets_root, + }, + outputs={"output_path": output_path}, + extra_args={"fps": fps, "alpha": alpha}, + dev=dev, + modules_dir=MODULES_DIR, + gpus=True, + ) + + +if __name__ == "__main__": + import argparse + + parser = argparse.ArgumentParser(description="Render projected MANO meshes onto video") + parser.add_argument("--frames_dir", required=True) + parser.add_argument("--hamer_dir", required=True) + parser.add_argument("--mano_assets_root", required=True) + parser.add_argument("--output_path", required=True) + parser.add_argument("--fps", type=float, default=30.0) + parser.add_argument("--alpha", type=float, default=0.55) + parser.add_argument("--dev", action="store_true") + args = parser.parse_args() + run_render_hands_video( + frames_dir = args.frames_dir, + hamer_dir = args.hamer_dir, + mano_assets_root = args.mano_assets_root, + output_path = args.output_path, + fps = args.fps, + alpha = args.alpha, + dev = args.dev, + ) diff --git a/third-party/video_to_data/reconstruction/modules/v2d_hamer/docker/run_shell.py b/third-party/video_to_data/reconstruction/modules/v2d_hamer/docker/run_shell.py new file mode 100644 index 0000000000000000000000000000000000000000..1a2ec2fc2c8c8376658f41f8d0fbd9c2135dd4fe --- /dev/null +++ b/third-party/video_to_data/reconstruction/modules/v2d_hamer/docker/run_shell.py @@ -0,0 +1,28 @@ +# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 +import os +import subprocess + +from v2d.hamer.docker._config import IMAGE_NAME, MODULES_DIR + + +def run_shell(dev: bool = False) -> None: + cmd = [ + "docker", "run", "-it", "--rm", + "--gpus", "all", + "--user", f"{os.getuid()}:{os.getgid()}", + "-e", "HOME=/tmp", + ] + if dev: + cmd += ["-v", f"{MODULES_DIR}:/workspace"] + cmd += [IMAGE_NAME, "bash"] + subprocess.run(cmd, check=True) + + +if __name__ == "__main__": + import argparse + + parser = argparse.ArgumentParser(description="Run shell in v2d_hamer container") + parser.add_argument("--dev", action="store_true") + args = parser.parse_args() + run_shell(dev=args.dev) diff --git a/third-party/video_to_data/reconstruction/modules/v2d_hamer/lib/__init__.py b/third-party/video_to_data/reconstruction/modules/v2d_hamer/lib/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..52a7a9daf028f654d6a02f65c99cc609a57b492f --- /dev/null +++ b/third-party/video_to_data/reconstruction/modules/v2d_hamer/lib/__init__.py @@ -0,0 +1,2 @@ +# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 diff --git a/third-party/video_to_data/reconstruction/modules/v2d_hamer/lib/_hamer.py b/third-party/video_to_data/reconstruction/modules/v2d_hamer/lib/_hamer.py new file mode 100644 index 0000000000000000000000000000000000000000..796ba36b152872d00d169e84b87865ee87b6b983 --- /dev/null +++ b/third-party/video_to_data/reconstruction/modules/v2d_hamer/lib/_hamer.py @@ -0,0 +1,228 @@ +# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 +"""Singleton HaMeR loader and per-crop forward helper. + +Wraps the upstream API: + - hamer.models.load_hamer → (model, cfg) + - hamer.datasets.utils.generate_image_patch_cv2 → 256×256 crop + +`cam_crop_to_full` is reimplemented locally — HaMeR ships it inside +``utils_detectron2.py`` which top-level imports ``detectron2``; we don't need +detectron2 for inference, so we keep that dep out of the image. +""" + +from __future__ import annotations + +import os +from typing import Tuple + +import numpy as np +import torch + +_MODEL = None +_CFG = None + + +def get_model(weights_dir: str) -> Tuple[object, object]: + """Return a singleton (HaMeR model, cfg). + + HaMeR's model_config.yaml carries relative paths (e.g. + ``./_DATA/data/mano_mean_params.npz``) that resolve against the *current + working directory*. We chdir into ``weights_dir`` for the duration of + model construction so those paths land on the user's mounted weights tree. + """ + global _MODEL, _CFG + if _MODEL is None: + from hamer.models import load_hamer + + ckpt = os.path.join(weights_dir, "_DATA", "hamer_ckpts", "checkpoints", "hamer.ckpt") + if not os.path.exists(ckpt): + raise FileNotFoundError( + f"HaMeR checkpoint not found at {ckpt}. " + "Run `python -m v2d.hamer.lib.download_weights --weights_dir ` first." + ) + prev_cwd = os.getcwd() + try: + os.chdir(weights_dir) + _MODEL, _CFG = load_hamer(ckpt) + finally: + os.chdir(prev_cwd) + _MODEL = _MODEL.to("cuda").eval() + return _MODEL, _CFG + + +def crop_for_hamer( + image: np.ndarray, cx: float, cy: float, size: float, cfg, flip: bool = False, +) -> Tuple[np.ndarray, np.ndarray, np.ndarray]: + """Square crop centred at (cx, cy) of side `size`, resized to HaMeR input. + + HaMeR is trained as a right-hand model and processes left hands by + horizontally flipping the input patch. The caller passes ``flip=True`` + for left hands so the model receives a right-hand-oriented patch. The + returned ``box_center`` is in original-image pixels (matching HaMeR's + demo convention; ``cam_crop_to_full`` lifts to the original frame). + + Returns: + patch (3, H, W) float32, normalized. + box_center (2,) the crop center in original-image pixels. + box_size scalar — the crop side in original-image pixels. + """ + from hamer.datasets.utils import generate_image_patch_cv2 + + patch_w = patch_h = cfg.MODEL.IMAGE_SIZE + bgr = image[..., ::-1].copy() # generate_image_patch_cv2 expects BGR + patch_bgr, _ = generate_image_patch_cv2( + bgr, cx, cy, size, size, patch_w, patch_h, + flip, 1.0, 0, # flip, scale, rot + # default border_mode = cv2.BORDER_CONSTANT + ) + patch_rgb = patch_bgr[..., ::-1].astype(np.float32) / 255.0 + mean = np.array(cfg.MODEL.IMAGE_MEAN, dtype=np.float32) + std = np.array(cfg.MODEL.IMAGE_STD, dtype=np.float32) + patch = (patch_rgb - mean) / std + patch = patch.transpose(2, 0, 1).astype(np.float32) # (3, H, W) + return patch, np.array([cx, cy], dtype=np.float64), float(size) + + +def _cam_crop_to_full( + cam_bbox: np.ndarray, # (3,) — (s, tx, ty) per-crop weak-perspective + box_center: np.ndarray, # (2,) in original-image pixels + box_size: float, # crop side in original-image pixels + img_size: np.ndarray, # (2,) — (W, H) + focal_length: float, +) -> np.ndarray: + """HaMeR's weak-perspective → full-image perspective conversion. + + Re-implemented to avoid ``detectron2`` (which HaMeR's bundled util pulls in + only because the file shares a module with detector glue). Output is the + 3-vec camera translation under a virtual pinhole at focal=focal_length, + principal point at the image center. + """ + img_w, img_h = float(img_size[0]), float(img_size[1]) + cx, cy = float(box_center[0]), float(box_center[1]) + b = float(box_size) + s, tx_c, ty_c = (float(v) for v in cam_bbox) + bs = b * s + 1e-9 + tz = 2.0 * focal_length / bs + tx = (2.0 * (cx - img_w / 2.0) / bs) + tx_c + ty = (2.0 * (cy - img_h / 2.0) / bs) + ty_c + return np.array([tx, ty, tz], dtype=np.float64) + + +def run_hamer( + model, cfg, image: np.ndarray, cx: float, cy: float, size: float, is_right: bool +) -> dict: + """Run HaMeR on a single hand crop. Returns a dict of CPU numpy arrays. + + Output keys: + betas (10,) + hand_pose (15, 3, 3) rotation matrices (raw HaMeR output) + global_orient (1, 3, 3) rotation matrix + pred_cam (3,) per-crop weak-perspective (s, tx, ty) + pred_cam_t (3,) per-crop camera translation + pred_cam_t_full (3,) translation lifted to full-image pinhole + scaled_focal_length scalar focal length for the full image + pred_vertices (778, 3) MANO vertices in cam space + pred_keypoints_3d (21, 3) + """ + H, W = image.shape[:2] + # Match HaMeR's demo: flip the patch for left hand so the right-hand-only + # model sees a canonical right-oriented input. + flip = not is_right + patch, box_center, box_size = crop_for_hamer(image, cx, cy, size, cfg, flip=flip) + patch_t = torch.from_numpy(patch)[None].to("cuda") + right_t = torch.tensor([1 if is_right else 0], dtype=torch.float32, device="cuda") + with torch.no_grad(): + out = model({"img": patch_t, "right": right_t}) + + pred_cam = out["pred_cam"][0].detach().cpu().numpy().copy() # (3,) + pred_cam_t = out["pred_cam_t"][0].detach().cpu().numpy() # (3,) + pred_mano = out["pred_mano_params"] + betas = pred_mano["betas"][0].detach().cpu().numpy() + hand_pose = pred_mano["hand_pose"][0].detach().cpu().numpy() + global_orient = pred_mano["global_orient"][0].detach().cpu().numpy() + vertices = out["pred_vertices"][0].detach().cpu().numpy().copy() + joints3d = out["pred_keypoints_3d"][0].detach().cpu().numpy().copy() + + # HaMeR demo: pred_cam[1] (= tx in crop frame) gets sign-flipped for left + # hand BEFORE cam_crop_to_full. This compensates for the patch flip so + # cam_t lands in the original-image frame, with box_center kept unflipped. + multiplier = 1 if is_right else -1 + pred_cam[1] *= multiplier + + scaled_focal_length = float( + cfg.EXTRA.FOCAL_LENGTH / cfg.MODEL.IMAGE_SIZE * max(W, H) + ) + pred_cam_t_full = _cam_crop_to_full( + pred_cam, box_center, box_size, np.array([W, H], dtype=np.float64), + scaled_focal_length, + ) + + # Vertex/joint x-flip for left hand. cam_t stays as-is — the pred_cam + # correction above already put it in the original-image frame. + if not is_right: + vertices[:, 0] *= -1 + joints3d[:, 0] *= -1 + + return { + "betas": betas, + "hand_pose": hand_pose, + "global_orient": global_orient, + "pred_cam": pred_cam, + "pred_cam_t": pred_cam_t, + "pred_cam_t_full": pred_cam_t_full, + "scaled_focal_length": scaled_focal_length, + "pred_vertices": vertices, + "pred_keypoints_3d": joints3d, + } + + +def rotmat_to_axis_angle(R: np.ndarray) -> np.ndarray: + """Batched rotation-matrix → axis-angle. Accepts (..., 3, 3); returns (..., 3). + + Pure numpy (no torch dependency at call sites). Standard log map, with the + 180° branch handled explicitly to avoid NaNs at singular rotations. + """ + R = np.asarray(R, dtype=np.float64) + trace = np.einsum("...ii->...", R) + cos_theta = np.clip((trace - 1.0) / 2.0, -1.0, 1.0) + theta = np.arccos(cos_theta) + + # Default (general) case: extract from skew-symmetric part. + sin_theta = np.sin(theta) + out = np.stack([ + R[..., 2, 1] - R[..., 1, 2], + R[..., 0, 2] - R[..., 2, 0], + R[..., 1, 0] - R[..., 0, 1], + ], axis=-1) + safe = sin_theta > 1e-6 + out = np.where( + safe[..., None], + out * (theta[..., None] / (2.0 * sin_theta[..., None] + 1e-12)), + np.zeros_like(out), # near-zero rotation → zero axis-angle + ) + + # 180°-rotation branch: theta ≈ π. Diagonal element-by-element. + near_pi = (np.pi - theta) < 1e-3 + if np.any(near_pi): + diag = np.diagonal(R, axis1=-2, axis2=-1) + idx = np.argmax(diag, axis=-1) + axis_basis = np.eye(3, dtype=np.float64) + # axis_k = sign(R[k, j]) * sqrt((R[k,k] + 1) / 2) on the largest diagonal + axis = np.zeros(R.shape[:-2] + (3,), dtype=np.float64) + for k in range(3): + mask = near_pi & (idx == k) + if not np.any(mask): + continue + Rk = R[mask] + x_k = np.sqrt(np.maximum((Rk[..., k, k] + 1.0) / 2.0, 0.0)) + axis_k = np.zeros(Rk.shape[:-2] + (3,), dtype=np.float64) + axis_k[..., k] = x_k + for j in range(3): + if j == k: + continue + axis_k[..., j] = (Rk[..., k, j] + Rk[..., j, k]) / (4.0 * x_k + 1e-12) + axis[mask] = axis_k + out = np.where(near_pi[..., None], axis * np.pi, out) + + return out diff --git a/third-party/video_to_data/reconstruction/modules/v2d_hamer/lib/align_hands.py b/third-party/video_to_data/reconstruction/modules/v2d_hamer/lib/align_hands.py new file mode 100644 index 0000000000000000000000000000000000000000..04eed0dfa30735eecabbbd8375a78cabb19af8a3 --- /dev/null +++ b/third-party/video_to_data/reconstruction/modules/v2d_hamer/lib/align_hands.py @@ -0,0 +1,432 @@ +# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 +"""Per-frame depth alignment of HaMeR predictions. + +Takes raw HaMeR JSONs (virtual-pinhole, scaled_focal_length ≈ 25000) plus a +real depth source (depth PNG + intrinsics JSON) and writes per-frame JSONs +in real-camera units, with cam_t shifted to match the depth image along the +centroid ray. + +For each (track, frame): + 1. Reconstruct MANO mesh from saved axis-angle (global_orient, hand_pose, + betas) via manotorch. Mirror x for left hand. + 2. Rescale HaMeR's pred_cam_t_full to real intrinsics: + cam_t_real = pred_cam_t_full · (fx_real / scaled_focal_length) + 3. Render mesh depth under real intrinsics with pyrender. + 4. Take mask = (rendered_depth > 0) + ∧ sam2_hand_mask (if --hand_masks_dir provided) + ∧ ¬object_mask (if --object_masks_dir provided). + Intersecting with SAM2's per-track hand mask restricts the depth + comparison to pixels that are *both* rendered-MANO and image-grounded + hand, which is more reliable than the rendered silhouette alone. + 5. dz = median(depth_image[mask] − rendered_depth[mask]). + 6. Shift cam_t_real along the centroid ray by dz so the silhouette stays + on the same image pixel but lands at depth_image's z. + +Output schema (per file, single detection): + { + "track_id": int, + "is_right": bool, + "frame_idx": int, + "image_size": [W, H], + "intrinsics": {"fx":..., "fy":..., "cx":..., "cy":...}, + "mano": { + "betas": [10 floats], + "global_orient": [3 floats], + "hand_pose": [45 floats] + }, + "cam_t": [tx, ty, tz], # aligned, in real intrinsics + "diagnostics": { + "dz": float, # depth shift applied + "n_pixels": int, # hand-mask area used + "scale": float, # median(depth_image / rendered_depth) + "cam_t_pre_dz": [tx,ty,tz], + "scaled_focal": float # HaMeR virtual focal (pre-rescale) + } + } + +Frames whose mask is below ``mask_min_pixels`` get no shift (cam_t_real saved +as-is, dz=0, scale=1) and ``n_pixels`` reports the actual count so downstream +code can treat them as low-confidence. + +Usage: + python -m v2d.hamer.lib.align_hands \\ + --hamer_dir /data/hamer \\ + --depth_dir /data/depth \\ + --intrinsics_path /data/intrinsics.json \\ + --mano_assets_root /data/weights/hamer/_DATA/data \\ + --output_dir /data/hamer_aligned \\ + [--object_masks_dir /data/object_masks] # optional occlusion exclusion +""" + +from __future__ import annotations + +import argparse +import glob +import json +import os +from typing import Tuple + +os.environ.setdefault("PYOPENGL_PLATFORM", "egl") + +import numpy as np +import pyrender +import torch +import trimesh +from manotorch.manolayer import ManoLayer +from PIL import Image +from tqdm import tqdm + + +_CV_TO_GL_4X4 = np.array([ + [1, 0, 0, 0], + [0, -1, 0, 0], + [0, 0, -1, 0], + [0, 0, 0, 1], +], dtype=np.float64) + + +def _load_depth(path: str) -> np.ndarray: + """uint16 PNG (px = 65535/(d+1)) → float32 metres.""" + px = np.asarray(Image.open(path)).astype(np.float32) + return 1.0 / (px / 65535.0) - 1.0 + + +def _load_intrinsics(path: str) -> Tuple[float, float, float, float, int, int]: + with open(path) as f: + d = json.load(f) + return ( + float(d["fx"]), float(d["fy"]), float(d["cx"]), float(d["cy"]), + int(d["width"]), int(d["height"]), + ) + + +def _make_mano(mano_assets_root: str) -> ManoLayer: + return ManoLayer( + rot_mode="axisang", + use_pca=False, + side="right", + center_idx=None, + mano_assets_root=mano_assets_root, + ) + + +def _mesh_for_record(rec: dict, mano: ManoLayer) -> trimesh.Trimesh: + pose_aa = np.concatenate([ + np.array(rec["mano"]["global_orient"], dtype=np.float32), + np.array(rec["mano"]["hand_pose"], dtype=np.float32), + ]) + betas = np.array(rec["mano"]["betas"], dtype=np.float32) + out = mano(torch.from_numpy(pose_aa)[None], torch.from_numpy(betas)[None]) + verts_local = out.verts[0].detach().numpy() # (778, 3) — right-frame + if not rec["is_right"]: + verts_local[:, 0] *= -1 + faces = mano.th_faces.numpy() + if not rec["is_right"]: + faces = faces[:, [0, 2, 1]] # reverse winding + return trimesh.Trimesh(verts_local, faces, process=False) + + +def _render_depth( + renderer: pyrender.OffscreenRenderer, + cam: pyrender.IntrinsicsCamera, + mesh: trimesh.Trimesh, + cam_t: np.ndarray, +) -> np.ndarray: + """Render `mesh` translated by `cam_t` in CV cam space, return depth (H, W). + + The caller owns ``renderer`` and ``cam``: creating an ``OffscreenRenderer`` + spins up an EGL context (~100 ms+), so we share one across all frames. + The Scene itself is cheap to rebuild. + """ + posed = mesh.copy() + posed.vertices = posed.vertices + cam_t[None, :] + + scene = pyrender.Scene() + scene.add(pyrender.Mesh.from_trimesh(posed, smooth=False)) + scene.add(cam, pose=_CV_TO_GL_4X4) + + _, depth = renderer.render(scene) + return depth.astype(np.float32) + + +def _ray_offset(centroid: np.ndarray, dz: float) -> np.ndarray: + """[dx, dy, dz] that shifts a centroid along its camera ray by dz in z.""" + x, y, z = float(centroid[0]), float(centroid[1]), float(centroid[2]) + z_p = z + dz + return np.array([x / z * z_p - x, y / z * z_p - y, dz], dtype=np.float64) + + +def _aggregate_hand_scales(output_dir: str) -> dict[str, dict]: + """Per-track n_pixels-weighted median of the per-frame ``diagnostics.scale``. + + Mirrors ``v2d_hand_alignment/lib/align_world_results.py`` aggregation: + reject frames with mask area < 256 px or scale outside (0.2, 5.0), take the + n_pixels-weighted median of what remains. The resulting per-track scalar + is the multiplicative size correction the renderer applies around the + mesh centroid (in addition to ``cam_t`` already carrying the additive ``dz`` + shift). With no valid frames the scale falls back to 1.0. + + Each record's ``hand_scale`` field is written back into the JSON for + schema self-containment; ``/hand_scale.json`` is also written + as a per-track summary (handy for inspection). + """ + summary: dict[str, dict] = {} + track_dirs = sorted( + d for d in glob.glob(os.path.join(output_dir, "*")) + if os.path.isdir(d) + ) + for track_dir in track_dirs: + oid = os.path.basename(track_dir) + files = sorted(glob.glob(os.path.join(track_dir, "*.json"))) + if not files: + continue + scales_arr: list[float] = [] + pixels_arr: list[int] = [] + for path in files: + with open(path) as f: + rec = json.load(f) + d = rec.get("diagnostics", {}) + scales_arr.append(float(d.get("scale", float("nan")))) + pixels_arr.append(int(d.get("n_pixels", 0))) + + s = np.asarray(scales_arr, dtype=np.float64) + w = np.asarray(pixels_arr, dtype=np.float64) + valid = np.isfinite(s) & (w >= 256) & (s > 0.2) & (s < 5.0) + n_valid = int(valid.sum()) + if n_valid == 0: + hs = 1.0 + else: + sv = s[valid]; wv = w[valid] + order = np.argsort(sv) + sv_sorted = sv[order]; wv_cum = np.cumsum(wv[order]) + cutoff = wv_cum[-1] / 2.0 + idx = int(np.searchsorted(wv_cum, cutoff)) + idx = min(idx, len(sv_sorted) - 1) + hs = float(sv_sorted[idx]) + + summary[oid] = { + "hand_scale": hs, + "n_valid_frames": n_valid, + "n_total_frames": len(files), + } + + # Patch records in place so consumers can read rec["hand_scale"] + # without a sibling lookup. + for path in files: + with open(path) as f: + rec = json.load(f) + if rec.get("hand_scale") != hs: + rec["hand_scale"] = hs + with open(path, "w") as f: + json.dump(rec, f, indent=2) + + print(f" track {oid}: hand_scale={hs:.4f} " + f"({n_valid}/{len(files)} valid frames)") + return summary + + +def align_hands( + hamer_dir: str, + depth_dir: str, + intrinsics_path: str, + mano_assets_root: str, + output_dir: str, + hand_masks_dir: str | None = None, + object_masks_dir: str | None = None, + mask_min_pixels: int = 256, +) -> None: + fx, fy, cx, cy, W, H = _load_intrinsics(intrinsics_path) + print(f"Real intrinsics: fx={fx:.1f} fy={fy:.1f} cx={cx:.1f} cy={cy:.1f} {W}×{H}") + + mano = _make_mano(mano_assets_root) + + track_dirs = sorted(d for d in glob.glob(os.path.join(hamer_dir, "*")) if os.path.isdir(d)) + if not track_dirs: + raise FileNotFoundError(f"No track subdirs in {hamer_dir}") + + # Pyrender renderer + camera are reused for every frame. Creating an + # OffscreenRenderer spins up an EGL context (~100 ms+), so the per-frame + # version of this loop was dominated by context init/teardown. Camera + # intrinsics are constant, so the IntrinsicsCamera instance is shared too. + cam = pyrender.IntrinsicsCamera(fx=fx, fy=fy, cx=cx, cy=cy, + znear=0.01, zfar=100.0) + renderer = pyrender.OffscreenRenderer(W, H) + try: + _align_loop( + track_dirs=track_dirs, + output_dir=output_dir, + depth_dir=depth_dir, + hand_masks_dir=hand_masks_dir, + object_masks_dir=object_masks_dir, + mask_min_pixels=mask_min_pixels, + mano=mano, + renderer=renderer, + cam=cam, + intrinsics=(fx, fy, cx, cy), + image_size=(W, H), + ) + finally: + renderer.delete() + + # Aggregate per-track multiplicative depth correction. ``cam_t`` already + # carries the additive (``dz``) shift; ``hand_scale`` is the partner that + # corrects multiplicative depth mismatch (the dominant monocular failure + # mode). The renderer reads ``rec["hand_scale"]`` (or falls back to 1.0). + print("\nAggregating per-track hand_scale...") + summary = _aggregate_hand_scales(output_dir) + if summary: + scale_path = os.path.join(output_dir, "hand_scale.json") + with open(scale_path, "w") as f: + json.dump(summary, f, indent=2) + print(f"Saved per-track hand_scale → {scale_path}") + + +def _align_loop( + track_dirs: list[str], + output_dir: str, + depth_dir: str, + hand_masks_dir: str | None, + object_masks_dir: str | None, + mask_min_pixels: int, + mano: ManoLayer, + renderer: pyrender.OffscreenRenderer, + cam: pyrender.IntrinsicsCamera, + intrinsics: tuple, # (fx, fy, cx, cy) + image_size: tuple, # (W, H) +) -> None: + fx, fy, cx, cy = intrinsics + W, H = image_size + + for track_dir in track_dirs: + oid = os.path.basename(track_dir) + out_track = os.path.join(output_dir, oid) + os.makedirs(out_track, exist_ok=True) + files = sorted(glob.glob(os.path.join(track_dir, "*.json"))) + print(f"\nTrack {oid}: {len(files)} frames") + + for src in tqdm(files, desc=f" track {oid}", ncols=80, unit="frame"): + frame_idx = int(os.path.splitext(os.path.basename(src))[0]) + out_path = os.path.join(out_track, f"{frame_idx:06d}.json") + if os.path.exists(out_path): + continue + + with open(src) as f: + rec = json.load(f) + scaled_focal = float(rec["camera"]["scaled_focal_length"]) + pred_cam_t_full = np.array(rec["camera"]["pred_cam_t_full"], dtype=np.float64) + + # (2) Rescale to real intrinsics — preserve the centroid pixel. + # + # Naive scalar scaling cam_t · (fx_real/scaled_focal) only works + # when cx_real = W/2 AND the centroid happens to lie on the + # optical axis. In general we project the centroid under the + # virtual pinhole, choose a real metric depth, then unproject + # through the real pinhole at that depth. + cx_v = W / 2.0 + cy_v = H / 2.0 + u_pix = scaled_focal * pred_cam_t_full[0] / pred_cam_t_full[2] + cx_v + v_pix = scaled_focal * pred_cam_t_full[1] / pred_cam_t_full[2] + cy_v + z_real = pred_cam_t_full[2] * (fx / scaled_focal) + x_real = (u_pix - cx) * z_real / fx + y_real = (v_pix - cy) * z_real / fy + cam_t_real_pre = np.array([x_real, y_real, z_real], dtype=np.float64) + + # (1) Render MANO depth at cam_t_real_pre, compare to depth image. + mesh = _mesh_for_record(rec, mano) + rendered_depth = _render_depth(renderer, cam, mesh, cam_t_real_pre) + hand_mask = rendered_depth > 0 + + depth_path = os.path.join(depth_dir, f"{frame_idx:06d}.png") + depth_present = os.path.exists(depth_path) + depth_image = _load_depth(depth_path) if depth_present else None + if depth_image is not None and depth_image.shape != (H, W): + # depth image at a different resolution — skip alignment for this frame + depth_image = None + + # Intersect with SAM2 hand mask for this track (if provided). + # Looks up //.png. + if hand_masks_dir is not None: + hp = os.path.join(hand_masks_dir, oid, f"{frame_idx:06d}.png") + if os.path.exists(hp): + sam_mask = np.asarray(Image.open(hp)) > 0 + if sam_mask.shape == (H, W): + hand_mask &= sam_mask + + occ_mask = None + if object_masks_dir is not None: + op = os.path.join(object_masks_dir, f"{frame_idx:06d}.png") + if os.path.exists(op): + occ_mask = np.asarray(Image.open(op)) > 0 + if occ_mask.shape != (H, W): + occ_mask = None + if occ_mask is not None: + hand_mask &= ~occ_mask + + n_pixels = int(hand_mask.sum()) + + if depth_image is not None and n_pixels >= mask_min_pixels: + di = depth_image[hand_mask] + dr = rendered_depth[hand_mask] + dz = float(np.median(di - dr)) + scale = float(np.median(di / dr)) + centroid_pre = mesh.vertices.mean(axis=0) + cam_t_real_pre + offset = _ray_offset(centroid_pre, dz) + cam_t_aligned = cam_t_real_pre + offset + else: + dz = 0.0 + scale = 1.0 + cam_t_aligned = cam_t_real_pre + + out_rec = { + "track_id": rec["track_id"], + "is_right": rec["is_right"], + "frame_idx": frame_idx, + "image_size": [int(W), int(H)], + "intrinsics": {"fx": fx, "fy": fy, "cx": cx, "cy": cy}, + "mano": rec["mano"], + "cam_t": cam_t_aligned.tolist(), + "diagnostics": { + "dz": dz, + "n_pixels": n_pixels, + "scale": scale, + "cam_t_pre_dz": cam_t_real_pre.tolist(), + "scaled_focal": scaled_focal, + }, + } + with open(out_path, "w") as f: + json.dump(out_rec, f, indent=2) + + +def main() -> None: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("--hamer_dir", required=True) + parser.add_argument("--depth_dir", required=True) + parser.add_argument("--intrinsics_path", required=True) + parser.add_argument("--mano_assets_root", required=True) + parser.add_argument("--output_dir", required=True) + parser.add_argument("--hand_masks_dir", default=None, + help="Optional root folder of SAM2 per-track hand " + "masks (subdirs named /). Restricts " + "the depth-comparison region to pixels that are " + "BOTH rendered-MANO and image-grounded hand.") + parser.add_argument("--object_masks_dir", default=None, + help="Optional folder of object-occlusion masks " + "(per-frame PNGs). Pixels in this mask are " + "excluded from the depth-comparison region.") + parser.add_argument("--mask_min_pixels", type=int, default=256) + args = parser.parse_args() + align_hands( + hamer_dir = args.hamer_dir, + depth_dir = args.depth_dir, + intrinsics_path = args.intrinsics_path, + mano_assets_root = args.mano_assets_root, + output_dir = args.output_dir, + hand_masks_dir = args.hand_masks_dir, + object_masks_dir = args.object_masks_dir, + mask_min_pixels = args.mask_min_pixels, + ) + + +if __name__ == "__main__": + main() diff --git a/third-party/video_to_data/reconstruction/modules/v2d_hamer/lib/download_weights.py b/third-party/video_to_data/reconstruction/modules/v2d_hamer/lib/download_weights.py new file mode 100644 index 0000000000000000000000000000000000000000..aea7d52ccf35b91a322edb8abd4a42ecd9c79a72 --- /dev/null +++ b/third-party/video_to_data/reconstruction/modules/v2d_hamer/lib/download_weights.py @@ -0,0 +1,51 @@ +# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 +"""Download HaMeR demo data + checkpoint. + +Downloads ``hamer_demo_data.tar.gz`` from the original HaMeR project page +and extracts it into ````. The expected layout afterwards: + + /_DATA/hamer_ckpts/ + checkpoints/hamer.ckpt + dataset_config.yaml + model_config.yaml + +Note: MANO_RIGHT.pkl is NOT downloaded (it requires registration at +https://mano.is.tue.mpg.de/). Place it manually under /data/mano/ +or wherever HaMeR's config expects it. +""" + +import argparse +import os +import subprocess +import tarfile + +_URL = "https://www.cs.utexas.edu/~pavlakos/hamer/data/hamer_demo_data.tar.gz" + + +def run_download(weights_dir: str) -> None: + os.makedirs(weights_dir, exist_ok=True) + tar_path = os.path.join(weights_dir, "hamer_demo_data.tar.gz") + ckpt = os.path.join(weights_dir, "_DATA", "hamer_ckpts", "checkpoints", "hamer.ckpt") + if os.path.exists(ckpt): + print(f" HaMeR checkpoint already present at {ckpt}; skipping download.") + return + print(f" Downloading HaMeR demo data → {tar_path}") + subprocess.run(["wget", "-q", "--show-progress", _URL, "-O", tar_path], check=True) + print(f" Extracting → {weights_dir}") + with tarfile.open(tar_path) as tf: + tf.extractall(weights_dir, filter="data") + os.remove(tar_path) + if not os.path.exists(ckpt): + raise RuntimeError( + f"Extraction succeeded but {ckpt} was not produced. " + "The archive layout may have changed upstream." + ) + print(f" Done. HaMeR checkpoint at {ckpt}") + + +if __name__ == "__main__": + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("--weights_dir", required=True) + args = parser.parse_args() + run_download(args.weights_dir) diff --git a/third-party/video_to_data/reconstruction/modules/v2d_hamer/lib/masks_to_hands.py b/third-party/video_to_data/reconstruction/modules/v2d_hamer/lib/masks_to_hands.py new file mode 100644 index 0000000000000000000000000000000000000000..dfe42eabd8ae427477382ba631af335ddc6958e6 --- /dev/null +++ b/third-party/video_to_data/reconstruction/modules/v2d_hamer/lib/masks_to_hands.py @@ -0,0 +1,179 @@ +# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 +"""Per-track per-frame HaMeR regression driven by SAM2 hand masks. + +For each (track, frame) pair, this module: + 1. Loads the SAM2 mask, computes its centroid and tight bbox. + 2. Builds a square crop centred at the centroid, sized as + ``max(mask_bbox_side) * bbox_expansion`` → forgiving to partial masks. + 3. Runs HaMeR on the crop. + 4. Saves a JSON record with MANO params + camera fields. + +Output layout: + //.json + +JSON schema (per file, single detection per track per frame): + { + "track_id": int, + "is_right": bool, + "frame_idx": int, + "image_size": [W, H], + "crop": {"cx": ..., "cy": ..., "size": ...}, + "mano": { + "betas": [10 floats], + "global_orient": [3 floats], # axis-angle, converted from rotmat + "hand_pose": [45 floats] # axis-angle, 15×3, converted + }, + "camera": { + "pred_cam_t_full": [tx, ty, tz], + "scaled_focal_length": float + } + } + +Frames where the mask is below ``mask_min_pixels`` (or absent) get no +output file — downstream code should treat missing as "hand not visible." + +Usage: + python -m v2d.hamer.lib.masks_to_hands \\ + --frames_dir /data/frames \\ + --masks_dir /data/masks \\ + --tracks_path /data/hand_tracks.json \\ + --output_dir /data/hamer \\ + --weights_dir /data/weights/hamer +""" + +from __future__ import annotations + +import argparse +import glob +import json +import os +from typing import List + +import numpy as np +from PIL import Image +from tqdm import tqdm + +from v2d.hamer.lib._hamer import get_model, run_hamer, rotmat_to_axis_angle + + +def _mask_centroid_and_size(mask: np.ndarray) -> tuple[float, float, float, int]: + """Return (cx, cy, side, n_pixels) of the mask's tight bbox.""" + ys, xs = np.nonzero(mask) + if xs.size == 0: + return 0.0, 0.0, 0.0, 0 + x0, x1 = int(xs.min()), int(xs.max()) + y0, y1 = int(ys.min()), int(ys.max()) + cx = (x0 + x1) * 0.5 + cy = (y0 + y1) * 0.5 + side = float(max(x1 - x0, y1 - y0)) + return cx, cy, side, int(xs.size) + + +def masks_to_hands( + frames_dir: str, + masks_dir: str, + tracks_path: str, + output_dir: str, + weights_dir: str, + bbox_expansion: float = 1.7, + mask_min_pixels: int = 256, +) -> None: + with open(tracks_path) as f: + tracks = json.load(f)["tracks"] + hand_tracks = [t for t in tracks if t.get("role", "hand") == "hand"] + if not hand_tracks: + raise RuntimeError(f"No hand tracks in {tracks_path}") + + print(f"Loading HaMeR from {weights_dir}...") + model, cfg = get_model(weights_dir) + + for track in hand_tracks: + oid = int(track["object_id"]) + is_right = bool(track["is_right"]) + track_dir = os.path.join(output_dir, str(oid)) + os.makedirs(track_dir, exist_ok=True) + + mask_files = sorted(glob.glob(os.path.join(masks_dir, str(oid), "*.png"))) + side = "right" if is_right else "left" + print(f"\nTrack {oid} ({side}): {len(mask_files)} mask frames") + + n_written = n_skipped = 0 + for mask_path in tqdm(mask_files, desc=f" track {oid}", ncols=80, unit="frame"): + frame_idx = int(os.path.splitext(os.path.basename(mask_path))[0]) + frame_path = os.path.join(frames_dir, f"{frame_idx:06d}.png") + if not os.path.exists(frame_path): + # try .jpg + frame_path = os.path.join(frames_dir, f"{frame_idx:06d}.jpg") + if not os.path.exists(frame_path): + continue + out_path = os.path.join(track_dir, f"{frame_idx:06d}.json") + if os.path.exists(out_path): + continue # skip already-done frames + + mask = np.asarray(Image.open(mask_path)) > 0 + cx, cy, mask_side, npx = _mask_centroid_and_size(mask) + if npx < mask_min_pixels: + n_skipped += 1 + continue + + image = np.asarray(Image.open(frame_path).convert("RGB")) + H, W = image.shape[:2] + size = mask_side * bbox_expansion + # Clamp center so the crop stays a real bbox (HaMeR's crop helper + # handles out-of-image padding internally, but keeping center sane + # avoids silly edge cases). + cx = float(np.clip(cx, 0.0, W - 1)) + cy = float(np.clip(cy, 0.0, H - 1)) + + out = run_hamer(model, cfg, image, cx, cy, size, is_right=is_right) + + record = { + "track_id": oid, + "is_right": is_right, + "frame_idx": frame_idx, + "image_size": [int(W), int(H)], + "crop": {"cx": cx, "cy": cy, "size": float(size)}, + "mano": { + "betas": out["betas"].tolist(), + "global_orient": rotmat_to_axis_angle(out["global_orient"]).reshape(-1).tolist(), + "hand_pose": rotmat_to_axis_angle(out["hand_pose"]).reshape(-1).tolist(), + }, + "camera": { + "pred_cam_t_full": out["pred_cam_t_full"].tolist(), + "scaled_focal_length": out["scaled_focal_length"], + }, + } + with open(out_path, "w") as f: + json.dump(record, f, indent=2) + n_written += 1 + + print(f" track {oid}: wrote {n_written}, skipped {n_skipped} (mask too small)") + + +def main() -> None: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("--frames_dir", required=True) + parser.add_argument("--masks_dir", required=True, + help="Root masks dir; contains /*.png subdirs.") + parser.add_argument("--tracks_path", required=True, + help="hand_tracks.json (object_id → is_right mapping).") + parser.add_argument("--output_dir", required=True) + parser.add_argument("--weights_dir", required=True, + help="Dir containing _DATA/hamer_ckpts/.") + parser.add_argument("--bbox_expansion", type=float, default=1.7) + parser.add_argument("--mask_min_pixels", type=int, default=256) + args = parser.parse_args() + masks_to_hands( + frames_dir = args.frames_dir, + masks_dir = args.masks_dir, + tracks_path = args.tracks_path, + output_dir = args.output_dir, + weights_dir = args.weights_dir, + bbox_expansion = args.bbox_expansion, + mask_min_pixels = args.mask_min_pixels, + ) + + +if __name__ == "__main__": + main() diff --git a/third-party/video_to_data/reconstruction/modules/v2d_hamer/lib/pyproject.toml b/third-party/video_to_data/reconstruction/modules/v2d_hamer/lib/pyproject.toml new file mode 100644 index 0000000000000000000000000000000000000000..4633f9b4c1211f395a9920ebd1ab921fdb2c6a90 --- /dev/null +++ b/third-party/video_to_data/reconstruction/modules/v2d_hamer/lib/pyproject.toml @@ -0,0 +1,23 @@ +# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 +[build-system] +requires = ["setuptools>=68.0", "wheel"] +build-backend = "setuptools.build_meta" + +[project] +name = "v2d-hamer-lib" +version = "0.1.0" +description = "HaMeR per-frame MANO regression driven by SAM2 hand masks" +requires-python = ">=3.10" +dependencies = [ + "numpy", + "Pillow", + "opencv-python", + "v2d-common", +] + +[tool.setuptools] +packages = ["v2d.hamer.lib"] + +[tool.setuptools.package-dir] +"v2d.hamer.lib" = "." diff --git a/third-party/video_to_data/reconstruction/modules/v2d_hamer/lib/render_hands_aligned_video.py b/third-party/video_to_data/reconstruction/modules/v2d_hamer/lib/render_hands_aligned_video.py new file mode 100644 index 0000000000000000000000000000000000000000..bf0b366f144dc37eb1b9148b0a0a1ed1719a7f80 --- /dev/null +++ b/third-party/video_to_data/reconstruction/modules/v2d_hamer/lib/render_hands_aligned_video.py @@ -0,0 +1,466 @@ +# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 +"""Render aligned MANO meshes (+ optional object) onto the source video. + +Consumes the JSONs written by ``align_hands.py`` (real intrinsics, +depth-shifted cam_t) plus optionally a FoundationPose-tracked object mesh +and per-frame poses. Emits a 2×2 grid: + + [src cam (image underlay)] [world top-down view] + [world side view ] [world front view ] + +The world cameras orbit the per-frame scene center (mean of hand vertices, +plus object centroid if present). Each frame is independently centered, +because HaMeR has no temporal world frame — every frame's camera defines +its own "world." + +Usage: + python -m v2d.hamer.lib.render_hands_aligned_video \\ + --frames_dir /data/frames \\ + --aligned_dir /data/hamer_aligned \\ + --mano_assets_root /data/weights/hamer/_DATA/data \\ + --output_path /data/hamer_aligned_overlay.mp4 \\ + [--object_mesh_path /data/mesh_scaled.obj] \\ + [--object_poses_dir /data/poses_smoothed] +""" + +from __future__ import annotations + +import argparse +import glob +import json +import os +import subprocess +import tempfile +from typing import Tuple + +os.environ.setdefault("PYOPENGL_PLATFORM", "egl") + +import numpy as np +import pyrender +import torch +import trimesh +from manotorch.manolayer import ManoLayer +from PIL import Image, ImageDraw, ImageFont +from tqdm import tqdm + + +_TRACK_COLORS = [ + (235, 70, 70), # red + ( 60, 150, 235), # blue + (245, 175, 40), # orange + (190, 80, 220), # purple + ( 60, 215, 215), # cyan + (245, 100, 180), # pink + (245, 230, 60), # yellow +] +_OBJECT_COLOR = (40, 220, 40) # vivid green — distinct from hand palette +_BG_DARKEN = 0.45 +_CV_TO_GL_VEC = np.array([1.0, -1.0, -1.0]) + + +def _material(rgb: tuple, alpha: float = 1.0) -> "pyrender.MetallicRoughnessMaterial": + """PBR material so pyrender's lighting actually shades the surface. + + Setting ``trimesh.visual.face_colors`` bakes flat colors that look + self-illuminating; a material with non-zero roughness picks up Lambert- + style shading from the scene lights and reveals 3D shape. + """ + return pyrender.MetallicRoughnessMaterial( + metallicFactor=0.0, + roughnessFactor=0.7, + alphaMode="OPAQUE", + baseColorFactor=(rgb[0] / 255.0, rgb[1] / 255.0, rgb[2] / 255.0, alpha), + ) + + +def _add_lights(scene: pyrender.Scene, cam_pose: np.ndarray) -> None: + """3-point lighting: key (front-right), fill (front-left), back (behind). + + All positioned relative to the camera so meshes are well-lit regardless + of which orbital view is rendering. + """ + R = cam_pose[:3, :3] + eye = cam_pose[:3, 3] + fwd = -R[:, 2] # camera looks down −Z in its local frame + right = R[:, 0] + up = R[:, 1] + + def _at(direction: np.ndarray) -> np.ndarray: + pose = np.eye(4) + # Light "looks" along its local −Z, so place it at eye + offset and + # orient it back toward the scene (eye - fwd*r, simple parallel-light + # works since DirectionalLight is direction-only — only rotation matters). + pose[:3, :3] = R + pose[:3, 3] = eye + direction + return pose + + # Pyrender's DirectionalLight uses the node's −Z as the light direction. + # All three lights inherit the camera's rotation so the direction is set + # by the rotation alone (translation is irrelevant for directional lights + # but pyrender wants a pose). + base = np.eye(4); base[:3, :3] = R; base[:3, 3] = eye + rot_y = np.array([ + [np.cos(np.radians(45)), 0, np.sin(np.radians(45))], + [0, 1, 0], + [-np.sin(np.radians(45)), 0, np.cos(np.radians(45))], + ]) + rot_y_neg = np.array([ + [np.cos(np.radians(-30)), 0, np.sin(np.radians(-30))], + [0, 1, 0], + [-np.sin(np.radians(-30)), 0, np.cos(np.radians(-30))], + ]) + + key = base.copy(); key[:3, :3] = R @ rot_y_neg + fill = base.copy(); fill[:3, :3] = R @ rot_y + back = base.copy() + # Back light points away from camera (~180° around y from key). + rot_y_180 = np.array([[-1, 0, 0], [0, 1, 0], [0, 0, -1]], dtype=np.float64) + back[:3, :3] = R @ rot_y_180 + + scene.add(pyrender.DirectionalLight(color=[1.0, 1.0, 1.0], intensity=4.0), pose=key) + scene.add(pyrender.DirectionalLight(color=[1.0, 1.0, 1.0], intensity=1.5), pose=fill) + scene.add(pyrender.DirectionalLight(color=[1.0, 1.0, 1.0], intensity=2.0), pose=back) + + +def _font(size: int = 18): + try: + return ImageFont.truetype("/usr/share/fonts/truetype/dejavu/DejaVuSans-Bold.ttf", size) + except OSError: + return ImageFont.load_default() + + +def _mano_layer(mano_assets_root: str) -> ManoLayer: + return ManoLayer( + rot_mode="axisang", + use_pca=False, + side="right", + center_idx=None, + mano_assets_root=mano_assets_root, + ) + + +def _frame_records(aligned_dir: str) -> dict[int, list[dict]]: + out: dict[int, list[dict]] = {} + for path in sorted(glob.glob(os.path.join(aligned_dir, "*", "*.json"))): + with open(path) as f: + rec = json.load(f) + out.setdefault(int(rec["frame_idx"]), []).append(rec) + return out + + +def _rec_cam_t(rec: dict, use_pre_dz_cam_t: bool) -> np.ndarray: + """``cam_t`` for the record. With ``use_pre_dz_cam_t``, read the pre-dz + value saved in ``diagnostics`` by ``align_hands`` (i.e. the cam_t after + intrinsics rescaling but *before* the per-frame depth shift). This makes + a single renderer/track-format double-duty: the same aligned tracks can + be projected with or without depth alignment for visual comparison. + """ + if use_pre_dz_cam_t: + return np.array(rec["diagnostics"]["cam_t_pre_dz"], dtype=np.float64) + return np.array(rec["cam_t"], dtype=np.float64) + + +def _build_hand_mesh( + rec: dict, + mano: ManoLayer, + use_pre_dz_cam_t: bool = False, +) -> Tuple[np.ndarray, np.ndarray]: + """Hand verts in CV cam space + faces.""" + pose_aa = np.concatenate([ + np.array(rec["mano"]["global_orient"], dtype=np.float32), + np.array(rec["mano"]["hand_pose"], dtype=np.float32), + ]) + betas = np.array(rec["mano"]["betas"], dtype=np.float32) + out = mano(torch.from_numpy(pose_aa)[None], torch.from_numpy(betas)[None]) + verts_local = out.verts[0].detach().numpy() + if not rec["is_right"]: + verts_local[:, 0] *= -1 + # Apply the per-track multiplicative depth correction emitted by + # align_hands' post-pass (when present). cam_t already carries the + # additive dz shift; hand_scale rescales the mesh around its centroid + # so the projected silhouette grows/shrinks to match the image while + # the centroid pixel is preserved. With ``use_pre_dz_cam_t`` we are + # explicitly rendering the un-aligned hand, so hand_scale is forced to 1. + hand_scale = 1.0 if use_pre_dz_cam_t else float(rec.get("hand_scale", 1.0)) + if hand_scale != 1.0: + c = verts_local.mean(axis=0, keepdims=True) + verts_local = (verts_local - c) * hand_scale + c + cam_t = _rec_cam_t(rec, use_pre_dz_cam_t) + verts_cam = verts_local + cam_t[None, :] + faces = mano.th_faces.numpy() + if not rec["is_right"]: + faces = faces[:, [0, 2, 1]] + return verts_cam.astype(np.float32), faces + + +def _quat_to_rot(qw, qx, qy, qz) -> np.ndarray: + return np.array([ + [1-2*qy*qy-2*qz*qz, 2*qx*qy-2*qw*qz, 2*qx*qz+2*qw*qy], + [2*qx*qy+2*qw*qz, 1-2*qx*qx-2*qz*qz, 2*qy*qz-2*qw*qx], + [2*qx*qz-2*qw*qy, 2*qy*qz+2*qw*qx, 1-2*qx*qx-2*qy*qy], + ], dtype=np.float64) + + +def _load_object_mesh(path: str) -> Tuple[np.ndarray, np.ndarray]: + tm = trimesh.load(path, force="mesh", process=False) + return np.asarray(tm.vertices, dtype=np.float64), np.asarray(tm.faces, dtype=np.int32) + + +def _object_verts_cam(verts_base: np.ndarray, pose_path: str) -> np.ndarray: + with open(pose_path) as f: + pd = json.load(f) + R = _quat_to_rot(*pd["rotation"]) + t = np.array(pd["translation"], dtype=np.float64) + s = np.array(pd["scale"], dtype=np.float64) + RS = R @ np.diag(s) + return ((RS @ verts_base.T).T + t).astype(np.float32) + + +def _lookat_pose(eye: np.ndarray, target: np.ndarray, + up: np.ndarray = np.array([0.0, 1.0, 0.0])) -> np.ndarray: + """4×4 cam-to-world (pyrender GL convention: cam looks down −Z, up = +Y).""" + z = eye - target + z = z / np.linalg.norm(z) + x = np.cross(up, z) + if np.linalg.norm(x) < 1e-6: + up = np.array([0.0, 0.0, 1.0]) + x = np.cross(up, z) + x = x / np.linalg.norm(x) + y = np.cross(z, x) + pose = np.eye(4) + pose[:3, 0] = x + pose[:3, 1] = y + pose[:3, 2] = z + pose[:3, 3] = eye + return pose + + +def _add_label(img: Image.Image, text: str) -> Image.Image: + draw = ImageDraw.Draw(img) + font = _font(18) + tw = draw.textlength(text, font=font) + draw.rectangle([4, 4, 4 + tw + 8, 28], fill=(0, 0, 0, 180)) + draw.text((8, 6), text, fill=(255, 255, 255), font=font) + return img + + +def render_hands_aligned_video( + frames_dir: str, + aligned_dir: str, + mano_assets_root: str, + output_path: str, + object_mesh_path: str | None = None, + object_poses_dir: str | None = None, + object_scale: float = 1.0, + fps: float = 30.0, + alpha: float = 0.55, + use_pre_dz_cam_t: bool = False, +) -> None: + frame_files = sorted( + glob.glob(os.path.join(frames_dir, "*.png")) + + glob.glob(os.path.join(frames_dir, "*.jpg")) + ) + if not frame_files: + raise FileNotFoundError(f"No frames in {frames_dir}") + + records = _frame_records(aligned_dir) + if not records: + raise FileNotFoundError(f"No aligned JSONs in {aligned_dir}//") + + mano = _mano_layer(mano_assets_root) + + obj_verts_base = None + obj_faces = None + if object_mesh_path is not None and object_poses_dir is not None: + obj_verts_base, obj_faces = _load_object_mesh(object_mesh_path) + if object_scale != 1.0: + # Apply learned global object scale once to the canonical mesh + # vertices, before any per-frame transform — Transform3d.scale + # in the per-frame JSONs is left to do whatever the upstream + # tracker baked in (typically [1,1,1] post-FoundationPose). + obj_verts_base = obj_verts_base * float(object_scale) + print(f" Applied object_scale={object_scale:.4f} to mesh.") + + W_full, H_full = Image.open(frame_files[0]).size + pw = (W_full // 2) & ~1 + ph = (H_full // 2) & ~1 + + # Real intrinsics from any aligned record (constant across frames in a run). + first = next(iter(records.values()))[0] + fx = float(first["intrinsics"]["fx"]) + fy = float(first["intrinsics"]["fy"]) + cx = float(first["intrinsics"]["cx"]) + cy = float(first["intrinsics"]["cy"]) + # Far plane covers the actual cam_t.z range with margin. + z_max = max( + _rec_cam_t(rec, use_pre_dz_cam_t)[2] + for recs in records.values() for rec in recs + ) + zfar = max(20.0, float(z_max) * 1.5) + + # src-cam: scaled intrinsics for the half-res panel, principal point shifts + # to the panel center. + scale_x = pw / W_full + scale_y = ph / H_full + cam_src = pyrender.IntrinsicsCamera( + fx=fx * scale_x, fy=fy * scale_y, + cx=cx * scale_x, cy=cy * scale_y, + znear=0.01, zfar=zfar, + ) + cam_world = pyrender.PerspectiveCamera( + yfov=np.radians(60.0), znear=0.01, zfar=zfar, + ) + + renderer = pyrender.OffscreenRenderer(viewport_width=pw, viewport_height=ph) + font = _font(18) + + panel_labels = ["src cam", "world top", "world side", "world front"] + + with tempfile.TemporaryDirectory() as tmpdir: + for f_idx, frame_path in enumerate(tqdm(frame_files, desc="render", ncols=80)): + bg_full = np.asarray(Image.open(frame_path).convert("RGB"), dtype=np.float32) + recs = records.get(f_idx, []) + + # Per-frame hand meshes (cam space). + hand_meshes_cv = [] + for rec in recs: + v_cv, f_ = _build_hand_mesh(rec, mano, use_pre_dz_cam_t) + color = _TRACK_COLORS[(rec["track_id"] - 1) % len(_TRACK_COLORS)] + hand_meshes_cv.append((v_cv, f_, color, rec)) + + # Per-frame object mesh (cam space) — optional. + obj_cv = None + if obj_verts_base is not None and object_poses_dir is not None: + pose_path = os.path.join(object_poses_dir, f"{f_idx:06d}.json") + if os.path.exists(pose_path): + obj_cv = _object_verts_cam(obj_verts_base, pose_path) + + # ---- Panel 0: src cam (with image underlay) ------------------ + scene_src = pyrender.Scene(bg_color=[0, 0, 0, 0], + ambient_light=[0.18, 0.18, 0.18]) + scene_src.add(cam_src, pose=np.eye(4)) + _add_lights(scene_src, cam_pose=np.eye(4)) + for v_cv, f_, color, _rec in hand_meshes_cv: + v_gl = v_cv * _CV_TO_GL_VEC + tm = trimesh.Trimesh(v_gl, f_, process=False) + scene_src.add(pyrender.Mesh.from_trimesh( + tm, material=_material(color), smooth=True)) + if obj_cv is not None: + v_gl = obj_cv * _CV_TO_GL_VEC + tm_o = trimesh.Trimesh(v_gl, obj_faces, process=False) + scene_src.add(pyrender.Mesh.from_trimesh( + tm_o, material=_material(_OBJECT_COLOR), smooth=True)) + rgba_src, _ = renderer.render(scene_src, flags=pyrender.RenderFlags.RGBA) + bg_panel = np.asarray( + Image.fromarray(bg_full.astype(np.uint8)).resize((pw, ph)), + dtype=np.float32, + ) + ov = rgba_src.astype(np.float32) + mask = ov[:, :, 3:4] / 255.0 + bg_dim = bg_panel * (1.0 - mask * (1.0 - _BG_DARKEN)) + src_panel = (mask * ov[:, :, :3] + (1.0 - mask) * bg_dim).clip(0, 255).astype(np.uint8) + + # ---- World panels (top / side / front, gray background) ------ + # Scene center: hand vertices + object vertices (CV → GL). + all_verts_gl = [] + for v_cv, _, _, _ in hand_meshes_cv: + all_verts_gl.append(v_cv * _CV_TO_GL_VEC) + if obj_cv is not None: + all_verts_gl.append(obj_cv * _CV_TO_GL_VEC) + if all_verts_gl: + stacked = np.concatenate(all_verts_gl, axis=0) + scene_center = stacked.mean(0) + scene_radius = float(np.linalg.norm(stacked - scene_center, axis=1).max()) + r = max(scene_radius * 2.5, 0.4) + else: + scene_center = np.zeros(3, dtype=np.float32) + r = 0.5 + + world_cam_poses = [ + _lookat_pose(scene_center + np.array([0.0, r, 0.0]), + scene_center, up=np.array([0.0, 0.0, -1.0])), # top + _lookat_pose(scene_center + np.array([ r, 0.0, 0.0]), + scene_center), # side + _lookat_pose(scene_center + np.array([0.0, 0.0, r]), + scene_center), # front + ] + + panels = [Image.fromarray(src_panel)] + for world_pose in world_cam_poses: + scene_w = pyrender.Scene(bg_color=[0.78, 0.78, 0.78, 1.0], + ambient_light=[0.20, 0.20, 0.20]) + scene_w.add(cam_world, pose=world_pose) + _add_lights(scene_w, cam_pose=world_pose) + for v_cv, f_, color, _rec in hand_meshes_cv: + v_gl = v_cv * _CV_TO_GL_VEC + tm = trimesh.Trimesh(v_gl, f_, process=False) + scene_w.add(pyrender.Mesh.from_trimesh( + tm, material=_material(color), smooth=True)) + if obj_cv is not None: + v_gl = obj_cv * _CV_TO_GL_VEC + tm_o = trimesh.Trimesh(v_gl, obj_faces, process=False) + scene_w.add(pyrender.Mesh.from_trimesh( + tm_o, material=_material(_OBJECT_COLOR), smooth=True)) + rgb_w, _ = renderer.render(scene_w) + panels.append(Image.fromarray(rgb_w, "RGB")) + + for i, (panel, label) in enumerate(zip(panels, panel_labels)): + panels[i] = _add_label(panel, label) + + grid = Image.new("RGB", (pw * 2, ph * 2)) + for panel, pos in zip(panels, [(0, 0), (pw, 0), (0, ph), (pw, ph)]): + grid.paste(panel, pos) + grid.save(os.path.join(tmpdir, f"{f_idx:06d}.png")) + + renderer.delete() + os.makedirs(os.path.dirname(os.path.abspath(output_path)) or ".", exist_ok=True) + subprocess.run([ + "ffmpeg", "-y", "-loglevel", "error", + "-r", str(fps), + "-i", os.path.join(tmpdir, "%06d.png"), + "-c:v", "libx264", "-pix_fmt", "yuv420p", "-crf", "20", + output_path, + ], check=True) + print(f"Saved → {output_path}") + + +def main() -> None: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("--frames_dir", required=True) + parser.add_argument("--aligned_dir", required=True) + parser.add_argument("--mano_assets_root", required=True) + parser.add_argument("--output_path", required=True) + parser.add_argument("--object_mesh_path", default=None, + help="Optional FoundationPose-scaled object mesh.") + parser.add_argument("--object_poses_dir", default=None, + help="Optional FoundationPose smoothed per-frame poses.") + parser.add_argument("--object_scale", type=float, default=1.0, + help="Global multiplier applied to object mesh " + "vertices before per-frame transforms. Use " + "for learned-scale outputs from the gsplat " + "refinement step.") + parser.add_argument("--fps", type=float, default=30.0) + parser.add_argument("--alpha", type=float, default=0.55) + parser.add_argument("--use_pre_dz_cam_t", action="store_true", + help="Project the un-aligned hand (cam_t from " + "diagnostics.cam_t_pre_dz, hand_scale=1) so the " + "same aligned-track dir can drive both aligned " + "and unaligned renders.") + args = parser.parse_args() + render_hands_aligned_video( + frames_dir = args.frames_dir, + aligned_dir = args.aligned_dir, + mano_assets_root = args.mano_assets_root, + output_path = args.output_path, + object_mesh_path = args.object_mesh_path, + object_poses_dir = args.object_poses_dir, + object_scale = args.object_scale, + fps = args.fps, + alpha = args.alpha, + use_pre_dz_cam_t = args.use_pre_dz_cam_t, + ) + + +if __name__ == "__main__": + main() diff --git a/third-party/video_to_data/reconstruction/modules/v2d_hamer/lib/render_hands_video.py b/third-party/video_to_data/reconstruction/modules/v2d_hamer/lib/render_hands_video.py new file mode 100644 index 0000000000000000000000000000000000000000..48ea0c4d6cc8d96caed460add117b154f0e03115 --- /dev/null +++ b/third-party/video_to_data/reconstruction/modules/v2d_hamer/lib/render_hands_video.py @@ -0,0 +1,211 @@ +# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 +"""Verification: render projected MANO meshes onto the source video. + +Takes the per-frame per-track JSONs written by ``masks_to_hands`` and +reconstructs the MANO mesh from the saved axis-angle params, projects it +through the virtual pinhole at the saved ``scaled_focal_length`` (principal +point at image center), and alpha-blends the rendered silhouette onto +the original frame. + +Usage: + python -m v2d.hamer.lib.render_hands_video \\ + --frames_dir /data/frames \\ + --hamer_dir /data/hamer \\ + --mano_assets_root /data/weights/hamer/_DATA/data \\ + --output_path /data/hamer_overlay.mp4 +""" + +from __future__ import annotations + +import argparse +import glob +import json +import os +import subprocess +import tempfile +from typing import Tuple + +os.environ.setdefault("PYOPENGL_PLATFORM", "egl") + +import numpy as np +import pyrender +import torch +import trimesh +from manotorch.manolayer import ManoLayer +from PIL import Image, ImageDraw, ImageFont +from tqdm import tqdm + + +_TRACK_COLORS = [ + (255, 60, 60), # red + ( 60, 160, 255), # blue + ( 60, 200, 60), # green + (255, 180, 40), # orange + (200, 80, 220), # purple +] +_CV_TO_GL = np.array([1.0, -1.0, -1.0]) + + +def _font(size: int = 18): + try: + return ImageFont.truetype("/usr/share/fonts/truetype/dejavu/DejaVuSans-Bold.ttf", size) + except OSError: + return ImageFont.load_default() + + +def _mano_layer(mano_assets_root: str) -> ManoLayer: + return ManoLayer( + rot_mode="axisang", + use_pca=False, + side="right", + center_idx=None, + mano_assets_root=mano_assets_root, + ) + + +def _frame_records(hamer_dir: str) -> dict[int, list[dict]]: + """Map frame_idx → list of records (one per track).""" + out: dict[int, list[dict]] = {} + for path in sorted(glob.glob(os.path.join(hamer_dir, "*", "*.json"))): + with open(path) as f: + rec = json.load(f) + out.setdefault(int(rec["frame_idx"]), []).append(rec) + return out + + +def _build_mesh_for_record(rec: dict, mano: ManoLayer) -> Tuple[np.ndarray, np.ndarray]: + """Compute MANO vertices in camera space and the corresponding faces. + + Verts are returned in CV camera space (z forward, y down). + """ + mano_p = rec["mano"] + pose_aa = np.concatenate([ + np.array(mano_p["global_orient"], dtype=np.float32), + np.array(mano_p["hand_pose"], dtype=np.float32), + ]) # (48,) + betas_aa = np.array(mano_p["betas"], dtype=np.float32) + out = mano( + torch.from_numpy(pose_aa)[None], + torch.from_numpy(betas_aa)[None], + ) + verts_local = out.verts[0].detach().numpy() # (778, 3) + if not rec["is_right"]: + verts_local[:, 0] *= -1 # mirror left hand + cam_t = np.array(rec["camera"]["pred_cam_t_full"], dtype=np.float64) + verts_cam = verts_local + cam_t[None, :] + faces = mano.th_faces.numpy() + if not rec["is_right"]: + faces = faces[:, [0, 2, 1]] # reverse winding for the mirrored mesh + return verts_cam.astype(np.float32), faces + + +def render_hands_video( + frames_dir: str, + hamer_dir: str, + mano_assets_root: str, + output_path: str, + fps: float = 30.0, + alpha: float = 0.55, +) -> None: + frame_files = sorted( + glob.glob(os.path.join(frames_dir, "*.png")) + + glob.glob(os.path.join(frames_dir, "*.jpg")) + ) + if not frame_files: + raise FileNotFoundError(f"No frames in {frames_dir}") + + records = _frame_records(hamer_dir) + if not records: + raise FileNotFoundError(f"No HaMeR JSONs in {hamer_dir}//") + + mano = _mano_layer(mano_assets_root) + + W, H = Image.open(frame_files[0]).size + # Use the first record's scaled_focal_length as the projection focal. + # All frames in a video share the same scaled_focal_length since it + # depends only on (cfg.EXTRA.FOCAL_LENGTH, cfg.MODEL.IMAGE_SIZE, max(W,H)). + first_rec = next(iter(records.values()))[0] + focal = first_rec["camera"]["scaled_focal_length"] + # HaMeR's virtual pinhole has scaled_focal_length ≈ 5000/256 * max(W,H), + # which puts hands at metric "depth" of tens of meters. Use a far plane + # that covers the actual range plus margin instead of the usual ~10 m. + z_max = max(rec["camera"]["pred_cam_t_full"][2] + for recs in records.values() for rec in recs) + zfar = max(50.0, float(z_max) * 1.5) + cam = pyrender.IntrinsicsCamera(fx=focal, fy=focal, cx=W / 2, cy=H / 2, + znear=0.01, zfar=zfar) + renderer = pyrender.OffscreenRenderer(viewport_width=W, viewport_height=H) + font = _font(18) + + with tempfile.TemporaryDirectory() as tmpdir: + for f_idx, frame_path in enumerate(tqdm(frame_files, desc="render", ncols=80)): + bg = np.asarray(Image.open(frame_path).convert("RGB"), dtype=np.float32) + recs = records.get(f_idx, []) + if not recs: + Image.fromarray(bg.astype(np.uint8)).save( + os.path.join(tmpdir, f"{f_idx:06d}.png")) + continue + + scene = pyrender.Scene(bg_color=[0, 0, 0, 0], ambient_light=[0.5, 0.5, 0.5]) + scene.add(cam, pose=np.eye(4)) + scene.add(pyrender.DirectionalLight(color=[1, 1, 1], intensity=3.0), + pose=np.eye(4)) + for rec in recs: + verts_cv, faces = _build_mesh_for_record(rec, mano) + verts_gl = verts_cv * _CV_TO_GL + color = _TRACK_COLORS[(rec["track_id"] - 1) % len(_TRACK_COLORS)] + tm = trimesh.Trimesh(verts_gl, faces, process=False) + tm.visual.face_colors = np.array([*color, 255], dtype=np.uint8) + scene.add(pyrender.Mesh.from_trimesh(tm, smooth=False)) + rgba, _ = renderer.render(scene, flags=pyrender.RenderFlags.RGBA) + ov = rgba.astype(np.float32) + mask = ov[:, :, 3:4] / 255.0 + out = bg * (1 - alpha * mask) + ov[:, :, :3] * (alpha * mask) + out_img = Image.fromarray(out.clip(0, 255).astype(np.uint8)) + + draw = ImageDraw.Draw(out_img) + for i, rec in enumerate(recs): + color = _TRACK_COLORS[(rec["track_id"] - 1) % len(_TRACK_COLORS)] + y = 8 + i * 24 + draw.rectangle([8, y, 28, y + 20], fill=color) + draw.text((34, y), + f"id={rec['track_id']} {'R' if rec['is_right'] else 'L'}", + fill=(255, 255, 255), font=font, + stroke_width=2, stroke_fill=(0, 0, 0)) + out_img.save(os.path.join(tmpdir, f"{f_idx:06d}.png")) + + renderer.delete() + os.makedirs(os.path.dirname(os.path.abspath(output_path)) or ".", exist_ok=True) + subprocess.run([ + "ffmpeg", "-y", "-loglevel", "error", + "-r", str(fps), + "-i", os.path.join(tmpdir, "%06d.png"), + "-c:v", "libx264", "-pix_fmt", "yuv420p", "-crf", "20", + output_path, + ], check=True) + print(f"Saved → {output_path}") + + +def main() -> None: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("--frames_dir", required=True) + parser.add_argument("--hamer_dir", required=True) + parser.add_argument("--mano_assets_root", required=True, + help="Dir containing MANO_RIGHT.pkl (manotorch convention).") + parser.add_argument("--output_path", required=True) + parser.add_argument("--fps", type=float, default=30.0) + parser.add_argument("--alpha", type=float, default=0.55) + args = parser.parse_args() + render_hands_video( + frames_dir = args.frames_dir, + hamer_dir = args.hamer_dir, + mano_assets_root = args.mano_assets_root, + output_path = args.output_path, + fps = args.fps, + alpha = args.alpha, + ) + + +if __name__ == "__main__": + main() diff --git a/third-party/video_to_data/reconstruction/modules/v2d_hand_alignment/LICENSE b/third-party/video_to_data/reconstruction/modules/v2d_hand_alignment/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..10caffae439b956cdda2b1ded9ecbe51ac10befb --- /dev/null +++ b/third-party/video_to_data/reconstruction/modules/v2d_hand_alignment/LICENSE @@ -0,0 +1,15 @@ +# Apache License 2.0 + +Copyright 2025 NVIDIA CORPORATION + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. diff --git a/third-party/video_to_data/reconstruction/modules/v2d_hand_alignment/docker/Dockerfile b/third-party/video_to_data/reconstruction/modules/v2d_hand_alignment/docker/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..0d73ac207c26973f8b32be235f91cdd683ae7426 --- /dev/null +++ b/third-party/video_to_data/reconstruction/modules/v2d_hand_alignment/docker/Dockerfile @@ -0,0 +1,17 @@ +FROM pytorch/pytorch:2.5.1-cuda12.4-cudnn9-devel +ENV DEBIAN_FRONTEND=noninteractive +WORKDIR /app + +RUN apt-get update && apt-get install -y \ + libgl1 \ + libegl1-mesa \ + libglib2.0-0 \ + ffmpeg \ + git \ + && rm -rf /var/lib/apt/lists/* + +COPY . /workspace +RUN pip install opencv-python-headless \ + git+https://github.com/mattloper/chumpy \ + git+https://github.com/lixiny/manotorch +RUN pip install -e /workspace/v2d_common -e /workspace/v2d_hand_alignment/lib diff --git a/third-party/video_to_data/reconstruction/modules/v2d_hand_alignment/docker/__init__.py b/third-party/video_to_data/reconstruction/modules/v2d_hand_alignment/docker/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..52a7a9daf028f654d6a02f65c99cc609a57b492f --- /dev/null +++ b/third-party/video_to_data/reconstruction/modules/v2d_hand_alignment/docker/__init__.py @@ -0,0 +1,2 @@ +# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 diff --git a/third-party/video_to_data/reconstruction/modules/v2d_hand_alignment/docker/_config.py b/third-party/video_to_data/reconstruction/modules/v2d_hand_alignment/docker/_config.py new file mode 100644 index 0000000000000000000000000000000000000000..703bca11b3640e83da84eaa3da8d3144c64bcbd6 --- /dev/null +++ b/third-party/video_to_data/reconstruction/modules/v2d_hand_alignment/docker/_config.py @@ -0,0 +1,6 @@ +# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 +import os + +IMAGE_NAME = "v2d_hand_alignment" +MODULES_DIR = os.path.abspath(os.path.join(os.path.dirname(os.path.abspath(__file__)), "..", "..")) diff --git a/third-party/video_to_data/reconstruction/modules/v2d_hand_alignment/docker/build.py b/third-party/video_to_data/reconstruction/modules/v2d_hand_alignment/docker/build.py new file mode 100644 index 0000000000000000000000000000000000000000..2278cc5f623b566900f2124131417e40810ca8fb --- /dev/null +++ b/third-party/video_to_data/reconstruction/modules/v2d_hand_alignment/docker/build.py @@ -0,0 +1,19 @@ +# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 +import subprocess +import os + +IMAGE_NAME = "v2d_hand_alignment" + +current_dir = os.path.dirname(os.path.abspath(__file__)) +module_dir = os.path.join(current_dir, "..") +root_dir = os.path.join(module_dir, "..") +dockerfile_path = os.path.join(current_dir, "Dockerfile") + + +def build_docker_image() -> None: + subprocess.run(["docker", "build", "-t", IMAGE_NAME, "-f", dockerfile_path, root_dir], check=True) + + +if __name__ == "__main__": + build_docker_image() diff --git a/third-party/video_to_data/reconstruction/modules/v2d_hand_alignment/docker/pyproject.toml b/third-party/video_to_data/reconstruction/modules/v2d_hand_alignment/docker/pyproject.toml new file mode 100644 index 0000000000000000000000000000000000000000..dfca8f20efc3800de4fe96b208aa62f4b9ea467f --- /dev/null +++ b/third-party/video_to_data/reconstruction/modules/v2d_hand_alignment/docker/pyproject.toml @@ -0,0 +1,18 @@ +# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 +[build-system] +requires = ["setuptools>=68.0", "wheel"] +build-backend = "setuptools.build_meta" + +[project] +name = "v2d-hand-alignment-docker" +version = "0.1.0" +description = "Docker orchestration for hand alignment" +requires-python = ">=3.10" +dependencies = ["v2d-docker"] + +[tool.setuptools] +packages = ["v2d.hand_alignment.docker"] + +[tool.setuptools.package-dir] +"v2d.hand_alignment.docker" = "." diff --git a/third-party/video_to_data/reconstruction/modules/v2d_hand_alignment/docker/run_align_hand_depth.py b/third-party/video_to_data/reconstruction/modules/v2d_hand_alignment/docker/run_align_hand_depth.py new file mode 100644 index 0000000000000000000000000000000000000000..104f41bd4765c3d2b7decba7d0fb3a91d93fddfa --- /dev/null +++ b/third-party/video_to_data/reconstruction/modules/v2d_hand_alignment/docker/run_align_hand_depth.py @@ -0,0 +1,72 @@ +# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 +from v2d.docker.container import run_in_container +from v2d.hand_alignment.docker._config import IMAGE_NAME, MODULES_DIR + + +def run_align_hand_depth( + input_path: str, + depth_path: str, + intrinsics_path: str, + output_path: str, + mesh_intrinsics_path: str | None = None, + per_frame: bool = False, + per_hand: bool = False, + align: str = 'scale', + smooth_sigma: float = 0.0, + diag_dir: str | None = None, + dev: bool = False, +) -> None: + inputs = { + "input_path": input_path, + "depth_path": depth_path, + "intrinsics_path": intrinsics_path, + } + if mesh_intrinsics_path is not None: + inputs["mesh_intrinsics_path"] = mesh_intrinsics_path + extra: dict = { + "per_frame": per_frame, + "per_hand": per_hand, + "align": align, + "smooth_sigma": smooth_sigma if smooth_sigma > 0 else None, + } + outputs = {"output_path": output_path} + if diag_dir is not None: + outputs["diag_dir"] = diag_dir + run_in_container( + image=IMAGE_NAME, + module="v2d.hand_alignment.lib.align_hand_depth", + inputs=inputs, + outputs=outputs, + extra_args=extra, + dev=dev, + modules_dir=MODULES_DIR, + gpus=False, + ) + + +if __name__ == "__main__": + import argparse + parser = argparse.ArgumentParser() + parser.add_argument("--input_path", required=True) + parser.add_argument("--depth_path", required=True) + parser.add_argument("--intrinsics_path", required=True) + parser.add_argument("--output_path", required=True) + parser.add_argument("--mesh_intrinsics_path", default=None) + parser.add_argument("--per_frame", action="store_true") + parser.add_argument("--per_hand", action="store_true") + parser.add_argument("--align", default="scale", choices=["scale", "offset"]) + parser.add_argument("--smooth_sigma", type=float, default=0.0) + parser.add_argument("--diag_dir", default=None) + parser.add_argument("--dev", action="store_true") + args = parser.parse_args() + run_align_hand_depth( + args.input_path, args.depth_path, args.intrinsics_path, args.output_path, + mesh_intrinsics_path=args.mesh_intrinsics_path, + per_frame=args.per_frame, + per_hand=args.per_hand, + align=args.align, + smooth_sigma=args.smooth_sigma, + diag_dir=args.diag_dir, + dev=args.dev, + ) diff --git a/third-party/video_to_data/reconstruction/modules/v2d_hand_alignment/docker/run_dynhamr_to_hamer_tracks.py b/third-party/video_to_data/reconstruction/modules/v2d_hand_alignment/docker/run_dynhamr_to_hamer_tracks.py new file mode 100644 index 0000000000000000000000000000000000000000..bb8bd793183bb541db5053b2bcabcb9d9cf74a0e --- /dev/null +++ b/third-party/video_to_data/reconstruction/modules/v2d_hand_alignment/docker/run_dynhamr_to_hamer_tracks.py @@ -0,0 +1,64 @@ +# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 +from v2d.docker.container import run_in_container +from v2d.hand_alignment.docker._config import IMAGE_NAME, MODULES_DIR + + +def run_dynhamr_to_hamer_tracks( + input_npz: str, + output_dir: str, + intrinsics_path: str | None = None, + left_id: int = 2, + right_id: int = 3, + dev: bool = False, +) -> None: + """Convert DynHaMR world_results.npz → per-frame v2d_hamer-style tracks. + + Output structure: + output_dir//.json (left hand records) + output_dir//.json (right hand records) + + The per-frame JSON places each hand in DynHaMR's per-frame camera + coordinates so v2d_hamer.lib.align_hands can consume the tracks just + like real HaMeR detections — bypassing ViPE's world frame entirely. + """ + inputs: dict[str, str] = { + "input_npz": input_npz, + } + if intrinsics_path is not None: + inputs["intrinsics_path"] = intrinsics_path + run_in_container( + image=IMAGE_NAME, + module="v2d.hand_alignment.lib.dynhamr_to_hamer_tracks", + inputs=inputs, + outputs={"output_dir": output_dir}, + extra_args={ + "left_id": left_id, + "right_id": right_id, + }, + dev=dev, + modules_dir=MODULES_DIR, + gpus=False, + ) + + +if __name__ == "__main__": + import argparse + p = argparse.ArgumentParser( + description="Convert DynHaMR world_results.npz → v2d_hamer-style tracks" + ) + p.add_argument("--input_npz", required=True) + p.add_argument("--output_dir", required=True) + p.add_argument("--intrinsics_path", default=None) + p.add_argument("--left_id", type=int, default=2) + p.add_argument("--right_id", type=int, default=3) + p.add_argument("--dev", action="store_true") + args = p.parse_args() + run_dynhamr_to_hamer_tracks( + input_npz = args.input_npz, + output_dir = args.output_dir, + intrinsics_path = args.intrinsics_path, + left_id = args.left_id, + right_id = args.right_id, + dev = args.dev, + ) diff --git a/third-party/video_to_data/reconstruction/modules/v2d_hand_alignment/docker/run_recover_mano_params.py b/third-party/video_to_data/reconstruction/modules/v2d_hand_alignment/docker/run_recover_mano_params.py new file mode 100644 index 0000000000000000000000000000000000000000..c699f44f1eef49de3f126ef52e18c08e33db5b0c --- /dev/null +++ b/third-party/video_to_data/reconstruction/modules/v2d_hand_alignment/docker/run_recover_mano_params.py @@ -0,0 +1,49 @@ +# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 +from v2d.docker.container import run_in_container +from v2d.hand_alignment.docker._config import IMAGE_NAME, MODULES_DIR + + +def run_recover_mano_params( + aligned_path: str, + world_results_path: str, + hand_mesh_traj_path: str, + mano_model_dir: str, + output_path: str, + dev: bool = False, +) -> None: + run_in_container( + image=IMAGE_NAME, + module="v2d.hand_alignment.lib.recover_mano_params", + inputs={ + "aligned_path": aligned_path, + "world_results_path": world_results_path, + "hand_mesh_traj_path": hand_mesh_traj_path, + "mano_model_dir": mano_model_dir, + }, + outputs={"output_path": output_path}, + extra_args={}, + dev=dev, + modules_dir=MODULES_DIR, + gpus=False, + ) + + +if __name__ == "__main__": + import argparse + parser = argparse.ArgumentParser() + parser.add_argument("--aligned_path", required=True) + parser.add_argument("--world_results_path", required=True) + parser.add_argument("--hand_mesh_traj_path", required=True) + parser.add_argument("--mano_model_dir", required=True) + parser.add_argument("--output_path", required=True) + parser.add_argument("--dev", action="store_true") + args = parser.parse_args() + run_recover_mano_params( + args.aligned_path, + args.world_results_path, + args.hand_mesh_traj_path, + args.mano_model_dir, + args.output_path, + dev=args.dev, + ) diff --git a/third-party/video_to_data/reconstruction/modules/v2d_hand_alignment/docker/run_render_mano_params_video.py b/third-party/video_to_data/reconstruction/modules/v2d_hand_alignment/docker/run_render_mano_params_video.py new file mode 100644 index 0000000000000000000000000000000000000000..e44f523699f50b086ead1929be48edd511500980 --- /dev/null +++ b/third-party/video_to_data/reconstruction/modules/v2d_hand_alignment/docker/run_render_mano_params_video.py @@ -0,0 +1,83 @@ +# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 +from v2d.docker.container import run_in_container +from v2d.hand_alignment.docker._config import IMAGE_NAME, MODULES_DIR + + +def run_render_mano_params_video( + mano_params_path: str, + intrinsics_path: str, + mano_model_dir: str, + output_path: str, + fps: float = 25.0, + frames_folder: str | None = None, + mesh_path: str | None = None, + poses_dir: str | None = None, + panel_w: int = 388, + panel_h: int = 516, + start: int = 0, + end: int | None = None, + dev: bool = False, +) -> None: + inputs = { + "mano_params": mano_params_path, + "intrinsics": intrinsics_path, + "mano_model_dir": mano_model_dir, + } + if frames_folder is not None: + inputs["frames_folder"] = frames_folder + if mesh_path is not None: + inputs["mesh"] = mesh_path + if poses_dir is not None: + inputs["poses_dir"] = poses_dir + run_in_container( + image=IMAGE_NAME, + module="v2d.hand_alignment.lib.render_mano_params_video", + inputs=inputs, + outputs={"output": output_path}, + extra_args={ + "fps": fps, + "panel_w": panel_w, + "panel_h": panel_h, + "start": start, + "end": end, + }, + dev=dev, + modules_dir=MODULES_DIR, + gpus=False, + env={"PYOPENGL_PLATFORM": "egl"}, + ) + + +if __name__ == "__main__": + import argparse + parser = argparse.ArgumentParser() + parser.add_argument("--mano_params_path", required=True) + parser.add_argument("--intrinsics_path", required=True) + parser.add_argument("--mano_model_dir", required=True) + parser.add_argument("--output_path", required=True) + parser.add_argument("--fps", type=float, default=25.0) + parser.add_argument("--frames_folder", default=None) + parser.add_argument("--mesh_path", default=None) + parser.add_argument("--poses_dir", default=None) + parser.add_argument("--panel_w", type=int, default=388) + parser.add_argument("--panel_h", type=int, default=516) + parser.add_argument("--start", type=int, default=0) + parser.add_argument("--end", type=int, default=None) + parser.add_argument("--dev", action="store_true") + args = parser.parse_args() + run_render_mano_params_video( + mano_params_path=args.mano_params_path, + intrinsics_path=args.intrinsics_path, + mano_model_dir=args.mano_model_dir, + output_path=args.output_path, + fps=args.fps, + frames_folder=args.frames_folder, + mesh_path=args.mesh_path, + poses_dir=args.poses_dir, + panel_w=args.panel_w, + panel_h=args.panel_h, + start=args.start, + end=args.end, + dev=args.dev, + ) diff --git a/third-party/video_to_data/reconstruction/modules/v2d_hand_alignment/docker/run_render_multiview_video.py b/third-party/video_to_data/reconstruction/modules/v2d_hand_alignment/docker/run_render_multiview_video.py new file mode 100644 index 0000000000000000000000000000000000000000..9cf78d5ee1b907c883680112888a1e73ca1629ee --- /dev/null +++ b/third-party/video_to_data/reconstruction/modules/v2d_hand_alignment/docker/run_render_multiview_video.py @@ -0,0 +1,74 @@ +# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 +from v2d.docker.container import run_in_container +from v2d.hand_alignment.docker._config import IMAGE_NAME, MODULES_DIR + + +def run_render_multiview_video( + mesh_path: str, + poses_dir: str, + hand_mesh_path: str, + intrinsics_path: str, + output_path: str, + fps: float = 30.0, + panel_w: int = 388, + panel_h: int = 516, + start: int = 0, + end: int | None = None, + frames_folder: str | None = None, + dev: bool = False, +) -> None: + inputs = { + "mesh_path": mesh_path, + "poses_dir": poses_dir, + "hand_mesh_path": hand_mesh_path, + "intrinsics_path": intrinsics_path, + } + if frames_folder is not None: + inputs["frames_folder"] = frames_folder + run_in_container( + image=IMAGE_NAME, + module="v2d.hand_alignment.lib.render_multiview_video", + inputs=inputs, + outputs={"output_path": output_path}, + extra_args={ + "fps": fps, + "panel_w": panel_w, + "panel_h": panel_h, + "start": start, + "end": end, + }, + dev=dev, + modules_dir=MODULES_DIR, + gpus=False, + env={"PYOPENGL_PLATFORM": "egl"}, + ) + + +if __name__ == "__main__": + import argparse + parser = argparse.ArgumentParser() + parser.add_argument("--mesh_path", required=True) + parser.add_argument("--poses_dir", required=True) + parser.add_argument("--hand_mesh_path", required=True) + parser.add_argument("--intrinsics_path", required=True) + parser.add_argument("--output_path", required=True) + parser.add_argument("--fps", type=float, default=30.0) + parser.add_argument("--panel_w", type=int, default=388) + parser.add_argument("--panel_h", type=int, default=516) + parser.add_argument("--start", type=int, default=0) + parser.add_argument("--end", type=int, default=None) + parser.add_argument("--frames_folder", default=None) + parser.add_argument("--dev", action="store_true") + args = parser.parse_args() + run_render_multiview_video( + args.mesh_path, args.poses_dir, args.hand_mesh_path, args.intrinsics_path, + args.output_path, + fps=args.fps, + panel_w=args.panel_w, + panel_h=args.panel_h, + start=args.start, + end=args.end, + frames_folder=args.frames_folder, + dev=args.dev, + ) diff --git a/third-party/video_to_data/reconstruction/modules/v2d_hand_alignment/docker/run_reproject_hand_mesh.py b/third-party/video_to_data/reconstruction/modules/v2d_hand_alignment/docker/run_reproject_hand_mesh.py new file mode 100644 index 0000000000000000000000000000000000000000..2b83973a9ce417bc2be8c0523e45f97c26b1b71c --- /dev/null +++ b/third-party/video_to_data/reconstruction/modules/v2d_hand_alignment/docker/run_reproject_hand_mesh.py @@ -0,0 +1,69 @@ +# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 +from v2d.docker.container import run_in_container +from v2d.hand_alignment.docker._config import IMAGE_NAME, MODULES_DIR + + +def run_reproject_hand_mesh( + input_path: str, + target_intrinsics_path: str, + output_path: str, + world_results_path: str | None = None, + pose_path: str | None = None, + hand_intrinsics_path: str | None = None, + apply_world_scale: bool = False, + smooth_poses_sigma: float = 0.0, + hand_width: int | None = None, + hand_height: int | None = None, + dev: bool = False, +) -> None: + inputs = {"input_path": input_path, "target_intrinsics_path": target_intrinsics_path} + if world_results_path is not None: + inputs["world_results_path"] = world_results_path + if pose_path is not None: + inputs["pose_path"] = pose_path + if hand_intrinsics_path is not None: + inputs["hand_intrinsics_path"] = hand_intrinsics_path + run_in_container( + image=IMAGE_NAME, + module="v2d.hand_alignment.lib.reproject_hand_mesh", + inputs=inputs, + outputs={"output_path": output_path}, + extra_args={ + "apply_world_scale": apply_world_scale, + "smooth_poses_sigma": smooth_poses_sigma if smooth_poses_sigma > 0 else None, + "hand_width": hand_width, + "hand_height": hand_height, + }, + dev=dev, + modules_dir=MODULES_DIR, + gpus=False, + ) + + +if __name__ == "__main__": + import argparse + parser = argparse.ArgumentParser() + parser.add_argument("--input_path", required=True) + parser.add_argument("--target_intrinsics_path", required=True) + parser.add_argument("--output_path", required=True) + parser.add_argument("--world_results_path", default=None) + parser.add_argument("--pose_path", default=None) + parser.add_argument("--hand_intrinsics_path", default=None) + parser.add_argument("--apply_world_scale", action="store_true") + parser.add_argument("--smooth_poses_sigma", type=float, default=0.0) + parser.add_argument("--hand_width", type=int, default=None) + parser.add_argument("--hand_height", type=int, default=None) + parser.add_argument("--dev", action="store_true") + args = parser.parse_args() + run_reproject_hand_mesh( + args.input_path, args.target_intrinsics_path, args.output_path, + world_results_path=args.world_results_path, + pose_path=args.pose_path, + hand_intrinsics_path=args.hand_intrinsics_path, + apply_world_scale=args.apply_world_scale, + smooth_poses_sigma=args.smooth_poses_sigma, + hand_width=args.hand_width, + hand_height=args.hand_height, + dev=args.dev, + ) diff --git a/third-party/video_to_data/reconstruction/modules/v2d_hand_alignment/docker/run_smooth_hand_mesh.py b/third-party/video_to_data/reconstruction/modules/v2d_hand_alignment/docker/run_smooth_hand_mesh.py new file mode 100644 index 0000000000000000000000000000000000000000..16c618f37354a71b818d2782d4360839da2adb72 --- /dev/null +++ b/third-party/video_to_data/reconstruction/modules/v2d_hand_alignment/docker/run_smooth_hand_mesh.py @@ -0,0 +1,37 @@ +# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 +from v2d.docker.container import run_in_container +from v2d.hand_alignment.docker._config import IMAGE_NAME, MODULES_DIR + + +def run_smooth_hand_mesh( + input_path: str, + output_path: str, + sigma: float = 5.0, + dev: bool = False, +) -> None: + run_in_container( + image=IMAGE_NAME, + module="v2d.hand_alignment.lib.smooth_hand_mesh", + inputs={"input_path": input_path}, + outputs={"output_path": output_path}, + extra_args={"sigma": sigma}, + dev=dev, + modules_dir=MODULES_DIR, + gpus=False, + ) + + +if __name__ == "__main__": + import argparse + parser = argparse.ArgumentParser() + parser.add_argument("--input_path", required=True) + parser.add_argument("--output_path", required=True) + parser.add_argument("--sigma", type=float, default=5.0) + parser.add_argument("--dev", action="store_true") + args = parser.parse_args() + run_smooth_hand_mesh( + args.input_path, args.output_path, + sigma=args.sigma, + dev=args.dev, + ) diff --git a/third-party/video_to_data/reconstruction/modules/v2d_hand_alignment/lib/__init__.py b/third-party/video_to_data/reconstruction/modules/v2d_hand_alignment/lib/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..52a7a9daf028f654d6a02f65c99cc609a57b492f --- /dev/null +++ b/third-party/video_to_data/reconstruction/modules/v2d_hand_alignment/lib/__init__.py @@ -0,0 +1,2 @@ +# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 diff --git a/third-party/video_to_data/reconstruction/modules/v2d_hand_alignment/lib/align_hand_depth.py b/third-party/video_to_data/reconstruction/modules/v2d_hand_alignment/lib/align_hand_depth.py new file mode 100644 index 0000000000000000000000000000000000000000..edb0a3beaed02ff762f8f2f3b1dd39e5c90fb983 --- /dev/null +++ b/third-party/video_to_data/reconstruction/modules/v2d_hand_alignment/lib/align_hand_depth.py @@ -0,0 +1,480 @@ +# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 +""" +Align hand mesh depth to MoGe depth by estimating a z-scale factor. + +For each frame with visible hands: + 1. Rasterize the hand mesh into a z-buffer (rendered hand depth) + 2. At pixels covered by the hand mesh, sample the MoGe depth + 3. Compute ratio: moge_z / hand_z → robust median gives the scale + +A global scale is estimated (median over all frames × hands) and applied to +all vert/joint z values. Use --per_frame to apply a per-frame scale instead. + +Usage: + python -m v2d.hand_alignment.lib.align_hand_depth \\ + --input data/.../hand/hand_mesh/airplane_hand_mesh_traj_000300_aligned.npz \\ + --depth data/.../outputs/depth_moge \\ + --intrinsics data/.../outputs/intrinsics_moge_stable.json \\ + --output data/.../hand/hand_mesh/airplane_hand_mesh_traj_000300_depth_aligned.npz + + # Diagnostic: save per-frame overlay images + python -m v2d.hand_alignment.lib.align_hand_depth ... --diag_dir /tmp/hand_depth_diag + + # Per-frame scale instead of global: + python -m v2d.hand_alignment.lib.align_hand_depth ... --per_frame + + # Per-frame per-hand scale (each hand aligned independently each frame): + python -m v2d.hand_alignment.lib.align_hand_depth ... --per_hand +""" + +import argparse +import glob +import json +import os + +import numpy as np +from scipy.ndimage import gaussian_filter1d + + +# --------------------------------------------------------------------------- +# Depth utilities +# --------------------------------------------------------------------------- + +def load_moge_depth(path: str) -> np.ndarray: + """Load uint16/int32 depth PNG → float64 metres. + Encoding: pixel = 65535 * 1/(depth_m + 1) → depth_m = 65535/pixel - 1 + """ + from PIL import Image + px = np.array(Image.open(path)).astype(np.float64) + with np.errstate(divide='ignore', invalid='ignore'): + depth = np.where(px > 0, 65535.0 / px - 1.0, np.nan) + return depth + + +def load_intrinsics(path: str) -> dict: + with open(path) as f: + return json.load(f) + + +# --------------------------------------------------------------------------- +# Z-buffer rasterizer +# --------------------------------------------------------------------------- + +def render_zbuffer( + verts_cam: np.ndarray, + faces: np.ndarray, + width: int, + height: int, + fx: float, fy: float, cx: float, cy: float, +) -> np.ndarray: + """ + Rasterize hand mesh triangles into a z-buffer. + + Args: + verts_cam: (N, 3) vertices in camera space (metres) + faces: (F, 3) integer face indices + width/height: image dimensions + fx/fy/cx/cy: camera intrinsics + + Returns: + (H, W) float64 array — depth in metres, nan where no mesh. + """ + z_buf = np.full((height, width), np.inf) + + z = verts_cam[:, 2].astype(np.float64) + safe_z = np.where(z > 1e-4, z, 1e-4) + pu = (verts_cam[:, 0] * fx / safe_z + cx).astype(np.float64) + pv = (verts_cam[:, 1] * fy / safe_z + cy).astype(np.float64) + + for tri in faces: + ia, ib, ic = int(tri[0]), int(tri[1]), int(tri[2]) + za, zb, zc = z[ia], z[ib], z[ic] + if za <= 0 or zb <= 0 or zc <= 0: + continue + + ax, ay = pu[ia], pv[ia] + bx, by = pu[ib], pv[ib] + dx, dy = pu[ic], pv[ic] # 'd' to avoid shadowing 'cx' + + x0 = max(0, int(np.floor(min(ax, bx, dx)))) + x1 = min(width, int(np.ceil( max(ax, bx, dx))) + 1) + y0 = max(0, int(np.floor(min(ay, by, dy)))) + y1 = min(height, int(np.ceil( max(ay, by, dy))) + 1) + + if x0 >= x1 or y0 >= y1: + continue + + # Pixel centres + xs = np.arange(x0, x1) + 0.5 + ys = np.arange(y0, y1) + 0.5 + gx, gy = np.meshgrid(xs, ys) # (rows, cols) + + # Barycentric weights w.r.t. A=a, B=b, C=d + v0x, v0y = bx - ax, by - ay # edge A→B + v1x, v1y = dx - ax, dy - ay # edge A→C + v2x = gx - ax + v2y = gy - ay + + d00 = v0x*v0x + v0y*v0y + d01 = v0x*v1x + v0y*v1y + d11 = v1x*v1x + v1y*v1y + d20 = v2x*v0x + v2y*v0y + d21 = v2x*v1x + v2y*v1y + + denom = d00*d11 - d01*d01 + if abs(denom) < 1e-10: + continue + + wb = (d11*d20 - d01*d21) / denom # weight for B + wc = (d00*d21 - d01*d20) / denom # weight for C + wa = 1.0 - wb - wc + + inside = (wa >= 0) & (wb >= 0) & (wc >= 0) + zinterp = wa*za + wb*zb + wc*zc + + patch = z_buf[y0:y1, x0:x1] + update = inside & (zinterp < patch) + patch[update] = zinterp[update] + z_buf[y0:y1, x0:x1] = patch + + return np.where(np.isfinite(z_buf), z_buf, np.nan) + + +# --------------------------------------------------------------------------- +# Alignment estimation +# --------------------------------------------------------------------------- + +def estimate_scale(hand_depth: np.ndarray, moge_depth: np.ndarray) -> tuple[float | None, int]: + """ + Estimate scale s such that s * hand_depth ≈ moge_depth. + Returns (median_ratio, n_inliers). + """ + mask = ( + np.isfinite(hand_depth) & (hand_depth > 0.01) & + np.isfinite(moge_depth) & (moge_depth > 0.01) + ) + n = int(mask.sum()) + if n < 20: + return None, n + + ratios = moge_depth[mask] / hand_depth[mask] + + # RANSAC-lite: keep ratios within 2× of the median + med = np.median(ratios) + inliers = np.abs(ratios - med) < 0.5 * med + if inliers.sum() < 10: + return float(med), n + + return float(np.median(ratios[inliers])), int(inliers.sum()) + + +def estimate_offset(hand_depth: np.ndarray, moge_depth: np.ndarray) -> tuple[float | None, int]: + """ + Estimate offset d such that hand_depth + d ≈ moge_depth. + Returns (median_diff, n_inliers). + """ + mask = ( + np.isfinite(hand_depth) & (hand_depth > 0.01) & + np.isfinite(moge_depth) & (moge_depth > 0.01) + ) + n = int(mask.sum()) + if n < 20: + return None, n + + diffs = moge_depth[mask] - hand_depth[mask] + + # RANSAC-lite: keep diffs within 0.5m of the median + med = np.median(diffs) + inliers = np.abs(diffs - med) < 0.5 + if inliers.sum() < 10: + return float(med), n + + return float(np.median(diffs[inliers])), int(inliers.sum()) + + +# --------------------------------------------------------------------------- +# Diagnostics +# --------------------------------------------------------------------------- + +def save_diag( + frame_id: int, + frames_folder: str | None, + hand_depth: np.ndarray, + moge_depth: np.ndarray, + scale_before: float, + scale_after: float, + diag_dir: str, +): + """Save side-by-side depth comparison image.""" + from PIL import Image, ImageDraw + + def depth_to_rgb(d: np.ndarray) -> np.ndarray: + valid = np.isfinite(d) & (d > 0) + out = np.zeros((*d.shape, 3), dtype=np.uint8) + if valid.any(): + lo, hi = d[valid].min(), d[valid].max() + norm = np.clip((d - lo) / max(hi - lo, 1e-6), 0, 1) + t = (norm * 255).astype(np.uint8) + out[..., 0] = np.where(valid, t, 0) + out[..., 2] = np.where(valid, 255 - t, 0) + return out + + hand_rgb = depth_to_rgb(hand_depth) + hand_sc = depth_to_rgb(hand_depth * scale_after) + moge_rgb = depth_to_rgb(moge_depth) + + # Mask overlay: where both are valid + mask = np.isfinite(hand_depth) & (hand_depth > 0) & np.isfinite(moge_depth) & (moge_depth > 0) + diff_before = np.abs(hand_depth * scale_before - moge_depth) + diff_after = np.abs(hand_depth * scale_after - moge_depth) + + H, W = hand_depth.shape + panel_w = W * 3 + canvas = np.zeros((H, panel_w, 3), dtype=np.uint8) + canvas[:, :W] = moge_rgb + canvas[:, W:2*W] = hand_rgb + canvas[:, 2*W:] = hand_sc + + img = Image.fromarray(canvas) + draw = ImageDraw.Draw(img) + draw.text((5, 5), f"MoGe depth", fill=(255,255,255)) + draw.text((W+5, 5), f"hand depth (raw, scale={scale_before:.3f})", fill=(255,255,255)) + draw.text((2*W+5, 5), f"hand depth (×{scale_after:.3f})", fill=(255,255,255)) + + if mask.any(): + me_before = float(np.median(diff_before[mask])) + me_after = float(np.median(diff_after[mask])) + draw.text((5, 20), f"median |err| before={me_before:.4f}m after={me_after:.4f}m", fill=(255,255,0)) + + os.makedirs(diag_dir, exist_ok=True) + img.save(os.path.join(diag_dir, f"depth_align_{frame_id:06d}.jpg")) + + +# --------------------------------------------------------------------------- +# Core implementation +# --------------------------------------------------------------------------- + +def align_hand_depth( + input_path: str, + depth_path: str, + intrinsics_path: str, + output_path: str, + mesh_intrinsics_path: str | None = None, + per_frame: bool = False, + per_hand: bool = False, + align: str = 'scale', + smooth_sigma: float = 0.0, + diag_dir: str | None = None, +) -> None: + """Align hand mesh depth to scene depth by estimating a z-scale or z-offset.""" + intr = load_intrinsics(intrinsics_path) + width = intr.get('width', 776) + height = intr.get('height', 1032) + + mesh_intr = load_intrinsics(mesh_intrinsics_path) if mesh_intrinsics_path else intr + fx, fy = mesh_intr['fx'], mesh_intr['fy'] + cx, cy = mesh_intr['cx'], mesh_intr['cy'] + if mesh_intrinsics_path: + print(f"Rasterizing with mesh intrinsics: fx={fx:.2f} fy={fy:.2f} cx={cx:.2f} cy={cy:.2f}") + print(f"Comparing against depth intrinsics: fx={intr['fx']:.2f} fy={intr['fy']:.2f}") + + mesh_data = np.load(input_path, allow_pickle=True) + verts = mesh_data['verts'].copy() # (n_hands, n_frames, n_verts, 3) + joints = mesh_data['joints'].copy() # (n_hands, n_frames, n_joints, 3) + faces_r = mesh_data['faces_right'] + faces_l = mesh_data['faces_left'] + is_right = mesh_data['is_right'] # (n_hands, n_frames) + vis_mask = mesh_data.get('vis_mask', np.ones(is_right.shape)) + + n_hands, n_frames = verts.shape[:2] + + depth_files = sorted(glob.glob(os.path.join(depth_path, '*.png'))) + if len(depth_files) != n_frames: + print(f"Warning: {len(depth_files)} depth files but {n_frames} hand frames") + + diag_frames = None + if diag_dir: + diag_frames = sorted({0, n_frames//4, n_frames//2, 3*n_frames//4, n_frames-1}) + + use_offset = (align == 'offset') + print(f"Alignment mode: {'offset (additive)' if use_offset else 'scale (multiplicative)'}") + + # ------------------------------------------------------------------ + # Pass 1: collect per-frame and per-hand alignment estimates + # ------------------------------------------------------------------ + per_frame_scales = [] # list of (frame_id, value) — median across hands + per_hand_frame_scales = {} # (fid, h) -> value + per_hand_all_scales = [[] for _ in range(n_hands)] # h -> [values across frames] + + for fid in range(min(n_frames, len(depth_files))): + moge_depth = load_moge_depth(depth_files[fid]) + frame_vals = [] + + for h in range(n_hands): + if vis_mask[h, fid] < 0.5: + continue + + v_cam = verts[h, fid].astype(np.float64) # (N, 3) + faces = faces_r if is_right[h, fid] > 0.5 else faces_l + + zb = render_zbuffer(v_cam, faces, width, height, fx, fy, cx, cy) + + if use_offset: + val, n_in = estimate_offset(zb, moge_depth) + valid = val is not None and -5.0 < val < 5.0 + else: + val, n_in = estimate_scale(zb, moge_depth) + valid = val is not None and 0.1 < val < 10.0 + + if valid: + frame_vals.append(val) + per_hand_frame_scales[(fid, h)] = val + per_hand_all_scales[h].append(val) + + if diag_dir and diag_frames and fid in diag_frames: + diag_scale = (1.0 + val / zb[np.isfinite(zb)].mean()) if use_offset else val + save_diag(fid, None, zb, moge_depth, 1.0, diag_scale, diag_dir) + + if frame_vals: + per_frame_scales.append((fid, float(np.median(frame_vals)))) + + if fid % 50 == 0 and per_frame_scales: + last = per_frame_scales[-1][1] if per_frame_scales else float('nan') + label = 'offset' if use_offset else 'scale' + print(f" frame {fid:4d} {label}={last:.4f} ({len(per_frame_scales)} frames collected)") + + if not per_frame_scales: + print("ERROR: no valid frames found — check input files and visibility mask") + return + + all_scales = [s for _, s in per_frame_scales] + global_scale = float(np.median(all_scales)) + print(f"\nPer-frame scale stats: median={global_scale:.4f} " + f"std={np.std(all_scales):.4f} " + f"min={min(all_scales):.4f} max={max(all_scales):.4f} " + f"n_frames={len(all_scales)}") + + # Per-hand global fallback (median of per-hand observations) + per_hand_global = {} + for h in range(n_hands): + if per_hand_all_scales[h]: + per_hand_global[h] = float(np.median(per_hand_all_scales[h])) + print(f" hand {h}: global median scale={per_hand_global[h]:.4f} " + f"n_frames={len(per_hand_all_scales[h])}") + + # ------------------------------------------------------------------ + # Optional: temporally smooth per-frame per-hand estimates + # ------------------------------------------------------------------ + if smooth_sigma > 0 and per_hand: + print(f"\nSmoothing per-frame per-hand offsets with sigma={smooth_sigma} frames...") + for h in range(n_hands): + fallback = per_hand_global.get(h, global_scale) + raw = np.array([ + per_hand_frame_scales.get((fid, h), fallback) + for fid in range(n_frames) + ]) + smoothed = gaussian_filter1d(raw, sigma=smooth_sigma) + for fid in range(n_frames): + per_hand_frame_scales[(fid, h)] = float(smoothed[fid]) + print(f" hand {h}: raw std={raw.std():.4f} smoothed std={smoothed.std():.4f}") + + # ------------------------------------------------------------------ + # Pass 2: apply alignment + # ------------------------------------------------------------------ + def _apply(v: np.ndarray, j: np.ndarray, val: float) -> None: + """Apply alignment value to verts/joints arrays (both shape (..., 3)).""" + if use_offset: + centroid = v.mean(axis=0) # (3,) + z_c = centroid[2] + if abs(z_c) < 1e-6: + return + delta = centroid * (val / z_c) # translate along centroid ray + v += delta + j += delta + else: + v *= val + j *= val + + if per_hand: + mode = 'offset' if use_offset else 'scale' + print(f"Applying per-frame per-hand {mode} (ray-preserving)...") + for fid in range(n_frames): + for h in range(n_hands): + val = per_hand_frame_scales.get( + (fid, h), + per_hand_global.get(h, global_scale), + ) + _apply(verts[h, fid], joints[h, fid], val) + elif per_frame: + mode = 'offset' if use_offset else 'scale' + print(f"Applying per-frame {mode} (ray-preserving)...") + scale_lookup = dict(per_frame_scales) + for fid in range(n_frames): + val = scale_lookup.get(fid, global_scale) + for h in range(n_hands): + _apply(verts[h, fid], joints[h, fid], val) + else: + mode = 'offset' if use_offset else 'scale' + print(f"Applying global {mode} {global_scale:.4f} to all frames (ray-preserving)...") + for fid in range(n_frames): + for h in range(n_hands): + _apply(verts[h, fid], joints[h, fid], global_scale) + + # ------------------------------------------------------------------ + # Save + # ------------------------------------------------------------------ + out = dict(mesh_data) + out['verts'] = verts.astype(np.float32) + out['joints'] = joints.astype(np.float32) + np.savez(output_path, **out) + print(f"Saved → {output_path}") + + # Sample vert before/after + h, f = 0, 0 + before = mesh_data['verts'][h, f, 0] + after = verts[h, f, 0] + print(f"\nSample vert [hand=0, frame=0, vert=0]:") + print(f" before: x={before[0]:.4f} y={before[1]:.4f} z={before[2]:.4f}m") + print(f" after: x={after[0]:.4f} y={after[1]:.4f} z={after[2]:.4f}m (×{global_scale:.4f})") + + +def main(): + parser = argparse.ArgumentParser(description="Align hand mesh depth to MoGe depth") + parser.add_argument('--input_path', required=True, help='Aligned hand mesh NPZ (camera-space verts)') + parser.add_argument('--depth_path', required=True, help='Folder of MoGe depth PNGs (000000.png, ...)') + parser.add_argument('--intrinsics_path', required=True, help='Target intrinsics JSON (depth image space)') + parser.add_argument('--mesh_intrinsics_path', default=None, + help='Intrinsics the hand mesh was aligned with (for rasterization). ' + 'Defaults to --intrinsics_path. Use when hand mesh was not reprojected to target.') + parser.add_argument('--output_path', required=True, help='Output NPZ path') + parser.add_argument('--per_frame', action='store_true', + help='Apply per-frame scale instead of a single global scale') + parser.add_argument('--per_hand', action='store_true', + help='Apply per-frame per-hand scale (each hand aligned independently each frame)') + parser.add_argument('--align', choices=['scale', 'offset'], default='scale', + help='Alignment mode: "scale" (multiplicative, s*z≈z_moge) or ' + '"offset" (additive, z+d≈z_moge, rigid ray translation). Default: scale') + parser.add_argument('--smooth_sigma', type=float, default=0.0, + help='Gaussian sigma (frames) for temporal smoothing of per-frame offsets/scales ' + 'before applying them.') + parser.add_argument('--diag_dir', default=None, + help='If set, save depth comparison images here') + args = parser.parse_args() + + align_hand_depth( + input_path=args.input_path, + depth_path=args.depth_path, + intrinsics_path=args.intrinsics_path, + output_path=args.output_path, + mesh_intrinsics_path=args.mesh_intrinsics_path, + per_frame=args.per_frame, + per_hand=args.per_hand, + align=args.align, + smooth_sigma=args.smooth_sigma, + diag_dir=args.diag_dir, + ) + + +if __name__ == '__main__': + main() diff --git a/third-party/video_to_data/reconstruction/modules/v2d_hand_alignment/lib/dynhamr_to_hamer_tracks.py b/third-party/video_to_data/reconstruction/modules/v2d_hand_alignment/lib/dynhamr_to_hamer_tracks.py new file mode 100644 index 0000000000000000000000000000000000000000..ba5dc486a3451e7b102b402d03331d1ee68d6a54 --- /dev/null +++ b/third-party/video_to_data/reconstruction/modules/v2d_hand_alignment/lib/dynhamr_to_hamer_tracks.py @@ -0,0 +1,271 @@ +# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 +"""Convert a DynHaMR ``world_results.npz`` to per-frame v2d_hamer-style tracks. + +Each frame's hand state is re-expressed in DynHaMR's *per-frame camera* +coordinates, so the output mirrors what a real HaMeR detection looks like +on disk. This lets ``v2d_hamer.lib.align_hands`` consume the tracks as-is +— no world / camera-pose interaction, no global SLAM, just per-frame +cam-frame hand detections that the proven HaMeR alignment can refine. + +Conceptually: we drop everything DynHaMR estimated about the world (and +about ViPE's noisy intrinsics-vs-pose entanglement) and keep only the +per-frame hand pose in cam frame. Whatever ViPE got right is preserved +(image-stability — DynHaMR's joint optimization keeps the hand anchored to +its pixels under ViPE intrins). Whatever ViPE got wrong (focal length, +camera-pose noise) is *fully absorbed* by the per-frame cam-frame +representation, which has no notion of world or inter-frame extrinsics. + +Schema produced (matches HaMeR pre-alignment, what ``v2d_hamer.align_hands`` +expects): + + //.json + { + "track_id": int, # e.g. 2=left, 3=right + "is_right": bool, + "frame_idx": int, + "image_size": [W, H], + "camera": { + "scaled_focal_length": float, # = fx_vipe; align_hands rescales to fx_real + "pred_cam_t_full": [x,y,z] # cam-frame translation in DynHaMR units + }, + "mano": { + "betas": [10], + "global_orient": [3], # axis-angle, in DynHaMR cam frame + "hand_pose": [45] + } + } + +Math +---- +Per (hand h, frame t): + Let M = diag(-1, 1, 1) for left, I for right (DynHaMR convention). + + R_root_cam = M · cam_R · M · R(root_orient_world) # = cam_R·R for right + global_aa = axis_angle(R_root_cam) + cam_t_cam = cam_R · (M · trans) + cam_t # = cam_R·trans+cam_t for right + +Verification (per-vertex projection equality): + v_world_dynhamr = M · (verts_local_mano + trans) # mirror after add for left + v_cam_dynhamr = cam_R · v_world_dynhamr + cam_t + = cam_R · M · verts_local + cam_R · M · trans + cam_t + = (cam_R·M·verts_local) + cam_t_cam + + v_cam_hamer = M · verts_local_hamer + cam_t_hamer # v2d_hamer left convention + = M · R(global_aa) · root_relative + cam_t_hamer + = M · (M·cam_R·M·R_root_world) · root_relative + cam_t_cam + = cam_R · M · R_root_world · root_relative + cam_t_cam + = cam_R · M · verts_local + cam_t_cam ✓ + +So projecting v_cam_hamer through the same intrinsics gives the same pixel +the unaligned DynHaMR render produces — image-stable by construction. + +Usage +----- + python -m v2d.hand_alignment.lib.dynhamr_to_hamer_tracks \\ + --input_npz /data/.../world_results.npz \\ + --output_dir /data/.../dynhamr_as_hamer_tracks \\ + [--intrinsics_path /data/.../intrinsics_stable.json] +""" +from __future__ import annotations + +import argparse +import json +import os +from typing import Optional + +import numpy as np + + +# --------------------------------------------------------------------------- +# Rotation helpers (axis-angle ↔ rotmat) +# --------------------------------------------------------------------------- + +def _axis_angle_to_rotmat(aa: np.ndarray) -> np.ndarray: + """(3,) axis-angle → (3, 3) rotation matrix via Rodrigues' formula. + + Handles the small-angle case with a Taylor expansion of (1 − cos θ)/θ² + so the result is smooth as ||aa|| → 0. + """ + aa = np.asarray(aa, dtype=np.float64) + theta = float(np.linalg.norm(aa)) + if theta < 1e-12: + return np.eye(3) + k = aa / theta + K = np.array([[0, -k[2], k[1]], + [k[2], 0, -k[0]], + [-k[1], k[0], 0]], dtype=np.float64) + s, c = np.sin(theta), np.cos(theta) + return np.eye(3) + s * K + (1.0 - c) * (K @ K) + + +def _rotmat_to_axis_angle(R: np.ndarray) -> np.ndarray: + """(3, 3) → (3,) axis-angle. Canonical |θ| ≤ π.""" + R = np.asarray(R, dtype=np.float64) + tr = R[0, 0] + R[1, 1] + R[2, 2] + cos_theta = np.clip((tr - 1.0) / 2.0, -1.0, 1.0) + theta = float(np.arccos(cos_theta)) + if theta < 1e-8: + # Near identity: axis is undefined; small-angle approximation gives + # aa ≈ (R − R.T)/2 vee-mapped. + return np.array([R[2, 1] - R[1, 2], + R[0, 2] - R[2, 0], + R[1, 0] - R[0, 1]], dtype=np.float64) * 0.5 + if theta > np.pi - 1e-6: + # Near π: (R − R.T) → 0, so recover axis from diagonal of (R + I)/2. + diag = np.array([R[0, 0], R[1, 1], R[2, 2]]) + i = int(np.argmax(diag)) + axis = np.sqrt(np.clip((diag + 1.0) / 2.0, 0.0, None)) + # Fix signs from off-diagonal: axis[j] = (R[i,j] + R[j,i]) / (4 axis[i]) + if axis[i] > 1e-8: + for j in range(3): + if j == i: + continue + axis[j] = (R[i, j] + R[j, i]) / (4.0 * axis[i]) + if axis[j] < 0: + axis[j] = -axis[j] + # Sign of axis[i] from R[i, i]. + # (Both ±axis represent the same rotation when θ = π, so pick + arbitrarily.) + return axis * theta + sin_theta = float(np.sin(theta)) + axis = np.array([R[2, 1] - R[1, 2], + R[0, 2] - R[2, 0], + R[1, 0] - R[0, 1]], dtype=np.float64) / (2.0 * sin_theta) + return axis * theta + + +# --------------------------------------------------------------------------- +# Conversion +# --------------------------------------------------------------------------- + +_M_MIRROR = np.diag([-1.0, 1.0, 1.0]) + + +def convert_dynhamr_to_hamer_tracks( + input_npz: str, + output_dir: str, + intrinsics_path: Optional[str] = None, + image_size: Optional[tuple[int, int]] = None, + left_id: int = 2, + right_id: int = 3, +) -> None: + """Write per-frame v2d_hamer-style JSON records into ``output_dir``. + + ``intrinsics_path`` is only used to override (W, H); intrinsic + conversion happens later inside ``align_hands`` (which reads its own + ``--intrinsics_path``). When ``intrinsics_path`` is omitted, (W, H) is + inferred from ViPE's ``cx, cy`` assuming a center-aligned principal + point. + """ + wr = np.load(input_npz, allow_pickle=True) + + trans = wr["trans"].astype(np.float64) # (B, T, 3) + root_orient = wr["root_orient"].astype(np.float64) # (B, T, 3) + pose_body = wr["pose_body"].astype(np.float64) # (B, T, 15, 3) + betas = wr["betas"].astype(np.float64) # (B, 10) + cam_R = wr["cam_R"].astype(np.float64) # (B, T, 3, 3) + cam_t = wr["cam_t"].astype(np.float64) # (B, T, 3) + is_right = wr["is_right"] # (B, T) + intrins_v = wr["intrins"].astype(np.float64) # (4,) + + B, T = trans.shape[:2] + is_right_track = is_right.mean(axis=1) > 0.5 # (B,) + + fx_vipe = float(intrins_v[0]) + if image_size is None: + if intrinsics_path is not None: + with open(intrinsics_path) as f: + k = json.load(f) + image_size = (int(k["width"]), int(k["height"])) + else: + # Fall back to 2·cx, 2·cy from ViPE (assumes center-aligned). + image_size = (int(round(2 * float(intrins_v[2]))), + int(round(2 * float(intrins_v[3])))) + W, H = image_size + + print(f"Converting DynHaMR npz → HaMeR-style tracks:") + print(f" hands: {B} frames: {T} image: {W}×{H}") + print(f" scaled_focal_length = fx_vipe = {fx_vipe:.1f}") + print(f" hand IDs: left={left_id} right={right_id}") + + os.makedirs(output_dir, exist_ok=True) + n_written = 0 + for h in range(B): + is_r = bool(is_right_track[h]) + track_id = right_id if is_r else left_id + track_dir = os.path.join(output_dir, str(track_id)) + os.makedirs(track_dir, exist_ok=True) + + M = np.eye(3) if is_r else _M_MIRROR + b_list = betas[h].tolist() + + for f in range(T): + R_root_world = _axis_angle_to_rotmat(root_orient[h, f]) + # Right: cam_R · R_world. Left: M · cam_R · M · R_world. + R_root_cam = M @ cam_R[h, f] @ M @ R_root_world + aa_cam = _rotmat_to_axis_angle(R_root_cam) + + # cam_t in DynHaMR cam frame. + # right: cam_R · trans + cam_t + # left: cam_R · (M · trans) + cam_t + cam_t_cam = cam_R[h, f] @ (M @ trans[h, f]) + cam_t[h, f] + + rec = { + "track_id": int(track_id), + "is_right": is_r, + "frame_idx": int(f), + "image_size": [int(W), int(H)], + "camera": { + "scaled_focal_length": fx_vipe, + "pred_cam_t_full": cam_t_cam.tolist(), + }, + "mano": { + "betas": list(b_list), + "global_orient": aa_cam.tolist(), + "hand_pose": pose_body[h, f].reshape(-1).tolist(), + }, + } + out_path = os.path.join(track_dir, f"{f:06d}.json") + with open(out_path, "w") as fp: + json.dump(rec, fp, indent=2) + n_written += 1 + + side = "right" if is_r else "left" + print(f" track {track_id} ({side}): wrote {T} frames → {track_dir}") + + print(f"Total {n_written} records → {output_dir}/") + + +# --------------------------------------------------------------------------- +# CLI +# --------------------------------------------------------------------------- + +def main() -> None: + p = argparse.ArgumentParser(description=__doc__, + formatter_class=argparse.RawDescriptionHelpFormatter) + p.add_argument("--input_npz", required=True, + help="Path to DynHaMR world_results.npz") + p.add_argument("--output_dir", required=True, + help="Output root; per-track subdirs are created inside") + p.add_argument("--intrinsics_path", default=None, + help="JSON with width/height — only used to set image_size. " + "Per-frame intrinsics rescaling happens later in " + "align_hands. If omitted, (W, H) is inferred from " + "ViPE's (cx, cy).") + p.add_argument("--left_id", type=int, default=2, + help="Track-id subdir for the left hand (default 2, " + "matching SAM2 mask convention).") + p.add_argument("--right_id", type=int, default=3, + help="Track-id subdir for the right hand (default 3).") + args = p.parse_args() + convert_dynhamr_to_hamer_tracks( + input_npz = args.input_npz, + output_dir = args.output_dir, + intrinsics_path = args.intrinsics_path, + left_id = args.left_id, + right_id = args.right_id, + ) + + +if __name__ == "__main__": + main() diff --git a/third-party/video_to_data/reconstruction/modules/v2d_hand_alignment/lib/hand_object_alignment.py b/third-party/video_to_data/reconstruction/modules/v2d_hand_alignment/lib/hand_object_alignment.py new file mode 100644 index 0000000000000000000000000000000000000000..2c5f906589f3125b22e22e2bd1527eb81a27059f --- /dev/null +++ b/third-party/video_to_data/reconstruction/modules/v2d_hand_alignment/lib/hand_object_alignment.py @@ -0,0 +1,261 @@ +# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 +""" +HandObjectAlignment — align DynHaMR hand parameters to monocular depth via pyrender. + +Extracted from experiments/mano.ipynb. Pre-computes MANO FK for all frames in +__init__, then exposes compute_offset(side, t) which renders the hand mesh and +returns the camera-space [dx, dy, dz] shift needed to align it to the depth image. +""" + +from __future__ import annotations + +import json +import os + +import numpy as np +import PIL.Image +import pyrender +import torch +import trimesh +from manotorch.manolayer import ManoLayer + + +os.environ.setdefault('PYOPENGL_PLATFORM', 'egl') + +_CV_TO_GL = np.array([ + [1, 0, 0, 0], + [0, -1, 0, 0], + [0, 0, -1, 0], + [0, 0, 0, 1], +], dtype=np.float64) + + +class HandObjectAlignment: + """ + Args: + pose_data_path: Path to DynHaMR world_results.npz. + depth_folder: Folder of depth PNGs (000000.png, …). + depth_intrinsics_path: JSON with {fx, fy, cx, cy, width, height}. + mano_assets_root: Root dir passed to ManoLayer (expects models/ subdir). + occlusion_mask_folder: Per-frame mask PNGs; masked pixels excluded from + depth comparison. None → no exclusion. + image_folder: RGB frames folder (optional; only needed for + visualisation helpers). + """ + + def __init__( + self, + pose_data_path: str, + depth_folder: str, + depth_intrinsics_path: str, + mano_assets_root: str, + occlusion_mask_folder: str | None = None, + image_folder: str | None = None, + ) -> None: + self.pose_data = np.load(pose_data_path, allow_pickle=True) + + self.mano_layer = ManoLayer( + rot_mode="axisang", + use_pca=False, + side="right", + center_idx=None, + mano_assets_root=mano_assets_root, + ) + + self.depth_folder = depth_folder + self.depth_intrinsics_path = depth_intrinsics_path + self.occlusion_mask_folder = occlusion_mask_folder + self.image_folder = image_folder + + self.left_verts_world, self.left_verts_cam, self.left_faces = self._compute_hand(0) + self.right_verts_world, self.right_verts_cam, self.right_faces = self._compute_hand(1) + self.left_verts_2d = self.render_verts_2d(0, self.pose_data['intrins']) + self.right_verts_2d = self.render_verts_2d(1, self.pose_data['intrins']) + + # ------------------------------------------------------------------ + # Hand FK + # ------------------------------------------------------------------ + + def _compute_hand(self, side: int): + """Run MANO FK for all frames. Returns (verts_world, verts_cam, faces).""" + pose_data = self.pose_data + root_pose = pose_data['root_orient'][side] # (T, 3) + finger_pose = pose_data['pose_body'][side].reshape( + pose_data['pose_body'].shape[1], -1) # (T, 45) + hand_pose = torch.from_numpy(np.concatenate([root_pose, finger_pose], axis=1)) + hand_betas = torch.from_numpy(pose_data['betas'][side])[None, :].repeat( + hand_pose.shape[0], 1) + + mano_output = self.mano_layer(hand_pose, hand_betas) + + verts_world = (torch.from_numpy(pose_data['trans'][side][:, None, :]) + + mano_output.verts) # (T, 778, 3) + + if side == 0: # left hand — flip x, reverse face winding + verts_world[..., 0] = -verts_world[..., 0] + faces = self.mano_layer.th_faces[:, [0, 2, 1]] + else: + faces = self.mano_layer.th_faces + + cam_R = torch.from_numpy(pose_data['cam_R'][side]) # (T, 3, 3) + cam_t = torch.from_numpy(pose_data['cam_t'][side]) # (T, 3) + verts_cam = (torch.bmm(cam_R, verts_world.transpose(1, 2)).transpose(1, 2) + + cam_t[:, None, :]) # (T, 778, 3) + + return verts_world, verts_cam, faces + + # ------------------------------------------------------------------ + # Data loaders + # ------------------------------------------------------------------ + + def get_depth_image(self, t: int) -> np.ndarray: + """Load depth PNG → float32 metres (encoding: px = 65535/(depth+1)).""" + px = np.array(PIL.Image.open( + os.path.join(self.depth_folder, f"{t:06d}.png"))).astype(np.float32) + return 1.0 / (px / 65535.0) - 1.0 + + def get_depth_intrinsics(self) -> np.ndarray: + """Return [fx, fy, cx, cy] from the depth intrinsics JSON.""" + with open(self.depth_intrinsics_path) as f: + d = json.load(f) + return np.array([d["fx"], d["fy"], d["cx"], d["cy"]], dtype=np.float64) + + def get_image(self, t: int) -> PIL.Image.Image: + if self.image_folder is None: + raise RuntimeError("image_folder not provided") + return PIL.Image.open(os.path.join(self.image_folder, f"{t:06d}.png")) + + def get_occlusion_mask(self, t: int) -> np.ndarray | None: + """Return bool mask (True = occluded/object pixel), or None if unavailable.""" + if self.occlusion_mask_folder is None: + return None + path = os.path.join(self.occlusion_mask_folder, f"{t:06d}.png") + if not os.path.exists(path): + return None + return np.array(PIL.Image.open(path)) > 0 + + # ------------------------------------------------------------------ + # Rendering + # ------------------------------------------------------------------ + + def render_verts_2d(self, side: int, intrinsics) -> torch.Tensor: + """Project camera-space verts to pixel coords. Returns (T, 778, 3) [u, v, z].""" + v_cam = self.left_verts_cam if side == 0 else self.right_verts_cam + fx, fy, cx, cy = intrinsics + z = v_cam[..., 2] + u = (v_cam[..., 0] / z) * fx + cx + v = (v_cam[..., 1] / z) * fy + cy + return torch.stack([u, v, z], dim=-1) + + def get_mesh(self, side: int, t: int) -> trimesh.Trimesh: + verts = self.left_verts_cam if side == 0 else self.right_verts_cam + faces = self.left_faces if side == 0 else self.right_faces + return trimesh.Trimesh(verts[t].numpy(), faces.numpy(), process=False) + + def render_mesh(self, mesh: trimesh.Trimesh, resolution: tuple[int, int], + intrinsics) -> tuple[np.ndarray, np.ndarray]: + """Render mesh with pyrender, returning (color, depth) arrays.""" + camera = pyrender.IntrinsicsCamera( + fx=float(intrinsics[0]), fy=float(intrinsics[1]), + cx=float(intrinsics[2]), cy=float(intrinsics[3]), + ) + scene = pyrender.Scene() + scene.add(pyrender.Mesh.from_trimesh(mesh)) + scene.add(camera, pose=_CV_TO_GL) + renderer = pyrender.OffscreenRenderer(resolution[0], resolution[1]) + color, depth = renderer.render(scene) + renderer.delete() + return color, depth + + # ------------------------------------------------------------------ + # Alignment + # ------------------------------------------------------------------ + + def _reproject(self, v: np.ndarray, src_intrinsics, target_intrinsics) -> np.ndarray: + """Reproject camera-space point(s) from src to target intrinsics (z unchanged).""" + fx, fy, cx, cy = src_intrinsics + fx_p, fy_p, cx_p, cy_p = target_intrinsics + x, y, z = v[..., 0], v[..., 1], v[..., 2] + x_p = (z / fx_p) * (x / z * fx + cx - cx_p) + y_p = (z / fy_p) * (y / z * fy + cy - cy_p) + return np.stack([x_p, y_p, np.broadcast_to(z, x_p.shape)], axis=-1) + + def compute_alignment(self, side: int, t: int) -> dict: + """Single render pass; returns offset, offset_reprojected, scale, n_pixels. + + Renders the hand under DynHaMR (ViPE) intrinsics once and derives: + offset — cam-space [dx, dy, dz] under ViPE intrinsics that + shifts the hand centroid to match the depth image + along its camera ray. + offset_reprojected — same shift but expressed in depth-image cam + coordinates (used when depth intrinsics differ + from ViPE). + scale — median(depth_image / rendered_depth) over hand + pixels. Constant across time when the depth + source disagrees with DynHaMR by a uniform scale, + which is the dominant monocular failure mode. + n_pixels — number of valid hand-mask pixels (use as a weight + when aggregating across frames). + + Raises if the hand mask is empty (e.g. fully occluded or off-image). + """ + mesh = self.get_mesh(side, t) + depth_image = self.get_depth_image(t) + occ_mask = self.get_occlusion_mask(t) + h, w = depth_image.shape + _, rendered = self.render_mesh(mesh, (w, h), self.pose_data['intrins']) + + hand_mask = rendered != 0 + if occ_mask is not None: + hand_mask &= ~occ_mask + + n_pixels = int(hand_mask.sum()) + if n_pixels == 0: + raise RuntimeError(f"empty hand mask (side={side}, t={t})") + + di = depth_image[hand_mask] + dr = rendered[hand_mask] + + dz = float(np.median(di - dr)) + scale = float(np.median(di / dr)) + + # Offset along the camera ray: shift centroid by (dx, dy, dz) so its + # pixel projection is unchanged but its depth becomes z + dz. + z = float(np.mean(mesh.vertices[:, 2])) + x = float(np.mean(mesh.vertices[:, 0])) + y = float(np.mean(mesh.vertices[:, 1])) + z_p = z + dz + offset = np.array([x / z * z_p - x, + y / z * z_p - y, + dz], dtype=np.float64) + + # Reproject the depth-shifted centroid into the depth-image cam frame. + verts = self.right_verts_cam if side == 1 else self.left_verts_cam + centroid = verts[t].numpy().mean(axis=0) + shifted = centroid + offset + reproj = self._reproject( + shifted.reshape(1, 3), + self.pose_data['intrins'], + self.get_depth_intrinsics(), + ).reshape(3) + offset_reprojected = (reproj - centroid).astype(np.float64) + + return { + "offset": offset, + "offset_reprojected": offset_reprojected, + "scale": scale, + "n_pixels": n_pixels, + } + + def compute_offset(self, side: int, t: int) -> np.ndarray: + """Backward-compat shim; prefer :meth:`compute_alignment`.""" + return self.compute_alignment(side, t)["offset"] + + def compute_offset_reprojected(self, side: int, t: int) -> np.ndarray: + """Backward-compat shim; prefer :meth:`compute_alignment`.""" + return self.compute_alignment(side, t)["offset_reprojected"] + + def compute_scale(self, side: int, t: int) -> float: + """Backward-compat shim; prefer :meth:`compute_alignment`.""" + return self.compute_alignment(side, t)["scale"] diff --git a/third-party/video_to_data/reconstruction/modules/v2d_hand_alignment/lib/pyproject.toml b/third-party/video_to_data/reconstruction/modules/v2d_hand_alignment/lib/pyproject.toml new file mode 100644 index 0000000000000000000000000000000000000000..256f311e69835c860cafe0966ce4ee2899d1e933 --- /dev/null +++ b/third-party/video_to_data/reconstruction/modules/v2d_hand_alignment/lib/pyproject.toml @@ -0,0 +1,26 @@ +# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 +[build-system] +requires = ["setuptools>=68.0", "wheel"] +build-backend = "setuptools.build_meta" + +[project] +name = "v2d-hand-alignment-lib" +version = "0.1.0" +description = "Hand mesh alignment and rendering utilities" +requires-python = ">=3.10" +dependencies = [ + "numpy", + "scipy", + "Pillow", + "trimesh", + "pyrender", + "pyopengl", + "v2d-common", +] + +[tool.setuptools] +packages = ["v2d.hand_alignment.lib"] + +[tool.setuptools.package-dir] +"v2d.hand_alignment.lib" = "." diff --git a/third-party/video_to_data/reconstruction/modules/v2d_hand_alignment/lib/recover_mano_params.py b/third-party/video_to_data/reconstruction/modules/v2d_hand_alignment/lib/recover_mano_params.py new file mode 100644 index 0000000000000000000000000000000000000000..07796622efbb43bf48ddf12f14ccb5e5c2a72338 --- /dev/null +++ b/third-party/video_to_data/reconstruction/modules/v2d_hand_alignment/lib/recover_mano_params.py @@ -0,0 +1,295 @@ +# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 +""" +Recover MANO parameters in aligned camera space from the alignment pipeline outputs. + +Strategy +-------- +Use DynHaMR's cam_R as the world→camera rotation, then compute translation +analytically so the centroid of the FK mesh matches the aligned mesh centroid. + +For each hand track and each frame: + 1. R_w2c = cam_R[h, f] (DynHaMR's world→camera rotation matrix). + 2. global_orient = R_w2c @ R_root_eff (R_root_eff is the DynHaMR root + orientation, converted to left-hand space for left tracks). + 3. transl is computed from MANO FK identities: + LBS(R, pose, beta, t=0) = R @ (v_I - J0) + J0 + where v_I = LBS(I, pose, beta, t=0) and J0 is the rest-pose root joint. + Equating the centroid of LBS + transl with mean(aligned_verts) gives: + transl = mean(aligned) - R_eff_full @ (mean(v_I) - J0) - J0 + +Note: Procrustes on the full mesh was tried but produces distorted rotations +because the alignment pipeline shifts depth by ~50 cm; this depth offset +changes the centered shape of the point cloud and confuses the Procrustes fit. + +DynHaMR/manotorch left-hand convention +--------------------------------------- +DynHaMR: runs MANO_RIGHT for ALL tracks, then negates x-coords for left tracks. + v_world_left = M_flip @ MANO_RIGHT_FK(root_orient, trans, pose_body, betas) + where M_flip = diag(-1, 1, 1). +manotorch: uses MANO_LEFT (= MANO_RIGHT with x-mirrored template/weights). + v = MANO_LEFT_FK(global_orient_l, transl_l, hand_pose_l, betas) + ≡ M_flip @ MANO_RIGHT_FK(M_flip @ R_l @ M_flip, M_flip @ t_l, r_l * [1,-1,-1], betas) +Equating these gives the axis-angle transform described above. + +Inputs +------ + aligned_path Final aligned NPZ (smooth_hand_mesh output). + Uses verts (B, T, 778, 3) in target camera space. + world_results_path DynHaMR world_results.npz. + Contains cam_R (B,T,3,3), cam_t (B,T,3), + root_orient (B,T,3), trans (B,T,3), world_scale, + betas (B,10), pose_body (B,T,15,3). + hand_mesh_traj_path Original hand_mesh_traj NPZ. + Contains verts (B, T, 778, 3) in DynHaMR world frame. + mano_model_dir Directory containing MANO_RIGHT.pkl and MANO_LEFT.pkl. + output_path Output NPZ path. + +Output NPZ schema +----------------- + betas (B, 10) shape params — passed through + global_orient (B, T, 3) axis-angle in camera space (manotorch convention) + transl (B, T, 3) metric camera space + hand_pose (B, T, 45) finger joints (manotorch convention, left converted) + is_right (B, T) passed through from aligned NPZ + vertex_rmsd (B, T) per-vertex RMS between FK mesh and aligned mesh (diagnostic) + flat_hand_mean scalar always True — DynHaMR pose_body is full axis-angle, hands_mean must NOT be re-added +""" + +import argparse +import os +import pickle +import sys +import types + +import numpy as np +from scipy.spatial.transform import Rotation + +# Flip matrix: negates x-axis. M_flip @ R(r) @ M_flip = R(FLIP_AA @ r) +M_FLIP = np.diag([-1.0, 1.0, 1.0]) +# Axis-angle conjugation by M_flip: (rx, ry, rz) → (rx, -ry, -rz) +FLIP_AA = np.array([1.0, -1.0, -1.0]) + + +# --------------------------------------------------------------------------- +# Minimal numpy MANO helpers +# --------------------------------------------------------------------------- + +def _rodrigues(r: np.ndarray) -> np.ndarray: + """(3,) axis-angle → (3,3) rotation matrix.""" + theta = float(np.linalg.norm(r)) + if theta < 1e-8: + return np.eye(3) + n = r / theta + K = np.array([[0, -n[2], n[1]], [n[2], 0, -n[0]], [-n[1], n[0], 0]]) + return np.eye(3) + np.sin(theta) * K + (1 - np.cos(theta)) * (K @ K) + + +def _load_mano_model(pkl_path: str) -> dict: + """Load MANO pkl, returning arrays needed for FK.""" + if 'chumpy' not in sys.modules: + class _Ch: + def __new__(cls, *args, **kwargs): + return object.__new__(cls) + def __init__(self, x=None, *args, **kwargs): + self._state = {'x': np.asarray(x)} if x is not None else {} + def __setstate__(self, state): + self._state = state if isinstance(state, dict) else {'x': state} + def _resolve(self) -> np.ndarray: + state = self._state + if 'x' in state: + v = state['x'] + return v._resolve() if isinstance(v, _Ch) else np.asarray(v) + if 'a' in state and 'idxs' in state: + a = state['a'] + a = a._resolve() if isinstance(a, _Ch) else np.asarray(a) + idxs = np.asarray(state['idxs']) + result = a.flatten()[idxs] + ps = state.get('preferred_shape') + return result.reshape(ps) if ps is not None else result + return np.array([]) + def __array__(self, dtype=None): + return np.asarray(self._resolve(), dtype=dtype) + @property + def r(self): + return self._resolve() + + class _ChumMod(types.ModuleType): + def __getattr__(self, name: str): + return _Ch + + stub = _ChumMod('chumpy') + stub.__path__ = [] + stub.Ch = _Ch + sys.modules['chumpy'] = stub + for _sub in ['reordering', 'utils', 'ch', 'logic']: + _m = _ChumMod(f'chumpy.{_sub}') + sys.modules[f'chumpy.{_sub}'] = _m + setattr(stub, _sub, _m) + + with open(pkl_path, 'rb') as f: + raw = pickle.load(f, encoding='latin1') + + model = { + 'v_template': np.array(raw['v_template'], dtype=np.float64), + 'shapedirs': np.array(raw['shapedirs'], dtype=np.float64), + 'posedirs': np.array(raw['posedirs'], dtype=np.float64), + 'weights': np.array(raw['weights'], dtype=np.float64), + 'hands_mean': np.array(raw['hands_mean'], dtype=np.float64), + 'parents': np.array(raw['kintree_table'][0], dtype=np.int32), + } + jr = raw['J_regressor'] + model['J_regressor'] = np.array(jr.todense(), dtype=np.float64) + return model + + +def _mano_fk_zero(model: dict, hand_pose: np.ndarray, betas: np.ndarray) -> tuple: + """MANO FK with identity global_orient and zero transl. + + hand_pose: (45,) without hands_mean (raw DynHaMR convention). + Returns (v_out (778,3), J0 (3,)). + """ + full_pose = np.concatenate([np.zeros(3), hand_pose]) + v_shaped = model['v_template'] + np.einsum('ijk,k->ij', model['shapedirs'], betas) + J = model['J_regressor'] @ v_shaped + R = np.stack([_rodrigues(full_pose[3*i:3*i+3]) for i in range(16)]) + pose_feature = (R[1:] - np.eye(3)).reshape(-1) + v_posed = v_shaped + np.einsum('ijk,k->ij', model['posedirs'], pose_feature) + parents = model['parents'] + G = np.zeros((16, 4, 4)) + for k in range(16): + local = np.eye(4) + local[:3, :3] = R[k] + local[:3, 3] = J[k] if k == 0 else J[k] - J[parents[k]] + G[k] = G[parents[k]] @ local if k > 0 else local + G_final = np.zeros((16, 4, 4)) + for k in range(16): + offset = np.eye(4) + offset[:3, 3] = -J[k] + G_final[k] = G[k] @ offset + T = np.einsum('vk,kij->vij', model['weights'], G_final) + v_homo = np.concatenate([v_posed, np.ones((len(v_posed), 1))], axis=1) + v_out = np.einsum('vij,vj->vi', T, v_homo)[:, :3] + return v_out.astype(np.float64), J[0] + + +def _to_left_hand(R_root: np.ndarray, pose_body_45: np.ndarray) -> tuple: + """Convert DynHaMR right-hand-space root rotation and finger pose to manotorch left-hand-space. + + DynHaMR stores ALL tracks (including left) in right-hand MANO space and + negates x at geometry level. manotorch LEFT expects params in the mirrored + coordinate system. The conversion is a conjugation by M_flip = diag(-1,1,1): + R_left = M_flip @ R_right @ M_flip + r_left = FLIP_AA * r_right (negate y,z of each axis-angle) + """ + R_root_left = M_FLIP @ R_root @ M_FLIP + pose_left = (pose_body_45.reshape(15, 3) * FLIP_AA).reshape(45).astype(np.float32) + return R_root_left, pose_left + + +def recover_mano_params( + aligned_path: str, + world_results_path: str, + hand_mesh_traj_path: str, + mano_model_dir: str, + output_path: str, +) -> None: + aligned = np.load(aligned_path, allow_pickle=True) + wr = np.load(world_results_path, allow_pickle=True) + + aligned_verts = aligned["verts"].astype(np.float64) # (B, T, 778, 3) camera space + + cam_R = wr["cam_R"].astype(np.float64) # (B, T, 3, 3) world→cam rotation + root_orient_world = wr["root_orient"].astype(np.float64) # (B, T, 3) axis-angle + pose_body = wr["pose_body"].astype(np.float32).reshape(*aligned_verts.shape[:2], 45) + betas_all = wr["betas"].astype(np.float64) # (B, 10) + is_right = aligned["is_right"] # (B, T) + + B, T = aligned_verts.shape[:2] + + global_orient = np.zeros((B, T, 3), dtype=np.float32) + transl = np.zeros((B, T, 3), dtype=np.float32) + hand_pose_out = pose_body.copy() + vertex_rmsd = np.zeros((B, T), dtype=np.float32) + + # Per-track left/right flag (majority vote across frames) + is_right_track = is_right.mean(axis=1) > 0.5 # (B,) + + models = { + 'right': _load_mano_model(os.path.join(mano_model_dir, 'MANO_RIGHT.pkl')), + 'left': _load_mano_model(os.path.join(mano_model_dir, 'MANO_LEFT.pkl')), + } + + for h in range(B): + left_hand = not is_right_track[h] + side = 'left' if left_hand else 'right' + betas_h = betas_all[h] + + for f in range(T): + # Use DynHaMR's cam_R as the world→camera rotation + R_w2c = cam_R[h, f] + + # Root orientation in DynHaMR world space + R_root = Rotation.from_rotvec(root_orient_world[h, f]).as_matrix() + + if left_hand: + R_root_eff, hand_pose_f = _to_left_hand(R_root, pose_body[h, f]) + else: + R_root_eff = R_root + hand_pose_f = pose_body[h, f] + + # Full camera-space rotation: world→cam composed with root orient + R_eff_full = R_w2c @ R_root_eff + global_orient[h, f] = Rotation.from_matrix(R_eff_full).as_rotvec().astype(np.float32) + + # Transl from MANO FK identity: LBS(R,...,t=0) = R @ (v_I - J0) + J0 + # => t = mean(aligned) - R_eff_full @ (mean(v_I) - J0) - J0 + v_I, J0 = _mano_fk_zero(models[side], hand_pose_f, betas_h) + mean_aligned = aligned_verts[h, f].mean(0) + t = mean_aligned - R_eff_full @ (v_I.mean(0) - J0) - J0 + transl[h, f] = t.astype(np.float32) + + # Diagnostic: per-vertex RMSD between FK mesh and aligned mesh + v_fk = (R_eff_full @ (v_I - J0).T).T + J0 + t + vertex_rmsd[h, f] = float(np.sqrt(((v_fk - aligned_verts[h, f]) ** 2).sum(-1).mean())) + + # Convert finger pose for left hands (done per-track over all frames at once) + if left_hand: + hand_pose_out[h] = (pose_body[h].reshape(T, 15, 3) * FLIP_AA).reshape(T, 45) + + np.savez_compressed( + output_path, + betas = wr["betas"].astype(np.float32), + global_orient = global_orient, + transl = transl, + hand_pose = hand_pose_out, + is_right = is_right, + vertex_rmsd = vertex_rmsd, + flat_hand_mean = np.bool_(True), + ) + + print(f"Vertex RMSD — mean: {vertex_rmsd.mean()*1000:.2f} mm " + f"max: {vertex_rmsd.max()*1000:.2f} mm") + print(f"Saved → {output_path}") + + +def main() -> None: + parser = argparse.ArgumentParser(description="Recover MANO params from aligned hand mesh") + parser.add_argument("--aligned_path", required=True) + parser.add_argument("--world_results_path", required=True) + parser.add_argument("--hand_mesh_traj_path", required=True) + parser.add_argument("--mano_model_dir", required=True) + parser.add_argument("--output_path", required=True) + args = parser.parse_args() + + recover_mano_params( + aligned_path = args.aligned_path, + world_results_path = args.world_results_path, + hand_mesh_traj_path = args.hand_mesh_traj_path, + mano_model_dir = args.mano_model_dir, + output_path = args.output_path, + ) + + +if __name__ == "__main__": + main() diff --git a/third-party/video_to_data/reconstruction/modules/v2d_hand_alignment/lib/render_mano_params_video.py b/third-party/video_to_data/reconstruction/modules/v2d_hand_alignment/lib/render_mano_params_video.py new file mode 100644 index 0000000000000000000000000000000000000000..1d6c4a26fb48e14c8f7053492ab4d45497aec6a8 --- /dev/null +++ b/third-party/video_to_data/reconstruction/modules/v2d_hand_alignment/lib/render_mano_params_video.py @@ -0,0 +1,367 @@ +# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 +""" +Render a video with MANO FK hands projected onto the camera view. + +Loads mano_params_*.npz (output of recover_mano_params), runs forward +kinematics entirely in numpy/scipy, and renders the resulting hand meshes +overlaid on the original frames using pyrender. + +This is a diagnostic tool: if the rendered hands align with the real hands in +the video, the recovered MANO parameters are correct. + +Usage: + python -m v2d.hand_alignment.lib.render_mano_params_video \\ + --mano_params /data/hand_mesh/mano_params_moge.npz \\ + --intrinsics /data/intrinsics_moge_stable.json \\ + --mano_model_dir /data/mano \\ + --output /tmp/mano_check.mp4 \\ + --frames_folder /data/frames # optional video underlay + --mesh /data/mesh_scaled.obj # optional object overlay + --poses_dir /data/poses_moge_smoothed # required if --mesh given +""" + +from __future__ import annotations + +import argparse +import glob +import json +import os +import subprocess +import tempfile + +os.environ['PYOPENGL_PLATFORM'] = 'egl' + +import numpy as np +import pickle +import pyrender +import trimesh +from PIL import Image +from scipy.spatial.transform import Rotation + +# --------------------------------------------------------------------------- +# Minimal numpy MANO LBS +# --------------------------------------------------------------------------- + +def _rodrigues(r: np.ndarray) -> np.ndarray: + """(3,) axis-angle → (3,3) rotation matrix.""" + theta = float(np.linalg.norm(r)) + if theta < 1e-8: + return np.eye(3) + n = r / theta + K = np.array([[0, -n[2], n[1]], [n[2], 0, -n[0]], [-n[1], n[0], 0]]) + return np.eye(3) + np.sin(theta) * K + (1 - np.cos(theta)) * (K @ K) + + +def _load_mano_model(pkl_path: str) -> dict: + """Load and cache a MANO pkl file, converting sparse J_regressor.""" + # Stub out chumpy so pkl files load without it installed. + import sys, types + if 'chumpy' not in sys.modules: + class _Ch: + """Minimal chumpy array stub — lazily resolves Select/Ch to numpy.""" + def __new__(cls, *args, **kwargs): + return object.__new__(cls) + def __init__(self, x=None, *args, **kwargs): + self._state = {'x': np.asarray(x)} if x is not None else {} + def __setstate__(self, state): + self._state = state if isinstance(state, dict) else {'x': state} + def _resolve(self) -> np.ndarray: + state = self._state + if 'x' in state: + v = state['x'] + return v._resolve() if isinstance(v, _Ch) else np.asarray(v) + if 'a' in state and 'idxs' in state: + a = state['a'] + a = a._resolve() if isinstance(a, _Ch) else np.asarray(a) + idxs = np.asarray(state['idxs']) + result = a.flatten()[idxs] + ps = state.get('preferred_shape') + return result.reshape(ps) if ps is not None else result + return np.array([]) + def __array__(self, dtype=None): + return np.asarray(self._resolve(), dtype=dtype) + @property + def r(self): + return self._resolve() + class _ChumMod(types.ModuleType): + def __getattr__(self, name: str): + return _Ch + stub = _ChumMod('chumpy') + stub.__path__ = [] + stub.Ch = _Ch + sys.modules['chumpy'] = stub + for _sub in ['reordering', 'utils', 'ch', 'logic']: + _m = _ChumMod(f'chumpy.{_sub}') + sys.modules[f'chumpy.{_sub}'] = _m + setattr(stub, _sub, _m) + with open(pkl_path, 'rb') as f: + raw = pickle.load(f, encoding='latin1') + model = { + 'v_template': np.array(raw['v_template'], dtype=np.float64), # (778, 3) + 'shapedirs': np.array(raw['shapedirs'], dtype=np.float64), # (778, 3, 10) + 'posedirs': np.array(raw['posedirs'], dtype=np.float64), # (778, 3, 135) + 'weights': np.array(raw['weights'], dtype=np.float64), # (778, 16) + 'hands_mean': np.array(raw['hands_mean'], dtype=np.float64), # (45,) + 'faces': np.array(raw['f'], dtype=np.int32), # (1538, 3) + 'parents': np.array(raw['kintree_table'][0], dtype=np.int32), # (16,) + } + # J_regressor is a sparse scipy matrix + jr = raw['J_regressor'] + model['J_regressor'] = np.array(jr.todense(), dtype=np.float64) # (16, 778) + return model + + +def mano_forward( + model: dict, + global_orient: np.ndarray, # (3,) axis-angle in camera space + hand_pose: np.ndarray, # (45,) axis-angle — already in model space (no mean added) + betas: np.ndarray, # (10,) + transl: np.ndarray, # (3,) camera space +) -> np.ndarray: + """Returns posed vertices (778, 3) in camera space.""" + full_pose = np.concatenate([global_orient, hand_pose]) # (48,) + + # Shape blend shapes: v_shaped = v_template + S @ betas + v_shaped = (model['v_template'] + + np.einsum('ijk,k->ij', model['shapedirs'], betas)) # (778, 3) + + # Joint locations in rest pose + J = model['J_regressor'] @ v_shaped # (16, 3) + + # Per-joint rotation matrices + R = np.stack([_rodrigues(full_pose[3*i:3*i+3]) for i in range(16)]) # (16, 3, 3) + + # Pose blend shapes + pose_feature = (R[1:] - np.eye(3)).reshape(-1) # (135,) + v_posed = v_shaped + np.einsum('ijk,k->ij', model['posedirs'], pose_feature) # (778, 3) + + # Global joint transforms via forward kinematics + G = np.zeros((16, 4, 4)) + parents = model['parents'] + for k in range(16): + local = np.eye(4) + local[:3, :3] = R[k] + local[:3, 3] = J[k] if k == 0 else J[k] - J[parents[k]] + G[k] = G[parents[k]] @ local if k > 0 else local + + # Subtract rest-pose joint offset so transform is relative + G_final = np.zeros((16, 4, 4)) + for k in range(16): + offset = np.eye(4) + offset[:3, 3] = -J[k] + G_final[k] = G[k] @ offset + + # LBS: weighted sum of transforms + T = np.einsum('vk,kij->vij', model['weights'], G_final) # (778, 4, 4) + v_homo = np.concatenate([v_posed, np.ones((len(v_posed), 1))], axis=1) # (778, 4) + v_out = np.einsum('vij,vj->vi', T, v_homo)[:, :3] # (778, 3) + + return (v_out + transl).astype(np.float32) + + +# --------------------------------------------------------------------------- +# Rendering helpers (same conventions as render_multiview_video.py) +# --------------------------------------------------------------------------- + +_FLIP = np.diag([1.0, -1.0, -1.0, 1.0]) # CV → GL + + +def _cv_to_gl(v: np.ndarray) -> np.ndarray: + """Flip (N,3) verts from OpenCV to OpenGL space.""" + return v * np.array([1.0, -1.0, -1.0]) + + +def _make_intrinsics_camera(intr: dict, scale_x: float = 1.0, scale_y: float = 1.0): + return pyrender.IntrinsicsCamera( + fx=intr['fx'] * scale_x, fy=intr['fy'] * scale_y, + cx=intr['cx'] * scale_x, cy=intr['cy'] * scale_y, + znear=0.01, zfar=10.0, + ) + + +def _make_hand_mesh(verts_cv: np.ndarray, faces: np.ndarray, + color: tuple) -> trimesh.Trimesh: + tm = trimesh.Trimesh(vertices=_cv_to_gl(verts_cv), faces=faces, process=False) + tm.visual.face_colors = np.array(list(color) + [200], dtype=np.uint8) + return tm + + +HAND_COLORS = [ + (100, 180, 255), # hand 0 — blue + (255, 160, 80), # hand 1 — orange +] + + +# --------------------------------------------------------------------------- +# Main render loop +# --------------------------------------------------------------------------- + +def render_mano_params_video( + mano_params_path: str, + intrinsics_path: str, + mano_model_dir: str, + output_path: str, + fps: float = 25.0, + frames_folder: str | None = None, + mesh_path: str | None = None, + poses_dir: str | None = None, + panel_w: int = 388, + panel_h: int = 516, + start: int = 0, + end: int | None = None, +) -> None: + with open(intrinsics_path) as f: + intr = json.load(f) + W, H = panel_w, panel_h + scale_x = W / intr.get('width', W) + scale_y = H / intr.get('height', H) + + params = np.load(mano_params_path, allow_pickle=True) + global_orient = params['global_orient'].astype(np.float64) # (B, T, 3) + transl = params['transl'].astype(np.float64) # (B, T, 3) + hand_pose = params['hand_pose'].astype(np.float64) # (B, T, 45) + betas = params['betas'].astype(np.float64) # (B, 10) + is_right = params['is_right'] # (B, T) + + B, T = global_orient.shape[:2] + is_right_track = is_right.mean(axis=1) > 0.5 + + # Load MANO models (right + left) + models = { + 'right': _load_mano_model(os.path.join(mano_model_dir, 'MANO_RIGHT.pkl')), + 'left': _load_mano_model(os.path.join(mano_model_dir, 'MANO_LEFT.pkl')), + } + + # Optional object mesh + obj_faces = obj_verts_gl = None + pose_files = [] + if mesh_path and poses_dir: + obj_tm = trimesh.load(mesh_path, force='mesh') + obj_faces = np.array(obj_tm.faces) + obj_verts = np.array(obj_tm.vertices) + pose_files = sorted(glob.glob(os.path.join(poses_dir, '*.json'))) + + # Optional video underlay frames + frame_files = [] + if frames_folder: + frame_files = sorted( + glob.glob(os.path.join(frames_folder, '*.png')) + + glob.glob(os.path.join(frames_folder, '*.jpg')) + ) + + n_frames = end if end is not None else T + if pose_files: + n_frames = min(n_frames, len(pose_files)) + + cam = _make_intrinsics_camera(intr, scale_x, scale_y) + # Identity pose: pyrender GL camera looks down -Z; CV→GL flip puts CV Z+ at GL Z-. + cam_pose_gl = np.eye(4) + + renderer = pyrender.OffscreenRenderer(viewport_width=W, viewport_height=H) + + with tempfile.TemporaryDirectory() as tmpdir: + for f in range(start, n_frames): + scene = pyrender.Scene(bg_color=[0, 0, 0, 0], ambient_light=[0.4, 0.4, 0.4]) + scene.add(cam, pose=cam_pose_gl) + scene.add(pyrender.DirectionalLight(color=[1,1,1], intensity=3.0), + pose=cam_pose_gl) + + # Object + if pose_files and obj_faces is not None: + with open(pose_files[f]) as fh: + pd = json.load(fh) + w, x, y, z = pd['rotation'] + R_obj = Rotation.from_quat([x, y, z, w]).as_matrix() + t_obj = np.array(pd['translation']) + ov = (R_obj @ obj_verts.T).T + t_obj + ov_gl = _cv_to_gl(ov) + obj_tm = trimesh.Trimesh(vertices=ov_gl, faces=obj_faces, process=False) + obj_tm.visual.face_colors = [180, 180, 180, 220] + scene.add(pyrender.Mesh.from_trimesh(obj_tm, smooth=False)) + + # MANO hands + for h in range(B): + side = 'right' if is_right_track[h] else 'left' + verts_cv = mano_forward( + models[side], + global_orient[h, f], + hand_pose[h, f], + betas[h], + transl[h, f], + ) + tm = _make_hand_mesh(verts_cv, models[side]['faces'], HAND_COLORS[h % 2]) + scene.add(pyrender.Mesh.from_trimesh(tm, smooth=False)) + + color, _ = renderer.render(scene, flags=pyrender.RenderFlags.RGBA) + render_img = Image.fromarray(color, 'RGBA') + + # Compose over video frame if available + if frame_files and f < len(frame_files): + bg = Image.open(frame_files[f]).convert('RGBA').resize((W, H)) + out_img = Image.alpha_composite(bg, render_img).convert('RGB') + else: + out_img = render_img.convert('RGB') + + out_img.save(os.path.join(tmpdir, f'{f:06d}.png')) + + renderer.delete() + + cmd = [ + 'ffmpeg', '-y', '-r', str(fps), + '-i', os.path.join(tmpdir, '%06d.png'), + '-c:v', 'libx264', '-pix_fmt', 'yuv420p', + '-crf', '18', output_path, + ] + subprocess.run(cmd, check=True) + + print(f'Saved → {output_path}') + + +# --------------------------------------------------------------------------- +# CLI +# --------------------------------------------------------------------------- + +def main() -> None: + parser = argparse.ArgumentParser( + description='Render MANO FK hand mesh projected onto camera view.' + ) + parser.add_argument('--mano_params', required=True, + help='Path to mano_params_*.npz') + parser.add_argument('--intrinsics', required=True, + help='Camera intrinsics JSON {fx,fy,cx,cy,width,height}') + parser.add_argument('--mano_model_dir', required=True, + help='Directory containing MANO_RIGHT.pkl and MANO_LEFT.pkl') + parser.add_argument('--output', required=True, + help='Output video path (.mp4)') + parser.add_argument('--fps', type=float, default=25.0) + parser.add_argument('--frames_folder', default=None, + help='Folder of video frames to use as background') + parser.add_argument('--mesh', default=None, + help='Object mesh .obj to overlay') + parser.add_argument('--poses_dir', default=None, + help='Per-frame object pose JSONs (required with --mesh)') + parser.add_argument('--panel_w', type=int, default=388) + parser.add_argument('--panel_h', type=int, default=516) + parser.add_argument('--start', type=int, default=0) + parser.add_argument('--end', type=int, default=None) + args = parser.parse_args() + + render_mano_params_video( + mano_params_path = args.mano_params, + intrinsics_path = args.intrinsics, + mano_model_dir = args.mano_model_dir, + output_path = args.output, + fps = args.fps, + frames_folder = args.frames_folder, + mesh_path = args.mesh, + poses_dir = args.poses_dir, + panel_w = args.panel_w, + panel_h = args.panel_h, + start = args.start, + end = args.end, + ) + + +if __name__ == '__main__': + main() diff --git a/third-party/video_to_data/reconstruction/modules/v2d_hand_alignment/lib/render_multiview_video.py b/third-party/video_to_data/reconstruction/modules/v2d_hand_alignment/lib/render_multiview_video.py new file mode 100644 index 0000000000000000000000000000000000000000..7b718a32e0cd3e275ab87133c6e2694382f487dd --- /dev/null +++ b/third-party/video_to_data/reconstruction/modules/v2d_hand_alignment/lib/render_multiview_video.py @@ -0,0 +1,438 @@ +# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 +""" +Render a 4-panel video of object mesh + hand meshes: + top-left: original camera perspective + top-right: top-down view (centered on object) + bottom-left: left-side view + bottom-right: right-side view + +Coordinate conventions: + - CV camera space: +X right, +Y down, +Z forward + - GL (pyrender) space: +X right, +Y up, -Z forward + - Conversion: flip Y and Z → gl = cv * [1, -1, -1] + +Usage: + python -m v2d.hand_alignment.lib.render_multiview_video \\ + --mesh data/.../sam3d/mesh_scaled.obj \\ + --poses data/.../poses_sam3d_moge \\ + --hand_mesh data/.../hand_mesh_traj_000300_depth_aligned.npz \\ + --intrinsics data/.../intrinsics_moge_stable.json \\ + --output /tmp/multiview.mp4 \\ + --fps 30 +""" + +import os +os.environ['PYOPENGL_PLATFORM'] = 'egl' + +import argparse +import glob +import json +import subprocess +import tempfile + +import numpy as np +import pyrender +import trimesh +from PIL import Image, ImageDraw +from scipy.spatial.transform import Rotation + +# --------------------------------------------------------------------------- +# Coordinate helpers +# --------------------------------------------------------------------------- +_FLIP = np.diag([1.0, -1.0, -1.0, 1.0]) # CV → GL (homogeneous) + + +def cv_to_gl(T: np.ndarray) -> np.ndarray: + """Convert 4×4 pose from CV convention to GL convention.""" + return _FLIP @ T @ _FLIP + + +def verts_cv_to_gl(v: np.ndarray) -> np.ndarray: + """Flip (N,3) verts from CV to GL.""" + return v * np.array([1.0, -1.0, -1.0]) + + +def load_pose_cv(path: str) -> np.ndarray: + """Load object-to-camera 4×4 pose (CV convention) from JSON. + Rotation is stored as [w, x, y, z]; scipy expects [x, y, z, w]. + """ + with open(path) as f: + d = json.load(f) + w, x, y, z = d['rotation'] + sx, sy, sz = d['scale'] + R = Rotation.from_quat([x, y, z, w]).as_matrix() @ np.diag([sx, sy, sz]) + t = np.array(d['translation'], dtype=np.float64) + T = np.eye(4) + T[:3, :3] = R + T[:3, 3] = t + return T + + +def make_look_at(eye: np.ndarray, target: np.ndarray, up: np.ndarray) -> np.ndarray: + """4×4 camera-to-world pose in GL convention (camera looks along -Z).""" + fwd = target - eye + fwd /= np.linalg.norm(fwd) + right = np.cross(fwd, up) + right /= np.linalg.norm(right) + true_up = np.cross(right, fwd) + # GL: columns = [right, true_up, -fwd] + R = np.stack([right, true_up, -fwd], axis=1) + T = np.eye(4) + T[:3, :3] = R + T[:3, 3] = eye + return T + + +# --------------------------------------------------------------------------- +# Intrinsics / camera setup +# --------------------------------------------------------------------------- + +def load_intrinsics(path: str) -> dict: + with open(path) as f: + return json.load(f) + + +def make_intrinsics_camera(intr: dict) -> pyrender.IntrinsicsCamera: + return pyrender.IntrinsicsCamera( + fx=intr['fx'], fy=intr['fy'], + cx=intr['cx'], cy=intr['cy'], + znear=0.01, zfar=10.0, + ) + + +def make_persp_camera(fov_deg: float = 50.0) -> pyrender.PerspectiveCamera: + return pyrender.PerspectiveCamera(yfov=np.radians(fov_deg), znear=0.01, zfar=10.0) + + +# --------------------------------------------------------------------------- +# Scene building +# --------------------------------------------------------------------------- + +def make_hand_trimesh(verts: np.ndarray, faces: np.ndarray, color_rgba) -> trimesh.Trimesh: + """Create a trimesh for a single hand (verts already in render space).""" + tm = trimesh.Trimesh(vertices=verts, faces=faces, process=False) + tm.visual.face_colors = color_rgba + return tm + + +HAND_COLORS = [ + np.array([80, 140, 255, 200], dtype=np.uint8), # left – blue + np.array([255, 100, 50, 200], dtype=np.uint8), # right – orange +] + + +def build_scene( + obj_mesh_gl: trimesh.Trimesh, + obj_pose_gl: np.ndarray, + hand_verts_list_gl: list[np.ndarray | None], + faces_list: list[np.ndarray], + camera: pyrender.Camera, + camera_pose_gl: np.ndarray, + panel_w: int, + panel_h: int, + transparent_bg: bool = False, +) -> tuple[pyrender.Scene, pyrender.OffscreenRenderer]: + """Build a pyrender scene and return (scene, renderer).""" + bg = np.array([0, 0, 0, 0], dtype=np.uint8) if transparent_bg else np.array([30, 30, 30, 255], dtype=np.uint8) + scene = pyrender.Scene( + ambient_light=np.array([0.4, 0.4, 0.4]), + bg_color=bg, + ) + + # Object mesh + pr_obj = pyrender.Mesh.from_trimesh(obj_mesh_gl, smooth=False) + scene.add(pr_obj, pose=obj_pose_gl) + + # Hand meshes + for h, (v_gl, faces) in enumerate(zip(hand_verts_list_gl, faces_list)): + if v_gl is None: + continue + tm = make_hand_trimesh(v_gl, faces, HAND_COLORS[h % 2]) + pr_hand = pyrender.Mesh.from_trimesh(tm, smooth=False) + scene.add(pr_hand) + + # Lights (two directional + one point to fill shadows) + dl1 = pyrender.DirectionalLight(color=np.ones(3), intensity=3.0) + scene.add(dl1, pose=camera_pose_gl) + dl2 = pyrender.DirectionalLight(color=np.ones(3), intensity=1.5) + scene.add(dl2, pose=np.eye(4)) + + # Camera + scene.add(camera, pose=camera_pose_gl) + + return scene + + +def render_scene( + obj_mesh_gl: trimesh.Trimesh, + obj_pose_gl: np.ndarray, + hand_verts_list_gl: list, + faces_list: list, + camera: pyrender.Camera, + camera_pose_gl: np.ndarray, + renderer: pyrender.OffscreenRenderer, + transparent_bg: bool = False, +) -> np.ndarray: + """Build scene, render, return (H, W, 4) RGBA.""" + scene = build_scene( + obj_mesh_gl, obj_pose_gl, + hand_verts_list_gl, faces_list, + camera, camera_pose_gl, + renderer.viewport_width, renderer.viewport_height, + transparent_bg=transparent_bg, + ) + color, _ = renderer.render(scene, flags=pyrender.RenderFlags.RGBA) + return color # (H, W, 4) RGBA + + +# --------------------------------------------------------------------------- +# Fixed-view camera poses (GL object space) +# --------------------------------------------------------------------------- + +def make_fixed_cameras_gl(obj_verts_gl: np.ndarray) -> dict[str, np.ndarray]: + """ + Three fixed camera-to-world poses in GL object space. + Object centroid is the look-at target. + """ + ctr = obj_verts_gl.mean(axis=0) + ext = obj_verts_gl.max(axis=0) - obj_verts_gl.min(axis=0) + dist = float(np.linalg.norm(ext)) * 1.8 # camera distance + + # In GL object space: +Y is up, +X is right, -Z is scene depth + cameras = { + 'top': make_look_at(ctr + np.array([0, dist, 0]), ctr, np.array([0, 0, -1])), + 'left': make_look_at(ctr + np.array([-dist, 0, 0]), ctr, np.array([0, 1, 0])), + 'right': make_look_at(ctr + np.array([ dist, 0, 0]), ctr, np.array([0, 1, 0])), + } + return cameras + + +# --------------------------------------------------------------------------- +# Core implementation +# --------------------------------------------------------------------------- + +def render_multiview_video( + mesh_path: str, + poses_dir: str, + hand_mesh_path: str, + intrinsics_path: str, + output_path: str, + fps: float = 30.0, + panel_w: int = 388, + panel_h: int = 516, + start: int = 0, + end: int | None = None, + frames_folder: str | None = None, +) -> None: + """Render a 4-panel multiview video of object mesh + hand meshes.""" + intr = load_intrinsics(intrinsics_path) + W, H = panel_w, panel_h + out_w = W * 2 + out_h = H * 2 + + # --- Load object mesh (strip textures for EGL compatibility) --- + obj_tm_raw = trimesh.load(mesh_path, force='mesh') + obj_verts = np.array(obj_tm_raw.vertices, dtype=np.float64) + obj_faces = np.array(obj_tm_raw.faces) + OBJ_COLOR = np.array([180, 180, 180, 255], dtype=np.uint8) + + def make_obj_tm(verts_gl): + tm = trimesh.Trimesh(vertices=verts_gl, faces=obj_faces, process=False) + tm.visual.face_colors = OBJ_COLOR + return tm + + # Object mesh in GL object space (for fixed views) + obj_verts_gl = verts_cv_to_gl(obj_verts) + obj_tm_gl = make_obj_tm(obj_verts_gl) + + fov_cam = make_persp_camera(fov_deg=55.0) + + # --- Load hand mesh --- + hand_data = np.load(hand_mesh_path, allow_pickle=True) + verts_all = hand_data['verts'] # (n_hands, n_frames, n_verts, 3) CV camera space + faces_r = hand_data['faces_right'] + faces_l = hand_data['faces_left'] + is_right = hand_data['is_right'] + vis_mask = hand_data.get('vis_mask', np.ones(is_right.shape)) + n_hands, n_frames = verts_all.shape[:2] + + # --- Load pose files --- + pose_files = sorted(glob.glob(os.path.join(poses_dir, '*.json'))) + n_pose_files = len(pose_files) + + # --- RGB frames (optional underlay for camera view) --- + frame_files = [] + if frames_folder: + frame_files = sorted( + glob.glob(os.path.join(frames_folder, '*.png')) + + glob.glob(os.path.join(frames_folder, '*.jpg')) + ) + print(f"RGB underlay: {len(frame_files)} frames from {frames_folder}") + + start_frame = start + end_frame = end if end is not None else min(n_frames, n_pose_files) + + # --- Fixed-view world frame: frame 0's camera space --- + T_cam0_obj_cv = load_pose_cv(pose_files[start_frame]) + obj_verts_cam0_cv = (T_cam0_obj_cv[:3, :3] @ obj_verts.T).T + T_cam0_obj_cv[:3, 3] + obj_verts_cam0_gl = verts_cv_to_gl(obj_verts_cam0_cv) + obj_tm_cam0 = make_obj_tm(obj_verts_cam0_gl) + + # Fixed cameras centered on object in cam0 GL space + fixed_cams_gl = make_fixed_cameras_gl(obj_verts_cam0_gl) + + print(f"Rendering {end_frame - start_frame} frames at {W}×{H} × 4 panels → {out_w}×{out_h}") + print(f"Fixed views centred on frame-{start_frame} object pose") + + # --- Pyrender setup --- + cam_renderer = pyrender.OffscreenRenderer(W, H) + fixed_renderer = pyrender.OffscreenRenderer(W, H) + + # Camera-view camera: intrinsics, scaled to panel size + scale_x = W / intr.get('width', 776) + scale_y = H / intr.get('height', 1032) + cam_intr_scaled = pyrender.IntrinsicsCamera( + fx=intr['fx'] * scale_x, fy=intr['fy'] * scale_y, + cx=intr['cx'] * scale_x, cy=intr['cy'] * scale_y, + znear=0.01, zfar=10.0, + ) + cam_view_pose_gl = np.eye(4) + + # --- Write frames --- + with tempfile.TemporaryDirectory() as tmp: + for fid in range(start_frame, end_frame): + T_cam_obj_cv = load_pose_cv(pose_files[fid]) # object→camera_f (CV) + + # == Panel 1: camera view == + obj_verts_cam_cv = (T_cam_obj_cv[:3, :3] @ obj_verts.T).T + T_cam_obj_cv[:3, 3] + obj_verts_cam_gl = verts_cv_to_gl(obj_verts_cam_cv) + obj_tm_cam = make_obj_tm(obj_verts_cam_gl) + + # Hands in GL camera space + hand_cam_list = [] + hand_faces_cam = [] + for h in range(n_hands): + if fid >= n_frames or vis_mask[h, fid] < 0.5: + hand_cam_list.append(None) + hand_faces_cam.append(faces_r) + continue + v_cv = verts_all[h, fid].astype(np.float64) + v_gl = verts_cv_to_gl(v_cv) + hand_cam_list.append(v_gl) + hand_faces_cam.append(faces_r if is_right[h, fid] > 0.5 else faces_l) + + rgba_cam = render_scene( + obj_tm_cam, np.eye(4), + hand_cam_list, hand_faces_cam, + cam_intr_scaled, cam_view_pose_gl, + cam_renderer, + transparent_bg=bool(frame_files), + ) # (H, W, 4) + + # Composite mesh over RGB underlay if available + if frame_files and fid < len(frame_files): + rgb_bg = np.array(Image.open(frame_files[fid]).convert('RGB').resize((W, H), Image.BILINEAR)) + alpha = rgba_cam[:, :, 3:4].astype(np.float32) / 255.0 + panel_cam = (rgb_bg * (1.0 - alpha) + rgba_cam[:, :, :3] * alpha).astype(np.uint8) + else: + panel_cam = rgba_cam[:, :, :3] + + # == Panels 2/3/4: fixed views == + obj_verts_fix_cv = (T_cam_obj_cv[:3, :3] @ obj_verts.T).T + T_cam_obj_cv[:3, 3] + obj_tm_fix = make_obj_tm(verts_cv_to_gl(obj_verts_fix_cv)) + + hand_fix_list = [] + hand_faces_fix = [] + for h in range(n_hands): + if fid >= n_frames or vis_mask[h, fid] < 0.5: + hand_fix_list.append(None) + hand_faces_fix.append(faces_r) + continue + v_gl = verts_cv_to_gl(verts_all[h, fid].astype(np.float64)) + hand_fix_list.append(v_gl) + hand_faces_fix.append(faces_r if is_right[h, fid] > 0.5 else faces_l) + + panels_fixed = {} + for view_name, cam_pose_gl in fixed_cams_gl.items(): + panels_fixed[view_name] = render_scene( + obj_tm_fix, np.eye(4), + hand_fix_list, hand_faces_fix, + fov_cam, cam_pose_gl, + fixed_renderer, + )[:, :, :3] + + # == Assemble 2×2 grid == + canvas = np.zeros((out_h, out_w, 3), dtype=np.uint8) + canvas[:H, :W] = panel_cam # top-left: camera view + canvas[:H, W:] = panels_fixed['top'] # top-right: top-down + canvas[H:, :W] = panels_fixed['left'] # bottom-left: left side + canvas[H:, W:] = panels_fixed['right'] # bottom-right: right side + + # Labels + img = Image.fromarray(canvas) + draw = ImageDraw.Draw(img) + for (tx, ty, label) in [ + (4, 4, "camera"), + (W + 4, 4, "top-down"), + (4, H + 4, "left"), + (W + 4, H + 4, "right"), + ]: + draw.text((tx + 1, ty + 1), label, fill=(0, 0, 0)) + draw.text((tx, ty), label, fill=(255, 255, 255)) + + img.save(os.path.join(tmp, f'{fid:06d}.jpg'), quality=92) + + if fid % 50 == 0: + print(f" frame {fid}/{end_frame}") + + # --- Encode with ffmpeg --- + os.makedirs(os.path.dirname(os.path.abspath(output_path)), exist_ok=True) + cmd = [ + 'ffmpeg', '-y', + '-framerate', str(fps), + '-i', os.path.join(tmp, '%06d.jpg'), + '-c:v', 'libx264', + '-crf', '18', + '-pix_fmt', 'yuv420p', + output_path, + ] + subprocess.run(cmd, check=True) + print(f"\nSaved → {output_path}") + + cam_renderer.delete() + fixed_renderer.delete() + + +def main(): + parser = argparse.ArgumentParser(description="Render 4-panel multiview video") + parser.add_argument('--mesh_path', required=True, help='Object mesh OBJ') + parser.add_argument('--poses_dir', required=True, help='Folder of per-frame pose JSONs') + parser.add_argument('--hand_mesh_path', required=True, help='Aligned hand mesh NPZ') + parser.add_argument('--intrinsics_path', required=True, help='Camera intrinsics JSON') + parser.add_argument('--frames_folder', default=None, help='RGB frame images folder (for camera-view underlay)') + parser.add_argument('--output_path', required=True, help='Output MP4 path') + parser.add_argument('--fps', type=float, default=30.0) + parser.add_argument('--panel_w', type=int, default=388, help='Width of each panel') + parser.add_argument('--panel_h', type=int, default=516, help='Height of each panel') + parser.add_argument('--start', type=int, default=0) + parser.add_argument('--end', type=int, default=None) + args = parser.parse_args() + + render_multiview_video( + mesh_path=args.mesh_path, + poses_dir=args.poses_dir, + hand_mesh_path=args.hand_mesh_path, + intrinsics_path=args.intrinsics_path, + output_path=args.output_path, + fps=args.fps, + panel_w=args.panel_w, + panel_h=args.panel_h, + start=args.start, + end=args.end, + frames_folder=args.frames_folder, + ) + + +if __name__ == '__main__': + main() diff --git a/third-party/video_to_data/reconstruction/modules/v2d_hand_alignment/lib/reproject_hand_mesh.py b/third-party/video_to_data/reconstruction/modules/v2d_hand_alignment/lib/reproject_hand_mesh.py new file mode 100644 index 0000000000000000000000000000000000000000..3c9b0de46421cf2e745861174e0a4b1df06a5cae --- /dev/null +++ b/third-party/video_to_data/reconstruction/modules/v2d_hand_alignment/lib/reproject_hand_mesh.py @@ -0,0 +1,276 @@ +# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 +""" +Reproject hand mesh vertices from world frame + hand intrinsics to per-frame +camera space using target intrinsics. + +Two transforms are applied in sequence: + + 0. World scale (optional) + DynHaMR solves with a monocular scale ambiguity. world_results.npz may + contain a scalar 'world_scale' that converts internal units to metric. + When present it is applied to verts/joints before the w2c transform: + v_metric = v_world * world_scale + + 1. World → camera space (per-frame) + DynHaMR outputs verts in a fixed world frame. To bring verts into frame + t's camera space: + v_cam = R @ v_world + t (w2c convention) + + Two pose sources are supported: + --world_results DynHaMR world_results.npz with cam_R (n_hands,n_frames,3,3) + and cam_t (n_hands,n_frames,3) — per-track, per-frame. + If the file also contains 'world_scale', it is applied + automatically before the transform. + --pose Legacy: NPZ with 'data' key (n_frames,4,4) w2c matrices + applied identically across all hand tracks. + + 2. Intrinsics re-projection + The hand estimator ran with intrinsics A; we want verts consistent with + intrinsics B (e.g. MoGe). Pixel observations are ground truth; only x/y + lateral positions change (z is preserved): + u = x * fx_A / z + cx_A + x' = (u - cx_B) * z / fx_B (same for y) + +Usage: + # Recommended: use world_results.npz with per-track poses + python -m v2d.hand_alignment.lib.reproject_hand_mesh \ + --input data/.../hand/hand_mesh/airplane_hand_mesh_traj_000300.npz \ + --world_results data/.../hand/airplane_000300_world_results.npz \ + --hand_intrinsics data/.../hand/intrinsics/intrinsics.json \ + --target_intrinsics data/.../outputs/intrinsics_moge_stable.json \ + --output data/.../hand/hand_mesh/airplane_hand_mesh_traj_000300_aligned.npz + + # Legacy: single pose file (same w2c for all hand tracks) + python -m v2d.hand_alignment.lib.reproject_hand_mesh \ + --input ... --pose ... --hand_intrinsics ... --target_intrinsics ... --output ... + + # Intrinsics-only (no pose, e.g. static camera): + python -m v2d.hand_alignment.lib.reproject_hand_mesh \ + --input ... --hand_intrinsics ... --target_intrinsics ... --output ... + + # No hand intrinsics (skip lateral reprojection, world→camera only): + python -m v2d.hand_alignment.lib.reproject_hand_mesh \ + --input ... --world_results ... --target_intrinsics ... --output ... +""" + +import argparse +import json + +import numpy as np +from scipy.ndimage import gaussian_filter1d +from scipy.spatial.transform import Rotation, Slerp + + +def load_intrinsics(path: str) -> dict: + with open(path) as f: + return json.load(f) + + +def apply_w2c(verts: np.ndarray, R: np.ndarray, t: np.ndarray) -> np.ndarray: + """ + Transform (..., 3) world-frame verts into camera space. + v_cam = R @ v_world + t + Matches DynHaMR's cam_util.reproject convention. + R: (3,3), t: (3,) + """ + shape = verts.shape + v = verts.reshape(-1, 3).astype(np.float64) + v_cam = (R @ v.T).T + t + return v_cam.reshape(shape).astype(np.float32) + + +def reproject_intrinsics( + verts: np.ndarray, + src: dict, + dst: dict, + src_res: tuple[int, int] | None = None, + dst_res: tuple[int, int] | None = None, +) -> np.ndarray: + """ + Reproject (..., 3) verts from src intrinsics to dst intrinsics. + + For each vertex: + 1. Project to pixel using src intrinsics (pixel position is ground truth) + 2. Compute metric depth: centroid z is scaled by (dst_fx/src_fx) to correct + the focal-length inflation; each vertex's depth relative to the centroid + is preserved unchanged (MANO shape is already in metric). + 3. Unproject from pixel using dst intrinsics at the new depth. + + This gives: + - Exact pixel alignment for every vertex (no drift at fingertips/wrist) + - Correct absolute depth (centroid at dst-camera metric scale) + - Correct 3D hand shape (relative depths not squished) + + src_res/dst_res: (width, height) — used to rescale pixel coords if + the estimator ran on a different resolution than the intrinsics describe. + """ + shape = verts.shape + v = verts.reshape(-1, 3).astype(np.float64) + + z = v[:, 2] + safe_z = np.where(z > 1e-6, z, 1e-6) + + # Step 1: project to pixels with src intrinsics + u = v[:, 0] * src['fx'] / safe_z + src['cx'] + vp = v[:, 1] * src['fy'] / safe_z + src['cy'] + + if src_res is not None and dst_res is not None: + u = u * dst_res[0] / src_res[0] + vp = vp * dst_res[1] / src_res[1] + + # Step 2: compute per-vertex metric depth + # centroid z is scaled by the focal-length ratio (corrects depth inflation) + # each vertex's depth relative to the centroid is kept as-is (already metric) + z_centroid = safe_z.mean() + scale = dst['fx'] / src['fx'] + z_new = z_centroid * scale + (safe_z - z_centroid) + z_new = np.where(z_new > 1e-6, z_new, 1e-6) + + # Step 3: unproject with dst intrinsics at the corrected depth + x_new = (u - dst['cx']) * z_new / dst['fx'] + y_new = (vp - dst['cy']) * z_new / dst['fy'] + + return np.stack([x_new, y_new, z_new], axis=-1).reshape(shape).astype(np.float32) + + +def reproject_hand_mesh( + input_path: str, + target_intrinsics_path: str, + output_path: str, + world_results_path: str | None = None, + pose_path: str | None = None, + hand_intrinsics_path: str | None = None, + apply_world_scale: bool = False, + smooth_poses_sigma: float = 0.0, + hand_width: int | None = None, + hand_height: int | None = None, +) -> None: + """Reproject hand mesh from world frame to per-frame camera space with target intrinsics.""" + hand_intr = load_intrinsics(hand_intrinsics_path) if hand_intrinsics_path else None + target_intr = load_intrinsics(target_intrinsics_path) + + if hand_intr is not None: + src_res = (hand_width, hand_height) if (hand_width and hand_height) else \ + (hand_intr.get('width'), hand_intr.get('height')) + dst_res = (target_intr.get('width'), target_intr.get('height')) + if None in (src_res or [None]): src_res = None + if None in (dst_res or [None]): dst_res = None + print(f"Hand intrinsics: fx={hand_intr['fx']:.2f} fy={hand_intr['fy']:.2f} " + f"cx={hand_intr['cx']:.2f} cy={hand_intr['cy']:.2f}" + + (f" res={src_res}" if src_res else "")) + print(f"Target intrinsics: fx={target_intr['fx']:.2f} fy={target_intr['fy']:.2f} " + f"cx={target_intr['cx']:.2f} cy={target_intr['cy']:.2f}" + + (f" res={dst_res}" if dst_res else "")) + else: + src_res = dst_res = None + print("No hand intrinsics provided — skipping lateral reprojection (z preserved)") + + mesh_data = np.load(input_path, allow_pickle=True) + out = dict(mesh_data) + + verts = mesh_data['verts'].copy() # (n_hands, n_frames, n_verts, 3) + joints = mesh_data['joints'].copy() # (n_hands, n_frames, n_joints, 3) + n_hands, n_frames = verts.shape[:2] + + # --- Step 1: world → per-frame camera space --- + if world_results_path: + wr = np.load(world_results_path, allow_pickle=True) + cam_R = wr['cam_R'].astype(np.float64) # (n_hands, n_frames, 3, 3) + cam_t = wr['cam_t'].astype(np.float64) # (n_hands, n_frames, 3) + + if apply_world_scale and 'world_scale' in wr: + world_scale = float(wr['world_scale'].flat[0]) + print(f"Applying world_scale={world_scale:.4f} to convert DynHaMR internal units to metric...") + verts *= world_scale + joints *= world_scale + elif 'world_scale' in wr and not apply_world_scale: + print(f"world_scale={float(wr['world_scale'].flat[0]):.4f} found but not applied (use apply_world_scale=True to enable)") + + if smooth_poses_sigma > 0: + sigma = smooth_poses_sigma + print(f"Smoothing cam_R/cam_t with sigma={sigma} frames...") + for h in range(n_hands): + # Smooth translation with Gaussian + cam_t[h] = gaussian_filter1d(cam_t[h], sigma=sigma, axis=0) + # Smooth rotation via SLERP on the Rotation object + rots = Rotation.from_matrix(cam_R[h]) # (n_frames,) + rotvecs = rots.as_rotvec() # (n_frames, 3) + smoothed_rv = gaussian_filter1d(rotvecs, sigma=sigma, axis=0) + cam_R[h] = Rotation.from_rotvec(smoothed_rv).as_matrix() + + print(f"Applying per-track per-frame w2c from world_results (cam_R/cam_t) across {n_hands} hands × {n_frames} frames...") + for h in range(n_hands): + for f in range(n_frames): + R, t = cam_R[h, f], cam_t[h, f] + verts[h, f] = apply_w2c(verts[h, f], R, t) + joints[h, f] = apply_w2c(joints[h, f], R, t) + elif pose_path: + pose_data = np.load(pose_path, allow_pickle=True) + w2c_matrices = pose_data['data'].astype(np.float64) # (n_frames, 4, 4) + print(f"Applying per-frame w2c from pose NPZ across {n_frames} frames...") + for f in range(n_frames): + R = w2c_matrices[f, :3, :3] + t = w2c_matrices[f, :3, 3] + for h in range(n_hands): + verts[h, f] = apply_w2c(verts[h, f], R, t) + joints[h, f] = apply_w2c(joints[h, f], R, t) + else: + print("No pose file provided — skipping world→camera transform.") + + # --- Step 2: re-project from hand intrinsics to target intrinsics --- + if hand_intr is not None: + print("Re-projecting from hand intrinsics to target intrinsics...") + out['verts'] = reproject_intrinsics(verts, hand_intr, target_intr, src_res, dst_res) + out['joints'] = reproject_intrinsics(joints, hand_intr, target_intr, src_res, dst_res) + else: + print("Skipping intrinsics reprojection.") + out['verts'] = verts + out['joints'] = joints + + np.savez(output_path, **out) + print(f"Saved → {output_path}") + + h, f = 0, 0 + before = mesh_data['verts'][h, f, 0] + after = out['verts'][h, f, 0] + print(f"\nSample vert [hand=0, frame=0, vert=0]:") + print(f" before: x={before[0]:.4f} y={before[1]:.4f} z={before[2]:.4f}") + print(f" after: x={after[0]:.4f} y={after[1]:.4f} z={after[2]:.4f}") + + +def main(): + parser = argparse.ArgumentParser(description="Reproject hand mesh to per-frame camera space + new intrinsics") + parser.add_argument('--input_path', required=True, help='Input NPZ hand mesh (world frame)') + parser.add_argument('--world_results_path', default=None, help='DynHaMR world_results.npz with cam_R/cam_t (n_hands,n_frames,...)') + parser.add_argument('--pose_path', default=None, help='Legacy pose NPZ with w2c matrices (data: N,4,4)') + parser.add_argument('--hand_intrinsics_path', default=None, help='Intrinsics used by hand estimator (JSON); if omitted, skips lateral reprojection') + parser.add_argument('--target_intrinsics_path', required=True, help='Target intrinsics to align to (JSON)') + parser.add_argument('--output_path', required=True, help='Output NPZ path') + parser.add_argument('--apply_world_scale', action='store_true', + help='Apply world_scale from world_results.npz (DynHaMR monocular scale factor) before w2c transform') + parser.add_argument('--smooth_poses_sigma', type=float, default=0.0, + help='Gaussian sigma (frames) for temporal smoothing of cam_R/cam_t before w2c. ' + 'Reduces DynHaMR camera-trajectory noise that causes per-frame image misalignment.') + parser.add_argument('--hand_width', type=int, default=None, + help='Image width hand estimator ran on (if different from hand_intrinsics["width"])') + parser.add_argument('--hand_height', type=int, default=None, + help='Image height hand estimator ran on (if different from hand_intrinsics["height"])') + args = parser.parse_args() + + reproject_hand_mesh( + input_path=args.input_path, + target_intrinsics_path=args.target_intrinsics_path, + output_path=args.output_path, + world_results_path=args.world_results_path, + pose_path=args.pose_path, + hand_intrinsics_path=args.hand_intrinsics_path, + apply_world_scale=args.apply_world_scale, + smooth_poses_sigma=args.smooth_poses_sigma, + hand_width=args.hand_width, + hand_height=args.hand_height, + ) + + +if __name__ == '__main__': + main() diff --git a/third-party/video_to_data/reconstruction/modules/v2d_hand_alignment/lib/smooth_hand_mesh.py b/third-party/video_to_data/reconstruction/modules/v2d_hand_alignment/lib/smooth_hand_mesh.py new file mode 100644 index 0000000000000000000000000000000000000000..abcd1b9f60f867a184ab4c8d466009fbbec9df15 --- /dev/null +++ b/third-party/video_to_data/reconstruction/modules/v2d_hand_alignment/lib/smooth_hand_mesh.py @@ -0,0 +1,102 @@ +# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 +""" +Smooth hand mesh center position temporally. + +For each hand track, the centroid (mean vertex position) is smoothed with a +Gaussian filter. Per-frame finger shapes are preserved by applying only the +smoothed centroid delta to all vertices. + +Algorithm per hand: + 1. Compute centroid[f] = mean(verts[h, f]) over visible frames + 2. Gaussian-smooth centroid over time → centroid_smooth[f] + 3. verts_out[h, f] = verts[h, f] + (centroid_smooth[f] - centroid[f]) + +Invisible frames are gap-filled by linear interpolation before smoothing, +then restored to their original values so only visible frames are affected. + +Usage: + python -m v2d.hand_alignment.lib.smooth_hand_mesh \\ + --input data/.../hand_mesh_traj_000300_moge_aligned_perhand.npz \\ + --output data/.../hand_mesh_traj_000300_moge_aligned_perhand_smooth.npz \\ + --sigma 5.0 +""" + +import argparse + +import numpy as np +from scipy.ndimage import gaussian_filter1d + + +def smooth_hand_mesh( + input_path: str, + output_path: str, + sigma: float = 5.0, +) -> None: + data = np.load(input_path, allow_pickle=True) + out = dict(data) + + verts = data['verts'].copy().astype(np.float64) # (n_hands, n_frames, n_verts, 3) + joints = data['joints'].copy().astype(np.float64) # (n_hands, n_frames, n_joints, 3) + vis_mask = data.get('vis_mask', np.ones(verts.shape[:2])) # (n_hands, n_frames) + + n_hands, n_frames = verts.shape[:2] + + for h in range(n_hands): + visible = vis_mask[h].astype(bool) # (n_frames,) + if visible.sum() < 2: + print(f" hand {h}: too few visible frames ({visible.sum()}), skipping") + continue + + # Centroid per frame: (n_frames, 3) + centroid = verts[h].mean(axis=1) # mean over vertices + + # Gap-fill invisible frames via linear interpolation so the Gaussian + # filter doesn't see hard zeros at the edges. + frames = np.arange(n_frames) + centroid_filled = centroid.copy() + for dim in range(3): + centroid_filled[:, dim] = np.interp( + frames, + frames[visible], + centroid[visible, dim], + ) + + # Gaussian smooth (each spatial dim independently) + centroid_smooth = np.stack([ + gaussian_filter1d(centroid_filled[:, dim], sigma=sigma) + for dim in range(3) + ], axis=-1) # (n_frames, 3) + + # Delta: only apply to visible frames + delta = np.zeros((n_frames, 3)) + delta[visible] = (centroid_smooth - centroid)[visible] # (n_frames, 3) + + # Shift verts and joints by delta (broadcast over vertices/joints) + verts[h] += delta[:, None, :] # (n_frames, 1, 3) broadcast + joints[h] += delta[:, None, :] + + applied = np.linalg.norm(delta[visible], axis=-1) + print(f" hand {h}: sigma={sigma:.1f} " + f"max_shift={applied.max():.4f}m mean_shift={applied.mean():.4f}m") + + out['verts'] = verts.astype(np.float32) + out['joints'] = joints.astype(np.float32) + np.savez(output_path, **out) + print(f"Saved → {output_path}") + + +def main(): + parser = argparse.ArgumentParser(description="Temporally smooth hand mesh center position") + parser.add_argument('--input_path', required=True, help='Input NPZ hand mesh') + parser.add_argument('--output_path', required=True, help='Output NPZ path') + parser.add_argument('--sigma', type=float, default=5.0, + help='Gaussian sigma in frames (default: 5.0)') + args = parser.parse_args() + + print(f"Smoothing hand centroid with sigma={args.sigma} frames...") + smooth_hand_mesh(args.input_path, args.output_path, sigma=args.sigma) + + +if __name__ == '__main__': + main() diff --git a/third-party/video_to_data/reconstruction/modules/v2d_hoi_object_reconstruction/LICENSE b/third-party/video_to_data/reconstruction/modules/v2d_hoi_object_reconstruction/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..10caffae439b956cdda2b1ded9ecbe51ac10befb --- /dev/null +++ b/third-party/video_to_data/reconstruction/modules/v2d_hoi_object_reconstruction/LICENSE @@ -0,0 +1,15 @@ +# Apache License 2.0 + +Copyright 2025 NVIDIA CORPORATION + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. diff --git a/third-party/video_to_data/reconstruction/modules/v2d_hoi_object_reconstruction/README.md b/third-party/video_to_data/reconstruction/modules/v2d_hoi_object_reconstruction/README.md new file mode 100644 index 0000000000000000000000000000000000000000..87e43dc0a65e75c57d0240b7b93d01b14933924e --- /dev/null +++ b/third-party/video_to_data/reconstruction/modules/v2d_hoi_object_reconstruction/README.md @@ -0,0 +1,743 @@ +# v2d_hoi_object_reconstruction + +End-to-end textured 3D mesh reconstruction from hand-object interaction video. + +Two reconstruction modes: +- **BundleSDF** (default) — two-stage scan (stationary → rotated → stationary) → full textured NeRF mesh +- **SAM3D** — select representative frames → per-frame single-image 3D → silhouette-based scale estimation + +--- + +## Agentic Workflow + +Repository-local agent support is split into three focused skills, matching the +setup/run/doctor pattern used by other modules: + +| Skill | Use it for | +|---|---| +| [`hoi-object-reconstruction-setup`](../../../.claude/skills/hoi-object-reconstruction-setup/SKILL.md) | Host packages, Docker/GPU checks, images, weights, and input preflight | +| [`hoi-object-reconstruction-run`](../../../.claude/skills/hoi-object-reconstruction-run/SKILL.md) | Launching, monitoring, resuming, and verifying BundleSDF or SAM3D | +| [`hoi-object-reconstruction-doctor`](../../../.claude/skills/hoi-object-reconstruction-doctor/SKILL.md) | Diagnosing the first bad setup, input, pipeline, or output stage | + +The run skill is action-oriented. Unless a command-only response is requested, +it launches the pipeline rather than stopping after a questionnaire. Missing +values use these safe defaults: BundleSDF, GPU 0, a fresh output directory, and +the included basketball capture with prompt `basketball`. Custom paths, modes, +prompts, GPUs, and output directories always take precedence. + +Start the agent from the repository checkout. Examples: + +```text +/hoi-object-reconstruction-setup Prepare BundleSDF on GPU 0. + +/hoi-object-reconstruction-run Run the included basketball example with +BundleSDF on GPU 0, monitor it, and verify the mesh and alignment video. + +/hoi-object-reconstruction-run Run SAM3D on +/absolute/path/to/mapping_data with prompt "toy airplane" and write a fresh job +under /absolute/path/to/outputs. + +/hoi-object-reconstruction-doctor Diagnose the failed job at +/absolute/path/to/job and give me the narrowest resume command. +``` + +Before a long GPU job, setup and run use a deterministic input check. It can +also be run manually from `reconstruction/`: + +```bash +python ../.claude/skills/hoi-object-reconstruction-setup/scripts/preflight_input.py \ + /absolute/path/to/mapping_data +``` + +A completed agentic run must still report the source revision, exact command, +input and output paths, selected mode and GPU, final artifact paths, and visual +QA result. A zero exit code or a generated GLB alone is not sufficient. + +These skills end at a reviewed reconstruction GLB. Mesh-to-USD conversion and +physics validation are separate downstream workflows and must have their own +output directory and status. + +--- + +## Data Collection + +### Capture hardware + +The reference data was collected with a backpack-based capture rig whose main +components are a **Hawk stereo camera** and an **NVIDIA Orin** compute and +recording unit. This hardware is not a pipeline requirement. Input may originate +from stereo videos, image sequences, or another capture format as long as it is +converted to synchronized left/right JPEG keyframes and calibration metadata in +the HOI reconstruction layout described in +[Input Data Format](#input-data-format). + +### Preparing the input dataset + +The base image and metadata format is defined by public +[PyCuSFM](https://github.com/nvidia-isaac/pyCuSFM). This module consumes a +stricter, single-stereo-pair profile of PyCuSFM's `frames_meta.json` contract. +See the public [PyCuSFM input +tutorial](https://github.com/nvidia-isaac/pyCuSFM/blob/main/docs/tutorial.md#raw-data-requirements) +for the underlying `KeyframesMetadataCollection` format. + +For source videos or another capture format: + +1. Extract synchronized left and right frames as JPEG images under + `front_stereo_camera_left/` and `front_stereo_camera_right/`. Preserve + nanosecond capture timestamps in the filenames when available. +2. Create a PyCuSFM generator YAML containing the real image dimensions, + rectified pinhole intrinsics, camera-to-rig transforms, sensor names, and + stereo baseline. Do not infer or copy calibration from the example dataset. +3. Use PyCuSFM's public [keyframe metadata + generator](https://github.com/nvidia-isaac/pyCuSFM/blob/main/pycusfm/generate_frame_meta.py) + in stereo-images mode: + +```bash +python pycusfm/generate_frame_meta.py \ + --images /path/to/mapping_data_dir \ + --config /path/to/camera_config.yaml \ + --output /path/to/mapping_data_dir/frames_meta.json +``` + +Add `--use-pseudo-timestamps` when synchronized image sequences have no capture +timestamps. The generator assigns synchronization IDs and emits the CuSFM +metadata structure. For rectified pinhole input, empty or zero distortion +coefficients cause it to emit the 3×4 `projection_matrix` required by this HOI +pipeline. + +Finally, validate the generated JSON against +[`schemas/frames_meta.schema.json`](schemas/frames_meta.schema.json), check the +cross-field invariants below, and compare the directory structure with +[`assets/basketball_example/`](assets/basketball_example/). A custom converter +is also compatible if it produces the same contract with correct +synchronization and calibration. + +Before a scan, verify that both stereo feeds are clear and synchronized, the +recording frame rate is stable (the reference collection uses 30 FPS), and the +capture system has enough free storage. + +### Object scanning guidelines + +Choose a rigid, opaque object with matte surfaces and visible texture whenever +possible. Transparent or reflective materials, nearly textureless surfaces, +very dark objects, and objects that deform while handled are substantially more +difficult to reconstruct. Use diffuse, stable lighting and a stationary, +feature-rich background; clean the object and make sure it can rest securely in +both scan orientations. + +Use one continuous two-round recording to obtain six-face coverage: + +1. Place the object near the center of the capture area with approximately + 20–30 cm of clearance. Keep it fully in frame, typically from a distance of + 50–100 cm. +2. Walk slowly through a full 360-degree pass at roughly the object's + mid-height. Keep the camera aimed at the object, maintain a consistent + distance, and target 50–70% overlap between consecutive views. A typical + pass takes 20–40 seconds. +3. Without stopping the recording, rotate the object about 90 degrees to expose + its previously hidden bottom face. Brief hand occlusion is expected; touch + edges or the base where possible and keep most of the object and background + visible. +4. Complete a second 360-degree pass around the new orientation, concentrating + on the newly exposed face and its adjacent surfaces. Confirm that all six + faces and any concave or easily missed areas have coverage, then stop and + verify the capture was saved. + +Move smoothly to limit motion blur and avoid abrupt changes in distance or +lighting. + +--- + +## Input Data Format + +`--mapping_data_dir` must point to a synchronized stereo dataset in this layout: + +```text +mapping_data_dir/ +├── frames_meta.json # required +├── frame_metadata.jsonl # optional compatibility metadata; not consumed +├── front_stereo_camera_left/ +│ └── .jpeg +└── front_stereo_camera_right/ + └── .jpeg +``` + +The bundled [`assets/basketball_example/`](assets/basketball_example/) is the +reference dataset (203 synchronized stereo pairs at 960×600). JPEG is the +known-good input format. Metadata image paths are relative to +`mapping_data_dir`. + +The reference directory also contains a `stereo.edex` source artifact, but it +is not part of this module's input contract and the current reconstruction path +does not read it. `frames_meta.json` is the calibration source of truth: its +camera entries provide the rectified projection matrices and image dimensions, +and its first `stereo_pair` entry provides the baseline. + +This is a **CuSFM-compatible HOI stereo profile**. CuSFM determines the core +`frames_meta.json` representation, relative image paths, timestamp units, +camera parameter map, and synchronization IDs. The HOI wrapper additionally +requires one usable stereo pair, the sensor names shown below, rectified 3×4 +projection matrices, and a positive baseline. JPEG is the currently tested +image format for the complete HOI pipeline even though CuSFM itself accepts +additional image formats. + +### `frames_meta.json` (required) + +This file is the pipeline's input contract: + +| Field | Required | Description | +|-------|----------|-------------| +| `keyframes_metadata` | yes | One entry per camera image: camera ID, synchronized sample ID, relative image path, and timestamp in microseconds. | +| `camera_params_id_to_camera_params` | yes | Camera definitions keyed by ID, including sensor name, image dimensions, and calibration matrices. | +| `stereo_pair` | yes | Left/right camera IDs and physical stereo baseline in meters. The pipeline uses the first pair. | +| `initial_pose_type` | yes | CuSFM pose interpretation, normally `"EGO_MOTION"` for sequential stereo input. | +| `camera_params_id_to_session_name` | no | Producer/session metadata; not interpreted here. | + +Minimal structural example (projection values abbreviated): + +```json +{ + "initial_pose_type": "EGO_MOTION", + "keyframes_metadata": [ + { + "id": "0", + "camera_params_id": "0", + "synced_sample_id": "5", + "image_name": "front_stereo_camera_left/1771445398921412053.jpeg", + "timestamp_microseconds": "1771445398921412" + }, + { + "id": "1", + "camera_params_id": "1", + "synced_sample_id": "5", + "image_name": "front_stereo_camera_right/1771445398921412053.jpeg", + "timestamp_microseconds": "1771445398921412" + } + ], + "camera_params_id_to_camera_params": { + "0": { + "sensor_meta_data": {"sensor_name": "front_stereo_camera_left"}, + "calibration_parameters": { + "image_width": 960, + "image_height": 600, + "projection_matrix": { + "row_count": 3, + "column_count": 4, + "data": [426.2, 0, 473.2, 0, 0, 426.2, 278.4, 0, 0, 0, 1, 0] + } + } + }, + "1": { + "sensor_meta_data": {"sensor_name": "front_stereo_camera_right"}, + "calibration_parameters": { + "image_width": 960, + "image_height": 600, + "projection_matrix": { + "row_count": 3, + "column_count": 4, + "data": [426.2, 0, 473.2, 0, 0, 426.2, 278.4, 0, 0, 0, 1, 0] + } + } + } + }, + "stereo_pair": [{ + "left_camera_param_id": "0", + "right_camera_param_id": "1", + "baseline_meters": 0.14956 + }] +} +``` + +Important invariants: + +- Left and right entries pair by equal `synced_sample_id`; incomplete pairs are + dropped. +- Camera IDs in frame and stereo-pair entries must reference keys in + `camera_params_id_to_camera_params`. +- Sensor names must be `front_stereo_camera_left` and + `front_stereo_camera_right`; current frame indexing relies on these names. +- `timestamp_microseconds` is a decimal string. Timestamp-based filenames use + nanoseconds, but `image_name` is the authoritative path. +- `projection_matrix.data` is a row-major 3×4 rectified projection matrix. The + pipeline reads `fx`, `fy`, `cx`, and `cy` from indices 0, 5, 2, and 6. +- `baseline_meters` is in meters and must be positive. + +See the machine-readable +[`schemas/frames_meta.schema.json`](schemas/frames_meta.schema.json). JSON +Schema cannot verify cross-field references, stereo pairing, image existence, +or calibration accuracy. + +### `frame_metadata.jsonl` (optional compatibility metadata) + +The current `run_reconstruction.py` path does not read this file, but some +dataset producers and older tools emit it. Each non-empty line is one +synchronized-frame JSON record: + +```json +{"frame_id":0,"cams":[{"id":0,"filename":"front_stereo_camera_left/1771445398921412053.jpeg","timestamp":1771445398921412000},{"id":1,"filename":"front_stereo_camera_right/1771445398921412053.jpeg","timestamp":1771445398921412000}]} +``` + +`timestamp` is in nanoseconds. Validate each line independently against +[`schemas/frame_metadata_record.schema.json`](schemas/frame_metadata_record.schema.json). +A JSONL file as a whole is not a single JSON value. + +--- + +## Environment Setup + +### GPU compatibility + +The v0.2 containers require NVIDIA Container Toolkit and an NVIDIA GPU with at +least 24 GB of VRAM. Development and local validation used RTX A6000 and L40S +GPUs. VRAM capacity alone does not indicate compatibility. + +Blackwell GPUs with compute capability 12.0 (`sm_120`), including the NVIDIA +RTX PRO 6000 Blackwell, are not supported by the TensorRT and cuVSLAM versions +in `v2d_cusfm` or by all current native CUDA extensions. Without the host +preflight, CuSFM can fail while building a TensorRT engine or another stage may +report `no kernel image is available for execution on the device`. + +`scripts/build_containers.sh` checks the host architecture before starting the +container builds, and `run_reconstruction.py` checks it again before launching +the pipeline. Use a validated GPU for v0.2. The build-only +`--skip-gpu-preflight` escape hatch is intended for cross-host image builds; +the runtime check remains mandatory. Blackwell support requires upgrading and +validating the `v2d_cusfm` TensorRT/cuVSLAM stack and rebuilding native CUDA +extensions with `sm_120` targets. + +### 1. Install host packages (from `reconstruction/`) + +Activate the Python 3.10+ environment used for this source checkout, then run +the repository-wide package installer: + +```bash +./scripts/install_packages.sh +``` + +If you do not already have an isolated environment, create one first with +`python3 -m venv .venv` and `source .venv/bin/activate`. Do not install +Matplotlib or SciPy manually to make this workflow pass. BundleSDF and SAM3D +numerical work—including scan checks, frame selection, SRT optimization, mask +processing, and media encoding—runs in containers. + +### 2. Build all required containers + +```bash +./scripts/build_containers.sh +``` + +The `v2d_sam3d` image built from this tree includes the EGL/GLVND loader and +Pyrender required for headless overlay-video rendering. Rebuild that image +after changing `v2d_sam3d` code or Docker dependencies; model weights remain a +separate runtime download. + +The release-image prerequisite check is: + +```bash +docker run --rm --gpus all v2d_sam3d:latest \ + python -c 'import pyrender; r=pyrender.OffscreenRenderer(64,64); \ +print("egl_renderer=pass"); r.delete()' +``` + +It must print `egl_renderer=pass`. + +### 3. Download model weights + +```bash +# Shared (both modes) +python -m v2d.sam2.docker.run_download_weights --output_dir data/weights/sam2 +python -m v2d.grounding_dino.docker.run_download_weights --output_dir data/weights/grounding_dino + +# BundleSDF mode +python modules/v2d_foundation_stereo/docker/run_download_weights.py \ + --output_dir data/weights/foundationstereo +python modules/v2d_foundation_pose/docker/run_download_weights.py \ + --output_dir data/weights/foundationpose +python modules/v2d_bundlesdf/docker/run_download_weights.py \ + --output_dir data/weights + +# SAM3D mode +python modules/v2d_sam3d/docker/run_download_weights.py \ + --output_dir data/weights/sam3d +# (optional: FoundationStereo for depth-assisted scale estimation) +python modules/v2d_foundation_stereo/docker/run_download_weights.py \ + --output_dir data/weights/foundationstereo +``` + +--- + +## BundleSDF Pipeline + +Two-stage scan: object stationary → rotated 360° → stationary again. + +### Quick Start + +```bash +python modules/v2d_hoi_object_reconstruction/docker/run_reconstruction.py \ + --mapping_data_dir data/hoi_obj_recon/raw_data/ \ + --job_dir data/outputs/hoi_recon/ \ + --prompt "basketball" +``` + +### Pipeline Steps + +```mermaid +flowchart TD + A["Calibrated stereo input
images + frames_meta.json"] --> B["Prepare job
left/right frames, calibration, video"] + B --> C["CuSFM + scan QA
camera poses and stage boundary"] + C --> D["Grounding DINO + SAM2
object boxes and masks"] + C --> E["FoundationStereo
stereo depth"] + D --> F["Stage-1 BundleSDF
initial textured mesh"] + E --> F + F --> G["FoundationPose
track the initial mesh"] + G --> H["World-pose alignment
merge stationary and rotated stages"] + H --> I["Final BundleSDF
merged_recon/output.glb"] + I --> J["Final overlay video
fp_render_final/render.mp4"] +``` + +### Results + +- `merged_recon/textured_mesh.obj` — final textured mesh (+ `.mtl`, `_0.png`) +- `merged_recon/output.glb` — self-contained GLB exported from the final textured mesh +- `stage1_recon/textured_mesh.obj` — Stage-1 mesh (bottom missing) +- `stage1_recon/output.glb` — self-contained GLB exported from the Stage-1 mesh + +### Key Options + +| Flag | Default | Description | +|------|---------|-------------| +| `--stage1_end_frame N` | auto | Override Stage-1 end (sequential frame index) | +| `--stage1_end_timestamp NS` | auto | Override Stage-1 end (nanosecond timestamp) | +| `--stage1_buffer_deg DEG` | 10.0 | Angle buffer before detected transition | +| `--config PATH` | bundlesdf default | NeRF/SDF config YAML | +| `--pipeline_config PATH` | `docker/data/configs/hoi_pipeline.yaml` | Pipeline config YAML | +| `--reference_frame N` | 0 | SAM2/FP reference frame | +| `--num_depth_workers N` | 2 | Parallel FoundationStereo workers | +| `--fp_weights_dir PATH` | `data/weights/foundationpose` | FoundationPose weights | + +### Skip Flags (BundleSDF) + +Resume from any checkpoint by skipping completed steps: + +``` +--skip_prepare --skip_sfm --skip_sfm_quality_check --skip_stage1_detect --skip_dino --skip_depth --skip_mask +--skip_stage1_setup --skip_stage1_nerf --skip_center_mesh +--skip_fp_tracking --skip_fp_render --skip_world_poses --skip_merged_setup --skip_full_nerf +--skip_glb_export --skip_final_fp_tracking --skip_final_fp_render +``` + +### Configuration + +**Pipeline config** — `docker/data/configs/hoi_pipeline.yaml` (override with `--pipeline_config`): + +| Section | Parameter | Default | Description | +|---------|-----------|---------|-------------| +| `stage1_detect` | `buffer_deg` | 10.0 | Angle buffer (°) before detected Stage-1 transition | +| `sfm` | `config_set` | `backpack` | CuSFM preset (`backpack` \| `av` \| `isaac` \| `rgbd`) | +| `sfm_scan_quality` | `enabled` | `true` | Validate CuSFM poses before automatic stage split | +| `sfm_scan_quality` | `min_angle_span_deg` | 600.0 | Minimum projected orbit span for the expected two-loop scan | +| `sfm_scan_quality` | `max_backtracking_fraction` | 0.25 | Maximum reverse angular motion fraction | +| `sfm_scan_quality` | `max_translation_step_m` | 2.0 | Maximum allowed consecutive CuSFM translation jump | +| `depth` | `num_workers` | 1 | FoundationStereo depth workers; increase explicitly for multi-GPU hosts | +| `foundationpose` | `reference_frame` | 0 | FP registration reference frame | +| `foundationpose` | `weights_dir` | `null` | FP weights path; `null` = `data/weights/foundationpose` | + +**NeRF/SDF config** — `modules/v2d_bundlesdf/lib/data/configs/theseus_optimizer_hawk.yaml` (override with `--config`): + +| Section | Parameter | Default | Description | +|---------|-----------|---------|-------------| +| `camera_config` | `step` | 4 | CuSFM keyframe subsampling for SDF training | +| `nerf` | `n_step` | 3000 | SDF training steps | +| `nerf` | `far` | `auto` | SDF training depth range, resolved from masked object depth | +| `nerf` | `trunc` | 0.01 | TSDF truncation distance (normalized). Larger = fewer holes | +| `nerf` | `mesh_resolution` | 0.005 | Voxel size for mesh extraction. Must be ≤ `trunc` | +| `texture_bake` | `texture_res` | 2048 | Output texture atlas resolution | +| `texture_bake` | `zfar` | `auto` | Texture-renderer clipping plane, resolved from camera distance | +| `texture_bake` | `downscale` | 1.0 | Image downscale for texture baking | +| `texture_bake` | `min_keyframe_translation` | 0.0 | Min camera translation (m) between texture keyframes | +| `texture_bake` | `min_keyframe_rotation_deg` | 5.0 | Min camera rotation (°) between texture keyframes | +| `texture_bake` | `min_keyframes` | 30 | Minimum keyframes after subsampling | + +--- + +## SAM3D Pipeline + +Single-image 3D reconstruction per representative frame. No multi-stage scan required. + +### Quick Start + +```bash +python modules/v2d_hoi_object_reconstruction/docker/run_reconstruction.py \ + --mapping_data_dir data/hoi_obj_recon/raw_data/ \ + --job_dir data/outputs/hoi_recon/ \ + --prompt "basketball" \ + --mode sam3d +``` + +With depth-assisted scale estimation: + +```bash +python modules/v2d_hoi_object_reconstruction/docker/run_reconstruction.py ... \ + --mode sam3d --sam3d_use_depth +``` + +### Pipeline Steps + +```mermaid +flowchart TD + A["Calibrated stereo input
images + frames_meta.json"] --> B["Prepare job
left/right frames, calibration, video"] + B --> C["CuSFM + scan QA
camera poses and stage boundary"] + C --> D["Grounding DINO + SAM2
object boxes and masks"] + D --> E["Select representative views
sam3d/selected_frames.json"] + E --> F["SAM3D per selected frame
mesh.glb + camera transform"] + F --> G["SRT scale and pose
output_scaled.glb"] + G --> H["Diagnostic overlays
render_debug.jpg + render_video.mp4"] + H --> I["Rank candidates
best/best_frame.json"] + I --> J["Suggested final mesh
best/output_scaled.glb"] + C -.-> K["Optional FoundationStereo
depth-assisted SRT"] + K -.-> G +``` + +### Results + +- `sam3d//mesh.glb` — raw SAM3D mesh (SAM3D camera space) +- `sam3d//srt/output_scaled.glb` — scale-corrected mesh (world space) +- `sam3d//srt/srt_result.json` — estimated scale, rotation, translation +- `sam3d//render_debug.jpg` — SAM3D mesh overlaid on source image (single frame) +- `sam3d//render_video.mp4` — textured mesh overlaid on all Stage-1 keyframes +- `sam3d/best/best_frame.json` — ranked candidate frames and selection score +- `sam3d/best/output_scaled.glb` — copied suggested best aligned mesh + +### Key Options + +| Flag | Default | Description | +|------|---------|-------------| +| `--sam3d_use_depth` | off | Use FoundationStereo depth as extra loss in SRT scale estimation | +| `--sam3d_bin_deg DEG` | 60.0 | Azimuthal bin size for frame selection | +| `--sam3d_seed N` | 42 | Random seed for SAM3D inference | +| `--sam3d_srt_max_views N` | 25 | Maximum silhouette views per SRT candidate | +| `--sam3d_srt_maxiter N` | 60 | Powell iterations per SRT optimisation | +| `--sam3d_srt_top_k N` | 1 | Axis orientations fully optimised when no SAM3D orientation prior is available | +| `--sam3d_srt_parallel N` | 8 | Candidate-level SRT workers; each worker caps native numerical threads to one | +| `--sam3d_force_srt` | off | Recompute candidates that already have a valid result and scaled mesh | + +The SRT defaults match the OSMO fast path. Candidates are independent and run +in parallel. A resumed run automatically reuses a candidate when both +`srt_result.json` and `output_scaled.glb` are valid; use `--sam3d_force_srt` to +deliberately recompute them. The underlying library retains its higher-cost +100-view, 120-iteration, top-5 defaults for direct callers that need the full +accuracy reference. + +### Skip Flags (SAM3D) + +``` +--skip_prepare --skip_sfm --skip_sfm_quality_check --skip_stage1_detect --skip_dino --skip_depth --skip_mask +--skip_select_frames --skip_sam3d --skip_srt_scale --skip_render_debug --skip_render_video +--skip_select_best_mesh +``` + +--- + +## Quality Envelope and Limitations + +### Reconstruction Trade-offs + +#### Reference Input and Final Outputs + +The reference input shows representative left-camera views from a calibrated +stereo scan. The airplane is stationary during the first scan stage and is then +rotated so the workflows can observe additional surfaces. + +![Toy-airplane reference input views](assets/expected_outputs/evt04_airplane/input_reference.gif) + +The turntables below were rendered from the final GLB produced by each +workflow. They illustrate the expected method trade-offs; visual QA should use +the acceptance criteria below rather than require an exact match to these +examples. + +| BundleSDF | SAM3D | +|:---------:|:-----:| +| ![BundleSDF final toy-airplane mesh turntable](assets/expected_outputs/evt04_airplane/bundlesdf.gif) | ![SAM3D final toy-airplane mesh turntable](assets/expected_outputs/evt04_airplane/sam3d.gif) | +| `merged_recon/output.glb` | `sam3d/best/output_scaled.glb` | + +BundleSDF and SAM3D optimize for different outcomes; their final meshes should +not be reviewed against the same visual standard. + +| Mode | Final output | Strength | Expected limitations | +|------|--------------|----------|----------------------| +| BundleSDF | `merged_recon/output.glb` | Reconstructs observed geometry with metric scale | Thin or partially observed parts can be missing or thickened. Small holes or fragments and texture bleeding between nearby parts can occur. | +| SAM3D | `sam3d/best/output_scaled.glb` | Usually produces a more visually complete shape and texture from a representative frame | Unseen geometry is generated rather than reconstructed, and shape dimensions and estimated metric scale can be less reliable. | + +#### Reference Performance + +These measurements are a reproducibility reference, not a performance SLA. +They exclude container builds and model-weight downloads. Runtime varies with +the GPU, driver, input size, selected views, and whether completed stages can be +resumed. + +| Workflow | Input / configuration | End-to-end runtime | Result | +|----------|-----------------------|--------------------|--------| +| BundleSDF | 2,433 stereo pairs, default two-stage workflow | 5,986 s (~100 min) | `merged_recon/output.glb` and final overlay produced | +| SAM3D | Same scan, 13 selected frames, default fast SRT settings | 4,130 s (~69 min) | 13 candidate meshes and `sam3d/best/output_scaled.glb` produced | + +Reference host: two NVIDIA RTX A6000 GPUs (48 GB each), driver 580.159.03, +measured on 2026-07-15. Within the SAM3D total, the 13 sequential neural mesh +inferences took 841 s (~14 min); parallel SRT scale/alignment was the largest +stage at approximately 37 minutes. + +For BundleSDF visual QA, accept the mesh when the object is recognizable, the +main body is coherent, and no defect materially changes its main geometry, +overall dimensions, or metric scale. Missing thin details, small reconstruction +fragments, minor holes, and local texture bleeding are expected limitations. +Use `fp_render_final/render.mp4` to confirm that the final mesh remains aligned +with the object. + +For SAM3D visual QA, inspect `render_debug.jpg` and `render_video.mp4` for the +selected candidate. A visually complete mesh is not by itself evidence that +unseen geometry, proportions, or metric scale are accurate. + +The current generated-mesh inventory is a practical guide, not a formal +benchmark. In general, the pipeline works best on rigid, opaque household +objects with enough visible surface area and texture for segmentation, stereo +depth, and camera tracking: boxes, bottles, cans, balls, mugs, toy tools, and +similar tabletop or carryable objects. + +Use extra visual QA for these cases: + +- **Thin or high-aspect-ratio geometry** — hoops, rackets, swords, canes, chair + legs, handles, and tool tips are easy to miss, thicken, fuse to nearby + surfaces, or reconstruct with holes. +- **Large support-like objects** — desks, tables, platforms, crates, and large + boxes need broad view coverage. Partial views often leave missing backs, + undersides, or weak texture alignment. +- **Reflective, dark, transparent, or textureless surfaces** — depth and SfM can + become unstable, and masks may leak onto background or hands. +- **Occluded hand-object interaction frames** — hands can hide important object + surfaces; BundleSDF quality depends on clean masks and coherent stereo depth + across the selected scan frames. +- **Two-stage alignment failures** — BundleSDF final meshes depend on + FoundationPose staying locked between the stationary and rotated stages. Drift + usually shows up in `fp_render/render.mp4` or `poses_world_debug.png`. +- **SAM3D scale and back-side geometry** — scale is estimated after inference, + and unseen geometry can be less reliable even when the mesh looks complete. + +For production assets, prefer an available scanner mesh as the geometric +reference. Treat HOI-generated meshes as requiring inspection with the overlay, +spin, point-cloud, and chamfer tools before accepting them. + +--- + +## Troubleshooting + +Start from the final output and work backwards. + +### BundleSDF: Bad final mesh + +**Step 1 — Check Stage-1 mesh** (`stage1_recon/textured_mesh.obj`). + +If Stage-1 mesh is bad, check inputs in order: + +1. **Masks** — Spot-check `masks/0/`. Object should be cleanly segmented in every frame. + - Wrong box: try a more specific `--prompt` (e.g. `"red spray bottle"` not `"bottle"`) + - Mask drifts: adjust `foundationpose.reference_frame` in the pipeline config + +2. **Camera poses and point cloud** — Run: + ```bash + python modules/v2d_bundlesdf/tools/visualize_reconstruction_standalone.py /stage1_recon/ + ``` + Cameras should orbit the object cleanly and the point cloud should form a coherent shape. + +3. **Surface holes** — If cameras/point cloud are good but mesh has holes: + - Increase `nerf.trunc` (default `0.01`, try `0.02`) + - Decrease `nerf.mesh_resolution`, must stay ≤ `trunc` (default `0.005`, try `0.003`) + - Increase `texture_bake.texture_res` for sharper texture (default `2048`, try `4096`) + +4. **No zero surface** — If BundleSDF logs + `Surface level must be within volume data range`, inspect + `stage1_recon/resolved_config.yaml`. + - `nerf.far` must cover the masked object depth range during SDF training. + - The default config resolves `nerf.far: auto` from masked depth; if using a custom config, use `nerf.far: auto` or set an explicit larger value. + - This is separate from `texture_bake.zfar`, which only affects texture rendering after a mesh exists. + +If Stage-1 is good but final mesh is bad, the problem is in two-stage alignment: + +1. **FP tracking** — Watch `fp_render/render.mp4`. The mesh overlay should stay locked to the object. Drifting indicates poor FoundationPose tracking. + +2. **World poses** — Inspect `poses_world_debug.png`: + - Object position (subplot 3): near-flat during Stage 1 and Stage 2 + - Angular velocity (subplot 5): spike only during stage transition + - Vertical lines show detected stage boundaries — verify they match the video + +### BundleSDF: FoundationPose weights not found + +``` +[error] FoundationPose weights not found at: ... +``` + +Download them: +```bash +python modules/v2d_foundation_pose/docker/run_download_weights.py \ + --output_dir data/weights/foundationpose +``` + +### BundleSDF: zfar clipping artifacts + +If the mesh appears sliced at a fixed distance, the zfar clipping plane is too close. This is patched in the `v2d_bundlesdf` Dockerfile — rebuild the container: +```bash +docker build -t v2d_bundlesdf modules/v2d_bundlesdf/docker/ +``` + +### SAM3D: `libEGL.so.1` missing during overlay-video rendering + +If SRT completes but `render_textured_video` exits with code 139 and reports +`Could not find library libEGL.so.1`, the local `v2d_sam3d` image predates the +EGL/Pyrender renderer dependencies. Rebuild only that image: + +```bash +python modules/v2d_sam3d/docker/build.py +``` + +Then rerun the same job with the documented skip flags. Complete SRT +candidates are reused automatically, so rebuilding the renderer does not +require regenerating meshes or scale results. + +### Internal: cross-container symlinks + +The pipeline uses **relative symlinks** to map sparse keyframe indices (from SfM) to contiguous `left{N:06d}` indices expected by BundleSDF, without copying large depth and mask files. + +All symlink targets must live under `job_dir`. The `v2d_hoi_object_reconstruction` container and the `v2d_bundlesdf` container each mount `job_dir` at a different internal path, so a relative symlink like `../../depth/000001.png` resolves correctly in both. + +**Constraints:** +- `depth/` must be a direct subdirectory of `job_dir` ✓ +- `masks/` must also be a direct subdirectory of `job_dir` ✓ + +If you supply external depth or mask directories outside `job_dir`, symlinks inside BundleSDF will be broken. Keep all intermediate data within `job_dir`. + +### FoundationPose Tracking Only + +To run FoundationPose tracking with an existing mesh (skips reconstruction): + +```bash +python modules/v2d_hoi_object_reconstruction/docker/run_reconstruction.py \ + --mapping_data_dir data/hoi_obj_recon/raw_data/ \ + --job_dir data/hoi_obj_recon/jobs/ \ + --prompt "basketball" \ + --skip_sfm --skip_stage1_detect --skip_stage1_setup \ + --skip_stage1_nerf --skip_center_mesh --skip_world_poses \ + --skip_merged_setup --skip_full_nerf +``` + +Place the mesh at `/mesh_input.obj` before running. + +--- + +## Tools + +| Tool | Location | Description | +|------|----------|-------------| +| `detect_stage1_end.py` | `v2d_hoi_object_reconstruction/lib/` | Manually inspect Stage-1 end detection from CuSFM trajectory | +| `visualize_reconstruction_standalone.py` | `v2d_bundlesdf/tools/` | Visualize camera trajectory and point cloud for reconstruction-quality checks | +| `plot_tum_file.py` | `v2d_cusfm/tools/` | Plot TUM-format trajectory file | +| `spin_mesh_video.py` | `tools/` | Render a spinning video of a mesh | +| `fuse_depth_to_pointcloud.py` | `v2d_bundlesdf/tools/` | Fuse depth maps into a point cloud | +| `view_glb.py` | `tools/` | View a `.glb` mesh file | diff --git a/third-party/video_to_data/reconstruction/modules/v2d_hoi_object_reconstruction/__init__.py b/third-party/video_to_data/reconstruction/modules/v2d_hoi_object_reconstruction/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..52a7a9daf028f654d6a02f65c99cc609a57b492f --- /dev/null +++ b/third-party/video_to_data/reconstruction/modules/v2d_hoi_object_reconstruction/__init__.py @@ -0,0 +1,2 @@ +# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 diff --git a/third-party/video_to_data/reconstruction/modules/v2d_hoi_object_reconstruction/assets/basketball_example/frame_metadata.jsonl b/third-party/video_to_data/reconstruction/modules/v2d_hoi_object_reconstruction/assets/basketball_example/frame_metadata.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..4e9b51a16fedd47dca11c29a02048a674ae713d5 --- /dev/null +++ b/third-party/video_to_data/reconstruction/modules/v2d_hoi_object_reconstruction/assets/basketball_example/frame_metadata.jsonl @@ -0,0 +1,203 @@ +{"cams":[{"filename":"front_stereo_camera_left/1771445398921412053.jpeg","id":0,"timestamp":1771445398921412000},{"filename":"front_stereo_camera_right/1771445398921412053.jpeg","id":1,"timestamp":1771445398921412000}],"frame_id":0} +{"cams":[{"filename":"front_stereo_camera_left/1771445399254733053.jpeg","id":0,"timestamp":1771445399254733000},{"filename":"front_stereo_camera_right/1771445399254733053.jpeg","id":1,"timestamp":1771445399254733000}],"frame_id":1} +{"cams":[{"filename":"front_stereo_camera_left/1771445399588055053.jpeg","id":0,"timestamp":1771445399588055000},{"filename":"front_stereo_camera_right/1771445399588055053.jpeg","id":1,"timestamp":1771445399588055000}],"frame_id":2} +{"cams":[{"filename":"front_stereo_camera_left/1771445399921377045.jpeg","id":0,"timestamp":1771445399921377000},{"filename":"front_stereo_camera_right/1771445399921377045.jpeg","id":1,"timestamp":1771445399921377000}],"frame_id":3} +{"cams":[{"filename":"front_stereo_camera_left/1771445400254693045.jpeg","id":0,"timestamp":1771445400254693000},{"filename":"front_stereo_camera_right/1771445400254693045.jpeg","id":1,"timestamp":1771445400254693000}],"frame_id":4} +{"cams":[{"filename":"front_stereo_camera_left/1771445400588032045.jpeg","id":0,"timestamp":1771445400588032000},{"filename":"front_stereo_camera_right/1771445400588032045.jpeg","id":1,"timestamp":1771445400588032000}],"frame_id":5} +{"cams":[{"filename":"front_stereo_camera_left/1771445400921353081.jpeg","id":0,"timestamp":1771445400921353000},{"filename":"front_stereo_camera_right/1771445400921353081.jpeg","id":1,"timestamp":1771445400921353000}],"frame_id":6} +{"cams":[{"filename":"front_stereo_camera_left/1771445401254674081.jpeg","id":0,"timestamp":1771445401254674000},{"filename":"front_stereo_camera_right/1771445401254674081.jpeg","id":1,"timestamp":1771445401254674000}],"frame_id":7} +{"cams":[{"filename":"front_stereo_camera_left/1771445401587995081.jpeg","id":0,"timestamp":1771445401587995000},{"filename":"front_stereo_camera_right/1771445401587995081.jpeg","id":1,"timestamp":1771445401587995000}],"frame_id":8} +{"cams":[{"filename":"front_stereo_camera_left/1771445401921334060.jpeg","id":0,"timestamp":1771445401921334000},{"filename":"front_stereo_camera_right/1771445401921334060.jpeg","id":1,"timestamp":1771445401921334000}],"frame_id":9} +{"cams":[{"filename":"front_stereo_camera_left/1771445402254654060.jpeg","id":0,"timestamp":1771445402254654000},{"filename":"front_stereo_camera_right/1771445402254654060.jpeg","id":1,"timestamp":1771445402254654000}],"frame_id":10} +{"cams":[{"filename":"front_stereo_camera_left/1771445402587975060.jpeg","id":0,"timestamp":1771445402587975000},{"filename":"front_stereo_camera_right/1771445402587975060.jpeg","id":1,"timestamp":1771445402587975000}],"frame_id":11} +{"cams":[{"filename":"front_stereo_camera_left/1771445402921296020.jpeg","id":0,"timestamp":1771445402921296000},{"filename":"front_stereo_camera_right/1771445402921296020.jpeg","id":1,"timestamp":1771445402921296000}],"frame_id":12} +{"cams":[{"filename":"front_stereo_camera_left/1771445403254617020.jpeg","id":0,"timestamp":1771445403254617000},{"filename":"front_stereo_camera_right/1771445403254617020.jpeg","id":1,"timestamp":1771445403254617000}],"frame_id":13} +{"cams":[{"filename":"front_stereo_camera_left/1771445403587955020.jpeg","id":0,"timestamp":1771445403587955000},{"filename":"front_stereo_camera_right/1771445403587955020.jpeg","id":1,"timestamp":1771445403587955000}],"frame_id":14} +{"cams":[{"filename":"front_stereo_camera_left/1771445403921276017.jpeg","id":0,"timestamp":1771445403921276000},{"filename":"front_stereo_camera_right/1771445403921276017.jpeg","id":1,"timestamp":1771445403921276000}],"frame_id":15} +{"cams":[{"filename":"front_stereo_camera_left/1771445404254597017.jpeg","id":0,"timestamp":1771445404254597000},{"filename":"front_stereo_camera_right/1771445404254597017.jpeg","id":1,"timestamp":1771445404254597000}],"frame_id":16} +{"cams":[{"filename":"front_stereo_camera_left/1771445404587918017.jpeg","id":0,"timestamp":1771445404587918000},{"filename":"front_stereo_camera_right/1771445404587918017.jpeg","id":1,"timestamp":1771445404587918000}],"frame_id":17} +{"cams":[{"filename":"front_stereo_camera_left/1771445404921238120.jpeg","id":0,"timestamp":1771445404921238000},{"filename":"front_stereo_camera_right/1771445404921238120.jpeg","id":1,"timestamp":1771445404921238000}],"frame_id":18} +{"cams":[{"filename":"front_stereo_camera_left/1771445405254580120.jpeg","id":0,"timestamp":1771445405254580000},{"filename":"front_stereo_camera_right/1771445405254580120.jpeg","id":1,"timestamp":1771445405254580000}],"frame_id":19} +{"cams":[{"filename":"front_stereo_camera_left/1771445405587902120.jpeg","id":0,"timestamp":1771445405587902000},{"filename":"front_stereo_camera_right/1771445405587902120.jpeg","id":1,"timestamp":1771445405587902000}],"frame_id":20} +{"cams":[{"filename":"front_stereo_camera_left/1771445405921219052.jpeg","id":0,"timestamp":1771445405921219000},{"filename":"front_stereo_camera_right/1771445405921219052.jpeg","id":1,"timestamp":1771445405921219000}],"frame_id":21} +{"cams":[{"filename":"front_stereo_camera_left/1771445406254540052.jpeg","id":0,"timestamp":1771445406254540000},{"filename":"front_stereo_camera_right/1771445406254540052.jpeg","id":1,"timestamp":1771445406254540000}],"frame_id":22} +{"cams":[{"filename":"front_stereo_camera_left/1771445406587879052.jpeg","id":0,"timestamp":1771445406587879000},{"filename":"front_stereo_camera_right/1771445406587879052.jpeg","id":1,"timestamp":1771445406587879000}],"frame_id":23} +{"cams":[{"filename":"front_stereo_camera_left/1771445406921199016.jpeg","id":0,"timestamp":1771445406921199000},{"filename":"front_stereo_camera_right/1771445406921199016.jpeg","id":1,"timestamp":1771445406921199000}],"frame_id":24} +{"cams":[{"filename":"front_stereo_camera_left/1771445407254520016.jpeg","id":0,"timestamp":1771445407254520000},{"filename":"front_stereo_camera_right/1771445407254520016.jpeg","id":1,"timestamp":1771445407254520000}],"frame_id":25} +{"cams":[{"filename":"front_stereo_camera_left/1771445407587841016.jpeg","id":0,"timestamp":1771445407587841000},{"filename":"front_stereo_camera_right/1771445407587841016.jpeg","id":1,"timestamp":1771445407587841000}],"frame_id":26} +{"cams":[{"filename":"front_stereo_camera_left/1771445407921162033.jpeg","id":0,"timestamp":1771445407921162000},{"filename":"front_stereo_camera_right/1771445407921162033.jpeg","id":1,"timestamp":1771445407921162000}],"frame_id":27} +{"cams":[{"filename":"front_stereo_camera_left/1771445408254500033.jpeg","id":0,"timestamp":1771445408254500000},{"filename":"front_stereo_camera_right/1771445408254500033.jpeg","id":1,"timestamp":1771445408254500000}],"frame_id":28} +{"cams":[{"filename":"front_stereo_camera_left/1771445408587821033.jpeg","id":0,"timestamp":1771445408587821000},{"filename":"front_stereo_camera_right/1771445408587821033.jpeg","id":1,"timestamp":1771445408587821000}],"frame_id":29} +{"cams":[{"filename":"front_stereo_camera_left/1771445408921142024.jpeg","id":0,"timestamp":1771445408921142000},{"filename":"front_stereo_camera_right/1771445408921142024.jpeg","id":1,"timestamp":1771445408921142000}],"frame_id":30} +{"cams":[{"filename":"front_stereo_camera_left/1771445409254463024.jpeg","id":0,"timestamp":1771445409254463000},{"filename":"front_stereo_camera_right/1771445409254463024.jpeg","id":1,"timestamp":1771445409254463000}],"frame_id":31} +{"cams":[{"filename":"front_stereo_camera_left/1771445409587802024.jpeg","id":0,"timestamp":1771445409587802000},{"filename":"front_stereo_camera_right/1771445409587802024.jpeg","id":1,"timestamp":1771445409587802000}],"frame_id":32} +{"cams":[{"filename":"front_stereo_camera_left/1771445409921122020.jpeg","id":0,"timestamp":1771445409921122000},{"filename":"front_stereo_camera_right/1771445409921122020.jpeg","id":1,"timestamp":1771445409921122000}],"frame_id":33} +{"cams":[{"filename":"front_stereo_camera_left/1771445410254443020.jpeg","id":0,"timestamp":1771445410254443000},{"filename":"front_stereo_camera_right/1771445410254443020.jpeg","id":1,"timestamp":1771445410254443000}],"frame_id":34} +{"cams":[{"filename":"front_stereo_camera_left/1771445410587765020.jpeg","id":0,"timestamp":1771445410587765000},{"filename":"front_stereo_camera_right/1771445410587765020.jpeg","id":1,"timestamp":1771445410587765000}],"frame_id":35} +{"cams":[{"filename":"front_stereo_camera_left/1771445410921087145.jpeg","id":0,"timestamp":1771445410921087000},{"filename":"front_stereo_camera_right/1771445410921087145.jpeg","id":1,"timestamp":1771445410921087000}],"frame_id":36} +{"cams":[{"filename":"front_stereo_camera_left/1771445411254427145.jpeg","id":0,"timestamp":1771445411254427000},{"filename":"front_stereo_camera_right/1771445411254427145.jpeg","id":1,"timestamp":1771445411254427000}],"frame_id":37} +{"cams":[{"filename":"front_stereo_camera_left/1771445411587744145.jpeg","id":0,"timestamp":1771445411587744000},{"filename":"front_stereo_camera_right/1771445411587744145.jpeg","id":1,"timestamp":1771445411587744000}],"frame_id":38} +{"cams":[{"filename":"front_stereo_camera_left/1771445411921065005.jpeg","id":0,"timestamp":1771445411921065000},{"filename":"front_stereo_camera_right/1771445411921065005.jpeg","id":1,"timestamp":1771445411921065000}],"frame_id":39} +{"cams":[{"filename":"front_stereo_camera_left/1771445412254386005.jpeg","id":0,"timestamp":1771445412254386000},{"filename":"front_stereo_camera_right/1771445412254386005.jpeg","id":1,"timestamp":1771445412254386000}],"frame_id":40} +{"cams":[{"filename":"front_stereo_camera_left/1771445412587707005.jpeg","id":0,"timestamp":1771445412587707000},{"filename":"front_stereo_camera_right/1771445412587707005.jpeg","id":1,"timestamp":1771445412587707000}],"frame_id":41} +{"cams":[{"filename":"front_stereo_camera_left/1771445412921046057.jpeg","id":0,"timestamp":1771445412921046000},{"filename":"front_stereo_camera_right/1771445412921046057.jpeg","id":1,"timestamp":1771445412921046000}],"frame_id":42} +{"cams":[{"filename":"front_stereo_camera_left/1771445413254366057.jpeg","id":0,"timestamp":1771445413254366000},{"filename":"front_stereo_camera_right/1771445413254366057.jpeg","id":1,"timestamp":1771445413254366000}],"frame_id":43} +{"cams":[{"filename":"front_stereo_camera_left/1771445413587687057.jpeg","id":0,"timestamp":1771445413587687000},{"filename":"front_stereo_camera_right/1771445413587687057.jpeg","id":1,"timestamp":1771445413587687000}],"frame_id":44} +{"cams":[{"filename":"front_stereo_camera_left/1771445413921008097.jpeg","id":0,"timestamp":1771445413921008000},{"filename":"front_stereo_camera_right/1771445413921008097.jpeg","id":1,"timestamp":1771445413921008000}],"frame_id":45} +{"cams":[{"filename":"front_stereo_camera_left/1771445414254347097.jpeg","id":0,"timestamp":1771445414254347000},{"filename":"front_stereo_camera_right/1771445414254347097.jpeg","id":1,"timestamp":1771445414254347000}],"frame_id":46} +{"cams":[{"filename":"front_stereo_camera_left/1771445414587667097.jpeg","id":0,"timestamp":1771445414587667000},{"filename":"front_stereo_camera_right/1771445414587667097.jpeg","id":1,"timestamp":1771445414587667000}],"frame_id":47} +{"cams":[{"filename":"front_stereo_camera_left/1771445414920988148.jpeg","id":0,"timestamp":1771445414920988000},{"filename":"front_stereo_camera_right/1771445414920988148.jpeg","id":1,"timestamp":1771445414920988000}],"frame_id":48} +{"cams":[{"filename":"front_stereo_camera_left/1771445415254309148.jpeg","id":0,"timestamp":1771445415254309000},{"filename":"front_stereo_camera_right/1771445415254309148.jpeg","id":1,"timestamp":1771445415254309000}],"frame_id":49} +{"cams":[{"filename":"front_stereo_camera_left/1771445415587630148.jpeg","id":0,"timestamp":1771445415587630000},{"filename":"front_stereo_camera_right/1771445415587630148.jpeg","id":1,"timestamp":1771445415587630000}],"frame_id":50} +{"cams":[{"filename":"front_stereo_camera_left/1771445415920969076.jpeg","id":0,"timestamp":1771445415920969000},{"filename":"front_stereo_camera_right/1771445415920969076.jpeg","id":1,"timestamp":1771445415920969000}],"frame_id":51} +{"cams":[{"filename":"front_stereo_camera_left/1771445416254290076.jpeg","id":0,"timestamp":1771445416254290000},{"filename":"front_stereo_camera_right/1771445416254290076.jpeg","id":1,"timestamp":1771445416254290000}],"frame_id":52} +{"cams":[{"filename":"front_stereo_camera_left/1771445416587612076.jpeg","id":0,"timestamp":1771445416587612000},{"filename":"front_stereo_camera_right/1771445416587612076.jpeg","id":1,"timestamp":1771445416587612000}],"frame_id":53} +{"cams":[{"filename":"front_stereo_camera_left/1771445416920934060.jpeg","id":0,"timestamp":1771445416920934000},{"filename":"front_stereo_camera_right/1771445416920934060.jpeg","id":1,"timestamp":1771445416920934000}],"frame_id":54} +{"cams":[{"filename":"front_stereo_camera_left/1771445417254255060.jpeg","id":0,"timestamp":1771445417254255000},{"filename":"front_stereo_camera_right/1771445417254255060.jpeg","id":1,"timestamp":1771445417254255000}],"frame_id":55} +{"cams":[{"filename":"front_stereo_camera_left/1771445417587591060.jpeg","id":0,"timestamp":1771445417587591000},{"filename":"front_stereo_camera_right/1771445417587591060.jpeg","id":1,"timestamp":1771445417587591000}],"frame_id":56} +{"cams":[{"filename":"front_stereo_camera_left/1771445417920911064.jpeg","id":0,"timestamp":1771445417920911000},{"filename":"front_stereo_camera_right/1771445417920911064.jpeg","id":1,"timestamp":1771445417920911000}],"frame_id":57} +{"cams":[{"filename":"front_stereo_camera_left/1771445418254232064.jpeg","id":0,"timestamp":1771445418254232000},{"filename":"front_stereo_camera_right/1771445418254232064.jpeg","id":1,"timestamp":1771445418254232000}],"frame_id":58} +{"cams":[{"filename":"front_stereo_camera_left/1771445418587553064.jpeg","id":0,"timestamp":1771445418587553000},{"filename":"front_stereo_camera_right/1771445418587553064.jpeg","id":1,"timestamp":1771445418587553000}],"frame_id":59} +{"cams":[{"filename":"front_stereo_camera_left/1771445418920892064.jpeg","id":0,"timestamp":1771445418920892000},{"filename":"front_stereo_camera_right/1771445418920892064.jpeg","id":1,"timestamp":1771445418920892000}],"frame_id":60} +{"cams":[{"filename":"front_stereo_camera_left/1771445419254212064.jpeg","id":0,"timestamp":1771445419254212000},{"filename":"front_stereo_camera_right/1771445419254212064.jpeg","id":1,"timestamp":1771445419254212000}],"frame_id":61} +{"cams":[{"filename":"front_stereo_camera_left/1771445419587533064.jpeg","id":0,"timestamp":1771445419587533000},{"filename":"front_stereo_camera_right/1771445419587533064.jpeg","id":1,"timestamp":1771445419587533000}],"frame_id":62} +{"cams":[{"filename":"front_stereo_camera_left/1771445419920854112.jpeg","id":0,"timestamp":1771445419920854000},{"filename":"front_stereo_camera_right/1771445419920854112.jpeg","id":1,"timestamp":1771445419920854000}],"frame_id":63} +{"cams":[{"filename":"front_stereo_camera_left/1771445420254175112.jpeg","id":0,"timestamp":1771445420254175000},{"filename":"front_stereo_camera_right/1771445420254175112.jpeg","id":1,"timestamp":1771445420254175000}],"frame_id":64} +{"cams":[{"filename":"front_stereo_camera_left/1771445420587514112.jpeg","id":0,"timestamp":1771445420587514000},{"filename":"front_stereo_camera_right/1771445420587514112.jpeg","id":1,"timestamp":1771445420587514000}],"frame_id":65} +{"cams":[{"filename":"front_stereo_camera_left/1771445420920834172.jpeg","id":0,"timestamp":1771445420920834000},{"filename":"front_stereo_camera_right/1771445420920834172.jpeg","id":1,"timestamp":1771445420920834000}],"frame_id":66} +{"cams":[{"filename":"front_stereo_camera_left/1771445421254155172.jpeg","id":0,"timestamp":1771445421254155000},{"filename":"front_stereo_camera_right/1771445421254155172.jpeg","id":1,"timestamp":1771445421254155000}],"frame_id":67} +{"cams":[{"filename":"front_stereo_camera_left/1771445421587476172.jpeg","id":0,"timestamp":1771445421587476000},{"filename":"front_stereo_camera_right/1771445421587476172.jpeg","id":1,"timestamp":1771445421587476000}],"frame_id":68} +{"cams":[{"filename":"front_stereo_camera_left/1771445421920797045.jpeg","id":0,"timestamp":1771445421920797000},{"filename":"front_stereo_camera_right/1771445421920797045.jpeg","id":1,"timestamp":1771445421920797000}],"frame_id":69} +{"cams":[{"filename":"front_stereo_camera_left/1771445422254137045.jpeg","id":0,"timestamp":1771445422254137000},{"filename":"front_stereo_camera_right/1771445422254137045.jpeg","id":1,"timestamp":1771445422254137000}],"frame_id":70} +{"cams":[{"filename":"front_stereo_camera_left/1771445422587458045.jpeg","id":0,"timestamp":1771445422587458000},{"filename":"front_stereo_camera_right/1771445422587458045.jpeg","id":1,"timestamp":1771445422587458000}],"frame_id":71} +{"cams":[{"filename":"front_stereo_camera_left/1771445422920780053.jpeg","id":0,"timestamp":1771445422920780000},{"filename":"front_stereo_camera_right/1771445422920780053.jpeg","id":1,"timestamp":1771445422920780000}],"frame_id":72} +{"cams":[{"filename":"front_stereo_camera_left/1771445423254102053.jpeg","id":0,"timestamp":1771445423254102000},{"filename":"front_stereo_camera_right/1771445423254102053.jpeg","id":1,"timestamp":1771445423254102000}],"frame_id":73} +{"cams":[{"filename":"front_stereo_camera_left/1771445423587437053.jpeg","id":0,"timestamp":1771445423587437000},{"filename":"front_stereo_camera_right/1771445423587437053.jpeg","id":1,"timestamp":1771445423587437000}],"frame_id":74} +{"cams":[{"filename":"front_stereo_camera_left/1771445423920757037.jpeg","id":0,"timestamp":1771445423920757000},{"filename":"front_stereo_camera_right/1771445423920757037.jpeg","id":1,"timestamp":1771445423920757000}],"frame_id":75} +{"cams":[{"filename":"front_stereo_camera_left/1771445424254078037.jpeg","id":0,"timestamp":1771445424254078000},{"filename":"front_stereo_camera_right/1771445424254078037.jpeg","id":1,"timestamp":1771445424254078000}],"frame_id":76} +{"cams":[{"filename":"front_stereo_camera_left/1771445424587399037.jpeg","id":0,"timestamp":1771445424587399000},{"filename":"front_stereo_camera_right/1771445424587399037.jpeg","id":1,"timestamp":1771445424587399000}],"frame_id":77} +{"cams":[{"filename":"front_stereo_camera_left/1771445424920720053.jpeg","id":0,"timestamp":1771445424920720000},{"filename":"front_stereo_camera_right/1771445424920720053.jpeg","id":1,"timestamp":1771445424920720000}],"frame_id":78} +{"cams":[{"filename":"front_stereo_camera_left/1771445425254058053.jpeg","id":0,"timestamp":1771445425254058000},{"filename":"front_stereo_camera_right/1771445425254058053.jpeg","id":1,"timestamp":1771445425254058000}],"frame_id":79} +{"cams":[{"filename":"front_stereo_camera_left/1771445425587379053.jpeg","id":0,"timestamp":1771445425587379000},{"filename":"front_stereo_camera_right/1771445425587379053.jpeg","id":1,"timestamp":1771445425587379000}],"frame_id":80} +{"cams":[{"filename":"front_stereo_camera_left/1771445425920700017.jpeg","id":0,"timestamp":1771445425920700000},{"filename":"front_stereo_camera_right/1771445425920700017.jpeg","id":1,"timestamp":1771445425920700000}],"frame_id":81} +{"cams":[{"filename":"front_stereo_camera_left/1771445426254021017.jpeg","id":0,"timestamp":1771445426254021000},{"filename":"front_stereo_camera_right/1771445426254021017.jpeg","id":1,"timestamp":1771445426254021000}],"frame_id":82} +{"cams":[{"filename":"front_stereo_camera_left/1771445426587341017.jpeg","id":0,"timestamp":1771445426587341000},{"filename":"front_stereo_camera_right/1771445426587341017.jpeg","id":1,"timestamp":1771445426587341000}],"frame_id":83} +{"cams":[{"filename":"front_stereo_camera_left/1771445426920680020.jpeg","id":0,"timestamp":1771445426920680000},{"filename":"front_stereo_camera_right/1771445426920680020.jpeg","id":1,"timestamp":1771445426920680000}],"frame_id":84} +{"cams":[{"filename":"front_stereo_camera_left/1771445427254001020.jpeg","id":0,"timestamp":1771445427254001000},{"filename":"front_stereo_camera_right/1771445427254001020.jpeg","id":1,"timestamp":1771445427254001000}],"frame_id":85} +{"cams":[{"filename":"front_stereo_camera_left/1771445427587322020.jpeg","id":0,"timestamp":1771445427587322000},{"filename":"front_stereo_camera_right/1771445427587322020.jpeg","id":1,"timestamp":1771445427587322000}],"frame_id":86} +{"cams":[{"filename":"front_stereo_camera_left/1771445427920643017.jpeg","id":0,"timestamp":1771445427920643000},{"filename":"front_stereo_camera_right/1771445427920643017.jpeg","id":1,"timestamp":1771445427920643000}],"frame_id":87} +{"cams":[{"filename":"front_stereo_camera_left/1771445428253983017.jpeg","id":0,"timestamp":1771445428253983000},{"filename":"front_stereo_camera_right/1771445428253983017.jpeg","id":1,"timestamp":1771445428253983000}],"frame_id":88} +{"cams":[{"filename":"front_stereo_camera_left/1771445428587305017.jpeg","id":0,"timestamp":1771445428587305000},{"filename":"front_stereo_camera_right/1771445428587305017.jpeg","id":1,"timestamp":1771445428587305000}],"frame_id":89} +{"cams":[{"filename":"front_stereo_camera_left/1771445428920627008.jpeg","id":0,"timestamp":1771445428920627000},{"filename":"front_stereo_camera_right/1771445428920627008.jpeg","id":1,"timestamp":1771445428920627000}],"frame_id":90} +{"cams":[{"filename":"front_stereo_camera_left/1771445429253944008.jpeg","id":0,"timestamp":1771445429253944000},{"filename":"front_stereo_camera_right/1771445429253944008.jpeg","id":1,"timestamp":1771445429253944000}],"frame_id":91} +{"cams":[{"filename":"front_stereo_camera_left/1771445429587264008.jpeg","id":0,"timestamp":1771445429587264000},{"filename":"front_stereo_camera_right/1771445429587264008.jpeg","id":1,"timestamp":1771445429587264000}],"frame_id":92} +{"cams":[{"filename":"front_stereo_camera_left/1771445429920603020.jpeg","id":0,"timestamp":1771445429920603000},{"filename":"front_stereo_camera_right/1771445429920603020.jpeg","id":1,"timestamp":1771445429920603000}],"frame_id":93} +{"cams":[{"filename":"front_stereo_camera_left/1771445430253924020.jpeg","id":0,"timestamp":1771445430253924000},{"filename":"front_stereo_camera_right/1771445430253924020.jpeg","id":1,"timestamp":1771445430253924000}],"frame_id":94} +{"cams":[{"filename":"front_stereo_camera_left/1771445430587245020.jpeg","id":0,"timestamp":1771445430587245000},{"filename":"front_stereo_camera_right/1771445430587245020.jpeg","id":1,"timestamp":1771445430587245000}],"frame_id":95} +{"cams":[{"filename":"front_stereo_camera_left/1771445430920566129.jpeg","id":0,"timestamp":1771445430920566000},{"filename":"front_stereo_camera_right/1771445430920566129.jpeg","id":1,"timestamp":1771445430920566000}],"frame_id":96} +{"cams":[{"filename":"front_stereo_camera_left/1771445431253886129.jpeg","id":0,"timestamp":1771445431253886000},{"filename":"front_stereo_camera_right/1771445431253886129.jpeg","id":1,"timestamp":1771445431253886000}],"frame_id":97} +{"cams":[{"filename":"front_stereo_camera_left/1771445431587225129.jpeg","id":0,"timestamp":1771445431587225000},{"filename":"front_stereo_camera_right/1771445431587225129.jpeg","id":1,"timestamp":1771445431587225000}],"frame_id":98} +{"cams":[{"filename":"front_stereo_camera_left/1771445431920546008.jpeg","id":0,"timestamp":1771445431920546000},{"filename":"front_stereo_camera_right/1771445431920546008.jpeg","id":1,"timestamp":1771445431920546000}],"frame_id":99} +{"cams":[{"filename":"front_stereo_camera_left/1771445432253867008.jpeg","id":0,"timestamp":1771445432253867000},{"filename":"front_stereo_camera_right/1771445432253867008.jpeg","id":1,"timestamp":1771445432253867000}],"frame_id":100} +{"cams":[{"filename":"front_stereo_camera_left/1771445432587187008.jpeg","id":0,"timestamp":1771445432587187000},{"filename":"front_stereo_camera_right/1771445432587187008.jpeg","id":1,"timestamp":1771445432587187000}],"frame_id":101} +{"cams":[{"filename":"front_stereo_camera_left/1771445432920526012.jpeg","id":0,"timestamp":1771445432920526000},{"filename":"front_stereo_camera_right/1771445432920526012.jpeg","id":1,"timestamp":1771445432920526000}],"frame_id":102} +{"cams":[{"filename":"front_stereo_camera_left/1771445433253847012.jpeg","id":0,"timestamp":1771445433253847000},{"filename":"front_stereo_camera_right/1771445433253847012.jpeg","id":1,"timestamp":1771445433253847000}],"frame_id":103} +{"cams":[{"filename":"front_stereo_camera_left/1771445433587168012.jpeg","id":0,"timestamp":1771445433587168000},{"filename":"front_stereo_camera_right/1771445433587168012.jpeg","id":1,"timestamp":1771445433587168000}],"frame_id":104} +{"cams":[{"filename":"front_stereo_camera_left/1771445433920489104.jpeg","id":0,"timestamp":1771445433920489000},{"filename":"front_stereo_camera_right/1771445433920489104.jpeg","id":1,"timestamp":1771445433920489000}],"frame_id":105} +{"cams":[{"filename":"front_stereo_camera_left/1771445434253809104.jpeg","id":0,"timestamp":1771445434253809000},{"filename":"front_stereo_camera_right/1771445434253809104.jpeg","id":1,"timestamp":1771445434253809000}],"frame_id":106} +{"cams":[{"filename":"front_stereo_camera_left/1771445434587151104.jpeg","id":0,"timestamp":1771445434587151000},{"filename":"front_stereo_camera_right/1771445434587151104.jpeg","id":1,"timestamp":1771445434587151000}],"frame_id":107} +{"cams":[{"filename":"front_stereo_camera_left/1771445434920473056.jpeg","id":0,"timestamp":1771445434920473000},{"filename":"front_stereo_camera_right/1771445434920473056.jpeg","id":1,"timestamp":1771445434920473000}],"frame_id":108} +{"cams":[{"filename":"front_stereo_camera_left/1771445435253790056.jpeg","id":0,"timestamp":1771445435253790000},{"filename":"front_stereo_camera_right/1771445435253790056.jpeg","id":1,"timestamp":1771445435253790000}],"frame_id":109} +{"cams":[{"filename":"front_stereo_camera_left/1771445435587110056.jpeg","id":0,"timestamp":1771445435587110000},{"filename":"front_stereo_camera_right/1771445435587110056.jpeg","id":1,"timestamp":1771445435587110000}],"frame_id":110} +{"cams":[{"filename":"front_stereo_camera_left/1771445435920431020.jpeg","id":0,"timestamp":1771445435920431000},{"filename":"front_stereo_camera_right/1771445435920431020.jpeg","id":1,"timestamp":1771445435920431000}],"frame_id":111} +{"cams":[{"filename":"front_stereo_camera_left/1771445436253770020.jpeg","id":0,"timestamp":1771445436253770000},{"filename":"front_stereo_camera_right/1771445436253770020.jpeg","id":1,"timestamp":1771445436253770000}],"frame_id":112} +{"cams":[{"filename":"front_stereo_camera_left/1771445436587091020.jpeg","id":0,"timestamp":1771445436587091000},{"filename":"front_stereo_camera_right/1771445436587091020.jpeg","id":1,"timestamp":1771445436587091000}],"frame_id":113} +{"cams":[{"filename":"front_stereo_camera_left/1771445436920411032.jpeg","id":0,"timestamp":1771445436920411000},{"filename":"front_stereo_camera_right/1771445436920411032.jpeg","id":1,"timestamp":1771445436920411000}],"frame_id":114} +{"cams":[{"filename":"front_stereo_camera_left/1771445437253732032.jpeg","id":0,"timestamp":1771445437253732000},{"filename":"front_stereo_camera_right/1771445437253732032.jpeg","id":1,"timestamp":1771445437253732000}],"frame_id":115} +{"cams":[{"filename":"front_stereo_camera_left/1771445437587071032.jpeg","id":0,"timestamp":1771445437587071000},{"filename":"front_stereo_camera_right/1771445437587071032.jpeg","id":1,"timestamp":1771445437587071000}],"frame_id":116} +{"cams":[{"filename":"front_stereo_camera_left/1771445437920392040.jpeg","id":0,"timestamp":1771445437920392000},{"filename":"front_stereo_camera_right/1771445437920392040.jpeg","id":1,"timestamp":1771445437920392000}],"frame_id":117} +{"cams":[{"filename":"front_stereo_camera_left/1771445438253712040.jpeg","id":0,"timestamp":1771445438253712000},{"filename":"front_stereo_camera_right/1771445438253712040.jpeg","id":1,"timestamp":1771445438253712000}],"frame_id":118} +{"cams":[{"filename":"front_stereo_camera_left/1771445438587033040.jpeg","id":0,"timestamp":1771445438587033000},{"filename":"front_stereo_camera_right/1771445438587033040.jpeg","id":1,"timestamp":1771445438587033000}],"frame_id":119} +{"cams":[{"filename":"front_stereo_camera_left/1771445438920354028.jpeg","id":0,"timestamp":1771445438920354000},{"filename":"front_stereo_camera_right/1771445438920354028.jpeg","id":1,"timestamp":1771445438920354000}],"frame_id":120} +{"cams":[{"filename":"front_stereo_camera_left/1771445439253693028.jpeg","id":0,"timestamp":1771445439253693000},{"filename":"front_stereo_camera_right/1771445439253693028.jpeg","id":1,"timestamp":1771445439253693000}],"frame_id":121} +{"cams":[{"filename":"front_stereo_camera_left/1771445439587014028.jpeg","id":0,"timestamp":1771445439587014000},{"filename":"front_stereo_camera_right/1771445439587014028.jpeg","id":1,"timestamp":1771445439587014000}],"frame_id":122} +{"cams":[{"filename":"front_stereo_camera_left/1771445439920336052.jpeg","id":0,"timestamp":1771445439920336000},{"filename":"front_stereo_camera_right/1771445439920336052.jpeg","id":1,"timestamp":1771445439920336000}],"frame_id":123} +{"cams":[{"filename":"front_stereo_camera_left/1771445440253658052.jpeg","id":0,"timestamp":1771445440253658000},{"filename":"front_stereo_camera_right/1771445440253658052.jpeg","id":1,"timestamp":1771445440253658000}],"frame_id":124} +{"cams":[{"filename":"front_stereo_camera_left/1771445440586997052.jpeg","id":0,"timestamp":1771445440586997000},{"filename":"front_stereo_camera_right/1771445440586997052.jpeg","id":1,"timestamp":1771445440586997000}],"frame_id":125} +{"cams":[{"filename":"front_stereo_camera_left/1771445440920315080.jpeg","id":0,"timestamp":1771445440920315000},{"filename":"front_stereo_camera_right/1771445440920315080.jpeg","id":1,"timestamp":1771445440920315000}],"frame_id":126} +{"cams":[{"filename":"front_stereo_camera_left/1771445441253635080.jpeg","id":0,"timestamp":1771445441253635000},{"filename":"front_stereo_camera_right/1771445441253635080.jpeg","id":1,"timestamp":1771445441253635000}],"frame_id":127} +{"cams":[{"filename":"front_stereo_camera_left/1771445441586956080.jpeg","id":0,"timestamp":1771445441586956000},{"filename":"front_stereo_camera_right/1771445441586956080.jpeg","id":1,"timestamp":1771445441586956000}],"frame_id":128} +{"cams":[{"filename":"front_stereo_camera_left/1771445441920277064.jpeg","id":0,"timestamp":1771445441920277000},{"filename":"front_stereo_camera_right/1771445441920277064.jpeg","id":1,"timestamp":1771445441920277000}],"frame_id":129} +{"cams":[{"filename":"front_stereo_camera_left/1771445442253616064.jpeg","id":0,"timestamp":1771445442253616000},{"filename":"front_stereo_camera_right/1771445442253616064.jpeg","id":1,"timestamp":1771445442253616000}],"frame_id":130} +{"cams":[{"filename":"front_stereo_camera_left/1771445442586936064.jpeg","id":0,"timestamp":1771445442586936000},{"filename":"front_stereo_camera_right/1771445442586936064.jpeg","id":1,"timestamp":1771445442586936000}],"frame_id":131} +{"cams":[{"filename":"front_stereo_camera_left/1771445442920257064.jpeg","id":0,"timestamp":1771445442920257000},{"filename":"front_stereo_camera_right/1771445442920257064.jpeg","id":1,"timestamp":1771445442920257000}],"frame_id":132} +{"cams":[{"filename":"front_stereo_camera_left/1771445443253578064.jpeg","id":0,"timestamp":1771445443253578000},{"filename":"front_stereo_camera_right/1771445443253578064.jpeg","id":1,"timestamp":1771445443253578000}],"frame_id":133} +{"cams":[{"filename":"front_stereo_camera_left/1771445443586899064.jpeg","id":0,"timestamp":1771445443586899000},{"filename":"front_stereo_camera_right/1771445443586899064.jpeg","id":1,"timestamp":1771445443586899000}],"frame_id":134} +{"cams":[{"filename":"front_stereo_camera_left/1771445443920237176.jpeg","id":0,"timestamp":1771445443920237000},{"filename":"front_stereo_camera_right/1771445443920237176.jpeg","id":1,"timestamp":1771445443920237000}],"frame_id":135} +{"cams":[{"filename":"front_stereo_camera_left/1771445444253558176.jpeg","id":0,"timestamp":1771445444253558000},{"filename":"front_stereo_camera_right/1771445444253558176.jpeg","id":1,"timestamp":1771445444253558000}],"frame_id":136} +{"cams":[{"filename":"front_stereo_camera_left/1771445444586879176.jpeg","id":0,"timestamp":1771445444586879000},{"filename":"front_stereo_camera_right/1771445444586879176.jpeg","id":1,"timestamp":1771445444586879000}],"frame_id":137} +{"cams":[{"filename":"front_stereo_camera_left/1771445444920200068.jpeg","id":0,"timestamp":1771445444920200000},{"filename":"front_stereo_camera_right/1771445444920200068.jpeg","id":1,"timestamp":1771445444920200000}],"frame_id":138} +{"cams":[{"filename":"front_stereo_camera_left/1771445445253539068.jpeg","id":0,"timestamp":1771445445253539000},{"filename":"front_stereo_camera_right/1771445445253539068.jpeg","id":1,"timestamp":1771445445253539000}],"frame_id":139} +{"cams":[{"filename":"front_stereo_camera_left/1771445445586860068.jpeg","id":0,"timestamp":1771445445586860000},{"filename":"front_stereo_camera_right/1771445445586860068.jpeg","id":1,"timestamp":1771445445586860000}],"frame_id":140} +{"cams":[{"filename":"front_stereo_camera_left/1771445445920182052.jpeg","id":0,"timestamp":1771445445920182000},{"filename":"front_stereo_camera_right/1771445445920182052.jpeg","id":1,"timestamp":1771445445920182000}],"frame_id":141} +{"cams":[{"filename":"front_stereo_camera_left/1771445446253504052.jpeg","id":0,"timestamp":1771445446253504000},{"filename":"front_stereo_camera_right/1771445446253504052.jpeg","id":1,"timestamp":1771445446253504000}],"frame_id":142} +{"cams":[{"filename":"front_stereo_camera_left/1771445446586825052.jpeg","id":0,"timestamp":1771445446586825000},{"filename":"front_stereo_camera_right/1771445446586825052.jpeg","id":1,"timestamp":1771445446586825000}],"frame_id":143} +{"cams":[{"filename":"front_stereo_camera_left/1771445446920160088.jpeg","id":0,"timestamp":1771445446920160000},{"filename":"front_stereo_camera_right/1771445446920160088.jpeg","id":1,"timestamp":1771445446920160000}],"frame_id":144} +{"cams":[{"filename":"front_stereo_camera_left/1771445447253481088.jpeg","id":0,"timestamp":1771445447253481000},{"filename":"front_stereo_camera_right/1771445447253481088.jpeg","id":1,"timestamp":1771445447253481000}],"frame_id":145} +{"cams":[{"filename":"front_stereo_camera_left/1771445447586802088.jpeg","id":0,"timestamp":1771445447586802000},{"filename":"front_stereo_camera_right/1771445447586802088.jpeg","id":1,"timestamp":1771445447586802000}],"frame_id":146} +{"cams":[{"filename":"front_stereo_camera_left/1771445447920123052.jpeg","id":0,"timestamp":1771445447920123000},{"filename":"front_stereo_camera_right/1771445447920123052.jpeg","id":1,"timestamp":1771445447920123000}],"frame_id":147} +{"cams":[{"filename":"front_stereo_camera_left/1771445448253443052.jpeg","id":0,"timestamp":1771445448253443000},{"filename":"front_stereo_camera_right/1771445448253443052.jpeg","id":1,"timestamp":1771445448253443000}],"frame_id":148} +{"cams":[{"filename":"front_stereo_camera_left/1771445448586782052.jpeg","id":0,"timestamp":1771445448586782000},{"filename":"front_stereo_camera_right/1771445448586782052.jpeg","id":1,"timestamp":1771445448586782000}],"frame_id":149} +{"cams":[{"filename":"front_stereo_camera_left/1771445448920103048.jpeg","id":0,"timestamp":1771445448920103000},{"filename":"front_stereo_camera_right/1771445448920103048.jpeg","id":1,"timestamp":1771445448920103000}],"frame_id":150} +{"cams":[{"filename":"front_stereo_camera_left/1771445449253424048.jpeg","id":0,"timestamp":1771445449253424000},{"filename":"front_stereo_camera_right/1771445449253424048.jpeg","id":1,"timestamp":1771445449253424000}],"frame_id":151} +{"cams":[{"filename":"front_stereo_camera_left/1771445449586744048.jpeg","id":0,"timestamp":1771445449586744000},{"filename":"front_stereo_camera_right/1771445449586744048.jpeg","id":1,"timestamp":1771445449586744000}],"frame_id":152} +{"cams":[{"filename":"front_stereo_camera_left/1771445449920083036.jpeg","id":0,"timestamp":1771445449920083000},{"filename":"front_stereo_camera_right/1771445449920083036.jpeg","id":1,"timestamp":1771445449920083000}],"frame_id":153} +{"cams":[{"filename":"front_stereo_camera_left/1771445450253404036.jpeg","id":0,"timestamp":1771445450253404000},{"filename":"front_stereo_camera_right/1771445450253404036.jpeg","id":1,"timestamp":1771445450253404000}],"frame_id":154} +{"cams":[{"filename":"front_stereo_camera_left/1771445450586725036.jpeg","id":0,"timestamp":1771445450586725000},{"filename":"front_stereo_camera_right/1771445450586725036.jpeg","id":1,"timestamp":1771445450586725000}],"frame_id":155} +{"cams":[{"filename":"front_stereo_camera_left/1771445450920045044.jpeg","id":0,"timestamp":1771445450920045000},{"filename":"front_stereo_camera_right/1771445450920045044.jpeg","id":1,"timestamp":1771445450920045000}],"frame_id":156} +{"cams":[{"filename":"front_stereo_camera_left/1771445451253366044.jpeg","id":0,"timestamp":1771445451253366000},{"filename":"front_stereo_camera_right/1771445451253366044.jpeg","id":1,"timestamp":1771445451253366000}],"frame_id":157} +{"cams":[{"filename":"front_stereo_camera_left/1771445451586706044.jpeg","id":0,"timestamp":1771445451586706000},{"filename":"front_stereo_camera_right/1771445451586706044.jpeg","id":1,"timestamp":1771445451586706000}],"frame_id":158} +{"cams":[{"filename":"front_stereo_camera_left/1771445451920028056.jpeg","id":0,"timestamp":1771445451920028000},{"filename":"front_stereo_camera_right/1771445451920028056.jpeg","id":1,"timestamp":1771445451920028000}],"frame_id":159} +{"cams":[{"filename":"front_stereo_camera_left/1771445452253350056.jpeg","id":0,"timestamp":1771445452253350000},{"filename":"front_stereo_camera_right/1771445452253350056.jpeg","id":1,"timestamp":1771445452253350000}],"frame_id":160} +{"cams":[{"filename":"front_stereo_camera_left/1771445452586671056.jpeg","id":0,"timestamp":1771445452586671000},{"filename":"front_stereo_camera_right/1771445452586671056.jpeg","id":1,"timestamp":1771445452586671000}],"frame_id":161} +{"cams":[{"filename":"front_stereo_camera_left/1771445452919988036.jpeg","id":0,"timestamp":1771445452919988000},{"filename":"front_stereo_camera_right/1771445452919988036.jpeg","id":1,"timestamp":1771445452919988000}],"frame_id":162} +{"cams":[{"filename":"front_stereo_camera_left/1771445453253327036.jpeg","id":0,"timestamp":1771445453253327000},{"filename":"front_stereo_camera_right/1771445453253327036.jpeg","id":1,"timestamp":1771445453253327000}],"frame_id":163} +{"cams":[{"filename":"front_stereo_camera_left/1771445453586647036.jpeg","id":0,"timestamp":1771445453586647000},{"filename":"front_stereo_camera_right/1771445453586647036.jpeg","id":1,"timestamp":1771445453586647000}],"frame_id":164} +{"cams":[{"filename":"front_stereo_camera_left/1771445453919968052.jpeg","id":0,"timestamp":1771445453919968000},{"filename":"front_stereo_camera_right/1771445453919968052.jpeg","id":1,"timestamp":1771445453919968000}],"frame_id":165} +{"cams":[{"filename":"front_stereo_camera_left/1771445454253289052.jpeg","id":0,"timestamp":1771445454253289000},{"filename":"front_stereo_camera_right/1771445454253289052.jpeg","id":1,"timestamp":1771445454253289000}],"frame_id":166} +{"cams":[{"filename":"front_stereo_camera_left/1771445454586628052.jpeg","id":0,"timestamp":1771445454586628000},{"filename":"front_stereo_camera_right/1771445454586628052.jpeg","id":1,"timestamp":1771445454586628000}],"frame_id":167} +{"cams":[{"filename":"front_stereo_camera_left/1771445454919948036.jpeg","id":0,"timestamp":1771445454919948000},{"filename":"front_stereo_camera_right/1771445454919948036.jpeg","id":1,"timestamp":1771445454919948000}],"frame_id":168} +{"cams":[{"filename":"front_stereo_camera_left/1771445455253269036.jpeg","id":0,"timestamp":1771445455253269000},{"filename":"front_stereo_camera_right/1771445455253269036.jpeg","id":1,"timestamp":1771445455253269000}],"frame_id":169} +{"cams":[{"filename":"front_stereo_camera_left/1771445455586590036.jpeg","id":0,"timestamp":1771445455586590000},{"filename":"front_stereo_camera_right/1771445455586590036.jpeg","id":1,"timestamp":1771445455586590000}],"frame_id":170} +{"cams":[{"filename":"front_stereo_camera_left/1771445455919911028.jpeg","id":0,"timestamp":1771445455919911000},{"filename":"front_stereo_camera_right/1771445455919911028.jpeg","id":1,"timestamp":1771445455919911000}],"frame_id":171} +{"cams":[{"filename":"front_stereo_camera_left/1771445456253250028.jpeg","id":0,"timestamp":1771445456253250000},{"filename":"front_stereo_camera_right/1771445456253250028.jpeg","id":1,"timestamp":1771445456253250000}],"frame_id":172} +{"cams":[{"filename":"front_stereo_camera_left/1771445456586570028.jpeg","id":0,"timestamp":1771445456586570000},{"filename":"front_stereo_camera_right/1771445456586570028.jpeg","id":1,"timestamp":1771445456586570000}],"frame_id":173} +{"cams":[{"filename":"front_stereo_camera_left/1771445456919891032.jpeg","id":0,"timestamp":1771445456919891000},{"filename":"front_stereo_camera_right/1771445456919891032.jpeg","id":1,"timestamp":1771445456919891000}],"frame_id":174} +{"cams":[{"filename":"front_stereo_camera_left/1771445457253212032.jpeg","id":0,"timestamp":1771445457253212000},{"filename":"front_stereo_camera_right/1771445457253212032.jpeg","id":1,"timestamp":1771445457253212000}],"frame_id":175} +{"cams":[{"filename":"front_stereo_camera_left/1771445457586533032.jpeg","id":0,"timestamp":1771445457586533000},{"filename":"front_stereo_camera_right/1771445457586533032.jpeg","id":1,"timestamp":1771445457586533000}],"frame_id":176} +{"cams":[{"filename":"front_stereo_camera_left/1771445457919874072.jpeg","id":0,"timestamp":1771445457919874000},{"filename":"front_stereo_camera_right/1771445457919874072.jpeg","id":1,"timestamp":1771445457919874000}],"frame_id":177} +{"cams":[{"filename":"front_stereo_camera_left/1771445458253196072.jpeg","id":0,"timestamp":1771445458253196000},{"filename":"front_stereo_camera_right/1771445458253196072.jpeg","id":1,"timestamp":1771445458253196000}],"frame_id":178} +{"cams":[{"filename":"front_stereo_camera_left/1771445458586513072.jpeg","id":0,"timestamp":1771445458586513000},{"filename":"front_stereo_camera_right/1771445458586513072.jpeg","id":1,"timestamp":1771445458586513000}],"frame_id":179} +{"cams":[{"filename":"front_stereo_camera_left/1771445458919833160.jpeg","id":0,"timestamp":1771445458919833000},{"filename":"front_stereo_camera_right/1771445458919833160.jpeg","id":1,"timestamp":1771445458919833000}],"frame_id":180} +{"cams":[{"filename":"front_stereo_camera_left/1771445459253172160.jpeg","id":0,"timestamp":1771445459253172000},{"filename":"front_stereo_camera_right/1771445459253172160.jpeg","id":1,"timestamp":1771445459253172000}],"frame_id":181} +{"cams":[{"filename":"front_stereo_camera_left/1771445459586493160.jpeg","id":0,"timestamp":1771445459586493000},{"filename":"front_stereo_camera_right/1771445459586493160.jpeg","id":1,"timestamp":1771445459586493000}],"frame_id":182} +{"cams":[{"filename":"front_stereo_camera_left/1771445459919814032.jpeg","id":0,"timestamp":1771445459919814000},{"filename":"front_stereo_camera_right/1771445459919814032.jpeg","id":1,"timestamp":1771445459919814000}],"frame_id":183} +{"cams":[{"filename":"front_stereo_camera_left/1771445460253134032.jpeg","id":0,"timestamp":1771445460253134000},{"filename":"front_stereo_camera_right/1771445460253134032.jpeg","id":1,"timestamp":1771445460253134000}],"frame_id":184} +{"cams":[{"filename":"front_stereo_camera_left/1771445460586455032.jpeg","id":0,"timestamp":1771445460586455000},{"filename":"front_stereo_camera_right/1771445460586455032.jpeg","id":1,"timestamp":1771445460586455000}],"frame_id":185} +{"cams":[{"filename":"front_stereo_camera_left/1771445460919794128.jpeg","id":0,"timestamp":1771445460919794000},{"filename":"front_stereo_camera_right/1771445460919794128.jpeg","id":1,"timestamp":1771445460919794000}],"frame_id":186} +{"cams":[{"filename":"front_stereo_camera_left/1771445461253115128.jpeg","id":0,"timestamp":1771445461253115000},{"filename":"front_stereo_camera_right/1771445461253115128.jpeg","id":1,"timestamp":1771445461253115000}],"frame_id":187} +{"cams":[{"filename":"front_stereo_camera_left/1771445461586435128.jpeg","id":0,"timestamp":1771445461586435000},{"filename":"front_stereo_camera_right/1771445461586435128.jpeg","id":1,"timestamp":1771445461586435000}],"frame_id":188} +{"cams":[{"filename":"front_stereo_camera_left/1771445461919756112.jpeg","id":0,"timestamp":1771445461919756000},{"filename":"front_stereo_camera_right/1771445461919756112.jpeg","id":1,"timestamp":1771445461919756000}],"frame_id":189} +{"cams":[{"filename":"front_stereo_camera_left/1771445462253077112.jpeg","id":0,"timestamp":1771445462253077000},{"filename":"front_stereo_camera_right/1771445462253077112.jpeg","id":1,"timestamp":1771445462253077000}],"frame_id":190} +{"cams":[{"filename":"front_stereo_camera_left/1771445462586416112.jpeg","id":0,"timestamp":1771445462586416000},{"filename":"front_stereo_camera_right/1771445462586416112.jpeg","id":1,"timestamp":1771445462586416000}],"frame_id":191} +{"cams":[{"filename":"front_stereo_camera_left/1771445462919736064.jpeg","id":0,"timestamp":1771445462919736000},{"filename":"front_stereo_camera_right/1771445462919736064.jpeg","id":1,"timestamp":1771445462919736000}],"frame_id":192} +{"cams":[{"filename":"front_stereo_camera_left/1771445463253058064.jpeg","id":0,"timestamp":1771445463253058000},{"filename":"front_stereo_camera_right/1771445463253058064.jpeg","id":1,"timestamp":1771445463253058000}],"frame_id":193} +{"cams":[{"filename":"front_stereo_camera_left/1771445463586380064.jpeg","id":0,"timestamp":1771445463586380000},{"filename":"front_stereo_camera_right/1771445463586380064.jpeg","id":1,"timestamp":1771445463586380000}],"frame_id":194} +{"cams":[{"filename":"front_stereo_camera_left/1771445463919699072.jpeg","id":0,"timestamp":1771445463919699000},{"filename":"front_stereo_camera_right/1771445463919699072.jpeg","id":1,"timestamp":1771445463919699000}],"frame_id":195} +{"cams":[{"filename":"front_stereo_camera_left/1771445464253041072.jpeg","id":0,"timestamp":1771445464253041000},{"filename":"front_stereo_camera_right/1771445464253041072.jpeg","id":1,"timestamp":1771445464253041000}],"frame_id":196} +{"cams":[{"filename":"front_stereo_camera_left/1771445464586358072.jpeg","id":0,"timestamp":1771445464586358000},{"filename":"front_stereo_camera_right/1771445464586358072.jpeg","id":1,"timestamp":1771445464586358000}],"frame_id":197} +{"cams":[{"filename":"front_stereo_camera_left/1771445464919679060.jpeg","id":0,"timestamp":1771445464919679000},{"filename":"front_stereo_camera_right/1771445464919679060.jpeg","id":1,"timestamp":1771445464919679000}],"frame_id":198} +{"cams":[{"filename":"front_stereo_camera_left/1771445465253000060.jpeg","id":0,"timestamp":1771445465253000000},{"filename":"front_stereo_camera_right/1771445465253000060.jpeg","id":1,"timestamp":1771445465253000000}],"frame_id":199} +{"cams":[{"filename":"front_stereo_camera_left/1771445465586339060.jpeg","id":0,"timestamp":1771445465586339000},{"filename":"front_stereo_camera_right/1771445465586339060.jpeg","id":1,"timestamp":1771445465586339000}],"frame_id":200} +{"cams":[{"filename":"front_stereo_camera_left/1771445465919659184.jpeg","id":0,"timestamp":1771445465919659000},{"filename":"front_stereo_camera_right/1771445465919659184.jpeg","id":1,"timestamp":1771445465919659000}],"frame_id":201} +{"cams":[{"filename":"front_stereo_camera_left/1771445466252980184.jpeg","id":0,"timestamp":1771445466252980000},{"filename":"front_stereo_camera_right/1771445466252980184.jpeg","id":1,"timestamp":1771445466252980000}],"frame_id":202} diff --git a/third-party/video_to_data/reconstruction/modules/v2d_hoi_object_reconstruction/assets/basketball_example/frames_meta.json b/third-party/video_to_data/reconstruction/modules/v2d_hoi_object_reconstruction/assets/basketball_example/frames_meta.json new file mode 100644 index 0000000000000000000000000000000000000000..dbacf5e4656b6e518eafbe654216af35827672cb --- /dev/null +++ b/third-party/video_to_data/reconstruction/modules/v2d_hoi_object_reconstruction/assets/basketball_example/frames_meta.json @@ -0,0 +1,3038 @@ +{ + "initial_pose_type": "EGO_MOTION", + "keyframes_metadata": [ + { + "id": "0", + "camera_params_id": "0", + "synced_sample_id": "5", + "image_name": "front_stereo_camera_left/1771445398921412053.jpeg", + "timestamp_microseconds": "1771445398921412" + }, + { + "id": "11", + "camera_params_id": "1", + "synced_sample_id": "5", + "image_name": "front_stereo_camera_right/1771445398921412053.jpeg", + "timestamp_microseconds": "1771445398921412" + }, + { + "id": "17", + "camera_params_id": "0", + "synced_sample_id": "15", + "image_name": "front_stereo_camera_left/1771445399254733053.jpeg", + "timestamp_microseconds": "1771445399254733" + }, + { + "id": "32", + "camera_params_id": "1", + "synced_sample_id": "15", + "image_name": "front_stereo_camera_right/1771445399254733053.jpeg", + "timestamp_microseconds": "1771445399254733" + }, + { + "id": "37", + "camera_params_id": "0", + "synced_sample_id": "25", + "image_name": "front_stereo_camera_left/1771445399588055053.jpeg", + "timestamp_microseconds": "1771445399588055" + }, + { + "id": "52", + "camera_params_id": "1", + "synced_sample_id": "25", + "image_name": "front_stereo_camera_right/1771445399588055053.jpeg", + "timestamp_microseconds": "1771445399588055" + }, + { + "id": "56", + "camera_params_id": "0", + "synced_sample_id": "35", + "image_name": "front_stereo_camera_left/1771445399921377045.jpeg", + "timestamp_microseconds": "1771445399921377" + }, + { + "id": "74", + "camera_params_id": "1", + "synced_sample_id": "35", + "image_name": "front_stereo_camera_right/1771445399921377045.jpeg", + "timestamp_microseconds": "1771445399921377" + }, + { + "id": "75", + "camera_params_id": "0", + "synced_sample_id": "45", + "image_name": "front_stereo_camera_left/1771445400254693045.jpeg", + "timestamp_microseconds": "1771445400254693" + }, + { + "id": "94", + "camera_params_id": "1", + "synced_sample_id": "45", + "image_name": "front_stereo_camera_right/1771445400254693045.jpeg", + "timestamp_microseconds": "1771445400254693" + }, + { + "id": "95", + "camera_params_id": "0", + "synced_sample_id": "55", + "image_name": "front_stereo_camera_left/1771445400588032045.jpeg", + "timestamp_microseconds": "1771445400588032" + }, + { + "id": "112", + "camera_params_id": "0", + "synced_sample_id": "65", + "image_name": "front_stereo_camera_left/1771445400921353081.jpeg", + "timestamp_microseconds": "1771445400921353" + }, + { + "id": "118", + "camera_params_id": "1", + "synced_sample_id": "55", + "image_name": "front_stereo_camera_right/1771445400588032045.jpeg", + "timestamp_microseconds": "1771445400588032" + }, + { + "id": "131", + "camera_params_id": "0", + "synced_sample_id": "75", + "image_name": "front_stereo_camera_left/1771445401254674081.jpeg", + "timestamp_microseconds": "1771445401254674" + }, + { + "id": "137", + "camera_params_id": "1", + "synced_sample_id": "65", + "image_name": "front_stereo_camera_right/1771445400921353081.jpeg", + "timestamp_microseconds": "1771445400921353" + }, + { + "id": "153", + "camera_params_id": "0", + "synced_sample_id": "85", + "image_name": "front_stereo_camera_left/1771445401587995081.jpeg", + "timestamp_microseconds": "1771445401587995" + }, + { + "id": "156", + "camera_params_id": "1", + "synced_sample_id": "75", + "image_name": "front_stereo_camera_right/1771445401254674081.jpeg", + "timestamp_microseconds": "1771445401254674" + }, + { + "id": "173", + "camera_params_id": "0", + "synced_sample_id": "95", + "image_name": "front_stereo_camera_left/1771445401921334060.jpeg", + "timestamp_microseconds": "1771445401921334" + }, + { + "id": "176", + "camera_params_id": "1", + "synced_sample_id": "85", + "image_name": "front_stereo_camera_right/1771445401587995081.jpeg", + "timestamp_microseconds": "1771445401587995" + }, + { + "id": "192", + "camera_params_id": "0", + "synced_sample_id": "105", + "image_name": "front_stereo_camera_left/1771445402254654060.jpeg", + "timestamp_microseconds": "1771445402254654" + }, + { + "id": "197", + "camera_params_id": "1", + "synced_sample_id": "95", + "image_name": "front_stereo_camera_right/1771445401921334060.jpeg", + "timestamp_microseconds": "1771445401921334" + }, + { + "id": "211", + "camera_params_id": "0", + "synced_sample_id": "115", + "image_name": "front_stereo_camera_left/1771445402587975060.jpeg", + "timestamp_microseconds": "1771445402587975" + }, + { + "id": "217", + "camera_params_id": "1", + "synced_sample_id": "105", + "image_name": "front_stereo_camera_right/1771445402254654060.jpeg", + "timestamp_microseconds": "1771445402254654" + }, + { + "id": "232", + "camera_params_id": "0", + "synced_sample_id": "125", + "image_name": "front_stereo_camera_left/1771445402921296020.jpeg", + "timestamp_microseconds": "1771445402921296" + }, + { + "id": "237", + "camera_params_id": "1", + "synced_sample_id": "115", + "image_name": "front_stereo_camera_right/1771445402587975060.jpeg", + "timestamp_microseconds": "1771445402587975" + }, + { + "id": "254", + "camera_params_id": "0", + "synced_sample_id": "135", + "image_name": "front_stereo_camera_left/1771445403254617020.jpeg", + "timestamp_microseconds": "1771445403254617" + }, + { + "id": "255", + "camera_params_id": "1", + "synced_sample_id": "125", + "image_name": "front_stereo_camera_right/1771445402921296020.jpeg", + "timestamp_microseconds": "1771445402921296" + }, + { + "id": "274", + "camera_params_id": "0", + "synced_sample_id": "145", + "image_name": "front_stereo_camera_left/1771445403587955020.jpeg", + "timestamp_microseconds": "1771445403587955" + }, + { + "id": "275", + "camera_params_id": "1", + "synced_sample_id": "135", + "image_name": "front_stereo_camera_right/1771445403254617020.jpeg", + "timestamp_microseconds": "1771445403254617" + }, + { + "id": "294", + "camera_params_id": "0", + "synced_sample_id": "155", + "image_name": "front_stereo_camera_left/1771445403921276017.jpeg", + "timestamp_microseconds": "1771445403921276" + }, + { + "id": "295", + "camera_params_id": "1", + "synced_sample_id": "145", + "image_name": "front_stereo_camera_right/1771445403587955020.jpeg", + "timestamp_microseconds": "1771445403587955" + }, + { + "id": "314", + "camera_params_id": "0", + "synced_sample_id": "165", + "image_name": "front_stereo_camera_left/1771445404254597017.jpeg", + "timestamp_microseconds": "1771445404254597" + }, + { + "id": "315", + "camera_params_id": "1", + "synced_sample_id": "155", + "image_name": "front_stereo_camera_right/1771445403921276017.jpeg", + "timestamp_microseconds": "1771445403921276" + }, + { + "id": "334", + "camera_params_id": "0", + "synced_sample_id": "175", + "image_name": "front_stereo_camera_left/1771445404587918017.jpeg", + "timestamp_microseconds": "1771445404587918" + }, + { + "id": "335", + "camera_params_id": "1", + "synced_sample_id": "165", + "image_name": "front_stereo_camera_right/1771445404254597017.jpeg", + "timestamp_microseconds": "1771445404254597" + }, + { + "id": "354", + "camera_params_id": "0", + "synced_sample_id": "185", + "image_name": "front_stereo_camera_left/1771445404921238120.jpeg", + "timestamp_microseconds": "1771445404921238" + }, + { + "id": "355", + "camera_params_id": "1", + "synced_sample_id": "175", + "image_name": "front_stereo_camera_right/1771445404587918017.jpeg", + "timestamp_microseconds": "1771445404587918" + }, + { + "id": "374", + "camera_params_id": "0", + "synced_sample_id": "195", + "image_name": "front_stereo_camera_left/1771445405254580120.jpeg", + "timestamp_microseconds": "1771445405254580" + }, + { + "id": "375", + "camera_params_id": "1", + "synced_sample_id": "185", + "image_name": "front_stereo_camera_right/1771445404921238120.jpeg", + "timestamp_microseconds": "1771445404921238" + }, + { + "id": "394", + "camera_params_id": "0", + "synced_sample_id": "205", + "image_name": "front_stereo_camera_left/1771445405587902120.jpeg", + "timestamp_microseconds": "1771445405587902" + }, + { + "id": "395", + "camera_params_id": "1", + "synced_sample_id": "195", + "image_name": "front_stereo_camera_right/1771445405254580120.jpeg", + "timestamp_microseconds": "1771445405254580" + }, + { + "id": "414", + "camera_params_id": "0", + "synced_sample_id": "215", + "image_name": "front_stereo_camera_left/1771445405921219052.jpeg", + "timestamp_microseconds": "1771445405921219" + }, + { + "id": "415", + "camera_params_id": "1", + "synced_sample_id": "205", + "image_name": "front_stereo_camera_right/1771445405587902120.jpeg", + "timestamp_microseconds": "1771445405587902" + }, + { + "id": "434", + "camera_params_id": "0", + "synced_sample_id": "225", + "image_name": "front_stereo_camera_left/1771445406254540052.jpeg", + "timestamp_microseconds": "1771445406254540" + }, + { + "id": "435", + "camera_params_id": "1", + "synced_sample_id": "215", + "image_name": "front_stereo_camera_right/1771445405921219052.jpeg", + "timestamp_microseconds": "1771445405921219" + }, + { + "id": "454", + "camera_params_id": "0", + "synced_sample_id": "235", + "image_name": "front_stereo_camera_left/1771445406587879052.jpeg", + "timestamp_microseconds": "1771445406587879" + }, + { + "id": "455", + "camera_params_id": "1", + "synced_sample_id": "225", + "image_name": "front_stereo_camera_right/1771445406254540052.jpeg", + "timestamp_microseconds": "1771445406254540" + }, + { + "id": "474", + "camera_params_id": "0", + "synced_sample_id": "245", + "image_name": "front_stereo_camera_left/1771445406921199016.jpeg", + "timestamp_microseconds": "1771445406921199" + }, + { + "id": "475", + "camera_params_id": "1", + "synced_sample_id": "235", + "image_name": "front_stereo_camera_right/1771445406587879052.jpeg", + "timestamp_microseconds": "1771445406587879" + }, + { + "id": "494", + "camera_params_id": "0", + "synced_sample_id": "255", + "image_name": "front_stereo_camera_left/1771445407254520016.jpeg", + "timestamp_microseconds": "1771445407254520" + }, + { + "id": "495", + "camera_params_id": "1", + "synced_sample_id": "245", + "image_name": "front_stereo_camera_right/1771445406921199016.jpeg", + "timestamp_microseconds": "1771445406921199" + }, + { + "id": "514", + "camera_params_id": "1", + "synced_sample_id": "255", + "image_name": "front_stereo_camera_right/1771445407254520016.jpeg", + "timestamp_microseconds": "1771445407254520" + }, + { + "id": "515", + "camera_params_id": "0", + "synced_sample_id": "265", + "image_name": "front_stereo_camera_left/1771445407587841016.jpeg", + "timestamp_microseconds": "1771445407587841" + }, + { + "id": "534", + "camera_params_id": "1", + "synced_sample_id": "265", + "image_name": "front_stereo_camera_right/1771445407587841016.jpeg", + "timestamp_microseconds": "1771445407587841" + }, + { + "id": "535", + "camera_params_id": "0", + "synced_sample_id": "275", + "image_name": "front_stereo_camera_left/1771445407921162033.jpeg", + "timestamp_microseconds": "1771445407921162" + }, + { + "id": "554", + "camera_params_id": "1", + "synced_sample_id": "275", + "image_name": "front_stereo_camera_right/1771445407921162033.jpeg", + "timestamp_microseconds": "1771445407921162" + }, + { + "id": "555", + "camera_params_id": "0", + "synced_sample_id": "285", + "image_name": "front_stereo_camera_left/1771445408254500033.jpeg", + "timestamp_microseconds": "1771445408254500" + }, + { + "id": "574", + "camera_params_id": "1", + "synced_sample_id": "285", + "image_name": "front_stereo_camera_right/1771445408254500033.jpeg", + "timestamp_microseconds": "1771445408254500" + }, + { + "id": "575", + "camera_params_id": "0", + "synced_sample_id": "295", + "image_name": "front_stereo_camera_left/1771445408587821033.jpeg", + "timestamp_microseconds": "1771445408587821" + }, + { + "id": "594", + "camera_params_id": "1", + "synced_sample_id": "295", + "image_name": "front_stereo_camera_right/1771445408587821033.jpeg", + "timestamp_microseconds": "1771445408587821" + }, + { + "id": "595", + "camera_params_id": "0", + "synced_sample_id": "305", + "image_name": "front_stereo_camera_left/1771445408921142024.jpeg", + "timestamp_microseconds": "1771445408921142" + }, + { + "id": "614", + "camera_params_id": "1", + "synced_sample_id": "305", + "image_name": "front_stereo_camera_right/1771445408921142024.jpeg", + "timestamp_microseconds": "1771445408921142" + }, + { + "id": "615", + "camera_params_id": "0", + "synced_sample_id": "315", + "image_name": "front_stereo_camera_left/1771445409254463024.jpeg", + "timestamp_microseconds": "1771445409254463" + }, + { + "id": "634", + "camera_params_id": "1", + "synced_sample_id": "315", + "image_name": "front_stereo_camera_right/1771445409254463024.jpeg", + "timestamp_microseconds": "1771445409254463" + }, + { + "id": "635", + "camera_params_id": "0", + "synced_sample_id": "325", + "image_name": "front_stereo_camera_left/1771445409587802024.jpeg", + "timestamp_microseconds": "1771445409587802" + }, + { + "id": "654", + "camera_params_id": "1", + "synced_sample_id": "325", + "image_name": "front_stereo_camera_right/1771445409587802024.jpeg", + "timestamp_microseconds": "1771445409587802" + }, + { + "id": "655", + "camera_params_id": "0", + "synced_sample_id": "335", + "image_name": "front_stereo_camera_left/1771445409921122020.jpeg", + "timestamp_microseconds": "1771445409921122" + }, + { + "id": "674", + "camera_params_id": "1", + "synced_sample_id": "335", + "image_name": "front_stereo_camera_right/1771445409921122020.jpeg", + "timestamp_microseconds": "1771445409921122" + }, + { + "id": "675", + "camera_params_id": "0", + "synced_sample_id": "345", + "image_name": "front_stereo_camera_left/1771445410254443020.jpeg", + "timestamp_microseconds": "1771445410254443" + }, + { + "id": "694", + "camera_params_id": "1", + "synced_sample_id": "345", + "image_name": "front_stereo_camera_right/1771445410254443020.jpeg", + "timestamp_microseconds": "1771445410254443" + }, + { + "id": "695", + "camera_params_id": "0", + "synced_sample_id": "355", + "image_name": "front_stereo_camera_left/1771445410587765020.jpeg", + "timestamp_microseconds": "1771445410587765" + }, + { + "id": "714", + "camera_params_id": "1", + "synced_sample_id": "355", + "image_name": "front_stereo_camera_right/1771445410587765020.jpeg", + "timestamp_microseconds": "1771445410587765" + }, + { + "id": "715", + "camera_params_id": "0", + "synced_sample_id": "365", + "image_name": "front_stereo_camera_left/1771445410921087145.jpeg", + "timestamp_microseconds": "1771445410921087" + }, + { + "id": "734", + "camera_params_id": "1", + "synced_sample_id": "365", + "image_name": "front_stereo_camera_right/1771445410921087145.jpeg", + "timestamp_microseconds": "1771445410921087" + }, + { + "id": "735", + "camera_params_id": "0", + "synced_sample_id": "375", + "image_name": "front_stereo_camera_left/1771445411254427145.jpeg", + "timestamp_microseconds": "1771445411254427" + }, + { + "id": "754", + "camera_params_id": "1", + "synced_sample_id": "375", + "image_name": "front_stereo_camera_right/1771445411254427145.jpeg", + "timestamp_microseconds": "1771445411254427" + }, + { + "id": "755", + "camera_params_id": "0", + "synced_sample_id": "385", + "image_name": "front_stereo_camera_left/1771445411587744145.jpeg", + "timestamp_microseconds": "1771445411587744" + }, + { + "id": "774", + "camera_params_id": "1", + "synced_sample_id": "385", + "image_name": "front_stereo_camera_right/1771445411587744145.jpeg", + "timestamp_microseconds": "1771445411587744" + }, + { + "id": "775", + "camera_params_id": "0", + "synced_sample_id": "395", + "image_name": "front_stereo_camera_left/1771445411921065005.jpeg", + "timestamp_microseconds": "1771445411921065" + }, + { + "id": "794", + "camera_params_id": "1", + "synced_sample_id": "395", + "image_name": "front_stereo_camera_right/1771445411921065005.jpeg", + "timestamp_microseconds": "1771445411921065" + }, + { + "id": "795", + "camera_params_id": "0", + "synced_sample_id": "405", + "image_name": "front_stereo_camera_left/1771445412254386005.jpeg", + "timestamp_microseconds": "1771445412254386" + }, + { + "id": "814", + "camera_params_id": "1", + "synced_sample_id": "405", + "image_name": "front_stereo_camera_right/1771445412254386005.jpeg", + "timestamp_microseconds": "1771445412254386" + }, + { + "id": "815", + "camera_params_id": "0", + "synced_sample_id": "415", + "image_name": "front_stereo_camera_left/1771445412587707005.jpeg", + "timestamp_microseconds": "1771445412587707" + }, + { + "id": "834", + "camera_params_id": "1", + "synced_sample_id": "415", + "image_name": "front_stereo_camera_right/1771445412587707005.jpeg", + "timestamp_microseconds": "1771445412587707" + }, + { + "id": "835", + "camera_params_id": "0", + "synced_sample_id": "425", + "image_name": "front_stereo_camera_left/1771445412921046057.jpeg", + "timestamp_microseconds": "1771445412921046" + }, + { + "id": "854", + "camera_params_id": "1", + "synced_sample_id": "425", + "image_name": "front_stereo_camera_right/1771445412921046057.jpeg", + "timestamp_microseconds": "1771445412921046" + }, + { + "id": "855", + "camera_params_id": "0", + "synced_sample_id": "435", + "image_name": "front_stereo_camera_left/1771445413254366057.jpeg", + "timestamp_microseconds": "1771445413254366" + }, + { + "id": "874", + "camera_params_id": "1", + "synced_sample_id": "435", + "image_name": "front_stereo_camera_right/1771445413254366057.jpeg", + "timestamp_microseconds": "1771445413254366" + }, + { + "id": "875", + "camera_params_id": "0", + "synced_sample_id": "445", + "image_name": "front_stereo_camera_left/1771445413587687057.jpeg", + "timestamp_microseconds": "1771445413587687" + }, + { + "id": "894", + "camera_params_id": "1", + "synced_sample_id": "445", + "image_name": "front_stereo_camera_right/1771445413587687057.jpeg", + "timestamp_microseconds": "1771445413587687" + }, + { + "id": "895", + "camera_params_id": "0", + "synced_sample_id": "455", + "image_name": "front_stereo_camera_left/1771445413921008097.jpeg", + "timestamp_microseconds": "1771445413921008" + }, + { + "id": "914", + "camera_params_id": "1", + "synced_sample_id": "455", + "image_name": "front_stereo_camera_right/1771445413921008097.jpeg", + "timestamp_microseconds": "1771445413921008" + }, + { + "id": "915", + "camera_params_id": "0", + "synced_sample_id": "465", + "image_name": "front_stereo_camera_left/1771445414254347097.jpeg", + "timestamp_microseconds": "1771445414254347" + }, + { + "id": "934", + "camera_params_id": "1", + "synced_sample_id": "465", + "image_name": "front_stereo_camera_right/1771445414254347097.jpeg", + "timestamp_microseconds": "1771445414254347" + }, + { + "id": "935", + "camera_params_id": "0", + "synced_sample_id": "475", + "image_name": "front_stereo_camera_left/1771445414587667097.jpeg", + "timestamp_microseconds": "1771445414587667" + }, + { + "id": "954", + "camera_params_id": "1", + "synced_sample_id": "475", + "image_name": "front_stereo_camera_right/1771445414587667097.jpeg", + "timestamp_microseconds": "1771445414587667" + }, + { + "id": "955", + "camera_params_id": "0", + "synced_sample_id": "485", + "image_name": "front_stereo_camera_left/1771445414920988148.jpeg", + "timestamp_microseconds": "1771445414920988" + }, + { + "id": "974", + "camera_params_id": "1", + "synced_sample_id": "485", + "image_name": "front_stereo_camera_right/1771445414920988148.jpeg", + "timestamp_microseconds": "1771445414920988" + }, + { + "id": "975", + "camera_params_id": "0", + "synced_sample_id": "495", + "image_name": "front_stereo_camera_left/1771445415254309148.jpeg", + "timestamp_microseconds": "1771445415254309" + }, + { + "id": "994", + "camera_params_id": "1", + "synced_sample_id": "495", + "image_name": "front_stereo_camera_right/1771445415254309148.jpeg", + "timestamp_microseconds": "1771445415254309" + }, + { + "id": "995", + "camera_params_id": "0", + "synced_sample_id": "505", + "image_name": "front_stereo_camera_left/1771445415587630148.jpeg", + "timestamp_microseconds": "1771445415587630" + }, + { + "id": "1014", + "camera_params_id": "1", + "synced_sample_id": "505", + "image_name": "front_stereo_camera_right/1771445415587630148.jpeg", + "timestamp_microseconds": "1771445415587630" + }, + { + "id": "1015", + "camera_params_id": "0", + "synced_sample_id": "515", + "image_name": "front_stereo_camera_left/1771445415920969076.jpeg", + "timestamp_microseconds": "1771445415920969" + }, + { + "id": "1034", + "camera_params_id": "1", + "synced_sample_id": "515", + "image_name": "front_stereo_camera_right/1771445415920969076.jpeg", + "timestamp_microseconds": "1771445415920969" + }, + { + "id": "1035", + "camera_params_id": "0", + "synced_sample_id": "525", + "image_name": "front_stereo_camera_left/1771445416254290076.jpeg", + "timestamp_microseconds": "1771445416254290" + }, + { + "id": "1054", + "camera_params_id": "1", + "synced_sample_id": "525", + "image_name": "front_stereo_camera_right/1771445416254290076.jpeg", + "timestamp_microseconds": "1771445416254290" + }, + { + "id": "1055", + "camera_params_id": "0", + "synced_sample_id": "535", + "image_name": "front_stereo_camera_left/1771445416587612076.jpeg", + "timestamp_microseconds": "1771445416587612" + }, + { + "id": "1074", + "camera_params_id": "1", + "synced_sample_id": "535", + "image_name": "front_stereo_camera_right/1771445416587612076.jpeg", + "timestamp_microseconds": "1771445416587612" + }, + { + "id": "1075", + "camera_params_id": "0", + "synced_sample_id": "545", + "image_name": "front_stereo_camera_left/1771445416920934060.jpeg", + "timestamp_microseconds": "1771445416920934" + }, + { + "id": "1094", + "camera_params_id": "1", + "synced_sample_id": "545", + "image_name": "front_stereo_camera_right/1771445416920934060.jpeg", + "timestamp_microseconds": "1771445416920934" + }, + { + "id": "1095", + "camera_params_id": "0", + "synced_sample_id": "555", + "image_name": "front_stereo_camera_left/1771445417254255060.jpeg", + "timestamp_microseconds": "1771445417254255" + }, + { + "id": "1114", + "camera_params_id": "1", + "synced_sample_id": "555", + "image_name": "front_stereo_camera_right/1771445417254255060.jpeg", + "timestamp_microseconds": "1771445417254255" + }, + { + "id": "1115", + "camera_params_id": "0", + "synced_sample_id": "565", + "image_name": "front_stereo_camera_left/1771445417587591060.jpeg", + "timestamp_microseconds": "1771445417587591" + }, + { + "id": "1134", + "camera_params_id": "1", + "synced_sample_id": "565", + "image_name": "front_stereo_camera_right/1771445417587591060.jpeg", + "timestamp_microseconds": "1771445417587591" + }, + { + "id": "1135", + "camera_params_id": "0", + "synced_sample_id": "575", + "image_name": "front_stereo_camera_left/1771445417920911064.jpeg", + "timestamp_microseconds": "1771445417920911" + }, + { + "id": "1154", + "camera_params_id": "1", + "synced_sample_id": "575", + "image_name": "front_stereo_camera_right/1771445417920911064.jpeg", + "timestamp_microseconds": "1771445417920911" + }, + { + "id": "1155", + "camera_params_id": "0", + "synced_sample_id": "585", + "image_name": "front_stereo_camera_left/1771445418254232064.jpeg", + "timestamp_microseconds": "1771445418254232" + }, + { + "id": "1174", + "camera_params_id": "1", + "synced_sample_id": "585", + "image_name": "front_stereo_camera_right/1771445418254232064.jpeg", + "timestamp_microseconds": "1771445418254232" + }, + { + "id": "1175", + "camera_params_id": "0", + "synced_sample_id": "595", + "image_name": "front_stereo_camera_left/1771445418587553064.jpeg", + "timestamp_microseconds": "1771445418587553" + }, + { + "id": "1194", + "camera_params_id": "1", + "synced_sample_id": "595", + "image_name": "front_stereo_camera_right/1771445418587553064.jpeg", + "timestamp_microseconds": "1771445418587553" + }, + { + "id": "1195", + "camera_params_id": "0", + "synced_sample_id": "605", + "image_name": "front_stereo_camera_left/1771445418920892064.jpeg", + "timestamp_microseconds": "1771445418920892" + }, + { + "id": "1214", + "camera_params_id": "0", + "synced_sample_id": "615", + "image_name": "front_stereo_camera_left/1771445419254212064.jpeg", + "timestamp_microseconds": "1771445419254212" + }, + { + "id": "1215", + "camera_params_id": "1", + "synced_sample_id": "605", + "image_name": "front_stereo_camera_right/1771445418920892064.jpeg", + "timestamp_microseconds": "1771445418920892" + }, + { + "id": "1234", + "camera_params_id": "0", + "synced_sample_id": "625", + "image_name": "front_stereo_camera_left/1771445419587533064.jpeg", + "timestamp_microseconds": "1771445419587533" + }, + { + "id": "1235", + "camera_params_id": "1", + "synced_sample_id": "615", + "image_name": "front_stereo_camera_right/1771445419254212064.jpeg", + "timestamp_microseconds": "1771445419254212" + }, + { + "id": "1254", + "camera_params_id": "0", + "synced_sample_id": "635", + "image_name": "front_stereo_camera_left/1771445419920854112.jpeg", + "timestamp_microseconds": "1771445419920854" + }, + { + "id": "1255", + "camera_params_id": "1", + "synced_sample_id": "625", + "image_name": "front_stereo_camera_right/1771445419587533064.jpeg", + "timestamp_microseconds": "1771445419587533" + }, + { + "id": "1274", + "camera_params_id": "0", + "synced_sample_id": "645", + "image_name": "front_stereo_camera_left/1771445420254175112.jpeg", + "timestamp_microseconds": "1771445420254175" + }, + { + "id": "1275", + "camera_params_id": "1", + "synced_sample_id": "635", + "image_name": "front_stereo_camera_right/1771445419920854112.jpeg", + "timestamp_microseconds": "1771445419920854" + }, + { + "id": "1294", + "camera_params_id": "0", + "synced_sample_id": "655", + "image_name": "front_stereo_camera_left/1771445420587514112.jpeg", + "timestamp_microseconds": "1771445420587514" + }, + { + "id": "1295", + "camera_params_id": "1", + "synced_sample_id": "645", + "image_name": "front_stereo_camera_right/1771445420254175112.jpeg", + "timestamp_microseconds": "1771445420254175" + }, + { + "id": "1314", + "camera_params_id": "0", + "synced_sample_id": "665", + "image_name": "front_stereo_camera_left/1771445420920834172.jpeg", + "timestamp_microseconds": "1771445420920834" + }, + { + "id": "1315", + "camera_params_id": "1", + "synced_sample_id": "655", + "image_name": "front_stereo_camera_right/1771445420587514112.jpeg", + "timestamp_microseconds": "1771445420587514" + }, + { + "id": "1334", + "camera_params_id": "0", + "synced_sample_id": "675", + "image_name": "front_stereo_camera_left/1771445421254155172.jpeg", + "timestamp_microseconds": "1771445421254155" + }, + { + "id": "1335", + "camera_params_id": "1", + "synced_sample_id": "665", + "image_name": "front_stereo_camera_right/1771445420920834172.jpeg", + "timestamp_microseconds": "1771445420920834" + }, + { + "id": "1354", + "camera_params_id": "0", + "synced_sample_id": "685", + "image_name": "front_stereo_camera_left/1771445421587476172.jpeg", + "timestamp_microseconds": "1771445421587476" + }, + { + "id": "1355", + "camera_params_id": "1", + "synced_sample_id": "675", + "image_name": "front_stereo_camera_right/1771445421254155172.jpeg", + "timestamp_microseconds": "1771445421254155" + }, + { + "id": "1374", + "camera_params_id": "0", + "synced_sample_id": "695", + "image_name": "front_stereo_camera_left/1771445421920797045.jpeg", + "timestamp_microseconds": "1771445421920797" + }, + { + "id": "1375", + "camera_params_id": "1", + "synced_sample_id": "685", + "image_name": "front_stereo_camera_right/1771445421587476172.jpeg", + "timestamp_microseconds": "1771445421587476" + }, + { + "id": "1394", + "camera_params_id": "0", + "synced_sample_id": "705", + "image_name": "front_stereo_camera_left/1771445422254137045.jpeg", + "timestamp_microseconds": "1771445422254137" + }, + { + "id": "1395", + "camera_params_id": "1", + "synced_sample_id": "695", + "image_name": "front_stereo_camera_right/1771445421920797045.jpeg", + "timestamp_microseconds": "1771445421920797" + }, + { + "id": "1414", + "camera_params_id": "0", + "synced_sample_id": "715", + "image_name": "front_stereo_camera_left/1771445422587458045.jpeg", + "timestamp_microseconds": "1771445422587458" + }, + { + "id": "1415", + "camera_params_id": "1", + "synced_sample_id": "705", + "image_name": "front_stereo_camera_right/1771445422254137045.jpeg", + "timestamp_microseconds": "1771445422254137" + }, + { + "id": "1434", + "camera_params_id": "0", + "synced_sample_id": "725", + "image_name": "front_stereo_camera_left/1771445422920780053.jpeg", + "timestamp_microseconds": "1771445422920780" + }, + { + "id": "1435", + "camera_params_id": "1", + "synced_sample_id": "715", + "image_name": "front_stereo_camera_right/1771445422587458045.jpeg", + "timestamp_microseconds": "1771445422587458" + }, + { + "id": "1454", + "camera_params_id": "0", + "synced_sample_id": "735", + "image_name": "front_stereo_camera_left/1771445423254102053.jpeg", + "timestamp_microseconds": "1771445423254102" + }, + { + "id": "1455", + "camera_params_id": "1", + "synced_sample_id": "725", + "image_name": "front_stereo_camera_right/1771445422920780053.jpeg", + "timestamp_microseconds": "1771445422920780" + }, + { + "id": "1474", + "camera_params_id": "0", + "synced_sample_id": "745", + "image_name": "front_stereo_camera_left/1771445423587437053.jpeg", + "timestamp_microseconds": "1771445423587437" + }, + { + "id": "1475", + "camera_params_id": "1", + "synced_sample_id": "735", + "image_name": "front_stereo_camera_right/1771445423254102053.jpeg", + "timestamp_microseconds": "1771445423254102" + }, + { + "id": "1494", + "camera_params_id": "0", + "synced_sample_id": "755", + "image_name": "front_stereo_camera_left/1771445423920757037.jpeg", + "timestamp_microseconds": "1771445423920757" + }, + { + "id": "1495", + "camera_params_id": "1", + "synced_sample_id": "745", + "image_name": "front_stereo_camera_right/1771445423587437053.jpeg", + "timestamp_microseconds": "1771445423587437" + }, + { + "id": "1514", + "camera_params_id": "0", + "synced_sample_id": "765", + "image_name": "front_stereo_camera_left/1771445424254078037.jpeg", + "timestamp_microseconds": "1771445424254078" + }, + { + "id": "1515", + "camera_params_id": "1", + "synced_sample_id": "755", + "image_name": "front_stereo_camera_right/1771445423920757037.jpeg", + "timestamp_microseconds": "1771445423920757" + }, + { + "id": "1534", + "camera_params_id": "0", + "synced_sample_id": "775", + "image_name": "front_stereo_camera_left/1771445424587399037.jpeg", + "timestamp_microseconds": "1771445424587399" + }, + { + "id": "1535", + "camera_params_id": "1", + "synced_sample_id": "765", + "image_name": "front_stereo_camera_right/1771445424254078037.jpeg", + "timestamp_microseconds": "1771445424254078" + }, + { + "id": "1554", + "camera_params_id": "0", + "synced_sample_id": "785", + "image_name": "front_stereo_camera_left/1771445424920720053.jpeg", + "timestamp_microseconds": "1771445424920720" + }, + { + "id": "1555", + "camera_params_id": "1", + "synced_sample_id": "775", + "image_name": "front_stereo_camera_right/1771445424587399037.jpeg", + "timestamp_microseconds": "1771445424587399" + }, + { + "id": "1574", + "camera_params_id": "0", + "synced_sample_id": "795", + "image_name": "front_stereo_camera_left/1771445425254058053.jpeg", + "timestamp_microseconds": "1771445425254058" + }, + { + "id": "1575", + "camera_params_id": "1", + "synced_sample_id": "785", + "image_name": "front_stereo_camera_right/1771445424920720053.jpeg", + "timestamp_microseconds": "1771445424920720" + }, + { + "id": "1594", + "camera_params_id": "0", + "synced_sample_id": "805", + "image_name": "front_stereo_camera_left/1771445425587379053.jpeg", + "timestamp_microseconds": "1771445425587379" + }, + { + "id": "1595", + "camera_params_id": "1", + "synced_sample_id": "795", + "image_name": "front_stereo_camera_right/1771445425254058053.jpeg", + "timestamp_microseconds": "1771445425254058" + }, + { + "id": "1614", + "camera_params_id": "0", + "synced_sample_id": "815", + "image_name": "front_stereo_camera_left/1771445425920700017.jpeg", + "timestamp_microseconds": "1771445425920700" + }, + { + "id": "1615", + "camera_params_id": "1", + "synced_sample_id": "805", + "image_name": "front_stereo_camera_right/1771445425587379053.jpeg", + "timestamp_microseconds": "1771445425587379" + }, + { + "id": "1634", + "camera_params_id": "0", + "synced_sample_id": "825", + "image_name": "front_stereo_camera_left/1771445426254021017.jpeg", + "timestamp_microseconds": "1771445426254021" + }, + { + "id": "1635", + "camera_params_id": "1", + "synced_sample_id": "815", + "image_name": "front_stereo_camera_right/1771445425920700017.jpeg", + "timestamp_microseconds": "1771445425920700" + }, + { + "id": "1654", + "camera_params_id": "0", + "synced_sample_id": "835", + "image_name": "front_stereo_camera_left/1771445426587341017.jpeg", + "timestamp_microseconds": "1771445426587341" + }, + { + "id": "1655", + "camera_params_id": "1", + "synced_sample_id": "825", + "image_name": "front_stereo_camera_right/1771445426254021017.jpeg", + "timestamp_microseconds": "1771445426254021" + }, + { + "id": "1674", + "camera_params_id": "0", + "synced_sample_id": "845", + "image_name": "front_stereo_camera_left/1771445426920680020.jpeg", + "timestamp_microseconds": "1771445426920680" + }, + { + "id": "1675", + "camera_params_id": "1", + "synced_sample_id": "835", + "image_name": "front_stereo_camera_right/1771445426587341017.jpeg", + "timestamp_microseconds": "1771445426587341" + }, + { + "id": "1694", + "camera_params_id": "0", + "synced_sample_id": "855", + "image_name": "front_stereo_camera_left/1771445427254001020.jpeg", + "timestamp_microseconds": "1771445427254001" + }, + { + "id": "1695", + "camera_params_id": "1", + "synced_sample_id": "845", + "image_name": "front_stereo_camera_right/1771445426920680020.jpeg", + "timestamp_microseconds": "1771445426920680" + }, + { + "id": "1714", + "camera_params_id": "0", + "synced_sample_id": "865", + "image_name": "front_stereo_camera_left/1771445427587322020.jpeg", + "timestamp_microseconds": "1771445427587322" + }, + { + "id": "1715", + "camera_params_id": "1", + "synced_sample_id": "855", + "image_name": "front_stereo_camera_right/1771445427254001020.jpeg", + "timestamp_microseconds": "1771445427254001" + }, + { + "id": "1733", + "camera_params_id": "0", + "synced_sample_id": "875", + "image_name": "front_stereo_camera_left/1771445427920643017.jpeg", + "timestamp_microseconds": "1771445427920643" + }, + { + "id": "1735", + "camera_params_id": "1", + "synced_sample_id": "865", + "image_name": "front_stereo_camera_right/1771445427587322020.jpeg", + "timestamp_microseconds": "1771445427587322" + }, + { + "id": "1754", + "camera_params_id": "0", + "synced_sample_id": "885", + "image_name": "front_stereo_camera_left/1771445428253983017.jpeg", + "timestamp_microseconds": "1771445428253983" + }, + { + "id": "1755", + "camera_params_id": "1", + "synced_sample_id": "875", + "image_name": "front_stereo_camera_right/1771445427920643017.jpeg", + "timestamp_microseconds": "1771445427920643" + }, + { + "id": "1774", + "camera_params_id": "0", + "synced_sample_id": "895", + "image_name": "front_stereo_camera_left/1771445428587305017.jpeg", + "timestamp_microseconds": "1771445428587305" + }, + { + "id": "1775", + "camera_params_id": "1", + "synced_sample_id": "885", + "image_name": "front_stereo_camera_right/1771445428253983017.jpeg", + "timestamp_microseconds": "1771445428253983" + }, + { + "id": "1794", + "camera_params_id": "0", + "synced_sample_id": "905", + "image_name": "front_stereo_camera_left/1771445428920627008.jpeg", + "timestamp_microseconds": "1771445428920627" + }, + { + "id": "1795", + "camera_params_id": "1", + "synced_sample_id": "895", + "image_name": "front_stereo_camera_right/1771445428587305017.jpeg", + "timestamp_microseconds": "1771445428587305" + }, + { + "id": "1814", + "camera_params_id": "0", + "synced_sample_id": "915", + "image_name": "front_stereo_camera_left/1771445429253944008.jpeg", + "timestamp_microseconds": "1771445429253944" + }, + { + "id": "1815", + "camera_params_id": "1", + "synced_sample_id": "905", + "image_name": "front_stereo_camera_right/1771445428920627008.jpeg", + "timestamp_microseconds": "1771445428920627" + }, + { + "id": "1834", + "camera_params_id": "0", + "synced_sample_id": "925", + "image_name": "front_stereo_camera_left/1771445429587264008.jpeg", + "timestamp_microseconds": "1771445429587264" + }, + { + "id": "1835", + "camera_params_id": "1", + "synced_sample_id": "915", + "image_name": "front_stereo_camera_right/1771445429253944008.jpeg", + "timestamp_microseconds": "1771445429253944" + }, + { + "id": "1854", + "camera_params_id": "0", + "synced_sample_id": "935", + "image_name": "front_stereo_camera_left/1771445429920603020.jpeg", + "timestamp_microseconds": "1771445429920603" + }, + { + "id": "1855", + "camera_params_id": "1", + "synced_sample_id": "925", + "image_name": "front_stereo_camera_right/1771445429587264008.jpeg", + "timestamp_microseconds": "1771445429587264" + }, + { + "id": "1874", + "camera_params_id": "0", + "synced_sample_id": "945", + "image_name": "front_stereo_camera_left/1771445430253924020.jpeg", + "timestamp_microseconds": "1771445430253924" + }, + { + "id": "1875", + "camera_params_id": "1", + "synced_sample_id": "935", + "image_name": "front_stereo_camera_right/1771445429920603020.jpeg", + "timestamp_microseconds": "1771445429920603" + }, + { + "id": "1894", + "camera_params_id": "0", + "synced_sample_id": "955", + "image_name": "front_stereo_camera_left/1771445430587245020.jpeg", + "timestamp_microseconds": "1771445430587245" + }, + { + "id": "1895", + "camera_params_id": "1", + "synced_sample_id": "945", + "image_name": "front_stereo_camera_right/1771445430253924020.jpeg", + "timestamp_microseconds": "1771445430253924" + }, + { + "id": "1914", + "camera_params_id": "0", + "synced_sample_id": "965", + "image_name": "front_stereo_camera_left/1771445430920566129.jpeg", + "timestamp_microseconds": "1771445430920566" + }, + { + "id": "1915", + "camera_params_id": "1", + "synced_sample_id": "955", + "image_name": "front_stereo_camera_right/1771445430587245020.jpeg", + "timestamp_microseconds": "1771445430587245" + }, + { + "id": "1934", + "camera_params_id": "0", + "synced_sample_id": "975", + "image_name": "front_stereo_camera_left/1771445431253886129.jpeg", + "timestamp_microseconds": "1771445431253886" + }, + { + "id": "1935", + "camera_params_id": "1", + "synced_sample_id": "965", + "image_name": "front_stereo_camera_right/1771445430920566129.jpeg", + "timestamp_microseconds": "1771445430920566" + }, + { + "id": "1954", + "camera_params_id": "0", + "synced_sample_id": "985", + "image_name": "front_stereo_camera_left/1771445431587225129.jpeg", + "timestamp_microseconds": "1771445431587225" + }, + { + "id": "1955", + "camera_params_id": "1", + "synced_sample_id": "975", + "image_name": "front_stereo_camera_right/1771445431253886129.jpeg", + "timestamp_microseconds": "1771445431253886" + }, + { + "id": "1974", + "camera_params_id": "0", + "synced_sample_id": "995", + "image_name": "front_stereo_camera_left/1771445431920546008.jpeg", + "timestamp_microseconds": "1771445431920546" + }, + { + "id": "1975", + "camera_params_id": "1", + "synced_sample_id": "985", + "image_name": "front_stereo_camera_right/1771445431587225129.jpeg", + "timestamp_microseconds": "1771445431587225" + }, + { + "id": "1994", + "camera_params_id": "0", + "synced_sample_id": "1005", + "image_name": "front_stereo_camera_left/1771445432253867008.jpeg", + "timestamp_microseconds": "1771445432253867" + }, + { + "id": "1995", + "camera_params_id": "1", + "synced_sample_id": "995", + "image_name": "front_stereo_camera_right/1771445431920546008.jpeg", + "timestamp_microseconds": "1771445431920546" + }, + { + "id": "2014", + "camera_params_id": "0", + "synced_sample_id": "1015", + "image_name": "front_stereo_camera_left/1771445432587187008.jpeg", + "timestamp_microseconds": "1771445432587187" + }, + { + "id": "2015", + "camera_params_id": "1", + "synced_sample_id": "1005", + "image_name": "front_stereo_camera_right/1771445432253867008.jpeg", + "timestamp_microseconds": "1771445432253867" + }, + { + "id": "2034", + "camera_params_id": "0", + "synced_sample_id": "1025", + "image_name": "front_stereo_camera_left/1771445432920526012.jpeg", + "timestamp_microseconds": "1771445432920526" + }, + { + "id": "2035", + "camera_params_id": "1", + "synced_sample_id": "1015", + "image_name": "front_stereo_camera_right/1771445432587187008.jpeg", + "timestamp_microseconds": "1771445432587187" + }, + { + "id": "2054", + "camera_params_id": "0", + "synced_sample_id": "1035", + "image_name": "front_stereo_camera_left/1771445433253847012.jpeg", + "timestamp_microseconds": "1771445433253847" + }, + { + "id": "2055", + "camera_params_id": "1", + "synced_sample_id": "1025", + "image_name": "front_stereo_camera_right/1771445432920526012.jpeg", + "timestamp_microseconds": "1771445432920526" + }, + { + "id": "2074", + "camera_params_id": "0", + "synced_sample_id": "1045", + "image_name": "front_stereo_camera_left/1771445433587168012.jpeg", + "timestamp_microseconds": "1771445433587168" + }, + { + "id": "2075", + "camera_params_id": "1", + "synced_sample_id": "1035", + "image_name": "front_stereo_camera_right/1771445433253847012.jpeg", + "timestamp_microseconds": "1771445433253847" + }, + { + "id": "2094", + "camera_params_id": "0", + "synced_sample_id": "1055", + "image_name": "front_stereo_camera_left/1771445433920489104.jpeg", + "timestamp_microseconds": "1771445433920489" + }, + { + "id": "2095", + "camera_params_id": "1", + "synced_sample_id": "1045", + "image_name": "front_stereo_camera_right/1771445433587168012.jpeg", + "timestamp_microseconds": "1771445433587168" + }, + { + "id": "2114", + "camera_params_id": "0", + "synced_sample_id": "1065", + "image_name": "front_stereo_camera_left/1771445434253809104.jpeg", + "timestamp_microseconds": "1771445434253809" + }, + { + "id": "2115", + "camera_params_id": "1", + "synced_sample_id": "1055", + "image_name": "front_stereo_camera_right/1771445433920489104.jpeg", + "timestamp_microseconds": "1771445433920489" + }, + { + "id": "2134", + "camera_params_id": "0", + "synced_sample_id": "1075", + "image_name": "front_stereo_camera_left/1771445434587151104.jpeg", + "timestamp_microseconds": "1771445434587151" + }, + { + "id": "2135", + "camera_params_id": "1", + "synced_sample_id": "1065", + "image_name": "front_stereo_camera_right/1771445434253809104.jpeg", + "timestamp_microseconds": "1771445434253809" + }, + { + "id": "2154", + "camera_params_id": "0", + "synced_sample_id": "1085", + "image_name": "front_stereo_camera_left/1771445434920473056.jpeg", + "timestamp_microseconds": "1771445434920473" + }, + { + "id": "2155", + "camera_params_id": "1", + "synced_sample_id": "1075", + "image_name": "front_stereo_camera_right/1771445434587151104.jpeg", + "timestamp_microseconds": "1771445434587151" + }, + { + "id": "2174", + "camera_params_id": "0", + "synced_sample_id": "1095", + "image_name": "front_stereo_camera_left/1771445435253790056.jpeg", + "timestamp_microseconds": "1771445435253790" + }, + { + "id": "2175", + "camera_params_id": "1", + "synced_sample_id": "1085", + "image_name": "front_stereo_camera_right/1771445434920473056.jpeg", + "timestamp_microseconds": "1771445434920473" + }, + { + "id": "2194", + "camera_params_id": "0", + "synced_sample_id": "1105", + "image_name": "front_stereo_camera_left/1771445435587110056.jpeg", + "timestamp_microseconds": "1771445435587110" + }, + { + "id": "2195", + "camera_params_id": "1", + "synced_sample_id": "1095", + "image_name": "front_stereo_camera_right/1771445435253790056.jpeg", + "timestamp_microseconds": "1771445435253790" + }, + { + "id": "2214", + "camera_params_id": "0", + "synced_sample_id": "1115", + "image_name": "front_stereo_camera_left/1771445435920431020.jpeg", + "timestamp_microseconds": "1771445435920431" + }, + { + "id": "2215", + "camera_params_id": "1", + "synced_sample_id": "1105", + "image_name": "front_stereo_camera_right/1771445435587110056.jpeg", + "timestamp_microseconds": "1771445435587110" + }, + { + "id": "2234", + "camera_params_id": "0", + "synced_sample_id": "1125", + "image_name": "front_stereo_camera_left/1771445436253770020.jpeg", + "timestamp_microseconds": "1771445436253770" + }, + { + "id": "2235", + "camera_params_id": "1", + "synced_sample_id": "1115", + "image_name": "front_stereo_camera_right/1771445435920431020.jpeg", + "timestamp_microseconds": "1771445435920431" + }, + { + "id": "2254", + "camera_params_id": "1", + "synced_sample_id": "1125", + "image_name": "front_stereo_camera_right/1771445436253770020.jpeg", + "timestamp_microseconds": "1771445436253770" + }, + { + "id": "2255", + "camera_params_id": "0", + "synced_sample_id": "1135", + "image_name": "front_stereo_camera_left/1771445436587091020.jpeg", + "timestamp_microseconds": "1771445436587091" + }, + { + "id": "2274", + "camera_params_id": "1", + "synced_sample_id": "1135", + "image_name": "front_stereo_camera_right/1771445436587091020.jpeg", + "timestamp_microseconds": "1771445436587091" + }, + { + "id": "2275", + "camera_params_id": "0", + "synced_sample_id": "1145", + "image_name": "front_stereo_camera_left/1771445436920411032.jpeg", + "timestamp_microseconds": "1771445436920411" + }, + { + "id": "2294", + "camera_params_id": "1", + "synced_sample_id": "1145", + "image_name": "front_stereo_camera_right/1771445436920411032.jpeg", + "timestamp_microseconds": "1771445436920411" + }, + { + "id": "2295", + "camera_params_id": "0", + "synced_sample_id": "1155", + "image_name": "front_stereo_camera_left/1771445437253732032.jpeg", + "timestamp_microseconds": "1771445437253732" + }, + { + "id": "2314", + "camera_params_id": "1", + "synced_sample_id": "1155", + "image_name": "front_stereo_camera_right/1771445437253732032.jpeg", + "timestamp_microseconds": "1771445437253732" + }, + { + "id": "2315", + "camera_params_id": "0", + "synced_sample_id": "1165", + "image_name": "front_stereo_camera_left/1771445437587071032.jpeg", + "timestamp_microseconds": "1771445437587071" + }, + { + "id": "2334", + "camera_params_id": "1", + "synced_sample_id": "1165", + "image_name": "front_stereo_camera_right/1771445437587071032.jpeg", + "timestamp_microseconds": "1771445437587071" + }, + { + "id": "2335", + "camera_params_id": "0", + "synced_sample_id": "1175", + "image_name": "front_stereo_camera_left/1771445437920392040.jpeg", + "timestamp_microseconds": "1771445437920392" + }, + { + "id": "2354", + "camera_params_id": "1", + "synced_sample_id": "1175", + "image_name": "front_stereo_camera_right/1771445437920392040.jpeg", + "timestamp_microseconds": "1771445437920392" + }, + { + "id": "2355", + "camera_params_id": "0", + "synced_sample_id": "1185", + "image_name": "front_stereo_camera_left/1771445438253712040.jpeg", + "timestamp_microseconds": "1771445438253712" + }, + { + "id": "2374", + "camera_params_id": "1", + "synced_sample_id": "1185", + "image_name": "front_stereo_camera_right/1771445438253712040.jpeg", + "timestamp_microseconds": "1771445438253712" + }, + { + "id": "2375", + "camera_params_id": "0", + "synced_sample_id": "1195", + "image_name": "front_stereo_camera_left/1771445438587033040.jpeg", + "timestamp_microseconds": "1771445438587033" + }, + { + "id": "2394", + "camera_params_id": "1", + "synced_sample_id": "1195", + "image_name": "front_stereo_camera_right/1771445438587033040.jpeg", + "timestamp_microseconds": "1771445438587033" + }, + { + "id": "2395", + "camera_params_id": "0", + "synced_sample_id": "1205", + "image_name": "front_stereo_camera_left/1771445438920354028.jpeg", + "timestamp_microseconds": "1771445438920354" + }, + { + "id": "2414", + "camera_params_id": "1", + "synced_sample_id": "1205", + "image_name": "front_stereo_camera_right/1771445438920354028.jpeg", + "timestamp_microseconds": "1771445438920354" + }, + { + "id": "2415", + "camera_params_id": "0", + "synced_sample_id": "1215", + "image_name": "front_stereo_camera_left/1771445439253693028.jpeg", + "timestamp_microseconds": "1771445439253693" + }, + { + "id": "2434", + "camera_params_id": "1", + "synced_sample_id": "1215", + "image_name": "front_stereo_camera_right/1771445439253693028.jpeg", + "timestamp_microseconds": "1771445439253693" + }, + { + "id": "2435", + "camera_params_id": "0", + "synced_sample_id": "1225", + "image_name": "front_stereo_camera_left/1771445439587014028.jpeg", + "timestamp_microseconds": "1771445439587014" + }, + { + "id": "2454", + "camera_params_id": "1", + "synced_sample_id": "1225", + "image_name": "front_stereo_camera_right/1771445439587014028.jpeg", + "timestamp_microseconds": "1771445439587014" + }, + { + "id": "2455", + "camera_params_id": "0", + "synced_sample_id": "1235", + "image_name": "front_stereo_camera_left/1771445439920336052.jpeg", + "timestamp_microseconds": "1771445439920336" + }, + { + "id": "2474", + "camera_params_id": "1", + "synced_sample_id": "1235", + "image_name": "front_stereo_camera_right/1771445439920336052.jpeg", + "timestamp_microseconds": "1771445439920336" + }, + { + "id": "2475", + "camera_params_id": "0", + "synced_sample_id": "1245", + "image_name": "front_stereo_camera_left/1771445440253658052.jpeg", + "timestamp_microseconds": "1771445440253658" + }, + { + "id": "2494", + "camera_params_id": "1", + "synced_sample_id": "1245", + "image_name": "front_stereo_camera_right/1771445440253658052.jpeg", + "timestamp_microseconds": "1771445440253658" + }, + { + "id": "2495", + "camera_params_id": "0", + "synced_sample_id": "1255", + "image_name": "front_stereo_camera_left/1771445440586997052.jpeg", + "timestamp_microseconds": "1771445440586997" + }, + { + "id": "2514", + "camera_params_id": "1", + "synced_sample_id": "1255", + "image_name": "front_stereo_camera_right/1771445440586997052.jpeg", + "timestamp_microseconds": "1771445440586997" + }, + { + "id": "2515", + "camera_params_id": "0", + "synced_sample_id": "1265", + "image_name": "front_stereo_camera_left/1771445440920315080.jpeg", + "timestamp_microseconds": "1771445440920315" + }, + { + "id": "2534", + "camera_params_id": "1", + "synced_sample_id": "1265", + "image_name": "front_stereo_camera_right/1771445440920315080.jpeg", + "timestamp_microseconds": "1771445440920315" + }, + { + "id": "2535", + "camera_params_id": "0", + "synced_sample_id": "1275", + "image_name": "front_stereo_camera_left/1771445441253635080.jpeg", + "timestamp_microseconds": "1771445441253635" + }, + { + "id": "2554", + "camera_params_id": "1", + "synced_sample_id": "1275", + "image_name": "front_stereo_camera_right/1771445441253635080.jpeg", + "timestamp_microseconds": "1771445441253635" + }, + { + "id": "2555", + "camera_params_id": "0", + "synced_sample_id": "1285", + "image_name": "front_stereo_camera_left/1771445441586956080.jpeg", + "timestamp_microseconds": "1771445441586956" + }, + { + "id": "2574", + "camera_params_id": "1", + "synced_sample_id": "1285", + "image_name": "front_stereo_camera_right/1771445441586956080.jpeg", + "timestamp_microseconds": "1771445441586956" + }, + { + "id": "2575", + "camera_params_id": "0", + "synced_sample_id": "1295", + "image_name": "front_stereo_camera_left/1771445441920277064.jpeg", + "timestamp_microseconds": "1771445441920277" + }, + { + "id": "2594", + "camera_params_id": "1", + "synced_sample_id": "1295", + "image_name": "front_stereo_camera_right/1771445441920277064.jpeg", + "timestamp_microseconds": "1771445441920277" + }, + { + "id": "2595", + "camera_params_id": "0", + "synced_sample_id": "1305", + "image_name": "front_stereo_camera_left/1771445442253616064.jpeg", + "timestamp_microseconds": "1771445442253616" + }, + { + "id": "2614", + "camera_params_id": "1", + "synced_sample_id": "1305", + "image_name": "front_stereo_camera_right/1771445442253616064.jpeg", + "timestamp_microseconds": "1771445442253616" + }, + { + "id": "2615", + "camera_params_id": "0", + "synced_sample_id": "1315", + "image_name": "front_stereo_camera_left/1771445442586936064.jpeg", + "timestamp_microseconds": "1771445442586936" + }, + { + "id": "2634", + "camera_params_id": "1", + "synced_sample_id": "1315", + "image_name": "front_stereo_camera_right/1771445442586936064.jpeg", + "timestamp_microseconds": "1771445442586936" + }, + { + "id": "2635", + "camera_params_id": "0", + "synced_sample_id": "1325", + "image_name": "front_stereo_camera_left/1771445442920257064.jpeg", + "timestamp_microseconds": "1771445442920257" + }, + { + "id": "2654", + "camera_params_id": "1", + "synced_sample_id": "1325", + "image_name": "front_stereo_camera_right/1771445442920257064.jpeg", + "timestamp_microseconds": "1771445442920257" + }, + { + "id": "2655", + "camera_params_id": "0", + "synced_sample_id": "1335", + "image_name": "front_stereo_camera_left/1771445443253578064.jpeg", + "timestamp_microseconds": "1771445443253578" + }, + { + "id": "2674", + "camera_params_id": "1", + "synced_sample_id": "1335", + "image_name": "front_stereo_camera_right/1771445443253578064.jpeg", + "timestamp_microseconds": "1771445443253578" + }, + { + "id": "2675", + "camera_params_id": "0", + "synced_sample_id": "1345", + "image_name": "front_stereo_camera_left/1771445443586899064.jpeg", + "timestamp_microseconds": "1771445443586899" + }, + { + "id": "2694", + "camera_params_id": "1", + "synced_sample_id": "1345", + "image_name": "front_stereo_camera_right/1771445443586899064.jpeg", + "timestamp_microseconds": "1771445443586899" + }, + { + "id": "2695", + "camera_params_id": "0", + "synced_sample_id": "1355", + "image_name": "front_stereo_camera_left/1771445443920237176.jpeg", + "timestamp_microseconds": "1771445443920237" + }, + { + "id": "2714", + "camera_params_id": "1", + "synced_sample_id": "1355", + "image_name": "front_stereo_camera_right/1771445443920237176.jpeg", + "timestamp_microseconds": "1771445443920237" + }, + { + "id": "2715", + "camera_params_id": "0", + "synced_sample_id": "1365", + "image_name": "front_stereo_camera_left/1771445444253558176.jpeg", + "timestamp_microseconds": "1771445444253558" + }, + { + "id": "2734", + "camera_params_id": "1", + "synced_sample_id": "1365", + "image_name": "front_stereo_camera_right/1771445444253558176.jpeg", + "timestamp_microseconds": "1771445444253558" + }, + { + "id": "2735", + "camera_params_id": "0", + "synced_sample_id": "1375", + "image_name": "front_stereo_camera_left/1771445444586879176.jpeg", + "timestamp_microseconds": "1771445444586879" + }, + { + "id": "2754", + "camera_params_id": "1", + "synced_sample_id": "1375", + "image_name": "front_stereo_camera_right/1771445444586879176.jpeg", + "timestamp_microseconds": "1771445444586879" + }, + { + "id": "2755", + "camera_params_id": "0", + "synced_sample_id": "1385", + "image_name": "front_stereo_camera_left/1771445444920200068.jpeg", + "timestamp_microseconds": "1771445444920200" + }, + { + "id": "2774", + "camera_params_id": "1", + "synced_sample_id": "1385", + "image_name": "front_stereo_camera_right/1771445444920200068.jpeg", + "timestamp_microseconds": "1771445444920200" + }, + { + "id": "2775", + "camera_params_id": "0", + "synced_sample_id": "1395", + "image_name": "front_stereo_camera_left/1771445445253539068.jpeg", + "timestamp_microseconds": "1771445445253539" + }, + { + "id": "2794", + "camera_params_id": "1", + "synced_sample_id": "1395", + "image_name": "front_stereo_camera_right/1771445445253539068.jpeg", + "timestamp_microseconds": "1771445445253539" + }, + { + "id": "2795", + "camera_params_id": "0", + "synced_sample_id": "1405", + "image_name": "front_stereo_camera_left/1771445445586860068.jpeg", + "timestamp_microseconds": "1771445445586860" + }, + { + "id": "2814", + "camera_params_id": "1", + "synced_sample_id": "1405", + "image_name": "front_stereo_camera_right/1771445445586860068.jpeg", + "timestamp_microseconds": "1771445445586860" + }, + { + "id": "2815", + "camera_params_id": "0", + "synced_sample_id": "1415", + "image_name": "front_stereo_camera_left/1771445445920182052.jpeg", + "timestamp_microseconds": "1771445445920182" + }, + { + "id": "2834", + "camera_params_id": "1", + "synced_sample_id": "1415", + "image_name": "front_stereo_camera_right/1771445445920182052.jpeg", + "timestamp_microseconds": "1771445445920182" + }, + { + "id": "2835", + "camera_params_id": "0", + "synced_sample_id": "1425", + "image_name": "front_stereo_camera_left/1771445446253504052.jpeg", + "timestamp_microseconds": "1771445446253504" + }, + { + "id": "2854", + "camera_params_id": "1", + "synced_sample_id": "1425", + "image_name": "front_stereo_camera_right/1771445446253504052.jpeg", + "timestamp_microseconds": "1771445446253504" + }, + { + "id": "2855", + "camera_params_id": "0", + "synced_sample_id": "1435", + "image_name": "front_stereo_camera_left/1771445446586825052.jpeg", + "timestamp_microseconds": "1771445446586825" + }, + { + "id": "2874", + "camera_params_id": "1", + "synced_sample_id": "1435", + "image_name": "front_stereo_camera_right/1771445446586825052.jpeg", + "timestamp_microseconds": "1771445446586825" + }, + { + "id": "2875", + "camera_params_id": "0", + "synced_sample_id": "1445", + "image_name": "front_stereo_camera_left/1771445446920160088.jpeg", + "timestamp_microseconds": "1771445446920160" + }, + { + "id": "2894", + "camera_params_id": "1", + "synced_sample_id": "1445", + "image_name": "front_stereo_camera_right/1771445446920160088.jpeg", + "timestamp_microseconds": "1771445446920160" + }, + { + "id": "2895", + "camera_params_id": "0", + "synced_sample_id": "1455", + "image_name": "front_stereo_camera_left/1771445447253481088.jpeg", + "timestamp_microseconds": "1771445447253481" + }, + { + "id": "2914", + "camera_params_id": "1", + "synced_sample_id": "1455", + "image_name": "front_stereo_camera_right/1771445447253481088.jpeg", + "timestamp_microseconds": "1771445447253481" + }, + { + "id": "2915", + "camera_params_id": "0", + "synced_sample_id": "1465", + "image_name": "front_stereo_camera_left/1771445447586802088.jpeg", + "timestamp_microseconds": "1771445447586802" + }, + { + "id": "2934", + "camera_params_id": "1", + "synced_sample_id": "1465", + "image_name": "front_stereo_camera_right/1771445447586802088.jpeg", + "timestamp_microseconds": "1771445447586802" + }, + { + "id": "2935", + "camera_params_id": "0", + "synced_sample_id": "1475", + "image_name": "front_stereo_camera_left/1771445447920123052.jpeg", + "timestamp_microseconds": "1771445447920123" + }, + { + "id": "2954", + "camera_params_id": "1", + "synced_sample_id": "1475", + "image_name": "front_stereo_camera_right/1771445447920123052.jpeg", + "timestamp_microseconds": "1771445447920123" + }, + { + "id": "2955", + "camera_params_id": "0", + "synced_sample_id": "1485", + "image_name": "front_stereo_camera_left/1771445448253443052.jpeg", + "timestamp_microseconds": "1771445448253443" + }, + { + "id": "2974", + "camera_params_id": "1", + "synced_sample_id": "1485", + "image_name": "front_stereo_camera_right/1771445448253443052.jpeg", + "timestamp_microseconds": "1771445448253443" + }, + { + "id": "2975", + "camera_params_id": "0", + "synced_sample_id": "1495", + "image_name": "front_stereo_camera_left/1771445448586782052.jpeg", + "timestamp_microseconds": "1771445448586782" + }, + { + "id": "2994", + "camera_params_id": "1", + "synced_sample_id": "1495", + "image_name": "front_stereo_camera_right/1771445448586782052.jpeg", + "timestamp_microseconds": "1771445448586782" + }, + { + "id": "2995", + "camera_params_id": "0", + "synced_sample_id": "1505", + "image_name": "front_stereo_camera_left/1771445448920103048.jpeg", + "timestamp_microseconds": "1771445448920103" + }, + { + "id": "3014", + "camera_params_id": "1", + "synced_sample_id": "1505", + "image_name": "front_stereo_camera_right/1771445448920103048.jpeg", + "timestamp_microseconds": "1771445448920103" + }, + { + "id": "3015", + "camera_params_id": "0", + "synced_sample_id": "1515", + "image_name": "front_stereo_camera_left/1771445449253424048.jpeg", + "timestamp_microseconds": "1771445449253424" + }, + { + "id": "3034", + "camera_params_id": "1", + "synced_sample_id": "1515", + "image_name": "front_stereo_camera_right/1771445449253424048.jpeg", + "timestamp_microseconds": "1771445449253424" + }, + { + "id": "3035", + "camera_params_id": "0", + "synced_sample_id": "1525", + "image_name": "front_stereo_camera_left/1771445449586744048.jpeg", + "timestamp_microseconds": "1771445449586744" + }, + { + "id": "3054", + "camera_params_id": "1", + "synced_sample_id": "1525", + "image_name": "front_stereo_camera_right/1771445449586744048.jpeg", + "timestamp_microseconds": "1771445449586744" + }, + { + "id": "3055", + "camera_params_id": "0", + "synced_sample_id": "1535", + "image_name": "front_stereo_camera_left/1771445449920083036.jpeg", + "timestamp_microseconds": "1771445449920083" + }, + { + "id": "3074", + "camera_params_id": "1", + "synced_sample_id": "1535", + "image_name": "front_stereo_camera_right/1771445449920083036.jpeg", + "timestamp_microseconds": "1771445449920083" + }, + { + "id": "3075", + "camera_params_id": "0", + "synced_sample_id": "1545", + "image_name": "front_stereo_camera_left/1771445450253404036.jpeg", + "timestamp_microseconds": "1771445450253404" + }, + { + "id": "3094", + "camera_params_id": "1", + "synced_sample_id": "1545", + "image_name": "front_stereo_camera_right/1771445450253404036.jpeg", + "timestamp_microseconds": "1771445450253404" + }, + { + "id": "3095", + "camera_params_id": "0", + "synced_sample_id": "1555", + "image_name": "front_stereo_camera_left/1771445450586725036.jpeg", + "timestamp_microseconds": "1771445450586725" + }, + { + "id": "3114", + "camera_params_id": "1", + "synced_sample_id": "1555", + "image_name": "front_stereo_camera_right/1771445450586725036.jpeg", + "timestamp_microseconds": "1771445450586725" + }, + { + "id": "3115", + "camera_params_id": "0", + "synced_sample_id": "1565", + "image_name": "front_stereo_camera_left/1771445450920045044.jpeg", + "timestamp_microseconds": "1771445450920045" + }, + { + "id": "3134", + "camera_params_id": "1", + "synced_sample_id": "1565", + "image_name": "front_stereo_camera_right/1771445450920045044.jpeg", + "timestamp_microseconds": "1771445450920045" + }, + { + "id": "3135", + "camera_params_id": "0", + "synced_sample_id": "1575", + "image_name": "front_stereo_camera_left/1771445451253366044.jpeg", + "timestamp_microseconds": "1771445451253366" + }, + { + "id": "3154", + "camera_params_id": "1", + "synced_sample_id": "1575", + "image_name": "front_stereo_camera_right/1771445451253366044.jpeg", + "timestamp_microseconds": "1771445451253366" + }, + { + "id": "3155", + "camera_params_id": "0", + "synced_sample_id": "1585", + "image_name": "front_stereo_camera_left/1771445451586706044.jpeg", + "timestamp_microseconds": "1771445451586706" + }, + { + "id": "3174", + "camera_params_id": "1", + "synced_sample_id": "1585", + "image_name": "front_stereo_camera_right/1771445451586706044.jpeg", + "timestamp_microseconds": "1771445451586706" + }, + { + "id": "3175", + "camera_params_id": "0", + "synced_sample_id": "1595", + "image_name": "front_stereo_camera_left/1771445451920028056.jpeg", + "timestamp_microseconds": "1771445451920028" + }, + { + "id": "3194", + "camera_params_id": "1", + "synced_sample_id": "1595", + "image_name": "front_stereo_camera_right/1771445451920028056.jpeg", + "timestamp_microseconds": "1771445451920028" + }, + { + "id": "3195", + "camera_params_id": "0", + "synced_sample_id": "1605", + "image_name": "front_stereo_camera_left/1771445452253350056.jpeg", + "timestamp_microseconds": "1771445452253350" + }, + { + "id": "3214", + "camera_params_id": "1", + "synced_sample_id": "1605", + "image_name": "front_stereo_camera_right/1771445452253350056.jpeg", + "timestamp_microseconds": "1771445452253350" + }, + { + "id": "3215", + "camera_params_id": "0", + "synced_sample_id": "1615", + "image_name": "front_stereo_camera_left/1771445452586671056.jpeg", + "timestamp_microseconds": "1771445452586671" + }, + { + "id": "3234", + "camera_params_id": "1", + "synced_sample_id": "1615", + "image_name": "front_stereo_camera_right/1771445452586671056.jpeg", + "timestamp_microseconds": "1771445452586671" + }, + { + "id": "3235", + "camera_params_id": "0", + "synced_sample_id": "1625", + "image_name": "front_stereo_camera_left/1771445452919988036.jpeg", + "timestamp_microseconds": "1771445452919988" + }, + { + "id": "3254", + "camera_params_id": "1", + "synced_sample_id": "1625", + "image_name": "front_stereo_camera_right/1771445452919988036.jpeg", + "timestamp_microseconds": "1771445452919988" + }, + { + "id": "3255", + "camera_params_id": "0", + "synced_sample_id": "1635", + "image_name": "front_stereo_camera_left/1771445453253327036.jpeg", + "timestamp_microseconds": "1771445453253327" + }, + { + "id": "3274", + "camera_params_id": "1", + "synced_sample_id": "1635", + "image_name": "front_stereo_camera_right/1771445453253327036.jpeg", + "timestamp_microseconds": "1771445453253327" + }, + { + "id": "3275", + "camera_params_id": "0", + "synced_sample_id": "1645", + "image_name": "front_stereo_camera_left/1771445453586647036.jpeg", + "timestamp_microseconds": "1771445453586647" + }, + { + "id": "3294", + "camera_params_id": "1", + "synced_sample_id": "1645", + "image_name": "front_stereo_camera_right/1771445453586647036.jpeg", + "timestamp_microseconds": "1771445453586647" + }, + { + "id": "3295", + "camera_params_id": "0", + "synced_sample_id": "1655", + "image_name": "front_stereo_camera_left/1771445453919968052.jpeg", + "timestamp_microseconds": "1771445453919968" + }, + { + "id": "3314", + "camera_params_id": "1", + "synced_sample_id": "1655", + "image_name": "front_stereo_camera_right/1771445453919968052.jpeg", + "timestamp_microseconds": "1771445453919968" + }, + { + "id": "3315", + "camera_params_id": "0", + "synced_sample_id": "1665", + "image_name": "front_stereo_camera_left/1771445454253289052.jpeg", + "timestamp_microseconds": "1771445454253289" + }, + { + "id": "3334", + "camera_params_id": "1", + "synced_sample_id": "1665", + "image_name": "front_stereo_camera_right/1771445454253289052.jpeg", + "timestamp_microseconds": "1771445454253289" + }, + { + "id": "3335", + "camera_params_id": "0", + "synced_sample_id": "1675", + "image_name": "front_stereo_camera_left/1771445454586628052.jpeg", + "timestamp_microseconds": "1771445454586628" + }, + { + "id": "3354", + "camera_params_id": "1", + "synced_sample_id": "1675", + "image_name": "front_stereo_camera_right/1771445454586628052.jpeg", + "timestamp_microseconds": "1771445454586628" + }, + { + "id": "3355", + "camera_params_id": "0", + "synced_sample_id": "1685", + "image_name": "front_stereo_camera_left/1771445454919948036.jpeg", + "timestamp_microseconds": "1771445454919948" + }, + { + "id": "3374", + "camera_params_id": "1", + "synced_sample_id": "1685", + "image_name": "front_stereo_camera_right/1771445454919948036.jpeg", + "timestamp_microseconds": "1771445454919948" + }, + { + "id": "3375", + "camera_params_id": "0", + "synced_sample_id": "1695", + "image_name": "front_stereo_camera_left/1771445455253269036.jpeg", + "timestamp_microseconds": "1771445455253269" + }, + { + "id": "3394", + "camera_params_id": "1", + "synced_sample_id": "1695", + "image_name": "front_stereo_camera_right/1771445455253269036.jpeg", + "timestamp_microseconds": "1771445455253269" + }, + { + "id": "3395", + "camera_params_id": "0", + "synced_sample_id": "1705", + "image_name": "front_stereo_camera_left/1771445455586590036.jpeg", + "timestamp_microseconds": "1771445455586590" + }, + { + "id": "3414", + "camera_params_id": "1", + "synced_sample_id": "1705", + "image_name": "front_stereo_camera_right/1771445455586590036.jpeg", + "timestamp_microseconds": "1771445455586590" + }, + { + "id": "3415", + "camera_params_id": "0", + "synced_sample_id": "1715", + "image_name": "front_stereo_camera_left/1771445455919911028.jpeg", + "timestamp_microseconds": "1771445455919911" + }, + { + "id": "3434", + "camera_params_id": "1", + "synced_sample_id": "1715", + "image_name": "front_stereo_camera_right/1771445455919911028.jpeg", + "timestamp_microseconds": "1771445455919911" + }, + { + "id": "3435", + "camera_params_id": "0", + "synced_sample_id": "1725", + "image_name": "front_stereo_camera_left/1771445456253250028.jpeg", + "timestamp_microseconds": "1771445456253250" + }, + { + "id": "3454", + "camera_params_id": "1", + "synced_sample_id": "1725", + "image_name": "front_stereo_camera_right/1771445456253250028.jpeg", + "timestamp_microseconds": "1771445456253250" + }, + { + "id": "3455", + "camera_params_id": "0", + "synced_sample_id": "1735", + "image_name": "front_stereo_camera_left/1771445456586570028.jpeg", + "timestamp_microseconds": "1771445456586570" + }, + { + "id": "3474", + "camera_params_id": "1", + "synced_sample_id": "1735", + "image_name": "front_stereo_camera_right/1771445456586570028.jpeg", + "timestamp_microseconds": "1771445456586570" + }, + { + "id": "3475", + "camera_params_id": "0", + "synced_sample_id": "1745", + "image_name": "front_stereo_camera_left/1771445456919891032.jpeg", + "timestamp_microseconds": "1771445456919891" + }, + { + "id": "3494", + "camera_params_id": "1", + "synced_sample_id": "1745", + "image_name": "front_stereo_camera_right/1771445456919891032.jpeg", + "timestamp_microseconds": "1771445456919891" + }, + { + "id": "3495", + "camera_params_id": "0", + "synced_sample_id": "1755", + "image_name": "front_stereo_camera_left/1771445457253212032.jpeg", + "timestamp_microseconds": "1771445457253212" + }, + { + "id": "3514", + "camera_params_id": "1", + "synced_sample_id": "1755", + "image_name": "front_stereo_camera_right/1771445457253212032.jpeg", + "timestamp_microseconds": "1771445457253212" + }, + { + "id": "3515", + "camera_params_id": "0", + "synced_sample_id": "1765", + "image_name": "front_stereo_camera_left/1771445457586533032.jpeg", + "timestamp_microseconds": "1771445457586533" + }, + { + "id": "3534", + "camera_params_id": "1", + "synced_sample_id": "1765", + "image_name": "front_stereo_camera_right/1771445457586533032.jpeg", + "timestamp_microseconds": "1771445457586533" + }, + { + "id": "3535", + "camera_params_id": "0", + "synced_sample_id": "1775", + "image_name": "front_stereo_camera_left/1771445457919874072.jpeg", + "timestamp_microseconds": "1771445457919874" + }, + { + "id": "3554", + "camera_params_id": "1", + "synced_sample_id": "1775", + "image_name": "front_stereo_camera_right/1771445457919874072.jpeg", + "timestamp_microseconds": "1771445457919874" + }, + { + "id": "3555", + "camera_params_id": "0", + "synced_sample_id": "1785", + "image_name": "front_stereo_camera_left/1771445458253196072.jpeg", + "timestamp_microseconds": "1771445458253196" + }, + { + "id": "3574", + "camera_params_id": "1", + "synced_sample_id": "1785", + "image_name": "front_stereo_camera_right/1771445458253196072.jpeg", + "timestamp_microseconds": "1771445458253196" + }, + { + "id": "3575", + "camera_params_id": "0", + "synced_sample_id": "1795", + "image_name": "front_stereo_camera_left/1771445458586513072.jpeg", + "timestamp_microseconds": "1771445458586513" + }, + { + "id": "3594", + "camera_params_id": "1", + "synced_sample_id": "1795", + "image_name": "front_stereo_camera_right/1771445458586513072.jpeg", + "timestamp_microseconds": "1771445458586513" + }, + { + "id": "3595", + "camera_params_id": "0", + "synced_sample_id": "1805", + "image_name": "front_stereo_camera_left/1771445458919833160.jpeg", + "timestamp_microseconds": "1771445458919833" + }, + { + "id": "3614", + "camera_params_id": "1", + "synced_sample_id": "1805", + "image_name": "front_stereo_camera_right/1771445458919833160.jpeg", + "timestamp_microseconds": "1771445458919833" + }, + { + "id": "3615", + "camera_params_id": "0", + "synced_sample_id": "1815", + "image_name": "front_stereo_camera_left/1771445459253172160.jpeg", + "timestamp_microseconds": "1771445459253172" + }, + { + "id": "3634", + "camera_params_id": "1", + "synced_sample_id": "1815", + "image_name": "front_stereo_camera_right/1771445459253172160.jpeg", + "timestamp_microseconds": "1771445459253172" + }, + { + "id": "3635", + "camera_params_id": "0", + "synced_sample_id": "1825", + "image_name": "front_stereo_camera_left/1771445459586493160.jpeg", + "timestamp_microseconds": "1771445459586493" + }, + { + "id": "3654", + "camera_params_id": "1", + "synced_sample_id": "1825", + "image_name": "front_stereo_camera_right/1771445459586493160.jpeg", + "timestamp_microseconds": "1771445459586493" + }, + { + "id": "3655", + "camera_params_id": "0", + "synced_sample_id": "1835", + "image_name": "front_stereo_camera_left/1771445459919814032.jpeg", + "timestamp_microseconds": "1771445459919814" + }, + { + "id": "3674", + "camera_params_id": "1", + "synced_sample_id": "1835", + "image_name": "front_stereo_camera_right/1771445459919814032.jpeg", + "timestamp_microseconds": "1771445459919814" + }, + { + "id": "3675", + "camera_params_id": "0", + "synced_sample_id": "1845", + "image_name": "front_stereo_camera_left/1771445460253134032.jpeg", + "timestamp_microseconds": "1771445460253134" + }, + { + "id": "3694", + "camera_params_id": "1", + "synced_sample_id": "1845", + "image_name": "front_stereo_camera_right/1771445460253134032.jpeg", + "timestamp_microseconds": "1771445460253134" + }, + { + "id": "3695", + "camera_params_id": "0", + "synced_sample_id": "1855", + "image_name": "front_stereo_camera_left/1771445460586455032.jpeg", + "timestamp_microseconds": "1771445460586455" + }, + { + "id": "3714", + "camera_params_id": "1", + "synced_sample_id": "1855", + "image_name": "front_stereo_camera_right/1771445460586455032.jpeg", + "timestamp_microseconds": "1771445460586455" + }, + { + "id": "3715", + "camera_params_id": "0", + "synced_sample_id": "1865", + "image_name": "front_stereo_camera_left/1771445460919794128.jpeg", + "timestamp_microseconds": "1771445460919794" + }, + { + "id": "3734", + "camera_params_id": "1", + "synced_sample_id": "1865", + "image_name": "front_stereo_camera_right/1771445460919794128.jpeg", + "timestamp_microseconds": "1771445460919794" + }, + { + "id": "3735", + "camera_params_id": "0", + "synced_sample_id": "1875", + "image_name": "front_stereo_camera_left/1771445461253115128.jpeg", + "timestamp_microseconds": "1771445461253115" + }, + { + "id": "3754", + "camera_params_id": "1", + "synced_sample_id": "1875", + "image_name": "front_stereo_camera_right/1771445461253115128.jpeg", + "timestamp_microseconds": "1771445461253115" + }, + { + "id": "3755", + "camera_params_id": "0", + "synced_sample_id": "1885", + "image_name": "front_stereo_camera_left/1771445461586435128.jpeg", + "timestamp_microseconds": "1771445461586435" + }, + { + "id": "3774", + "camera_params_id": "1", + "synced_sample_id": "1885", + "image_name": "front_stereo_camera_right/1771445461586435128.jpeg", + "timestamp_microseconds": "1771445461586435" + }, + { + "id": "3775", + "camera_params_id": "0", + "synced_sample_id": "1895", + "image_name": "front_stereo_camera_left/1771445461919756112.jpeg", + "timestamp_microseconds": "1771445461919756" + }, + { + "id": "3794", + "camera_params_id": "1", + "synced_sample_id": "1895", + "image_name": "front_stereo_camera_right/1771445461919756112.jpeg", + "timestamp_microseconds": "1771445461919756" + }, + { + "id": "3795", + "camera_params_id": "0", + "synced_sample_id": "1905", + "image_name": "front_stereo_camera_left/1771445462253077112.jpeg", + "timestamp_microseconds": "1771445462253077" + }, + { + "id": "3814", + "camera_params_id": "1", + "synced_sample_id": "1905", + "image_name": "front_stereo_camera_right/1771445462253077112.jpeg", + "timestamp_microseconds": "1771445462253077" + }, + { + "id": "3815", + "camera_params_id": "0", + "synced_sample_id": "1915", + "image_name": "front_stereo_camera_left/1771445462586416112.jpeg", + "timestamp_microseconds": "1771445462586416" + }, + { + "id": "3834", + "camera_params_id": "1", + "synced_sample_id": "1915", + "image_name": "front_stereo_camera_right/1771445462586416112.jpeg", + "timestamp_microseconds": "1771445462586416" + }, + { + "id": "3835", + "camera_params_id": "0", + "synced_sample_id": "1925", + "image_name": "front_stereo_camera_left/1771445462919736064.jpeg", + "timestamp_microseconds": "1771445462919736" + }, + { + "id": "3854", + "camera_params_id": "1", + "synced_sample_id": "1925", + "image_name": "front_stereo_camera_right/1771445462919736064.jpeg", + "timestamp_microseconds": "1771445462919736" + }, + { + "id": "3855", + "camera_params_id": "0", + "synced_sample_id": "1935", + "image_name": "front_stereo_camera_left/1771445463253058064.jpeg", + "timestamp_microseconds": "1771445463253058" + }, + { + "id": "3874", + "camera_params_id": "1", + "synced_sample_id": "1935", + "image_name": "front_stereo_camera_right/1771445463253058064.jpeg", + "timestamp_microseconds": "1771445463253058" + }, + { + "id": "3875", + "camera_params_id": "0", + "synced_sample_id": "1945", + "image_name": "front_stereo_camera_left/1771445463586380064.jpeg", + "timestamp_microseconds": "1771445463586380" + }, + { + "id": "3894", + "camera_params_id": "1", + "synced_sample_id": "1945", + "image_name": "front_stereo_camera_right/1771445463586380064.jpeg", + "timestamp_microseconds": "1771445463586380" + }, + { + "id": "3895", + "camera_params_id": "0", + "synced_sample_id": "1955", + "image_name": "front_stereo_camera_left/1771445463919699072.jpeg", + "timestamp_microseconds": "1771445463919699" + }, + { + "id": "3914", + "camera_params_id": "1", + "synced_sample_id": "1955", + "image_name": "front_stereo_camera_right/1771445463919699072.jpeg", + "timestamp_microseconds": "1771445463919699" + }, + { + "id": "3915", + "camera_params_id": "0", + "synced_sample_id": "1965", + "image_name": "front_stereo_camera_left/1771445464253041072.jpeg", + "timestamp_microseconds": "1771445464253041" + }, + { + "id": "3934", + "camera_params_id": "1", + "synced_sample_id": "1965", + "image_name": "front_stereo_camera_right/1771445464253041072.jpeg", + "timestamp_microseconds": "1771445464253041" + }, + { + "id": "3935", + "camera_params_id": "0", + "synced_sample_id": "1975", + "image_name": "front_stereo_camera_left/1771445464586358072.jpeg", + "timestamp_microseconds": "1771445464586358" + }, + { + "id": "3954", + "camera_params_id": "1", + "synced_sample_id": "1975", + "image_name": "front_stereo_camera_right/1771445464586358072.jpeg", + "timestamp_microseconds": "1771445464586358" + }, + { + "id": "3955", + "camera_params_id": "0", + "synced_sample_id": "1985", + "image_name": "front_stereo_camera_left/1771445464919679060.jpeg", + "timestamp_microseconds": "1771445464919679" + }, + { + "id": "3974", + "camera_params_id": "1", + "synced_sample_id": "1985", + "image_name": "front_stereo_camera_right/1771445464919679060.jpeg", + "timestamp_microseconds": "1771445464919679" + }, + { + "id": "3975", + "camera_params_id": "0", + "synced_sample_id": "1995", + "image_name": "front_stereo_camera_left/1771445465253000060.jpeg", + "timestamp_microseconds": "1771445465253000" + }, + { + "id": "3994", + "camera_params_id": "1", + "synced_sample_id": "1995", + "image_name": "front_stereo_camera_right/1771445465253000060.jpeg", + "timestamp_microseconds": "1771445465253000" + }, + { + "id": "3995", + "camera_params_id": "0", + "synced_sample_id": "2005", + "image_name": "front_stereo_camera_left/1771445465586339060.jpeg", + "timestamp_microseconds": "1771445465586339" + }, + { + "id": "4014", + "camera_params_id": "1", + "synced_sample_id": "2005", + "image_name": "front_stereo_camera_right/1771445465586339060.jpeg", + "timestamp_microseconds": "1771445465586339" + }, + { + "id": "4015", + "camera_params_id": "0", + "synced_sample_id": "2015", + "image_name": "front_stereo_camera_left/1771445465919659184.jpeg", + "timestamp_microseconds": "1771445465919659" + }, + { + "id": "4034", + "camera_params_id": "1", + "synced_sample_id": "2015", + "image_name": "front_stereo_camera_right/1771445465919659184.jpeg", + "timestamp_microseconds": "1771445465919659" + }, + { + "id": "4035", + "camera_params_id": "0", + "synced_sample_id": "2025", + "image_name": "front_stereo_camera_left/1771445466252980184.jpeg", + "timestamp_microseconds": "1771445466252980" + }, + { + "id": "4048", + "camera_params_id": "1", + "synced_sample_id": "2025", + "image_name": "front_stereo_camera_right/1771445466252980184.jpeg", + "timestamp_microseconds": "1771445466252980" + } + ], + "camera_params_id_to_camera_params": { + "0": { + "sensor_meta_data": { + "sensor_type": "CAMERA", + "sensor_id": 0, + "sensor_name": "front_stereo_camera_left", + "frequency": 30, + "sensor_to_vehicle_transform": { + "translation": { + "x": 0.0, + "y": 0.0, + "z": 0.0 + }, + "axis_angle": { + "x": -0.5775958428296969, + "y": 0.5771702412237825, + "z": -0.5772846394903755, + "angle_degrees": 120.06961847953714 + } + } + }, + "chroma": "COLOR", + "calibration_parameters": { + "image_width": 960, + "image_height": 600, + "camera_matrix": { + "row_count": 3, + "column_count": 3, + "data": [ + 481.9788818359375, + 0.0, + 479.2020263671875, + 0.0, + 481.17022705078125, + 292.2539978027344, + 0.0, + 0.0, + 1.0 + ] + }, + "rectification_matrix": { + "row_count": 3, + "column_count": 3, + "data": [ + 0.999999463558197, + -0.0010134882759302855, + -0.0002755408931989223, + 0.0010132633615285158, + 0.9999991655349731, + -0.000815302599221468, + 0.0002763669763226062, + 0.0008150229696184397, + 0.9999996423721313 + ] + }, + "projection_matrix": { + "row_count": 3, + "column_count": 4, + "data": [ + 426.205322265625, + 0.0, + 473.22314453125, + 0.0, + 0.0, + 426.205322265625, + 278.40216064453125, + 0.0, + 0.0, + 0.0, + 1.0, + 0.0 + ] + }, + "distortion_coefficients": { + "row_count": 1, + "column_count": 8, + "data": [ + 19.803178787231445, + 12.599993705749512, + 2.5517636458971538e-05, + 1.8582593838800676e-05, + 0.6390519142150879, + 20.165348052978516, + 19.945968627929688, + 3.352372646331787 + ] + } + }, + "camera_projection_model_type": 0 + }, + "1": { + "sensor_meta_data": { + "sensor_type": "CAMERA", + "sensor_id": 1, + "sensor_name": "front_stereo_camera_right", + "frequency": 30, + "sensor_to_vehicle_transform": { + "translation": { + "x": -4.121037043321269e-05, + "y": -0.14956167798888134, + "z": 0.000151579093224206 + }, + "axis_angle": { + "x": -0.5775958428288566, + "y": 0.5771702412089346, + "z": -0.5772846395060611, + "angle_degrees": 120.06961847884203 + } + } + }, + "chroma": "COLOR", + "calibration_parameters": { + "image_width": 960, + "image_height": 600, + "camera_matrix": { + "row_count": 3, + "column_count": 3, + "data": [ + 482.6893615722656, + 0.0, + 473.9661560058594, + 0.0, + 481.9247741699219, + 294.19342041015625, + 0.0, + 0.0, + 1.0 + ] + }, + "rectification_matrix": { + "row_count": 3, + "column_count": 3, + "data": [ + 0.9999814033508301, + -0.00018898359849117696, + -0.006098800804466009, + 0.00019395507115405053, + 0.9999996423721313, + 0.0008145752362906933, + 0.006098644807934761, + -0.0008157429401762784, + 0.9999810457229614 + ] + }, + "projection_matrix": { + "row_count": 3, + "column_count": 4, + "data": [ + 426.205322265625, + 0.0, + 473.22314453125, + 0.0, + 0.0, + 426.205322265625, + 278.40216064453125, + 0.0, + 0.0, + 0.0, + 1.0, + 0.0 + ] + }, + "distortion_coefficients": { + "row_count": 1, + "column_count": 8, + "data": [ + 0.868979275226593, + 0.1305328607559204, + 2.7841537303174846e-05, + 5.961514398222789e-05, + 0.002356345998123288, + 1.2451058626174927, + 0.3521876633167267, + 0.018716152757406235 + ] + } + }, + "camera_projection_model_type": 0 + } + }, + "camera_params_id_to_session_name": { + "0": "data", + "1": "data" + }, + "stereo_pair": [ + { + "left_camera_param_id": "0", + "right_camera_param_id": "1", + "baseline_meters": 0.1495617627365213 + } + ] +} \ No newline at end of file diff --git a/third-party/video_to_data/reconstruction/modules/v2d_hoi_object_reconstruction/assets/basketball_example/front_stereo_camera_left/1771445398921412053.jpeg b/third-party/video_to_data/reconstruction/modules/v2d_hoi_object_reconstruction/assets/basketball_example/front_stereo_camera_left/1771445398921412053.jpeg new file mode 100644 index 0000000000000000000000000000000000000000..04e7f7f53055837941715c9262b2f233236a543c --- /dev/null +++ b/third-party/video_to_data/reconstruction/modules/v2d_hoi_object_reconstruction/assets/basketball_example/front_stereo_camera_left/1771445398921412053.jpeg @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:82fd58991e01f1c1b23fa435e326ea791c5a2fe2632a535c9fbecdb545c47209 +size 92771 diff --git a/third-party/video_to_data/reconstruction/modules/v2d_hoi_object_reconstruction/assets/basketball_example/front_stereo_camera_left/1771445399254733053.jpeg b/third-party/video_to_data/reconstruction/modules/v2d_hoi_object_reconstruction/assets/basketball_example/front_stereo_camera_left/1771445399254733053.jpeg new file mode 100644 index 0000000000000000000000000000000000000000..c577983c15a50325a75e04806f0bfa4864ab3e12 --- /dev/null +++ b/third-party/video_to_data/reconstruction/modules/v2d_hoi_object_reconstruction/assets/basketball_example/front_stereo_camera_left/1771445399254733053.jpeg @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:a9e62cd34ea611f604ae2de9e50e99e327b8ba04fcc116a5c5db445fbaca2a88 +size 92174 diff --git a/third-party/video_to_data/reconstruction/modules/v2d_hoi_object_reconstruction/assets/basketball_example/front_stereo_camera_left/1771445399588055053.jpeg b/third-party/video_to_data/reconstruction/modules/v2d_hoi_object_reconstruction/assets/basketball_example/front_stereo_camera_left/1771445399588055053.jpeg new file mode 100644 index 0000000000000000000000000000000000000000..de05d40c11ce8981f0c91db81bbc22abe0b508b4 --- /dev/null +++ b/third-party/video_to_data/reconstruction/modules/v2d_hoi_object_reconstruction/assets/basketball_example/front_stereo_camera_left/1771445399588055053.jpeg @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:f0246ee9eaa91f6dbce82bc79a2fced5ae9279a0f6ad6f9af2c3219ab9e123c5 +size 92102 diff --git a/third-party/video_to_data/reconstruction/modules/v2d_hoi_object_reconstruction/assets/basketball_example/front_stereo_camera_left/1771445399921377045.jpeg b/third-party/video_to_data/reconstruction/modules/v2d_hoi_object_reconstruction/assets/basketball_example/front_stereo_camera_left/1771445399921377045.jpeg new file mode 100644 index 0000000000000000000000000000000000000000..7dc3b27d57af8c2b529a51e496545c769f3bbb12 --- /dev/null +++ b/third-party/video_to_data/reconstruction/modules/v2d_hoi_object_reconstruction/assets/basketball_example/front_stereo_camera_left/1771445399921377045.jpeg @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:63a744cd69d87cad0f644e8bea927fece18fe54d09f205c34f90ff9898aa080c +size 92012 diff --git a/third-party/video_to_data/reconstruction/modules/v2d_hoi_object_reconstruction/assets/basketball_example/front_stereo_camera_left/1771445400254693045.jpeg b/third-party/video_to_data/reconstruction/modules/v2d_hoi_object_reconstruction/assets/basketball_example/front_stereo_camera_left/1771445400254693045.jpeg new file mode 100644 index 0000000000000000000000000000000000000000..a598772c7bee5892b56bda6f927d76dcec184577 --- /dev/null +++ b/third-party/video_to_data/reconstruction/modules/v2d_hoi_object_reconstruction/assets/basketball_example/front_stereo_camera_left/1771445400254693045.jpeg @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:64949522eb9740de92527dda8142f19d65081a198748f3b49b8f8591fa267d5f +size 93840 diff --git a/third-party/video_to_data/reconstruction/modules/v2d_hoi_object_reconstruction/assets/basketball_example/front_stereo_camera_left/1771445400588032045.jpeg b/third-party/video_to_data/reconstruction/modules/v2d_hoi_object_reconstruction/assets/basketball_example/front_stereo_camera_left/1771445400588032045.jpeg new file mode 100644 index 0000000000000000000000000000000000000000..c9bb5e73e72fe240ad2cb1456d75f20c0003370f --- /dev/null +++ b/third-party/video_to_data/reconstruction/modules/v2d_hoi_object_reconstruction/assets/basketball_example/front_stereo_camera_left/1771445400588032045.jpeg @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:e41e44180329182e785b6902dba539920c7d2216c8a752c44cc667667c6cd2b5 +size 94034 diff --git a/third-party/video_to_data/reconstruction/modules/v2d_hoi_object_reconstruction/assets/basketball_example/front_stereo_camera_left/1771445400921353081.jpeg b/third-party/video_to_data/reconstruction/modules/v2d_hoi_object_reconstruction/assets/basketball_example/front_stereo_camera_left/1771445400921353081.jpeg new file mode 100644 index 0000000000000000000000000000000000000000..01e491e2d1e299ecaea9989a8e541db0e1765436 --- /dev/null +++ b/third-party/video_to_data/reconstruction/modules/v2d_hoi_object_reconstruction/assets/basketball_example/front_stereo_camera_left/1771445400921353081.jpeg @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:2a821ed956aa7e52f7b148730896ee9926001252eca9baf2dcef200884afd5f8 +size 97456 diff --git a/third-party/video_to_data/reconstruction/modules/v2d_hoi_object_reconstruction/assets/basketball_example/front_stereo_camera_left/1771445401254674081.jpeg b/third-party/video_to_data/reconstruction/modules/v2d_hoi_object_reconstruction/assets/basketball_example/front_stereo_camera_left/1771445401254674081.jpeg new file mode 100644 index 0000000000000000000000000000000000000000..8c1ebd300d7ef1979bdef771b1ef7a25cdbb6056 --- /dev/null +++ b/third-party/video_to_data/reconstruction/modules/v2d_hoi_object_reconstruction/assets/basketball_example/front_stereo_camera_left/1771445401254674081.jpeg @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:44582fe0ece216baf57f0b41fb909ced974adc3b0a726c41fee9a9864088b081 +size 97380 diff --git a/third-party/video_to_data/reconstruction/modules/v2d_hoi_object_reconstruction/assets/basketball_example/front_stereo_camera_left/1771445401587995081.jpeg b/third-party/video_to_data/reconstruction/modules/v2d_hoi_object_reconstruction/assets/basketball_example/front_stereo_camera_left/1771445401587995081.jpeg new file mode 100644 index 0000000000000000000000000000000000000000..6e138d76d3138017531013cae280de51ed51595e --- /dev/null +++ b/third-party/video_to_data/reconstruction/modules/v2d_hoi_object_reconstruction/assets/basketball_example/front_stereo_camera_left/1771445401587995081.jpeg @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:a7b916b5bc90c4bb76960c8df46fae4f3b5fffd1d3ca8b0ef39e6e416ba88649 +size 100034 diff --git a/third-party/video_to_data/reconstruction/modules/v2d_hoi_object_reconstruction/assets/basketball_example/front_stereo_camera_left/1771445401921334060.jpeg b/third-party/video_to_data/reconstruction/modules/v2d_hoi_object_reconstruction/assets/basketball_example/front_stereo_camera_left/1771445401921334060.jpeg new file mode 100644 index 0000000000000000000000000000000000000000..65375b0bb25f2a7c804c8589dcb9652c601f9462 --- /dev/null +++ b/third-party/video_to_data/reconstruction/modules/v2d_hoi_object_reconstruction/assets/basketball_example/front_stereo_camera_left/1771445401921334060.jpeg @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:f954c0ea00d84c64fb56ff48a25a74dd5224621f87ee9d0ff9921e6e030df840 +size 101893 diff --git a/third-party/video_to_data/reconstruction/modules/v2d_hoi_object_reconstruction/assets/basketball_example/front_stereo_camera_left/1771445402254654060.jpeg b/third-party/video_to_data/reconstruction/modules/v2d_hoi_object_reconstruction/assets/basketball_example/front_stereo_camera_left/1771445402254654060.jpeg new file mode 100644 index 0000000000000000000000000000000000000000..92814f5054903a8b04885b55efb081fea7d19eb9 --- /dev/null +++ b/third-party/video_to_data/reconstruction/modules/v2d_hoi_object_reconstruction/assets/basketball_example/front_stereo_camera_left/1771445402254654060.jpeg @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:6ff18479650e23e3d18a886e19915d437f1a0907f74039845a789fe48856f6ab +size 100938 diff --git a/third-party/video_to_data/reconstruction/modules/v2d_hoi_object_reconstruction/assets/basketball_example/front_stereo_camera_left/1771445402587975060.jpeg b/third-party/video_to_data/reconstruction/modules/v2d_hoi_object_reconstruction/assets/basketball_example/front_stereo_camera_left/1771445402587975060.jpeg new file mode 100644 index 0000000000000000000000000000000000000000..4c7e08ba443d95c1d725937a624daf164b73654f --- /dev/null +++ b/third-party/video_to_data/reconstruction/modules/v2d_hoi_object_reconstruction/assets/basketball_example/front_stereo_camera_left/1771445402587975060.jpeg @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:c1109a7fa71b1e8db4f26398969addee7f294d3f821be7ada371a90601e1f772 +size 101044 diff --git a/third-party/video_to_data/reconstruction/modules/v2d_hoi_object_reconstruction/assets/basketball_example/front_stereo_camera_left/1771445402921296020.jpeg b/third-party/video_to_data/reconstruction/modules/v2d_hoi_object_reconstruction/assets/basketball_example/front_stereo_camera_left/1771445402921296020.jpeg new file mode 100644 index 0000000000000000000000000000000000000000..436444f8ddb8e02ae7cb47d56f0468c5dcf82c1a --- /dev/null +++ b/third-party/video_to_data/reconstruction/modules/v2d_hoi_object_reconstruction/assets/basketball_example/front_stereo_camera_left/1771445402921296020.jpeg @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:99f8ca2a08cb1123c99276abd4fcba4eabc0b6847828f23f77c7ad620f5ac22c +size 106515 diff --git a/third-party/video_to_data/reconstruction/modules/v2d_hoi_object_reconstruction/assets/basketball_example/front_stereo_camera_left/1771445403254617020.jpeg b/third-party/video_to_data/reconstruction/modules/v2d_hoi_object_reconstruction/assets/basketball_example/front_stereo_camera_left/1771445403254617020.jpeg new file mode 100644 index 0000000000000000000000000000000000000000..41df0f8a6686874d65d3b2b3b32a8c3a43a4eff5 --- /dev/null +++ b/third-party/video_to_data/reconstruction/modules/v2d_hoi_object_reconstruction/assets/basketball_example/front_stereo_camera_left/1771445403254617020.jpeg @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:bc0f6b73bec2ccd006b0381f7914f8c7f274a444ab55731abdd97819f87e9e0a +size 102568 diff --git a/third-party/video_to_data/reconstruction/modules/v2d_hoi_object_reconstruction/assets/basketball_example/front_stereo_camera_left/1771445403587955020.jpeg b/third-party/video_to_data/reconstruction/modules/v2d_hoi_object_reconstruction/assets/basketball_example/front_stereo_camera_left/1771445403587955020.jpeg new file mode 100644 index 0000000000000000000000000000000000000000..0d37fb5693a2dfd20b58af108a3587ff57d7a9a6 --- /dev/null +++ b/third-party/video_to_data/reconstruction/modules/v2d_hoi_object_reconstruction/assets/basketball_example/front_stereo_camera_left/1771445403587955020.jpeg @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:96be09e35daa2c7fd401042b769c82af4747b9ab09c91b09326612e4b80b9fd3 +size 102679 diff --git a/third-party/video_to_data/reconstruction/modules/v2d_hoi_object_reconstruction/assets/basketball_example/front_stereo_camera_left/1771445403921276017.jpeg b/third-party/video_to_data/reconstruction/modules/v2d_hoi_object_reconstruction/assets/basketball_example/front_stereo_camera_left/1771445403921276017.jpeg new file mode 100644 index 0000000000000000000000000000000000000000..3209fe5a370a3f1d2ff5c3183161b3bb82fdaf76 --- /dev/null +++ b/third-party/video_to_data/reconstruction/modules/v2d_hoi_object_reconstruction/assets/basketball_example/front_stereo_camera_left/1771445403921276017.jpeg @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:009f70778e16fca5cdddeb1c50645f128fe50de2a32ec6183feb480000bafadb +size 103998 diff --git a/third-party/video_to_data/reconstruction/modules/v2d_hoi_object_reconstruction/assets/basketball_example/front_stereo_camera_left/1771445404254597017.jpeg b/third-party/video_to_data/reconstruction/modules/v2d_hoi_object_reconstruction/assets/basketball_example/front_stereo_camera_left/1771445404254597017.jpeg new file mode 100644 index 0000000000000000000000000000000000000000..79d9912e07607b389828835cf2788edc3f3c60bc --- /dev/null +++ b/third-party/video_to_data/reconstruction/modules/v2d_hoi_object_reconstruction/assets/basketball_example/front_stereo_camera_left/1771445404254597017.jpeg @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:3eba39c62734f7640da991088b68cc4b819d279b3cd9338e936caca56ccfa0d8 +size 109986 diff --git a/third-party/video_to_data/reconstruction/modules/v2d_hoi_object_reconstruction/assets/basketball_example/front_stereo_camera_left/1771445404587918017.jpeg b/third-party/video_to_data/reconstruction/modules/v2d_hoi_object_reconstruction/assets/basketball_example/front_stereo_camera_left/1771445404587918017.jpeg new file mode 100644 index 0000000000000000000000000000000000000000..e383637b4287a962868005ec0e7ee9abbc94df5f --- /dev/null +++ b/third-party/video_to_data/reconstruction/modules/v2d_hoi_object_reconstruction/assets/basketball_example/front_stereo_camera_left/1771445404587918017.jpeg @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:5d12b0e9653f4d4310f4f1a18b523fac65183888b3a7ca3cf30c0656c3fafdcc +size 108668 diff --git a/third-party/video_to_data/reconstruction/modules/v2d_hoi_object_reconstruction/assets/basketball_example/front_stereo_camera_left/1771445404921238120.jpeg b/third-party/video_to_data/reconstruction/modules/v2d_hoi_object_reconstruction/assets/basketball_example/front_stereo_camera_left/1771445404921238120.jpeg new file mode 100644 index 0000000000000000000000000000000000000000..4460c30e9fdfa2fded2f1207f6099d28c81ee787 --- /dev/null +++ b/third-party/video_to_data/reconstruction/modules/v2d_hoi_object_reconstruction/assets/basketball_example/front_stereo_camera_left/1771445404921238120.jpeg @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:7679fe03b2ecf8d367928b8117f13b3266e6371a699c9321ce39ddf757723116 +size 99050 diff --git a/third-party/video_to_data/reconstruction/modules/v2d_hoi_object_reconstruction/assets/basketball_example/front_stereo_camera_left/1771445405254580120.jpeg b/third-party/video_to_data/reconstruction/modules/v2d_hoi_object_reconstruction/assets/basketball_example/front_stereo_camera_left/1771445405254580120.jpeg new file mode 100644 index 0000000000000000000000000000000000000000..17c3516bfd5d6a6123929eefc34661f7f91828ce --- /dev/null +++ b/third-party/video_to_data/reconstruction/modules/v2d_hoi_object_reconstruction/assets/basketball_example/front_stereo_camera_left/1771445405254580120.jpeg @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:416be377ab79a11df833f7b448eb6dd12972addac6a25fd4ae5c75f1253b439b +size 101300 diff --git a/third-party/video_to_data/reconstruction/modules/v2d_hoi_object_reconstruction/assets/basketball_example/front_stereo_camera_left/1771445405587902120.jpeg b/third-party/video_to_data/reconstruction/modules/v2d_hoi_object_reconstruction/assets/basketball_example/front_stereo_camera_left/1771445405587902120.jpeg new file mode 100644 index 0000000000000000000000000000000000000000..08c6d47f1f411925c3645bdd170d9569bef12f16 --- /dev/null +++ b/third-party/video_to_data/reconstruction/modules/v2d_hoi_object_reconstruction/assets/basketball_example/front_stereo_camera_left/1771445405587902120.jpeg @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:453a4216a0f24f6bdfed176dd9caa2982d6f40ffc493f0835b007b4410b72103 +size 96792 diff --git a/third-party/video_to_data/reconstruction/modules/v2d_hoi_object_reconstruction/assets/basketball_example/front_stereo_camera_left/1771445405921219052.jpeg b/third-party/video_to_data/reconstruction/modules/v2d_hoi_object_reconstruction/assets/basketball_example/front_stereo_camera_left/1771445405921219052.jpeg new file mode 100644 index 0000000000000000000000000000000000000000..fe901deff836eb737a096eebe2a509d0142b548b --- /dev/null +++ b/third-party/video_to_data/reconstruction/modules/v2d_hoi_object_reconstruction/assets/basketball_example/front_stereo_camera_left/1771445405921219052.jpeg @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:994fab194c621442d023f635bc28ba4083c6b1acdb656cd202f7e58b612da177 +size 104444 diff --git a/third-party/video_to_data/reconstruction/modules/v2d_hoi_object_reconstruction/assets/basketball_example/front_stereo_camera_left/1771445406254540052.jpeg b/third-party/video_to_data/reconstruction/modules/v2d_hoi_object_reconstruction/assets/basketball_example/front_stereo_camera_left/1771445406254540052.jpeg new file mode 100644 index 0000000000000000000000000000000000000000..a6925d6ac078568c3e2b25a85f6792e28caf4082 --- /dev/null +++ b/third-party/video_to_data/reconstruction/modules/v2d_hoi_object_reconstruction/assets/basketball_example/front_stereo_camera_left/1771445406254540052.jpeg @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:e8792132d757b6653fb65445a9c452fdc7b5b3d2ffe379ae7bff65681dac5271 +size 97867 diff --git a/third-party/video_to_data/reconstruction/modules/v2d_hoi_object_reconstruction/assets/basketball_example/front_stereo_camera_left/1771445406587879052.jpeg b/third-party/video_to_data/reconstruction/modules/v2d_hoi_object_reconstruction/assets/basketball_example/front_stereo_camera_left/1771445406587879052.jpeg new file mode 100644 index 0000000000000000000000000000000000000000..657b1d07b1ef569fe2e307312d73a5f40056b68b --- /dev/null +++ b/third-party/video_to_data/reconstruction/modules/v2d_hoi_object_reconstruction/assets/basketball_example/front_stereo_camera_left/1771445406587879052.jpeg @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:9436e50a4ccf6f091a5cb0279f5a75d346161cdfc04da3196a41cadb9fb338f1 +size 95077 diff --git a/third-party/video_to_data/reconstruction/modules/v2d_hoi_object_reconstruction/assets/basketball_example/front_stereo_camera_left/1771445406921199016.jpeg b/third-party/video_to_data/reconstruction/modules/v2d_hoi_object_reconstruction/assets/basketball_example/front_stereo_camera_left/1771445406921199016.jpeg new file mode 100644 index 0000000000000000000000000000000000000000..337a849c1858fb8465a767df990031e4d03a0081 --- /dev/null +++ b/third-party/video_to_data/reconstruction/modules/v2d_hoi_object_reconstruction/assets/basketball_example/front_stereo_camera_left/1771445406921199016.jpeg @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:771dd23e40b91fa69d28e4aa3fb93f5b9b7c1c39d10a9c776a184a4581c27475 +size 94172 diff --git a/third-party/video_to_data/reconstruction/modules/v2d_hoi_object_reconstruction/assets/basketball_example/front_stereo_camera_left/1771445407254520016.jpeg b/third-party/video_to_data/reconstruction/modules/v2d_hoi_object_reconstruction/assets/basketball_example/front_stereo_camera_left/1771445407254520016.jpeg new file mode 100644 index 0000000000000000000000000000000000000000..57153119825a4a237e1dce80aaf2d684ed977b40 --- /dev/null +++ b/third-party/video_to_data/reconstruction/modules/v2d_hoi_object_reconstruction/assets/basketball_example/front_stereo_camera_left/1771445407254520016.jpeg @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:d12a3d93360971881e8e325b9e743fe6c0b2b0af52a305bdae7ec8471517b15a +size 97691 diff --git a/third-party/video_to_data/reconstruction/modules/v2d_hoi_object_reconstruction/assets/basketball_example/front_stereo_camera_left/1771445407587841016.jpeg b/third-party/video_to_data/reconstruction/modules/v2d_hoi_object_reconstruction/assets/basketball_example/front_stereo_camera_left/1771445407587841016.jpeg new file mode 100644 index 0000000000000000000000000000000000000000..525e26ae08a88ff59e35606fe5ca66e00c291ccf --- /dev/null +++ b/third-party/video_to_data/reconstruction/modules/v2d_hoi_object_reconstruction/assets/basketball_example/front_stereo_camera_left/1771445407587841016.jpeg @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:faaab4f0a68f1be766bfca912564f0386ef62698aebd37b526f832118b6e8a04 +size 93835 diff --git a/third-party/video_to_data/reconstruction/modules/v2d_hoi_object_reconstruction/assets/basketball_example/front_stereo_camera_left/1771445407921162033.jpeg b/third-party/video_to_data/reconstruction/modules/v2d_hoi_object_reconstruction/assets/basketball_example/front_stereo_camera_left/1771445407921162033.jpeg new file mode 100644 index 0000000000000000000000000000000000000000..2135e513d2f9e02ed1c3bc7a4b8bd42c2f601351 --- /dev/null +++ b/third-party/video_to_data/reconstruction/modules/v2d_hoi_object_reconstruction/assets/basketball_example/front_stereo_camera_left/1771445407921162033.jpeg @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:8f63e0041437693714659f9c5ec1f662149d3ae838c3ef4a9bb93eab3f6173a9 +size 93904 diff --git a/third-party/video_to_data/reconstruction/modules/v2d_hoi_object_reconstruction/assets/basketball_example/front_stereo_camera_left/1771445408254500033.jpeg b/third-party/video_to_data/reconstruction/modules/v2d_hoi_object_reconstruction/assets/basketball_example/front_stereo_camera_left/1771445408254500033.jpeg new file mode 100644 index 0000000000000000000000000000000000000000..f6369bc2d83dff53bfc69db4271d19ded6cbe68c --- /dev/null +++ b/third-party/video_to_data/reconstruction/modules/v2d_hoi_object_reconstruction/assets/basketball_example/front_stereo_camera_left/1771445408254500033.jpeg @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:c86d618a63998ca4bc6ff471231b4810e40ff9c11854279365a97c76a827b7a9 +size 92980 diff --git a/third-party/video_to_data/reconstruction/modules/v2d_hoi_object_reconstruction/assets/basketball_example/front_stereo_camera_left/1771445408587821033.jpeg b/third-party/video_to_data/reconstruction/modules/v2d_hoi_object_reconstruction/assets/basketball_example/front_stereo_camera_left/1771445408587821033.jpeg new file mode 100644 index 0000000000000000000000000000000000000000..017703d57dc8dadd797a16c65b509b5c0bb37941 --- /dev/null +++ b/third-party/video_to_data/reconstruction/modules/v2d_hoi_object_reconstruction/assets/basketball_example/front_stereo_camera_left/1771445408587821033.jpeg @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:faa088e962904b608f6bcdfc1255bf0507319e6c89da42c5b05fdd7d2633504a +size 88689 diff --git a/third-party/video_to_data/reconstruction/modules/v2d_hoi_object_reconstruction/assets/basketball_example/front_stereo_camera_left/1771445408921142024.jpeg b/third-party/video_to_data/reconstruction/modules/v2d_hoi_object_reconstruction/assets/basketball_example/front_stereo_camera_left/1771445408921142024.jpeg new file mode 100644 index 0000000000000000000000000000000000000000..d12ad970404611c3c383ebc5297cf6b7863e100c --- /dev/null +++ b/third-party/video_to_data/reconstruction/modules/v2d_hoi_object_reconstruction/assets/basketball_example/front_stereo_camera_left/1771445408921142024.jpeg @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:d8169881489f936ed09b4bd67a40ac09c51841a49377f5027095b737d490ce4b +size 90033 diff --git a/third-party/video_to_data/reconstruction/modules/v2d_hoi_object_reconstruction/assets/basketball_example/front_stereo_camera_left/1771445409254463024.jpeg b/third-party/video_to_data/reconstruction/modules/v2d_hoi_object_reconstruction/assets/basketball_example/front_stereo_camera_left/1771445409254463024.jpeg new file mode 100644 index 0000000000000000000000000000000000000000..78bee8a9430da714bbfab209032ae5edec684ced --- /dev/null +++ b/third-party/video_to_data/reconstruction/modules/v2d_hoi_object_reconstruction/assets/basketball_example/front_stereo_camera_left/1771445409254463024.jpeg @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:bc1b42b2bc44eef5b07becf66af43616e6014a5589b2bd4190a5944eb1bfa08a +size 85910 diff --git a/third-party/video_to_data/reconstruction/modules/v2d_hoi_object_reconstruction/assets/basketball_example/front_stereo_camera_left/1771445409587802024.jpeg b/third-party/video_to_data/reconstruction/modules/v2d_hoi_object_reconstruction/assets/basketball_example/front_stereo_camera_left/1771445409587802024.jpeg new file mode 100644 index 0000000000000000000000000000000000000000..366ecc59614395521d4ecbfa42edf4a318bb7f86 --- /dev/null +++ b/third-party/video_to_data/reconstruction/modules/v2d_hoi_object_reconstruction/assets/basketball_example/front_stereo_camera_left/1771445409587802024.jpeg @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:aa6635396e6acce54e67cef29115de624789641042f6b6cf810bf66a2761e866 +size 88564 diff --git a/third-party/video_to_data/reconstruction/modules/v2d_hoi_object_reconstruction/assets/basketball_example/front_stereo_camera_left/1771445409921122020.jpeg b/third-party/video_to_data/reconstruction/modules/v2d_hoi_object_reconstruction/assets/basketball_example/front_stereo_camera_left/1771445409921122020.jpeg new file mode 100644 index 0000000000000000000000000000000000000000..9b109062b8751a68c772f48d84eab1dfdcea2307 --- /dev/null +++ b/third-party/video_to_data/reconstruction/modules/v2d_hoi_object_reconstruction/assets/basketball_example/front_stereo_camera_left/1771445409921122020.jpeg @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:b0dc2529934c5d916d9e0f907b8f498dd2c5bed9438d00e2454d516e086e48c2 +size 87272 diff --git a/third-party/video_to_data/reconstruction/modules/v2d_hoi_object_reconstruction/assets/basketball_example/front_stereo_camera_left/1771445410254443020.jpeg b/third-party/video_to_data/reconstruction/modules/v2d_hoi_object_reconstruction/assets/basketball_example/front_stereo_camera_left/1771445410254443020.jpeg new file mode 100644 index 0000000000000000000000000000000000000000..b4200161f1d678e810cd2e6a4ae489bc5790c124 --- /dev/null +++ b/third-party/video_to_data/reconstruction/modules/v2d_hoi_object_reconstruction/assets/basketball_example/front_stereo_camera_left/1771445410254443020.jpeg @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:fe51deaaca9dea72cdb8a1ccbcc3a5305a1b328ed5c123dd92227758b3610b36 +size 87026 diff --git a/third-party/video_to_data/reconstruction/modules/v2d_hoi_object_reconstruction/assets/basketball_example/front_stereo_camera_left/1771445410587765020.jpeg b/third-party/video_to_data/reconstruction/modules/v2d_hoi_object_reconstruction/assets/basketball_example/front_stereo_camera_left/1771445410587765020.jpeg new file mode 100644 index 0000000000000000000000000000000000000000..27898d04b2a3e6bf2a2dda1609d2fdc3ff6b806f --- /dev/null +++ b/third-party/video_to_data/reconstruction/modules/v2d_hoi_object_reconstruction/assets/basketball_example/front_stereo_camera_left/1771445410587765020.jpeg @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:23dded999aec331b6592de05ddbe0029de3e39d1a371d6ad2880fc1a5b75f3c6 +size 86899 diff --git a/third-party/video_to_data/reconstruction/modules/v2d_hoi_object_reconstruction/assets/basketball_example/front_stereo_camera_left/1771445410921087145.jpeg b/third-party/video_to_data/reconstruction/modules/v2d_hoi_object_reconstruction/assets/basketball_example/front_stereo_camera_left/1771445410921087145.jpeg new file mode 100644 index 0000000000000000000000000000000000000000..7c64e6a6ef4c19bcee0bcf8eee01c02fbc9b801e --- /dev/null +++ b/third-party/video_to_data/reconstruction/modules/v2d_hoi_object_reconstruction/assets/basketball_example/front_stereo_camera_left/1771445410921087145.jpeg @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:a25c50e497d236cf27ee55a3218e726b584c7ab9bbd72656941d709f1890c42d +size 84413 diff --git a/third-party/video_to_data/reconstruction/modules/v2d_hoi_object_reconstruction/assets/basketball_example/front_stereo_camera_left/1771445411254427145.jpeg b/third-party/video_to_data/reconstruction/modules/v2d_hoi_object_reconstruction/assets/basketball_example/front_stereo_camera_left/1771445411254427145.jpeg new file mode 100644 index 0000000000000000000000000000000000000000..75686cca7011859d736a6808b4c798d4cdebd703 --- /dev/null +++ b/third-party/video_to_data/reconstruction/modules/v2d_hoi_object_reconstruction/assets/basketball_example/front_stereo_camera_left/1771445411254427145.jpeg @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:3273d0e90472d4b7f039ebc9f840b1d55c45c3ce40797075a0653a1f992fb6d7 +size 85530 diff --git a/third-party/video_to_data/reconstruction/modules/v2d_hoi_object_reconstruction/assets/basketball_example/front_stereo_camera_left/1771445411587744145.jpeg b/third-party/video_to_data/reconstruction/modules/v2d_hoi_object_reconstruction/assets/basketball_example/front_stereo_camera_left/1771445411587744145.jpeg new file mode 100644 index 0000000000000000000000000000000000000000..ae3fec2c9d2df076b6d4c7450cf9168a65335855 --- /dev/null +++ b/third-party/video_to_data/reconstruction/modules/v2d_hoi_object_reconstruction/assets/basketball_example/front_stereo_camera_left/1771445411587744145.jpeg @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:1e40441742332835c079d268528d45842a4b86b90b7f734345330ffa893c236f +size 85991 diff --git a/third-party/video_to_data/reconstruction/modules/v2d_hoi_object_reconstruction/assets/basketball_example/front_stereo_camera_left/1771445411921065005.jpeg b/third-party/video_to_data/reconstruction/modules/v2d_hoi_object_reconstruction/assets/basketball_example/front_stereo_camera_left/1771445411921065005.jpeg new file mode 100644 index 0000000000000000000000000000000000000000..b6d9785307d54918bb3d645a0fdedb9465330c96 --- /dev/null +++ b/third-party/video_to_data/reconstruction/modules/v2d_hoi_object_reconstruction/assets/basketball_example/front_stereo_camera_left/1771445411921065005.jpeg @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:45e66a25d95f07fcf9eb134d7a9798ca3a0d105ac6ad4a9a023309e1ce3622de +size 84830 diff --git a/third-party/video_to_data/reconstruction/modules/v2d_hoi_object_reconstruction/assets/basketball_example/front_stereo_camera_left/1771445412254386005.jpeg b/third-party/video_to_data/reconstruction/modules/v2d_hoi_object_reconstruction/assets/basketball_example/front_stereo_camera_left/1771445412254386005.jpeg new file mode 100644 index 0000000000000000000000000000000000000000..7fa0b3211ecf265ea1efa5b882ce04f62b084434 --- /dev/null +++ b/third-party/video_to_data/reconstruction/modules/v2d_hoi_object_reconstruction/assets/basketball_example/front_stereo_camera_left/1771445412254386005.jpeg @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:3ac6572980bed205659ea3d9923ebfe7806ad7277890cc7985d8d3e11f1ea2df +size 89509 diff --git a/third-party/video_to_data/reconstruction/modules/v2d_hoi_object_reconstruction/assets/basketball_example/front_stereo_camera_left/1771445412587707005.jpeg b/third-party/video_to_data/reconstruction/modules/v2d_hoi_object_reconstruction/assets/basketball_example/front_stereo_camera_left/1771445412587707005.jpeg new file mode 100644 index 0000000000000000000000000000000000000000..cad6ec7ff68092770015b8b0b946464e04d8a5dc --- /dev/null +++ b/third-party/video_to_data/reconstruction/modules/v2d_hoi_object_reconstruction/assets/basketball_example/front_stereo_camera_left/1771445412587707005.jpeg @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:4df5f0a40b0332dde229de2b8e598da736f364af01e187c38df0692e282b1849 +size 88643 diff --git a/third-party/video_to_data/reconstruction/modules/v2d_hoi_object_reconstruction/assets/basketball_example/front_stereo_camera_left/1771445412921046057.jpeg b/third-party/video_to_data/reconstruction/modules/v2d_hoi_object_reconstruction/assets/basketball_example/front_stereo_camera_left/1771445412921046057.jpeg new file mode 100644 index 0000000000000000000000000000000000000000..344bed340d000f51fa561d213b32e54fdf0ec667 --- /dev/null +++ b/third-party/video_to_data/reconstruction/modules/v2d_hoi_object_reconstruction/assets/basketball_example/front_stereo_camera_left/1771445412921046057.jpeg @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:188694ad0543bb4c9b0f36f568cef82cb30c1b0032956447bcf2da066f1197fa +size 90316 diff --git a/third-party/video_to_data/reconstruction/modules/v2d_hoi_object_reconstruction/assets/basketball_example/front_stereo_camera_left/1771445413254366057.jpeg b/third-party/video_to_data/reconstruction/modules/v2d_hoi_object_reconstruction/assets/basketball_example/front_stereo_camera_left/1771445413254366057.jpeg new file mode 100644 index 0000000000000000000000000000000000000000..6faabbaf61249ff719e26f7b7d7ea490c7c805b9 --- /dev/null +++ b/third-party/video_to_data/reconstruction/modules/v2d_hoi_object_reconstruction/assets/basketball_example/front_stereo_camera_left/1771445413254366057.jpeg @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:a2955f545e5e173ee25e56e4348c61fee7bc81291b6665afcc3be3e2f9babd19 +size 86908 diff --git a/third-party/video_to_data/reconstruction/modules/v2d_hoi_object_reconstruction/assets/basketball_example/front_stereo_camera_left/1771445413587687057.jpeg b/third-party/video_to_data/reconstruction/modules/v2d_hoi_object_reconstruction/assets/basketball_example/front_stereo_camera_left/1771445413587687057.jpeg new file mode 100644 index 0000000000000000000000000000000000000000..aba1d163e76ac441a28e7dd30ab2f48e66719e1e --- /dev/null +++ b/third-party/video_to_data/reconstruction/modules/v2d_hoi_object_reconstruction/assets/basketball_example/front_stereo_camera_left/1771445413587687057.jpeg @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:18412477db5ec273189f19d98de69d6237b0888ee591ce601e29f19a412d28f2 +size 87574 diff --git a/third-party/video_to_data/reconstruction/modules/v2d_hoi_object_reconstruction/assets/basketball_example/front_stereo_camera_left/1771445413921008097.jpeg b/third-party/video_to_data/reconstruction/modules/v2d_hoi_object_reconstruction/assets/basketball_example/front_stereo_camera_left/1771445413921008097.jpeg new file mode 100644 index 0000000000000000000000000000000000000000..71e78fd46e741cd613674e014ac82118d8b0ce66 --- /dev/null +++ b/third-party/video_to_data/reconstruction/modules/v2d_hoi_object_reconstruction/assets/basketball_example/front_stereo_camera_left/1771445413921008097.jpeg @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:38f352092db7542630d0cc357b3c9346ac545d5771020f4de14d3a3fbf31694e +size 87453 diff --git a/third-party/video_to_data/reconstruction/modules/v2d_hoi_object_reconstruction/assets/basketball_example/front_stereo_camera_left/1771445414254347097.jpeg b/third-party/video_to_data/reconstruction/modules/v2d_hoi_object_reconstruction/assets/basketball_example/front_stereo_camera_left/1771445414254347097.jpeg new file mode 100644 index 0000000000000000000000000000000000000000..520c56723debb772f1e4487cf7866cd8b593f82d --- /dev/null +++ b/third-party/video_to_data/reconstruction/modules/v2d_hoi_object_reconstruction/assets/basketball_example/front_stereo_camera_left/1771445414254347097.jpeg @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:dd30f8ffb349807734b228bcc9a0177611685b4e4e03282a03df00273ca81549 +size 85814 diff --git a/third-party/video_to_data/reconstruction/modules/v2d_hoi_object_reconstruction/assets/basketball_example/front_stereo_camera_left/1771445414587667097.jpeg b/third-party/video_to_data/reconstruction/modules/v2d_hoi_object_reconstruction/assets/basketball_example/front_stereo_camera_left/1771445414587667097.jpeg new file mode 100644 index 0000000000000000000000000000000000000000..52cc7d9e76ae5ed90c82036f7e0eeae17ca832bb --- /dev/null +++ b/third-party/video_to_data/reconstruction/modules/v2d_hoi_object_reconstruction/assets/basketball_example/front_stereo_camera_left/1771445414587667097.jpeg @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:c8b10c2dd9b82dc467a8267f8e64ed53cbbe0ee9ca93105d59c7d12b05ae67a2 +size 85470 diff --git a/third-party/video_to_data/reconstruction/modules/v2d_hoi_object_reconstruction/assets/basketball_example/front_stereo_camera_left/1771445414920988148.jpeg b/third-party/video_to_data/reconstruction/modules/v2d_hoi_object_reconstruction/assets/basketball_example/front_stereo_camera_left/1771445414920988148.jpeg new file mode 100644 index 0000000000000000000000000000000000000000..e45803a87d009daa9b17a555902d1d183f0558e6 --- /dev/null +++ b/third-party/video_to_data/reconstruction/modules/v2d_hoi_object_reconstruction/assets/basketball_example/front_stereo_camera_left/1771445414920988148.jpeg @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:c296b075f7ffd9bc2588ec63f6b91697d70c1697e619ed096980a16284adadf3 +size 86297 diff --git a/third-party/video_to_data/reconstruction/modules/v2d_hoi_object_reconstruction/assets/basketball_example/front_stereo_camera_left/1771445415254309148.jpeg b/third-party/video_to_data/reconstruction/modules/v2d_hoi_object_reconstruction/assets/basketball_example/front_stereo_camera_left/1771445415254309148.jpeg new file mode 100644 index 0000000000000000000000000000000000000000..99bf99f31507465259f5324a95fcf08b4274695b --- /dev/null +++ b/third-party/video_to_data/reconstruction/modules/v2d_hoi_object_reconstruction/assets/basketball_example/front_stereo_camera_left/1771445415254309148.jpeg @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:b4364df6f65224da520518fa105e00301a7f8f9199533f5591ccbb64993929a1 +size 92250 diff --git a/third-party/video_to_data/reconstruction/modules/v2d_hoi_object_reconstruction/assets/basketball_example/front_stereo_camera_left/1771445415587630148.jpeg b/third-party/video_to_data/reconstruction/modules/v2d_hoi_object_reconstruction/assets/basketball_example/front_stereo_camera_left/1771445415587630148.jpeg new file mode 100644 index 0000000000000000000000000000000000000000..9e26affc67d603eb17b511b5eb1f60e221e6f1d3 --- /dev/null +++ b/third-party/video_to_data/reconstruction/modules/v2d_hoi_object_reconstruction/assets/basketball_example/front_stereo_camera_left/1771445415587630148.jpeg @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:a7e6b9dbf55b7034ed468e7d95361752eb8f4303bcf95e6a1f6324597427aa1a +size 95751 diff --git a/third-party/video_to_data/reconstruction/modules/v2d_hoi_object_reconstruction/assets/basketball_example/front_stereo_camera_left/1771445415920969076.jpeg b/third-party/video_to_data/reconstruction/modules/v2d_hoi_object_reconstruction/assets/basketball_example/front_stereo_camera_left/1771445415920969076.jpeg new file mode 100644 index 0000000000000000000000000000000000000000..e4b691b43ef038949477fb84dfba0cb5ba441886 --- /dev/null +++ b/third-party/video_to_data/reconstruction/modules/v2d_hoi_object_reconstruction/assets/basketball_example/front_stereo_camera_left/1771445415920969076.jpeg @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:e7ac5c33ce1293a8f74726c86425045f4c9e8882226ba9784e3b2bab3502a5d6 +size 93084 diff --git a/third-party/video_to_data/reconstruction/modules/v2d_hoi_object_reconstruction/assets/basketball_example/front_stereo_camera_left/1771445416254290076.jpeg b/third-party/video_to_data/reconstruction/modules/v2d_hoi_object_reconstruction/assets/basketball_example/front_stereo_camera_left/1771445416254290076.jpeg new file mode 100644 index 0000000000000000000000000000000000000000..c5cdbcabe35aefe2b7e8c38829dee7a643b17675 --- /dev/null +++ b/third-party/video_to_data/reconstruction/modules/v2d_hoi_object_reconstruction/assets/basketball_example/front_stereo_camera_left/1771445416254290076.jpeg @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:f81f2552ff059d9d70552b95da81dc0c91c670adaa6c400b9f2a663f83739b16 +size 95512 diff --git a/third-party/video_to_data/reconstruction/modules/v2d_hoi_object_reconstruction/assets/basketball_example/front_stereo_camera_left/1771445416587612076.jpeg b/third-party/video_to_data/reconstruction/modules/v2d_hoi_object_reconstruction/assets/basketball_example/front_stereo_camera_left/1771445416587612076.jpeg new file mode 100644 index 0000000000000000000000000000000000000000..7ef2b10e07f3029f8c8feb050908c695d5bc521d --- /dev/null +++ b/third-party/video_to_data/reconstruction/modules/v2d_hoi_object_reconstruction/assets/basketball_example/front_stereo_camera_left/1771445416587612076.jpeg @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:f3340600d01b5e416943b5a6c7656502403621fbdf061aff37805b5095e8e1dd +size 98301 diff --git a/third-party/video_to_data/reconstruction/modules/v2d_hoi_object_reconstruction/assets/basketball_example/front_stereo_camera_left/1771445416920934060.jpeg b/third-party/video_to_data/reconstruction/modules/v2d_hoi_object_reconstruction/assets/basketball_example/front_stereo_camera_left/1771445416920934060.jpeg new file mode 100644 index 0000000000000000000000000000000000000000..c46985cd0b864e6fd9b781678a655a35c6e2417a --- /dev/null +++ b/third-party/video_to_data/reconstruction/modules/v2d_hoi_object_reconstruction/assets/basketball_example/front_stereo_camera_left/1771445416920934060.jpeg @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:7b98a13772197580814ea5252f356bf74330e03b6b7def0b7ea29b64c28fa86c +size 102801 diff --git a/third-party/video_to_data/reconstruction/modules/v2d_hoi_object_reconstruction/assets/basketball_example/front_stereo_camera_left/1771445417254255060.jpeg b/third-party/video_to_data/reconstruction/modules/v2d_hoi_object_reconstruction/assets/basketball_example/front_stereo_camera_left/1771445417254255060.jpeg new file mode 100644 index 0000000000000000000000000000000000000000..52c2c4c330358ee557411658ebce92169713333b --- /dev/null +++ b/third-party/video_to_data/reconstruction/modules/v2d_hoi_object_reconstruction/assets/basketball_example/front_stereo_camera_left/1771445417254255060.jpeg @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:1b6e40106dcc75cdfee31f1f478d8e4c046dd3a2be795fda5a87a2e6f0cdb3dd +size 100590 diff --git a/third-party/video_to_data/reconstruction/modules/v2d_hoi_object_reconstruction/assets/basketball_example/front_stereo_camera_left/1771445417587591060.jpeg b/third-party/video_to_data/reconstruction/modules/v2d_hoi_object_reconstruction/assets/basketball_example/front_stereo_camera_left/1771445417587591060.jpeg new file mode 100644 index 0000000000000000000000000000000000000000..3a3564663043e884f8a529250dd4f80a8207eb9a --- /dev/null +++ b/third-party/video_to_data/reconstruction/modules/v2d_hoi_object_reconstruction/assets/basketball_example/front_stereo_camera_left/1771445417587591060.jpeg @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:3c410e4e2f1ed8ed02993c1ebcaea314e71d7817dfbbb07a6221d857a8c3b9c3 +size 100469 diff --git a/third-party/video_to_data/reconstruction/modules/v2d_hoi_object_reconstruction/assets/basketball_example/front_stereo_camera_left/1771445417920911064.jpeg b/third-party/video_to_data/reconstruction/modules/v2d_hoi_object_reconstruction/assets/basketball_example/front_stereo_camera_left/1771445417920911064.jpeg new file mode 100644 index 0000000000000000000000000000000000000000..9a63fad3689bb7017cbd478df651419f7a0c17ae --- /dev/null +++ b/third-party/video_to_data/reconstruction/modules/v2d_hoi_object_reconstruction/assets/basketball_example/front_stereo_camera_left/1771445417920911064.jpeg @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:a8513ee5c45c2a0f2701ef4fbce94393a514393d65bd906a5ddb071cde1cddb5 +size 102702 diff --git a/third-party/video_to_data/reconstruction/modules/v2d_hoi_object_reconstruction/assets/basketball_example/front_stereo_camera_left/1771445418254232064.jpeg b/third-party/video_to_data/reconstruction/modules/v2d_hoi_object_reconstruction/assets/basketball_example/front_stereo_camera_left/1771445418254232064.jpeg new file mode 100644 index 0000000000000000000000000000000000000000..94e749a11c74b204097311b4627f5fc1db62e009 --- /dev/null +++ b/third-party/video_to_data/reconstruction/modules/v2d_hoi_object_reconstruction/assets/basketball_example/front_stereo_camera_left/1771445418254232064.jpeg @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:4f29161981033b1c3e0d1b9c6eebdc3fe28ab6a944a138888f7dfaee43be2a8c +size 104520 diff --git a/third-party/video_to_data/reconstruction/modules/v2d_hoi_object_reconstruction/assets/basketball_example/front_stereo_camera_left/1771445418587553064.jpeg b/third-party/video_to_data/reconstruction/modules/v2d_hoi_object_reconstruction/assets/basketball_example/front_stereo_camera_left/1771445418587553064.jpeg new file mode 100644 index 0000000000000000000000000000000000000000..3b852429c2680ae1d5a89bdeaa250b6df3ad9d26 --- /dev/null +++ b/third-party/video_to_data/reconstruction/modules/v2d_hoi_object_reconstruction/assets/basketball_example/front_stereo_camera_left/1771445418587553064.jpeg @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:0036815bbb79ce7d85d0605d566bb437e56f9feaee9e7c6fcd34678d6fb580a4 +size 107202 diff --git a/third-party/video_to_data/reconstruction/modules/v2d_hoi_object_reconstruction/assets/basketball_example/front_stereo_camera_left/1771445418920892064.jpeg b/third-party/video_to_data/reconstruction/modules/v2d_hoi_object_reconstruction/assets/basketball_example/front_stereo_camera_left/1771445418920892064.jpeg new file mode 100644 index 0000000000000000000000000000000000000000..c13f7f61f4745d6baf652e3f17fbb80f8ed08034 --- /dev/null +++ b/third-party/video_to_data/reconstruction/modules/v2d_hoi_object_reconstruction/assets/basketball_example/front_stereo_camera_left/1771445418920892064.jpeg @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:b4f3a648e7d80ea626285995273cb676570d91a81b6bf53e940f17ad5fe6ea7d +size 106328 diff --git a/third-party/video_to_data/reconstruction/modules/v2d_hoi_object_reconstruction/assets/basketball_example/front_stereo_camera_left/1771445419254212064.jpeg b/third-party/video_to_data/reconstruction/modules/v2d_hoi_object_reconstruction/assets/basketball_example/front_stereo_camera_left/1771445419254212064.jpeg new file mode 100644 index 0000000000000000000000000000000000000000..d282c096ac2adac6561383f2151bd9a557058cad --- /dev/null +++ b/third-party/video_to_data/reconstruction/modules/v2d_hoi_object_reconstruction/assets/basketball_example/front_stereo_camera_left/1771445419254212064.jpeg @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:67749542006e79d5da495d514e66bd1e0412b76b93f8cfa12aad2e9185b1cb00 +size 99794 diff --git a/third-party/video_to_data/reconstruction/modules/v2d_hoi_object_reconstruction/assets/basketball_example/front_stereo_camera_left/1771445419587533064.jpeg b/third-party/video_to_data/reconstruction/modules/v2d_hoi_object_reconstruction/assets/basketball_example/front_stereo_camera_left/1771445419587533064.jpeg new file mode 100644 index 0000000000000000000000000000000000000000..eeee2c42060e94c31b20bd711cbd162ec4864c78 --- /dev/null +++ b/third-party/video_to_data/reconstruction/modules/v2d_hoi_object_reconstruction/assets/basketball_example/front_stereo_camera_left/1771445419587533064.jpeg @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:713cebb1662383590ad028b20c8c34cf0b37fd0500f129ab9a17eabf3d17d475 +size 99721 diff --git a/third-party/video_to_data/reconstruction/modules/v2d_hoi_object_reconstruction/assets/basketball_example/front_stereo_camera_left/1771445419920854112.jpeg b/third-party/video_to_data/reconstruction/modules/v2d_hoi_object_reconstruction/assets/basketball_example/front_stereo_camera_left/1771445419920854112.jpeg new file mode 100644 index 0000000000000000000000000000000000000000..04ecc75645ccd1eaafb849271fa81df11339e722 --- /dev/null +++ b/third-party/video_to_data/reconstruction/modules/v2d_hoi_object_reconstruction/assets/basketball_example/front_stereo_camera_left/1771445419920854112.jpeg @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:01344974a2c70bd5fe2b8752429ac6adfa5b9be97d8f27f6b9d8929d65e6485c +size 97702 diff --git a/third-party/video_to_data/reconstruction/modules/v2d_hoi_object_reconstruction/assets/basketball_example/front_stereo_camera_left/1771445420254175112.jpeg b/third-party/video_to_data/reconstruction/modules/v2d_hoi_object_reconstruction/assets/basketball_example/front_stereo_camera_left/1771445420254175112.jpeg new file mode 100644 index 0000000000000000000000000000000000000000..db6e6b1320e83fb493e3561d4e3a93f2a1cda54e --- /dev/null +++ b/third-party/video_to_data/reconstruction/modules/v2d_hoi_object_reconstruction/assets/basketball_example/front_stereo_camera_left/1771445420254175112.jpeg @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:8fd9a1a25ff37692309d91acea6c440b05837f521fdb89283426ea6069fa121f +size 96820 diff --git a/third-party/video_to_data/reconstruction/modules/v2d_hoi_object_reconstruction/assets/basketball_example/front_stereo_camera_left/1771445420587514112.jpeg b/third-party/video_to_data/reconstruction/modules/v2d_hoi_object_reconstruction/assets/basketball_example/front_stereo_camera_left/1771445420587514112.jpeg new file mode 100644 index 0000000000000000000000000000000000000000..cae6e794340e62d606e84e4d7eac9c3eb3184ef9 --- /dev/null +++ b/third-party/video_to_data/reconstruction/modules/v2d_hoi_object_reconstruction/assets/basketball_example/front_stereo_camera_left/1771445420587514112.jpeg @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:ec1920fce24177ef7bc8a786b81fa0e41fd44c2a15fd057038e6dd31bede1d52 +size 92948 diff --git a/third-party/video_to_data/reconstruction/modules/v2d_hoi_object_reconstruction/assets/basketball_example/front_stereo_camera_left/1771445420920834172.jpeg b/third-party/video_to_data/reconstruction/modules/v2d_hoi_object_reconstruction/assets/basketball_example/front_stereo_camera_left/1771445420920834172.jpeg new file mode 100644 index 0000000000000000000000000000000000000000..fd0cbead1f70ca06afec5732f103f0bda19a3c15 --- /dev/null +++ b/third-party/video_to_data/reconstruction/modules/v2d_hoi_object_reconstruction/assets/basketball_example/front_stereo_camera_left/1771445420920834172.jpeg @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:11ea54c9bed9f4a566809ebb31f341ccb6c11e2cc4e23cc7f90c87b8e76c8394 +size 93533 diff --git a/third-party/video_to_data/reconstruction/modules/v2d_hoi_object_reconstruction/assets/basketball_example/front_stereo_camera_left/1771445421254155172.jpeg b/third-party/video_to_data/reconstruction/modules/v2d_hoi_object_reconstruction/assets/basketball_example/front_stereo_camera_left/1771445421254155172.jpeg new file mode 100644 index 0000000000000000000000000000000000000000..87df8caa7a479082ecfa6c4d5c7aab385104cb64 --- /dev/null +++ b/third-party/video_to_data/reconstruction/modules/v2d_hoi_object_reconstruction/assets/basketball_example/front_stereo_camera_left/1771445421254155172.jpeg @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:8f05577f61ca91b0e5f4f5bf3d7c36beefe5c88d943c1a64ad7095e7f600c89c +size 94002 diff --git a/third-party/video_to_data/reconstruction/modules/v2d_hoi_object_reconstruction/assets/basketball_example/front_stereo_camera_left/1771445421587476172.jpeg b/third-party/video_to_data/reconstruction/modules/v2d_hoi_object_reconstruction/assets/basketball_example/front_stereo_camera_left/1771445421587476172.jpeg new file mode 100644 index 0000000000000000000000000000000000000000..eed7243fdb826d5c6b9dcefe406832ab2fdcbd60 --- /dev/null +++ b/third-party/video_to_data/reconstruction/modules/v2d_hoi_object_reconstruction/assets/basketball_example/front_stereo_camera_left/1771445421587476172.jpeg @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:a2f4044981e1d376d863adf900806fb89dfb90a6035221c72d96795cd9f4900b +size 95292 diff --git a/third-party/video_to_data/reconstruction/modules/v2d_hoi_object_reconstruction/assets/basketball_example/front_stereo_camera_left/1771445421920797045.jpeg b/third-party/video_to_data/reconstruction/modules/v2d_hoi_object_reconstruction/assets/basketball_example/front_stereo_camera_left/1771445421920797045.jpeg new file mode 100644 index 0000000000000000000000000000000000000000..f699067a89b675a50fcc5fbe5d16fd5f8201ecd9 --- /dev/null +++ b/third-party/video_to_data/reconstruction/modules/v2d_hoi_object_reconstruction/assets/basketball_example/front_stereo_camera_left/1771445421920797045.jpeg @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:affae9a495b9c3306d1bed85d158ba9c4c15438bd113429a7ce580c9c3a510df +size 97328 diff --git a/third-party/video_to_data/reconstruction/modules/v2d_hoi_object_reconstruction/assets/basketball_example/front_stereo_camera_left/1771445422254137045.jpeg b/third-party/video_to_data/reconstruction/modules/v2d_hoi_object_reconstruction/assets/basketball_example/front_stereo_camera_left/1771445422254137045.jpeg new file mode 100644 index 0000000000000000000000000000000000000000..55a6e5e82b9fcdf381cff67078c05b14dd9716cd --- /dev/null +++ b/third-party/video_to_data/reconstruction/modules/v2d_hoi_object_reconstruction/assets/basketball_example/front_stereo_camera_left/1771445422254137045.jpeg @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:a25a5ff43a92bd6fafea463a72dc9e6116f9ccdff9a658fccd7b9f18067acf27 +size 95421 diff --git a/third-party/video_to_data/reconstruction/modules/v2d_hoi_object_reconstruction/assets/basketball_example/front_stereo_camera_left/1771445422587458045.jpeg b/third-party/video_to_data/reconstruction/modules/v2d_hoi_object_reconstruction/assets/basketball_example/front_stereo_camera_left/1771445422587458045.jpeg new file mode 100644 index 0000000000000000000000000000000000000000..36b56165198c45e5bd6b9a5910d4014710a5f0c4 --- /dev/null +++ b/third-party/video_to_data/reconstruction/modules/v2d_hoi_object_reconstruction/assets/basketball_example/front_stereo_camera_left/1771445422587458045.jpeg @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:445c24095b0ccf5a5a9d6e0efab21c9b27e7424fa8a7067f80db667bb39bdc5f +size 95981 diff --git a/third-party/video_to_data/reconstruction/modules/v2d_hoi_object_reconstruction/assets/basketball_example/front_stereo_camera_left/1771445422920780053.jpeg b/third-party/video_to_data/reconstruction/modules/v2d_hoi_object_reconstruction/assets/basketball_example/front_stereo_camera_left/1771445422920780053.jpeg new file mode 100644 index 0000000000000000000000000000000000000000..8bfc7616ba6339f1592203eaa4577052dbbd2250 --- /dev/null +++ b/third-party/video_to_data/reconstruction/modules/v2d_hoi_object_reconstruction/assets/basketball_example/front_stereo_camera_left/1771445422920780053.jpeg @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:f5fe4ff61694600a032bf2b32ee7d5bf04eda324cd86974f2e49185490f35e8b +size 99342 diff --git a/third-party/video_to_data/reconstruction/modules/v2d_hoi_object_reconstruction/assets/basketball_example/front_stereo_camera_left/1771445423254102053.jpeg b/third-party/video_to_data/reconstruction/modules/v2d_hoi_object_reconstruction/assets/basketball_example/front_stereo_camera_left/1771445423254102053.jpeg new file mode 100644 index 0000000000000000000000000000000000000000..2328169fb1f20b33f7d3fcdbab0dcbe47f11b1e4 --- /dev/null +++ b/third-party/video_to_data/reconstruction/modules/v2d_hoi_object_reconstruction/assets/basketball_example/front_stereo_camera_left/1771445423254102053.jpeg @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:f0c8a905408344ebea5b85bd77d9c934cb0556a8dbf92d173c8b70080799138c +size 98852 diff --git a/third-party/video_to_data/reconstruction/modules/v2d_hoi_object_reconstruction/assets/basketball_example/front_stereo_camera_left/1771445423587437053.jpeg b/third-party/video_to_data/reconstruction/modules/v2d_hoi_object_reconstruction/assets/basketball_example/front_stereo_camera_left/1771445423587437053.jpeg new file mode 100644 index 0000000000000000000000000000000000000000..b1bec9e124156f5b7aa1089f016bdd8603612f67 --- /dev/null +++ b/third-party/video_to_data/reconstruction/modules/v2d_hoi_object_reconstruction/assets/basketball_example/front_stereo_camera_left/1771445423587437053.jpeg @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:edda7ce03868486765fc982cebaec269905b04b5a03c87deffa8dc9dbd592bf3 +size 95934 diff --git a/third-party/video_to_data/reconstruction/modules/v2d_hoi_object_reconstruction/assets/basketball_example/front_stereo_camera_left/1771445423920757037.jpeg b/third-party/video_to_data/reconstruction/modules/v2d_hoi_object_reconstruction/assets/basketball_example/front_stereo_camera_left/1771445423920757037.jpeg new file mode 100644 index 0000000000000000000000000000000000000000..caf460f7f7587dbe56f8309f4b0e70582532d46c --- /dev/null +++ b/third-party/video_to_data/reconstruction/modules/v2d_hoi_object_reconstruction/assets/basketball_example/front_stereo_camera_left/1771445423920757037.jpeg @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:10464897d231f29884330222cf8f72f4987c0e496ef86d926f79b5b86fecbc2a +size 95792 diff --git a/third-party/video_to_data/reconstruction/modules/v2d_hoi_object_reconstruction/assets/basketball_example/front_stereo_camera_left/1771445424254078037.jpeg b/third-party/video_to_data/reconstruction/modules/v2d_hoi_object_reconstruction/assets/basketball_example/front_stereo_camera_left/1771445424254078037.jpeg new file mode 100644 index 0000000000000000000000000000000000000000..d2bb589c3dfc9bd6257ede258a33c48d258d7329 --- /dev/null +++ b/third-party/video_to_data/reconstruction/modules/v2d_hoi_object_reconstruction/assets/basketball_example/front_stereo_camera_left/1771445424254078037.jpeg @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:905d8243163b01bc2b13cb090ae6db78ee3006fedd1c5df83d3d2df70b5455ce +size 95263 diff --git a/third-party/video_to_data/reconstruction/modules/v2d_hoi_object_reconstruction/assets/basketball_example/front_stereo_camera_left/1771445424587399037.jpeg b/third-party/video_to_data/reconstruction/modules/v2d_hoi_object_reconstruction/assets/basketball_example/front_stereo_camera_left/1771445424587399037.jpeg new file mode 100644 index 0000000000000000000000000000000000000000..61411c489504fa047a76af966f738885c276ae02 --- /dev/null +++ b/third-party/video_to_data/reconstruction/modules/v2d_hoi_object_reconstruction/assets/basketball_example/front_stereo_camera_left/1771445424587399037.jpeg @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:4d5b06d88d1861f730696fa8ee52f42b709c2bb005b76df1ae800b619b0dc64a +size 91729 diff --git a/third-party/video_to_data/reconstruction/modules/v2d_hoi_object_reconstruction/assets/basketball_example/front_stereo_camera_left/1771445424920720053.jpeg b/third-party/video_to_data/reconstruction/modules/v2d_hoi_object_reconstruction/assets/basketball_example/front_stereo_camera_left/1771445424920720053.jpeg new file mode 100644 index 0000000000000000000000000000000000000000..1f37311bbf16bc2a1efc0f85fc995b102c0277d4 --- /dev/null +++ b/third-party/video_to_data/reconstruction/modules/v2d_hoi_object_reconstruction/assets/basketball_example/front_stereo_camera_left/1771445424920720053.jpeg @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:cb633e58522cab25d8333b0365044ea2cbe1079f61341866e5d8dd03cacb72e1 +size 88025 diff --git a/third-party/video_to_data/reconstruction/modules/v2d_hoi_object_reconstruction/assets/basketball_example/front_stereo_camera_left/1771445425254058053.jpeg b/third-party/video_to_data/reconstruction/modules/v2d_hoi_object_reconstruction/assets/basketball_example/front_stereo_camera_left/1771445425254058053.jpeg new file mode 100644 index 0000000000000000000000000000000000000000..362a6d73fe72d374b7de53d8c27f3657449be717 --- /dev/null +++ b/third-party/video_to_data/reconstruction/modules/v2d_hoi_object_reconstruction/assets/basketball_example/front_stereo_camera_left/1771445425254058053.jpeg @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:82ef78882febd52a2de9d9edb27bf943c7c6326bb77043eb07f6f04b54fc2bf7 +size 90216 diff --git a/third-party/video_to_data/reconstruction/modules/v2d_hoi_object_reconstruction/assets/basketball_example/front_stereo_camera_left/1771445425587379053.jpeg b/third-party/video_to_data/reconstruction/modules/v2d_hoi_object_reconstruction/assets/basketball_example/front_stereo_camera_left/1771445425587379053.jpeg new file mode 100644 index 0000000000000000000000000000000000000000..3d9e87f8b08bbdf3f9f50789f1a80901182bafef --- /dev/null +++ b/third-party/video_to_data/reconstruction/modules/v2d_hoi_object_reconstruction/assets/basketball_example/front_stereo_camera_left/1771445425587379053.jpeg @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:050d70211324e0021ef1b5259f013d713805d974f9039f16369faed50c4b5c67 +size 88983 diff --git a/third-party/video_to_data/reconstruction/modules/v2d_hoi_object_reconstruction/assets/basketball_example/front_stereo_camera_left/1771445425920700017.jpeg b/third-party/video_to_data/reconstruction/modules/v2d_hoi_object_reconstruction/assets/basketball_example/front_stereo_camera_left/1771445425920700017.jpeg new file mode 100644 index 0000000000000000000000000000000000000000..95d5551d17c99ec95afe11b109028e5bab599a25 --- /dev/null +++ b/third-party/video_to_data/reconstruction/modules/v2d_hoi_object_reconstruction/assets/basketball_example/front_stereo_camera_left/1771445425920700017.jpeg @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:d8f078ed20c35341ca4e75d95986086cd473d1a6f6b21d12a63e07b0565971d0 +size 89392 diff --git a/third-party/video_to_data/reconstruction/modules/v2d_hoi_object_reconstruction/assets/basketball_example/front_stereo_camera_left/1771445426254021017.jpeg b/third-party/video_to_data/reconstruction/modules/v2d_hoi_object_reconstruction/assets/basketball_example/front_stereo_camera_left/1771445426254021017.jpeg new file mode 100644 index 0000000000000000000000000000000000000000..018a943b052317a00a5abce6ba42353c1a8256e4 --- /dev/null +++ b/third-party/video_to_data/reconstruction/modules/v2d_hoi_object_reconstruction/assets/basketball_example/front_stereo_camera_left/1771445426254021017.jpeg @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:7d6476a64d9d764bdd43cc50c391fe62e0123589d5d20169078f7b2a11c12fa9 +size 89199 diff --git a/third-party/video_to_data/reconstruction/modules/v2d_hoi_object_reconstruction/assets/basketball_example/front_stereo_camera_left/1771445426587341017.jpeg b/third-party/video_to_data/reconstruction/modules/v2d_hoi_object_reconstruction/assets/basketball_example/front_stereo_camera_left/1771445426587341017.jpeg new file mode 100644 index 0000000000000000000000000000000000000000..dae4c73f890c14f541ca8c358202e92965b7bd30 --- /dev/null +++ b/third-party/video_to_data/reconstruction/modules/v2d_hoi_object_reconstruction/assets/basketball_example/front_stereo_camera_left/1771445426587341017.jpeg @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:7bd5c5beea947c335a94cdb98d104db3d13372f77060edbd615a9fc947b1901a +size 88604 diff --git a/third-party/video_to_data/reconstruction/modules/v2d_hoi_object_reconstruction/assets/basketball_example/front_stereo_camera_left/1771445426920680020.jpeg b/third-party/video_to_data/reconstruction/modules/v2d_hoi_object_reconstruction/assets/basketball_example/front_stereo_camera_left/1771445426920680020.jpeg new file mode 100644 index 0000000000000000000000000000000000000000..a6ce2f3f9a9f94caf26013e2f84bd5b3321e502e --- /dev/null +++ b/third-party/video_to_data/reconstruction/modules/v2d_hoi_object_reconstruction/assets/basketball_example/front_stereo_camera_left/1771445426920680020.jpeg @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:f95e0e1773020cea5300d9ca5e63f7216b8b918d93b61f8a3d0895cb96950a7d +size 89369 diff --git a/third-party/video_to_data/reconstruction/modules/v2d_hoi_object_reconstruction/assets/basketball_example/front_stereo_camera_left/1771445427254001020.jpeg b/third-party/video_to_data/reconstruction/modules/v2d_hoi_object_reconstruction/assets/basketball_example/front_stereo_camera_left/1771445427254001020.jpeg new file mode 100644 index 0000000000000000000000000000000000000000..3f71ed3277d88c1a11a64d67f6219ee3524b90b3 --- /dev/null +++ b/third-party/video_to_data/reconstruction/modules/v2d_hoi_object_reconstruction/assets/basketball_example/front_stereo_camera_left/1771445427254001020.jpeg @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:fafe0bb751ba20f74b416888c041f817482a649033b25d5f6f6f22756e83ae40 +size 88928 diff --git a/third-party/video_to_data/reconstruction/modules/v2d_hoi_object_reconstruction/assets/basketball_example/front_stereo_camera_left/1771445427587322020.jpeg b/third-party/video_to_data/reconstruction/modules/v2d_hoi_object_reconstruction/assets/basketball_example/front_stereo_camera_left/1771445427587322020.jpeg new file mode 100644 index 0000000000000000000000000000000000000000..b6b373fd864abf6afd66d9c86290a9a1677f5ae1 --- /dev/null +++ b/third-party/video_to_data/reconstruction/modules/v2d_hoi_object_reconstruction/assets/basketball_example/front_stereo_camera_left/1771445427587322020.jpeg @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:c09186d8a049419ca3a635f8b558923a1943c6ee48f72d124c890c8227449d21 +size 89334 diff --git a/third-party/video_to_data/reconstruction/modules/v2d_hoi_object_reconstruction/assets/basketball_example/front_stereo_camera_left/1771445427920643017.jpeg b/third-party/video_to_data/reconstruction/modules/v2d_hoi_object_reconstruction/assets/basketball_example/front_stereo_camera_left/1771445427920643017.jpeg new file mode 100644 index 0000000000000000000000000000000000000000..9b07e5e53979e8695f4002dffb780a2f2ae327d8 --- /dev/null +++ b/third-party/video_to_data/reconstruction/modules/v2d_hoi_object_reconstruction/assets/basketball_example/front_stereo_camera_left/1771445427920643017.jpeg @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:6ab325f2ff6b8bb9c03737be845bfde814fe99508676d4b72576ebd04075edc6 +size 90027 diff --git a/third-party/video_to_data/reconstruction/modules/v2d_hoi_object_reconstruction/assets/basketball_example/front_stereo_camera_left/1771445428253983017.jpeg b/third-party/video_to_data/reconstruction/modules/v2d_hoi_object_reconstruction/assets/basketball_example/front_stereo_camera_left/1771445428253983017.jpeg new file mode 100644 index 0000000000000000000000000000000000000000..f4b197e71e6e9ec4ff3d8e3d74b4949feb6bd87b --- /dev/null +++ b/third-party/video_to_data/reconstruction/modules/v2d_hoi_object_reconstruction/assets/basketball_example/front_stereo_camera_left/1771445428253983017.jpeg @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:c31a9751d352b2757fdfa3e952398c28a3eafc4aa3da223ecae8f7d71c7d7501 +size 89609 diff --git a/third-party/video_to_data/reconstruction/modules/v2d_hoi_object_reconstruction/assets/basketball_example/front_stereo_camera_left/1771445428587305017.jpeg b/third-party/video_to_data/reconstruction/modules/v2d_hoi_object_reconstruction/assets/basketball_example/front_stereo_camera_left/1771445428587305017.jpeg new file mode 100644 index 0000000000000000000000000000000000000000..20f5acd1472a14c800cbcf215ecbe4aa2a5f2523 --- /dev/null +++ b/third-party/video_to_data/reconstruction/modules/v2d_hoi_object_reconstruction/assets/basketball_example/front_stereo_camera_left/1771445428587305017.jpeg @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:7818ef4e65edc070cc40289fae3c85a0851ba31c959db89fc44e020e0166fde6 +size 90492 diff --git a/third-party/video_to_data/reconstruction/modules/v2d_hoi_object_reconstruction/assets/basketball_example/front_stereo_camera_left/1771445428920627008.jpeg b/third-party/video_to_data/reconstruction/modules/v2d_hoi_object_reconstruction/assets/basketball_example/front_stereo_camera_left/1771445428920627008.jpeg new file mode 100644 index 0000000000000000000000000000000000000000..4de698340d112d604c5e9d88522588da155668a9 --- /dev/null +++ b/third-party/video_to_data/reconstruction/modules/v2d_hoi_object_reconstruction/assets/basketball_example/front_stereo_camera_left/1771445428920627008.jpeg @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:675ab6a5fe13de4eb209f29bdced2ac33f0971ccf55e72c4ac7d5e50abff6f76 +size 90245 diff --git a/third-party/video_to_data/reconstruction/modules/v2d_hoi_object_reconstruction/assets/basketball_example/front_stereo_camera_left/1771445429253944008.jpeg b/third-party/video_to_data/reconstruction/modules/v2d_hoi_object_reconstruction/assets/basketball_example/front_stereo_camera_left/1771445429253944008.jpeg new file mode 100644 index 0000000000000000000000000000000000000000..7acce09cc1b310f6e472573c2c08f73243fd174f --- /dev/null +++ b/third-party/video_to_data/reconstruction/modules/v2d_hoi_object_reconstruction/assets/basketball_example/front_stereo_camera_left/1771445429253944008.jpeg @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:07b97bdee3eea0d6a8edf8dc6df432ad188c26372376647406975c85136e97ce +size 90382 diff --git a/third-party/video_to_data/reconstruction/modules/v2d_hoi_object_reconstruction/assets/basketball_example/front_stereo_camera_left/1771445429587264008.jpeg b/third-party/video_to_data/reconstruction/modules/v2d_hoi_object_reconstruction/assets/basketball_example/front_stereo_camera_left/1771445429587264008.jpeg new file mode 100644 index 0000000000000000000000000000000000000000..2e304fd8c07290ae1ad90751b1f6b5230f1dc2a3 --- /dev/null +++ b/third-party/video_to_data/reconstruction/modules/v2d_hoi_object_reconstruction/assets/basketball_example/front_stereo_camera_left/1771445429587264008.jpeg @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:822d1c6746266bef0fd159d049f087b17790bf05d92ec44af07dbbf1d6ad29b0 +size 90063 diff --git a/third-party/video_to_data/reconstruction/modules/v2d_hoi_object_reconstruction/assets/basketball_example/front_stereo_camera_left/1771445429920603020.jpeg b/third-party/video_to_data/reconstruction/modules/v2d_hoi_object_reconstruction/assets/basketball_example/front_stereo_camera_left/1771445429920603020.jpeg new file mode 100644 index 0000000000000000000000000000000000000000..16db333bff9a517d7e7c029fa9f1b6039836a5a0 --- /dev/null +++ b/third-party/video_to_data/reconstruction/modules/v2d_hoi_object_reconstruction/assets/basketball_example/front_stereo_camera_left/1771445429920603020.jpeg @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:5efff189d3a48ec9715d4bdbf88e3ee15412aa161276c4e4417d57520f6902d9 +size 89029 diff --git a/third-party/video_to_data/reconstruction/modules/v2d_hoi_object_reconstruction/assets/basketball_example/front_stereo_camera_left/1771445430253924020.jpeg b/third-party/video_to_data/reconstruction/modules/v2d_hoi_object_reconstruction/assets/basketball_example/front_stereo_camera_left/1771445430253924020.jpeg new file mode 100644 index 0000000000000000000000000000000000000000..167b73a2091c510dc8c8421bba0da4d024fbaa67 --- /dev/null +++ b/third-party/video_to_data/reconstruction/modules/v2d_hoi_object_reconstruction/assets/basketball_example/front_stereo_camera_left/1771445430253924020.jpeg @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:29d1bd9428633b160fc642adcd91b7d73533b784ae40b46056816f3ccccc40b6 +size 89837 diff --git a/third-party/video_to_data/reconstruction/modules/v2d_hoi_object_reconstruction/assets/basketball_example/front_stereo_camera_left/1771445430587245020.jpeg b/third-party/video_to_data/reconstruction/modules/v2d_hoi_object_reconstruction/assets/basketball_example/front_stereo_camera_left/1771445430587245020.jpeg new file mode 100644 index 0000000000000000000000000000000000000000..a772313a3991c615668bfcf7f4d9ebc342acffaa --- /dev/null +++ b/third-party/video_to_data/reconstruction/modules/v2d_hoi_object_reconstruction/assets/basketball_example/front_stereo_camera_left/1771445430587245020.jpeg @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:dfd237ac0d91323d6a8e15b209a1d4d593822570902a01df8bb0b783649b836f +size 90603 diff --git a/third-party/video_to_data/reconstruction/modules/v2d_hoi_object_reconstruction/assets/basketball_example/front_stereo_camera_left/1771445430920566129.jpeg b/third-party/video_to_data/reconstruction/modules/v2d_hoi_object_reconstruction/assets/basketball_example/front_stereo_camera_left/1771445430920566129.jpeg new file mode 100644 index 0000000000000000000000000000000000000000..6555014b52d5221f0a386382b5cd4fd7b3aa6de5 --- /dev/null +++ b/third-party/video_to_data/reconstruction/modules/v2d_hoi_object_reconstruction/assets/basketball_example/front_stereo_camera_left/1771445430920566129.jpeg @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:a80fc7757e94d68bc15e2c927c1a8bb922bdbb20ec69f3cec470831e93e5bbaa +size 87240 diff --git a/third-party/video_to_data/reconstruction/modules/v2d_hoi_object_reconstruction/assets/basketball_example/front_stereo_camera_left/1771445431253886129.jpeg b/third-party/video_to_data/reconstruction/modules/v2d_hoi_object_reconstruction/assets/basketball_example/front_stereo_camera_left/1771445431253886129.jpeg new file mode 100644 index 0000000000000000000000000000000000000000..53d6164aefd49d52e72321f0fce4739b0b6eb2af --- /dev/null +++ b/third-party/video_to_data/reconstruction/modules/v2d_hoi_object_reconstruction/assets/basketball_example/front_stereo_camera_left/1771445431253886129.jpeg @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:dcc39079b9a97c8b0ce0c51ac999542921fe0887cd434eb1c4828304bb2f233a +size 90610 diff --git a/third-party/video_to_data/reconstruction/modules/v2d_hoi_object_reconstruction/assets/basketball_example/front_stereo_camera_left/1771445431587225129.jpeg b/third-party/video_to_data/reconstruction/modules/v2d_hoi_object_reconstruction/assets/basketball_example/front_stereo_camera_left/1771445431587225129.jpeg new file mode 100644 index 0000000000000000000000000000000000000000..09f5417a169337d24efc5900b9c09be29ddb20fc --- /dev/null +++ b/third-party/video_to_data/reconstruction/modules/v2d_hoi_object_reconstruction/assets/basketball_example/front_stereo_camera_left/1771445431587225129.jpeg @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:1f84f42a149dd961c7a40b620fbf46879c48ae402ac96bcb8e54d89839b61616 +size 90637 diff --git a/third-party/video_to_data/reconstruction/modules/v2d_hoi_object_reconstruction/assets/basketball_example/front_stereo_camera_left/1771445431920546008.jpeg b/third-party/video_to_data/reconstruction/modules/v2d_hoi_object_reconstruction/assets/basketball_example/front_stereo_camera_left/1771445431920546008.jpeg new file mode 100644 index 0000000000000000000000000000000000000000..5588f1e0418c9ce21842ac8c6051e84858989879 --- /dev/null +++ b/third-party/video_to_data/reconstruction/modules/v2d_hoi_object_reconstruction/assets/basketball_example/front_stereo_camera_left/1771445431920546008.jpeg @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:f1320ecd62725b1668d5f46ef7801aa781b6a40dce783f6aeee71c85b7994265 +size 90497 diff --git a/third-party/video_to_data/reconstruction/modules/v2d_hoi_object_reconstruction/assets/basketball_example/front_stereo_camera_left/1771445432253867008.jpeg b/third-party/video_to_data/reconstruction/modules/v2d_hoi_object_reconstruction/assets/basketball_example/front_stereo_camera_left/1771445432253867008.jpeg new file mode 100644 index 0000000000000000000000000000000000000000..3fb64025d66f02fdf36be215d0496786ddc4e071 --- /dev/null +++ b/third-party/video_to_data/reconstruction/modules/v2d_hoi_object_reconstruction/assets/basketball_example/front_stereo_camera_left/1771445432253867008.jpeg @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:fdf37b75a2d0378693f349665549dc8a420f9c7863168a08c0a29a31db0d055d +size 90733 diff --git a/third-party/video_to_data/reconstruction/modules/v2d_hoi_object_reconstruction/assets/basketball_example/front_stereo_camera_left/1771445432587187008.jpeg b/third-party/video_to_data/reconstruction/modules/v2d_hoi_object_reconstruction/assets/basketball_example/front_stereo_camera_left/1771445432587187008.jpeg new file mode 100644 index 0000000000000000000000000000000000000000..d811796abadb27c941c2aa7fcd306aa4efd2fd2d --- /dev/null +++ b/third-party/video_to_data/reconstruction/modules/v2d_hoi_object_reconstruction/assets/basketball_example/front_stereo_camera_left/1771445432587187008.jpeg @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:728bb208b10953b15959c271b4feb807820a746d6a0a91bfda36f7466032acfb +size 90764 diff --git a/third-party/video_to_data/reconstruction/modules/v2d_hoi_object_reconstruction/assets/basketball_example/front_stereo_camera_left/1771445432920526012.jpeg b/third-party/video_to_data/reconstruction/modules/v2d_hoi_object_reconstruction/assets/basketball_example/front_stereo_camera_left/1771445432920526012.jpeg new file mode 100644 index 0000000000000000000000000000000000000000..e62b5eb802847f8994ad743d8273fe1d0c619433 --- /dev/null +++ b/third-party/video_to_data/reconstruction/modules/v2d_hoi_object_reconstruction/assets/basketball_example/front_stereo_camera_left/1771445432920526012.jpeg @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:5ceaced1ef7fa459228723c1cbea3bf5dbcd41823437161a10980f1661eba9f1 +size 90999 diff --git a/third-party/video_to_data/reconstruction/modules/v2d_hoi_object_reconstruction/assets/basketball_example/front_stereo_camera_left/1771445433253847012.jpeg b/third-party/video_to_data/reconstruction/modules/v2d_hoi_object_reconstruction/assets/basketball_example/front_stereo_camera_left/1771445433253847012.jpeg new file mode 100644 index 0000000000000000000000000000000000000000..58c10d2031950e6ac9565c291526ae252127482b --- /dev/null +++ b/third-party/video_to_data/reconstruction/modules/v2d_hoi_object_reconstruction/assets/basketball_example/front_stereo_camera_left/1771445433253847012.jpeg @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:9c4b11cc18dd0da8d0ad79c0fddfb025911a2ae96d6b19e529807d145a2becdd +size 91044 diff --git a/third-party/video_to_data/reconstruction/modules/v2d_hoi_object_reconstruction/assets/basketball_example/front_stereo_camera_left/1771445433587168012.jpeg b/third-party/video_to_data/reconstruction/modules/v2d_hoi_object_reconstruction/assets/basketball_example/front_stereo_camera_left/1771445433587168012.jpeg new file mode 100644 index 0000000000000000000000000000000000000000..def8f89fbde20808022fc3aecec6ee79893481bc --- /dev/null +++ b/third-party/video_to_data/reconstruction/modules/v2d_hoi_object_reconstruction/assets/basketball_example/front_stereo_camera_left/1771445433587168012.jpeg @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:6e2af65a5b47e7e975633970b12cc56628e9620970f7eea7384ee7cd430552dc +size 90924 diff --git a/third-party/video_to_data/reconstruction/modules/v2d_hoi_object_reconstruction/assets/basketball_example/front_stereo_camera_left/1771445433920489104.jpeg b/third-party/video_to_data/reconstruction/modules/v2d_hoi_object_reconstruction/assets/basketball_example/front_stereo_camera_left/1771445433920489104.jpeg new file mode 100644 index 0000000000000000000000000000000000000000..137e5ad6efdb084b1f54e6d9d0f22176b16768da --- /dev/null +++ b/third-party/video_to_data/reconstruction/modules/v2d_hoi_object_reconstruction/assets/basketball_example/front_stereo_camera_left/1771445433920489104.jpeg @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:6bb8404910d7eb554ae67a3a86167a75bcd5504abd1784cf6c588505c24fc503 +size 90964 diff --git a/third-party/video_to_data/reconstruction/modules/v2d_hoi_object_reconstruction/assets/basketball_example/front_stereo_camera_left/1771445434253809104.jpeg b/third-party/video_to_data/reconstruction/modules/v2d_hoi_object_reconstruction/assets/basketball_example/front_stereo_camera_left/1771445434253809104.jpeg new file mode 100644 index 0000000000000000000000000000000000000000..ab161cb8b16b3f756f25f81554055aa0b5dbea8e --- /dev/null +++ b/third-party/video_to_data/reconstruction/modules/v2d_hoi_object_reconstruction/assets/basketball_example/front_stereo_camera_left/1771445434253809104.jpeg @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:acf3cc6575da690d283ed841a336909b62d458f2b6243116e619d49c1312ec0b +size 91143 diff --git a/third-party/video_to_data/reconstruction/modules/v2d_hoi_object_reconstruction/assets/basketball_example/front_stereo_camera_left/1771445434587151104.jpeg b/third-party/video_to_data/reconstruction/modules/v2d_hoi_object_reconstruction/assets/basketball_example/front_stereo_camera_left/1771445434587151104.jpeg new file mode 100644 index 0000000000000000000000000000000000000000..8a9c7c592fecffed0ab9bbc083a127d7a423b9f5 --- /dev/null +++ b/third-party/video_to_data/reconstruction/modules/v2d_hoi_object_reconstruction/assets/basketball_example/front_stereo_camera_left/1771445434587151104.jpeg @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:4a8447c17b302e1d8e5c051b52fb83804033aa3f79cd216c81cce5acf5dbd17d +size 91833 diff --git a/third-party/video_to_data/reconstruction/modules/v2d_hoi_object_reconstruction/assets/basketball_example/front_stereo_camera_left/1771445434920473056.jpeg b/third-party/video_to_data/reconstruction/modules/v2d_hoi_object_reconstruction/assets/basketball_example/front_stereo_camera_left/1771445434920473056.jpeg new file mode 100644 index 0000000000000000000000000000000000000000..425f2c0091682e25c75d8bbd7f5659887a6ca612 --- /dev/null +++ b/third-party/video_to_data/reconstruction/modules/v2d_hoi_object_reconstruction/assets/basketball_example/front_stereo_camera_left/1771445434920473056.jpeg @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:f07f05b0d70cf059ad5b3c8a19702afd66c01d09bf9e66904d0be3cbe87314f9 +size 92249 diff --git a/third-party/video_to_data/reconstruction/modules/v2d_hoi_object_reconstruction/assets/basketball_example/front_stereo_camera_left/1771445435253790056.jpeg b/third-party/video_to_data/reconstruction/modules/v2d_hoi_object_reconstruction/assets/basketball_example/front_stereo_camera_left/1771445435253790056.jpeg new file mode 100644 index 0000000000000000000000000000000000000000..65b42859cb482a79682cfe3cb0659311f53c3b27 --- /dev/null +++ b/third-party/video_to_data/reconstruction/modules/v2d_hoi_object_reconstruction/assets/basketball_example/front_stereo_camera_left/1771445435253790056.jpeg @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:0cd24e8f1de2cf9eb587c5378f41292fedb0f7eb7001a50b2a3bf3c240de7b94 +size 92404 diff --git a/third-party/video_to_data/reconstruction/modules/v2d_hoi_object_reconstruction/assets/basketball_example/front_stereo_camera_left/1771445435587110056.jpeg b/third-party/video_to_data/reconstruction/modules/v2d_hoi_object_reconstruction/assets/basketball_example/front_stereo_camera_left/1771445435587110056.jpeg new file mode 100644 index 0000000000000000000000000000000000000000..ca676ebe1c8fd1edb61544aa6453926c57080d6a --- /dev/null +++ b/third-party/video_to_data/reconstruction/modules/v2d_hoi_object_reconstruction/assets/basketball_example/front_stereo_camera_left/1771445435587110056.jpeg @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:ee926d909505bf8cae09d1eb012fb7574da873786e3e6737eb7c6015ff1bb971 +size 92116 diff --git a/third-party/video_to_data/reconstruction/modules/v2d_hoi_object_reconstruction/assets/basketball_example/front_stereo_camera_left/1771445435920431020.jpeg b/third-party/video_to_data/reconstruction/modules/v2d_hoi_object_reconstruction/assets/basketball_example/front_stereo_camera_left/1771445435920431020.jpeg new file mode 100644 index 0000000000000000000000000000000000000000..96c06ed70e6d99471acccb3e7ac8c8034ee39225 --- /dev/null +++ b/third-party/video_to_data/reconstruction/modules/v2d_hoi_object_reconstruction/assets/basketball_example/front_stereo_camera_left/1771445435920431020.jpeg @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:43898c349eb098220da94481802060ad7e923310372fbcc11068b7878041f109 +size 92040 diff --git a/third-party/video_to_data/reconstruction/modules/v2d_hoi_object_reconstruction/assets/basketball_example/front_stereo_camera_left/1771445436253770020.jpeg b/third-party/video_to_data/reconstruction/modules/v2d_hoi_object_reconstruction/assets/basketball_example/front_stereo_camera_left/1771445436253770020.jpeg new file mode 100644 index 0000000000000000000000000000000000000000..ff00d29aa17800dc529c9b9b93ab92187f8c90f0 --- /dev/null +++ b/third-party/video_to_data/reconstruction/modules/v2d_hoi_object_reconstruction/assets/basketball_example/front_stereo_camera_left/1771445436253770020.jpeg @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:ce0e076232b0f042ad75938250c6d83cdc0d80fdf8ce7571998e440d13d7399b +size 92357 diff --git a/third-party/video_to_data/reconstruction/modules/v2d_hoi_object_reconstruction/assets/basketball_example/front_stereo_camera_left/1771445436587091020.jpeg b/third-party/video_to_data/reconstruction/modules/v2d_hoi_object_reconstruction/assets/basketball_example/front_stereo_camera_left/1771445436587091020.jpeg new file mode 100644 index 0000000000000000000000000000000000000000..7cc168e3a676c62878f36f04b508beb62b81f46f --- /dev/null +++ b/third-party/video_to_data/reconstruction/modules/v2d_hoi_object_reconstruction/assets/basketball_example/front_stereo_camera_left/1771445436587091020.jpeg @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:94df597f5c40d0837c6d9d9e33e8ee64bf2a8f859a35c4a1ee19bb31118ad66c +size 92204 diff --git a/third-party/video_to_data/reconstruction/modules/v2d_hoi_object_reconstruction/assets/basketball_example/front_stereo_camera_left/1771445436920411032.jpeg b/third-party/video_to_data/reconstruction/modules/v2d_hoi_object_reconstruction/assets/basketball_example/front_stereo_camera_left/1771445436920411032.jpeg new file mode 100644 index 0000000000000000000000000000000000000000..5bab9ae49d40f737e02906a56f8a6aa3c703ca7e --- /dev/null +++ b/third-party/video_to_data/reconstruction/modules/v2d_hoi_object_reconstruction/assets/basketball_example/front_stereo_camera_left/1771445436920411032.jpeg @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:b4bd752b25830be3c8174d83397ebc15c63b4cc4ada81429b06610fafe02145b +size 91912 diff --git a/third-party/video_to_data/reconstruction/modules/v2d_hoi_object_reconstruction/assets/basketball_example/front_stereo_camera_left/1771445437253732032.jpeg b/third-party/video_to_data/reconstruction/modules/v2d_hoi_object_reconstruction/assets/basketball_example/front_stereo_camera_left/1771445437253732032.jpeg new file mode 100644 index 0000000000000000000000000000000000000000..84e295112f343ced4843c01efb0ceecd32989516 --- /dev/null +++ b/third-party/video_to_data/reconstruction/modules/v2d_hoi_object_reconstruction/assets/basketball_example/front_stereo_camera_left/1771445437253732032.jpeg @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:86fde3f22343566f39b203d72cb353697af74396c145176caf03215ac425376c +size 91264 diff --git a/third-party/video_to_data/reconstruction/modules/v2d_hoi_object_reconstruction/assets/basketball_example/front_stereo_camera_left/1771445437587071032.jpeg b/third-party/video_to_data/reconstruction/modules/v2d_hoi_object_reconstruction/assets/basketball_example/front_stereo_camera_left/1771445437587071032.jpeg new file mode 100644 index 0000000000000000000000000000000000000000..e596c2130810ee4fed180780acc10644d9944636 --- /dev/null +++ b/third-party/video_to_data/reconstruction/modules/v2d_hoi_object_reconstruction/assets/basketball_example/front_stereo_camera_left/1771445437587071032.jpeg @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:49e09e569a12a777220a28eebcad5f3b69598f36904cb611930d0c8601aa5b3b +size 91701 diff --git a/third-party/video_to_data/reconstruction/modules/v2d_hoi_object_reconstruction/assets/basketball_example/front_stereo_camera_left/1771445437920392040.jpeg b/third-party/video_to_data/reconstruction/modules/v2d_hoi_object_reconstruction/assets/basketball_example/front_stereo_camera_left/1771445437920392040.jpeg new file mode 100644 index 0000000000000000000000000000000000000000..258ba2ec87628aa3946228004efa48c7c7ca79ad --- /dev/null +++ b/third-party/video_to_data/reconstruction/modules/v2d_hoi_object_reconstruction/assets/basketball_example/front_stereo_camera_left/1771445437920392040.jpeg @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:46472df49c9b0ef4c4a2270340c4c70d887a8379c7280cc1677ed52f03db413e +size 91570 diff --git a/third-party/video_to_data/reconstruction/modules/v2d_hoi_object_reconstruction/assets/basketball_example/front_stereo_camera_left/1771445438253712040.jpeg b/third-party/video_to_data/reconstruction/modules/v2d_hoi_object_reconstruction/assets/basketball_example/front_stereo_camera_left/1771445438253712040.jpeg new file mode 100644 index 0000000000000000000000000000000000000000..debaaed521e25359880926a95ae246a57867d303 --- /dev/null +++ b/third-party/video_to_data/reconstruction/modules/v2d_hoi_object_reconstruction/assets/basketball_example/front_stereo_camera_left/1771445438253712040.jpeg @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:6bd0dbed58c2095a8d51004fc7bb0099b11025a60437a31ad6267bccc8e61b80 +size 93005 diff --git a/third-party/video_to_data/reconstruction/modules/v2d_hoi_object_reconstruction/assets/basketball_example/front_stereo_camera_left/1771445438587033040.jpeg b/third-party/video_to_data/reconstruction/modules/v2d_hoi_object_reconstruction/assets/basketball_example/front_stereo_camera_left/1771445438587033040.jpeg new file mode 100644 index 0000000000000000000000000000000000000000..42f908e71f23fa0f2f4ec960f02585eb10e1cd1c --- /dev/null +++ b/third-party/video_to_data/reconstruction/modules/v2d_hoi_object_reconstruction/assets/basketball_example/front_stereo_camera_left/1771445438587033040.jpeg @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:92078d476fa12d544cc2e30b3f2bc3c88ed3b088d803b563e2c39f70fa7b8b2e +size 96807 diff --git a/third-party/video_to_data/reconstruction/modules/v2d_hoi_object_reconstruction/assets/basketball_example/front_stereo_camera_left/1771445438920354028.jpeg b/third-party/video_to_data/reconstruction/modules/v2d_hoi_object_reconstruction/assets/basketball_example/front_stereo_camera_left/1771445438920354028.jpeg new file mode 100644 index 0000000000000000000000000000000000000000..394b3d1d1ea6c28e379012ec3610cd08e17aa02f --- /dev/null +++ b/third-party/video_to_data/reconstruction/modules/v2d_hoi_object_reconstruction/assets/basketball_example/front_stereo_camera_left/1771445438920354028.jpeg @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:c594262db998b350604b465f5a1bbdbf7de58b9131b6e590a0881fc32b3d0b1f +size 96987 diff --git a/third-party/video_to_data/reconstruction/modules/v2d_hoi_object_reconstruction/assets/basketball_example/front_stereo_camera_left/1771445439253693028.jpeg b/third-party/video_to_data/reconstruction/modules/v2d_hoi_object_reconstruction/assets/basketball_example/front_stereo_camera_left/1771445439253693028.jpeg new file mode 100644 index 0000000000000000000000000000000000000000..249ee5bc03fe84ffd3eca50b5155cedd985335f7 --- /dev/null +++ b/third-party/video_to_data/reconstruction/modules/v2d_hoi_object_reconstruction/assets/basketball_example/front_stereo_camera_left/1771445439253693028.jpeg @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:b6f83568c6adb61ed893c693c8571ea2ead193ea6c92b029fb388d5f93e034bd +size 97311 diff --git a/third-party/video_to_data/reconstruction/modules/v2d_hoi_object_reconstruction/assets/basketball_example/front_stereo_camera_left/1771445439587014028.jpeg b/third-party/video_to_data/reconstruction/modules/v2d_hoi_object_reconstruction/assets/basketball_example/front_stereo_camera_left/1771445439587014028.jpeg new file mode 100644 index 0000000000000000000000000000000000000000..801b671ebb7fe426693782afd29677c2dd281eed --- /dev/null +++ b/third-party/video_to_data/reconstruction/modules/v2d_hoi_object_reconstruction/assets/basketball_example/front_stereo_camera_left/1771445439587014028.jpeg @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:14c521032f04c08f1679d7d1e6b392e5e3e7cac13f323cde4d699d0332722e72 +size 97881 diff --git a/third-party/video_to_data/reconstruction/modules/v2d_hoi_object_reconstruction/assets/basketball_example/front_stereo_camera_left/1771445439920336052.jpeg b/third-party/video_to_data/reconstruction/modules/v2d_hoi_object_reconstruction/assets/basketball_example/front_stereo_camera_left/1771445439920336052.jpeg new file mode 100644 index 0000000000000000000000000000000000000000..129c3ffbc8cb118b9de9ce8939ddc5ced9c3719b --- /dev/null +++ b/third-party/video_to_data/reconstruction/modules/v2d_hoi_object_reconstruction/assets/basketball_example/front_stereo_camera_left/1771445439920336052.jpeg @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:7ce73a4e2cca59a2e2c29252c60eb3199974a781bd41246e93cc9a37b943a0da +size 96814 diff --git a/third-party/video_to_data/reconstruction/modules/v2d_hoi_object_reconstruction/assets/basketball_example/front_stereo_camera_left/1771445440253658052.jpeg b/third-party/video_to_data/reconstruction/modules/v2d_hoi_object_reconstruction/assets/basketball_example/front_stereo_camera_left/1771445440253658052.jpeg new file mode 100644 index 0000000000000000000000000000000000000000..2bad2f1a3b9cdb1d2d2f28a3b2e9f985077bee24 --- /dev/null +++ b/third-party/video_to_data/reconstruction/modules/v2d_hoi_object_reconstruction/assets/basketball_example/front_stereo_camera_left/1771445440253658052.jpeg @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:a45bc10116fccd0460c08fd5179a85e9e77a925cb93669f507b79d268b7c2425 +size 83591 diff --git a/third-party/video_to_data/reconstruction/modules/v2d_hoi_object_reconstruction/assets/basketball_example/front_stereo_camera_left/1771445440586997052.jpeg b/third-party/video_to_data/reconstruction/modules/v2d_hoi_object_reconstruction/assets/basketball_example/front_stereo_camera_left/1771445440586997052.jpeg new file mode 100644 index 0000000000000000000000000000000000000000..f87d9e42fffe28e8207a409367adf175fb669e75 --- /dev/null +++ b/third-party/video_to_data/reconstruction/modules/v2d_hoi_object_reconstruction/assets/basketball_example/front_stereo_camera_left/1771445440586997052.jpeg @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:64d3c5347ed70d02bdd860c76bcb5f6ceb65ca05b3cb05249ae14b38413367fa +size 93002 diff --git a/third-party/video_to_data/reconstruction/modules/v2d_hoi_object_reconstruction/assets/basketball_example/front_stereo_camera_left/1771445440920315080.jpeg b/third-party/video_to_data/reconstruction/modules/v2d_hoi_object_reconstruction/assets/basketball_example/front_stereo_camera_left/1771445440920315080.jpeg new file mode 100644 index 0000000000000000000000000000000000000000..643644f65504a1dee9f78f4dffb8e49d77b40686 --- /dev/null +++ b/third-party/video_to_data/reconstruction/modules/v2d_hoi_object_reconstruction/assets/basketball_example/front_stereo_camera_left/1771445440920315080.jpeg @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:b20c1b92bd4f49c48c63e3931ceae530c90c1ab763f1bc852b767de46234c540 +size 93474 diff --git a/third-party/video_to_data/reconstruction/modules/v2d_hoi_object_reconstruction/assets/basketball_example/front_stereo_camera_left/1771445441253635080.jpeg b/third-party/video_to_data/reconstruction/modules/v2d_hoi_object_reconstruction/assets/basketball_example/front_stereo_camera_left/1771445441253635080.jpeg new file mode 100644 index 0000000000000000000000000000000000000000..2a07f9360907201c4bcca6867bd1330272caf10e --- /dev/null +++ b/third-party/video_to_data/reconstruction/modules/v2d_hoi_object_reconstruction/assets/basketball_example/front_stereo_camera_left/1771445441253635080.jpeg @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:44ddcc817ac957a4b8581e91a3fa13e7825067765dfc180bf444ba3128b6cb19 +size 96034 diff --git a/third-party/video_to_data/reconstruction/modules/v2d_hoi_object_reconstruction/assets/basketball_example/front_stereo_camera_left/1771445441586956080.jpeg b/third-party/video_to_data/reconstruction/modules/v2d_hoi_object_reconstruction/assets/basketball_example/front_stereo_camera_left/1771445441586956080.jpeg new file mode 100644 index 0000000000000000000000000000000000000000..a10b9e6997a3aeca5a8d1267133fdd4666cca520 --- /dev/null +++ b/third-party/video_to_data/reconstruction/modules/v2d_hoi_object_reconstruction/assets/basketball_example/front_stereo_camera_left/1771445441586956080.jpeg @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:d1a29218ff22abfb835805f531cf093be78d19804b16f77d14f56d7ce3b42190 +size 91901 diff --git a/third-party/video_to_data/reconstruction/modules/v2d_hoi_object_reconstruction/assets/basketball_example/front_stereo_camera_left/1771445441920277064.jpeg b/third-party/video_to_data/reconstruction/modules/v2d_hoi_object_reconstruction/assets/basketball_example/front_stereo_camera_left/1771445441920277064.jpeg new file mode 100644 index 0000000000000000000000000000000000000000..e118c98b79e28cb2ac991424dc1f745095d77e3e --- /dev/null +++ b/third-party/video_to_data/reconstruction/modules/v2d_hoi_object_reconstruction/assets/basketball_example/front_stereo_camera_left/1771445441920277064.jpeg @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:572e09dd943700f62c45ed10ecd2b5948da124a13eca22c26daa2f27e7ce4063 +size 99541 diff --git a/third-party/video_to_data/reconstruction/modules/v2d_hoi_object_reconstruction/assets/basketball_example/front_stereo_camera_left/1771445442253616064.jpeg b/third-party/video_to_data/reconstruction/modules/v2d_hoi_object_reconstruction/assets/basketball_example/front_stereo_camera_left/1771445442253616064.jpeg new file mode 100644 index 0000000000000000000000000000000000000000..2290c2695d4eabb609b7602ac8b923f4b586875e --- /dev/null +++ b/third-party/video_to_data/reconstruction/modules/v2d_hoi_object_reconstruction/assets/basketball_example/front_stereo_camera_left/1771445442253616064.jpeg @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:112edd48b1de95a8451bff14cdc9f31a89402afa9ae4db47c659badeddf13610 +size 97064 diff --git a/third-party/video_to_data/reconstruction/modules/v2d_hoi_object_reconstruction/assets/basketball_example/front_stereo_camera_left/1771445442586936064.jpeg b/third-party/video_to_data/reconstruction/modules/v2d_hoi_object_reconstruction/assets/basketball_example/front_stereo_camera_left/1771445442586936064.jpeg new file mode 100644 index 0000000000000000000000000000000000000000..409538a078b92eb37c6541a0ccb8361a0b3c3e8c --- /dev/null +++ b/third-party/video_to_data/reconstruction/modules/v2d_hoi_object_reconstruction/assets/basketball_example/front_stereo_camera_left/1771445442586936064.jpeg @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:a664a1e19e37f4d860845ec1227f1aa812eee86a2927d56081b2736c5bab8d4b +size 98821 diff --git a/third-party/video_to_data/reconstruction/modules/v2d_hoi_object_reconstruction/assets/basketball_example/front_stereo_camera_left/1771445442920257064.jpeg b/third-party/video_to_data/reconstruction/modules/v2d_hoi_object_reconstruction/assets/basketball_example/front_stereo_camera_left/1771445442920257064.jpeg new file mode 100644 index 0000000000000000000000000000000000000000..c85ea19667fbd3544ef0c974b993d7223771ed66 --- /dev/null +++ b/third-party/video_to_data/reconstruction/modules/v2d_hoi_object_reconstruction/assets/basketball_example/front_stereo_camera_left/1771445442920257064.jpeg @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:20b21506851317f5c829c985402d6ec75f21a443d13ba5f29082cd344762f8fe +size 97033 diff --git a/third-party/video_to_data/reconstruction/modules/v2d_hoi_object_reconstruction/assets/basketball_example/front_stereo_camera_left/1771445443253578064.jpeg b/third-party/video_to_data/reconstruction/modules/v2d_hoi_object_reconstruction/assets/basketball_example/front_stereo_camera_left/1771445443253578064.jpeg new file mode 100644 index 0000000000000000000000000000000000000000..840dd5ad51f899aeda091453b0776ad7daf06c08 --- /dev/null +++ b/third-party/video_to_data/reconstruction/modules/v2d_hoi_object_reconstruction/assets/basketball_example/front_stereo_camera_left/1771445443253578064.jpeg @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:f1542f6470fde2466a0c99047b5c0645bd24fe8f9293fa045c42aad96a7aad66 +size 103194 diff --git a/third-party/video_to_data/reconstruction/modules/v2d_hoi_object_reconstruction/assets/basketball_example/front_stereo_camera_left/1771445443586899064.jpeg b/third-party/video_to_data/reconstruction/modules/v2d_hoi_object_reconstruction/assets/basketball_example/front_stereo_camera_left/1771445443586899064.jpeg new file mode 100644 index 0000000000000000000000000000000000000000..71abeb9409e8d97f9f828fbc3f4852a9022ffbe0 --- /dev/null +++ b/third-party/video_to_data/reconstruction/modules/v2d_hoi_object_reconstruction/assets/basketball_example/front_stereo_camera_left/1771445443586899064.jpeg @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:e3ee540baa59ce2068d44573df5f3033116dd7a3e2db76e67d4b785ffff8bb5b +size 99962 diff --git a/third-party/video_to_data/reconstruction/modules/v2d_hoi_object_reconstruction/assets/basketball_example/front_stereo_camera_left/1771445443920237176.jpeg b/third-party/video_to_data/reconstruction/modules/v2d_hoi_object_reconstruction/assets/basketball_example/front_stereo_camera_left/1771445443920237176.jpeg new file mode 100644 index 0000000000000000000000000000000000000000..dddd85e895430edc3e60ef93599f175ad688c267 --- /dev/null +++ b/third-party/video_to_data/reconstruction/modules/v2d_hoi_object_reconstruction/assets/basketball_example/front_stereo_camera_left/1771445443920237176.jpeg @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:9a2f3c9b149a5a5d87b994af73d1d46a3137fb74ede7f5419e4874b5fc2cc953 +size 98418 diff --git a/third-party/video_to_data/reconstruction/modules/v2d_hoi_object_reconstruction/assets/basketball_example/front_stereo_camera_left/1771445444253558176.jpeg b/third-party/video_to_data/reconstruction/modules/v2d_hoi_object_reconstruction/assets/basketball_example/front_stereo_camera_left/1771445444253558176.jpeg new file mode 100644 index 0000000000000000000000000000000000000000..6812e287e084b2a9b249b1909b185f218976a6df --- /dev/null +++ b/third-party/video_to_data/reconstruction/modules/v2d_hoi_object_reconstruction/assets/basketball_example/front_stereo_camera_left/1771445444253558176.jpeg @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:641de50170db5cde654e6a2506433be76d51eeed7c5d5cf60d3c84eb025a6e7c +size 95475 diff --git a/third-party/video_to_data/reconstruction/modules/v2d_hoi_object_reconstruction/assets/basketball_example/front_stereo_camera_left/1771445444586879176.jpeg b/third-party/video_to_data/reconstruction/modules/v2d_hoi_object_reconstruction/assets/basketball_example/front_stereo_camera_left/1771445444586879176.jpeg new file mode 100644 index 0000000000000000000000000000000000000000..9818eb85ad24c915f55ece0c825f06e2d80e8b68 --- /dev/null +++ b/third-party/video_to_data/reconstruction/modules/v2d_hoi_object_reconstruction/assets/basketball_example/front_stereo_camera_left/1771445444586879176.jpeg @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:a7681429b7fa64aac3ab267bd06801c58ed050173dd77ba331426f99da8c95c1 +size 94785 diff --git a/third-party/video_to_data/reconstruction/modules/v2d_hoi_object_reconstruction/assets/basketball_example/front_stereo_camera_left/1771445444920200068.jpeg b/third-party/video_to_data/reconstruction/modules/v2d_hoi_object_reconstruction/assets/basketball_example/front_stereo_camera_left/1771445444920200068.jpeg new file mode 100644 index 0000000000000000000000000000000000000000..381e0f5403dd3cd73e840f0d097080012e93c994 --- /dev/null +++ b/third-party/video_to_data/reconstruction/modules/v2d_hoi_object_reconstruction/assets/basketball_example/front_stereo_camera_left/1771445444920200068.jpeg @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:1b77b9f5f6a143853ab033ce269c28634865f6cc3771951bcbeba143a235e283 +size 99451 diff --git a/third-party/video_to_data/reconstruction/modules/v2d_hoi_object_reconstruction/assets/basketball_example/front_stereo_camera_left/1771445445253539068.jpeg b/third-party/video_to_data/reconstruction/modules/v2d_hoi_object_reconstruction/assets/basketball_example/front_stereo_camera_left/1771445445253539068.jpeg new file mode 100644 index 0000000000000000000000000000000000000000..6578ca27d2957072515d04dbf9290051610d0579 --- /dev/null +++ b/third-party/video_to_data/reconstruction/modules/v2d_hoi_object_reconstruction/assets/basketball_example/front_stereo_camera_left/1771445445253539068.jpeg @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:e6015e950df13806cb63b9f4bbb45a7d5f789b342aa25ad8c95510a68f6fddb5 +size 95712 diff --git a/third-party/video_to_data/reconstruction/modules/v2d_hoi_object_reconstruction/assets/basketball_example/front_stereo_camera_left/1771445445586860068.jpeg b/third-party/video_to_data/reconstruction/modules/v2d_hoi_object_reconstruction/assets/basketball_example/front_stereo_camera_left/1771445445586860068.jpeg new file mode 100644 index 0000000000000000000000000000000000000000..77efd8578eb83db6aa734323bd9227fccfd2eeda --- /dev/null +++ b/third-party/video_to_data/reconstruction/modules/v2d_hoi_object_reconstruction/assets/basketball_example/front_stereo_camera_left/1771445445586860068.jpeg @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:2ff4f9a3ae0c0f014eccbe1d77f266e37531eaede09f4ceb86505b7306cf1449 +size 94103 diff --git a/third-party/video_to_data/reconstruction/modules/v2d_hoi_object_reconstruction/assets/basketball_example/front_stereo_camera_left/1771445445920182052.jpeg b/third-party/video_to_data/reconstruction/modules/v2d_hoi_object_reconstruction/assets/basketball_example/front_stereo_camera_left/1771445445920182052.jpeg new file mode 100644 index 0000000000000000000000000000000000000000..d692e62a08eba66b9ffdfb5944d60199ef8398e4 --- /dev/null +++ b/third-party/video_to_data/reconstruction/modules/v2d_hoi_object_reconstruction/assets/basketball_example/front_stereo_camera_left/1771445445920182052.jpeg @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:f1bd4e23a2046d9018cf622c73cc9b200914ec1a1cb23884e220065832fc6c7d +size 95045 diff --git a/third-party/video_to_data/reconstruction/modules/v2d_hoi_object_reconstruction/assets/basketball_example/front_stereo_camera_left/1771445446253504052.jpeg b/third-party/video_to_data/reconstruction/modules/v2d_hoi_object_reconstruction/assets/basketball_example/front_stereo_camera_left/1771445446253504052.jpeg new file mode 100644 index 0000000000000000000000000000000000000000..45c75cc987c18f0bbdbb309115f644d1f5f45a51 --- /dev/null +++ b/third-party/video_to_data/reconstruction/modules/v2d_hoi_object_reconstruction/assets/basketball_example/front_stereo_camera_left/1771445446253504052.jpeg @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:b68534c7f83bda4f9751a39bca6a84fd3a5922724574b0d7d21220f97f3628d1 +size 98682 diff --git a/third-party/video_to_data/reconstruction/modules/v2d_hoi_object_reconstruction/assets/basketball_example/front_stereo_camera_left/1771445446586825052.jpeg b/third-party/video_to_data/reconstruction/modules/v2d_hoi_object_reconstruction/assets/basketball_example/front_stereo_camera_left/1771445446586825052.jpeg new file mode 100644 index 0000000000000000000000000000000000000000..9633d5305575527d4e29edb8961fdacf2dbafa88 --- /dev/null +++ b/third-party/video_to_data/reconstruction/modules/v2d_hoi_object_reconstruction/assets/basketball_example/front_stereo_camera_left/1771445446586825052.jpeg @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:b21525f84991b6da07160275dcff46c3045cb13d799adf6432ab0d8a1ff9bb38 +size 97219 diff --git a/third-party/video_to_data/reconstruction/modules/v2d_hoi_object_reconstruction/assets/basketball_example/front_stereo_camera_left/1771445446920160088.jpeg b/third-party/video_to_data/reconstruction/modules/v2d_hoi_object_reconstruction/assets/basketball_example/front_stereo_camera_left/1771445446920160088.jpeg new file mode 100644 index 0000000000000000000000000000000000000000..8e98dfadfa072a45254c5cab0740e2765d430dfa --- /dev/null +++ b/third-party/video_to_data/reconstruction/modules/v2d_hoi_object_reconstruction/assets/basketball_example/front_stereo_camera_left/1771445446920160088.jpeg @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:834ae8748da3a0d4f145aaeef453c0c475565f2af94d1851792fc317dd5f8e76 +size 95329 diff --git a/third-party/video_to_data/reconstruction/modules/v2d_hoi_object_reconstruction/assets/basketball_example/front_stereo_camera_left/1771445447253481088.jpeg b/third-party/video_to_data/reconstruction/modules/v2d_hoi_object_reconstruction/assets/basketball_example/front_stereo_camera_left/1771445447253481088.jpeg new file mode 100644 index 0000000000000000000000000000000000000000..fc53852aee4ab08307b1f4dd4a2ee9c38ea7471a --- /dev/null +++ b/third-party/video_to_data/reconstruction/modules/v2d_hoi_object_reconstruction/assets/basketball_example/front_stereo_camera_left/1771445447253481088.jpeg @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:846407258215c05a95da068551dd50f8042c957000db48e01563e7c100d986fd +size 93763 diff --git a/third-party/video_to_data/reconstruction/modules/v2d_hoi_object_reconstruction/assets/basketball_example/front_stereo_camera_left/1771445447586802088.jpeg b/third-party/video_to_data/reconstruction/modules/v2d_hoi_object_reconstruction/assets/basketball_example/front_stereo_camera_left/1771445447586802088.jpeg new file mode 100644 index 0000000000000000000000000000000000000000..792c214af0812f0a18d0f286e5feee51fe0e9aa8 --- /dev/null +++ b/third-party/video_to_data/reconstruction/modules/v2d_hoi_object_reconstruction/assets/basketball_example/front_stereo_camera_left/1771445447586802088.jpeg @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:9206155c564a3488db1ba472870017803b941cfe3b7ec090d4b055809a6a3d69 +size 93240 diff --git a/third-party/video_to_data/reconstruction/modules/v2d_hoi_object_reconstruction/assets/basketball_example/front_stereo_camera_left/1771445447920123052.jpeg b/third-party/video_to_data/reconstruction/modules/v2d_hoi_object_reconstruction/assets/basketball_example/front_stereo_camera_left/1771445447920123052.jpeg new file mode 100644 index 0000000000000000000000000000000000000000..ab5834f3a8a88be60f9805432720b1f9eb582de0 --- /dev/null +++ b/third-party/video_to_data/reconstruction/modules/v2d_hoi_object_reconstruction/assets/basketball_example/front_stereo_camera_left/1771445447920123052.jpeg @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:9c53a16afb5b70f9bc8e19a9b58de3fef01979ccb8e9d66c7cdca4015e7bedb1 +size 93256 diff --git a/third-party/video_to_data/reconstruction/modules/v2d_hoi_object_reconstruction/assets/basketball_example/front_stereo_camera_left/1771445448253443052.jpeg b/third-party/video_to_data/reconstruction/modules/v2d_hoi_object_reconstruction/assets/basketball_example/front_stereo_camera_left/1771445448253443052.jpeg new file mode 100644 index 0000000000000000000000000000000000000000..da655cb4e7e7f81a663647f3c2bbcb7381d9687a --- /dev/null +++ b/third-party/video_to_data/reconstruction/modules/v2d_hoi_object_reconstruction/assets/basketball_example/front_stereo_camera_left/1771445448253443052.jpeg @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:da4bb6215ce2bb2e80c41bf1535619c8dff2832c4663b51db4d04334ed1d36e5 +size 91470 diff --git a/third-party/video_to_data/reconstruction/modules/v2d_hoi_object_reconstruction/assets/basketball_example/front_stereo_camera_left/1771445448586782052.jpeg b/third-party/video_to_data/reconstruction/modules/v2d_hoi_object_reconstruction/assets/basketball_example/front_stereo_camera_left/1771445448586782052.jpeg new file mode 100644 index 0000000000000000000000000000000000000000..78623bede177a76f09b42d522b350e5c6330c500 --- /dev/null +++ b/third-party/video_to_data/reconstruction/modules/v2d_hoi_object_reconstruction/assets/basketball_example/front_stereo_camera_left/1771445448586782052.jpeg @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:c947f09611f0e1b4bd9876ac1bd8d94bee79ad003e94f8cf1e15d7056f6921c6 +size 90213 diff --git a/third-party/video_to_data/reconstruction/modules/v2d_hoi_object_reconstruction/assets/basketball_example/front_stereo_camera_left/1771445448920103048.jpeg b/third-party/video_to_data/reconstruction/modules/v2d_hoi_object_reconstruction/assets/basketball_example/front_stereo_camera_left/1771445448920103048.jpeg new file mode 100644 index 0000000000000000000000000000000000000000..db446206fd41837a42e54fb4a7df855c672452f5 --- /dev/null +++ b/third-party/video_to_data/reconstruction/modules/v2d_hoi_object_reconstruction/assets/basketball_example/front_stereo_camera_left/1771445448920103048.jpeg @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:1c72ec8bf769cbd11db24c9e07d926709020a5229594ba79b1f8e69b66c0908b +size 89449 diff --git a/third-party/video_to_data/reconstruction/modules/v2d_hoi_object_reconstruction/assets/basketball_example/front_stereo_camera_left/1771445449253424048.jpeg b/third-party/video_to_data/reconstruction/modules/v2d_hoi_object_reconstruction/assets/basketball_example/front_stereo_camera_left/1771445449253424048.jpeg new file mode 100644 index 0000000000000000000000000000000000000000..02eab9385f9928a7c8aede4b22d3d9ecf64d62bd --- /dev/null +++ b/third-party/video_to_data/reconstruction/modules/v2d_hoi_object_reconstruction/assets/basketball_example/front_stereo_camera_left/1771445449253424048.jpeg @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:d8ee351b63564be3b45605ef943e6bf5eafe5cda08fe05114c94d3b04e3eda06 +size 87251 diff --git a/third-party/video_to_data/reconstruction/modules/v2d_hoi_object_reconstruction/assets/basketball_example/front_stereo_camera_left/1771445449586744048.jpeg b/third-party/video_to_data/reconstruction/modules/v2d_hoi_object_reconstruction/assets/basketball_example/front_stereo_camera_left/1771445449586744048.jpeg new file mode 100644 index 0000000000000000000000000000000000000000..58dfb3fc7beba300a4f2895f1df182b61b0f46f2 --- /dev/null +++ b/third-party/video_to_data/reconstruction/modules/v2d_hoi_object_reconstruction/assets/basketball_example/front_stereo_camera_left/1771445449586744048.jpeg @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:01aafee9e7b5eebf1dd774470cbb81c403b9f892d10c418dc1dd52dcdde62509 +size 88052 diff --git a/third-party/video_to_data/reconstruction/modules/v2d_hoi_object_reconstruction/assets/basketball_example/front_stereo_camera_left/1771445449920083036.jpeg b/third-party/video_to_data/reconstruction/modules/v2d_hoi_object_reconstruction/assets/basketball_example/front_stereo_camera_left/1771445449920083036.jpeg new file mode 100644 index 0000000000000000000000000000000000000000..017348321c53224ed85ac32d1b3781e530304c70 --- /dev/null +++ b/third-party/video_to_data/reconstruction/modules/v2d_hoi_object_reconstruction/assets/basketball_example/front_stereo_camera_left/1771445449920083036.jpeg @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:4d340f533b7f8c9edaa275ce13486b46afd7b0e800699210d2bec5e0f59e7df1 +size 86527 diff --git a/third-party/video_to_data/reconstruction/modules/v2d_hoi_object_reconstruction/assets/basketball_example/front_stereo_camera_left/1771445450253404036.jpeg b/third-party/video_to_data/reconstruction/modules/v2d_hoi_object_reconstruction/assets/basketball_example/front_stereo_camera_left/1771445450253404036.jpeg new file mode 100644 index 0000000000000000000000000000000000000000..2a38166374abb20149a134cf08cbe5e7106e1a50 --- /dev/null +++ b/third-party/video_to_data/reconstruction/modules/v2d_hoi_object_reconstruction/assets/basketball_example/front_stereo_camera_left/1771445450253404036.jpeg @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:9db0cc73996ba3b9db2ad4628ffd9d34bb473a4f1cff8513a340001ca1fe8943 +size 86928 diff --git a/third-party/video_to_data/reconstruction/modules/v2d_hoi_object_reconstruction/assets/basketball_example/front_stereo_camera_left/1771445450586725036.jpeg b/third-party/video_to_data/reconstruction/modules/v2d_hoi_object_reconstruction/assets/basketball_example/front_stereo_camera_left/1771445450586725036.jpeg new file mode 100644 index 0000000000000000000000000000000000000000..fae21a13ec21ac5b7cdd3808e7a5288a6dc4450a --- /dev/null +++ b/third-party/video_to_data/reconstruction/modules/v2d_hoi_object_reconstruction/assets/basketball_example/front_stereo_camera_left/1771445450586725036.jpeg @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:33faa10f50890ec1684102fe759f2a3baf6ee3cdc40a77e4657209d37a071100 +size 85111 diff --git a/third-party/video_to_data/reconstruction/modules/v2d_hoi_object_reconstruction/assets/basketball_example/front_stereo_camera_left/1771445450920045044.jpeg b/third-party/video_to_data/reconstruction/modules/v2d_hoi_object_reconstruction/assets/basketball_example/front_stereo_camera_left/1771445450920045044.jpeg new file mode 100644 index 0000000000000000000000000000000000000000..d69707aecb9c8ec40fa4c22b816e9b7090fc6af1 --- /dev/null +++ b/third-party/video_to_data/reconstruction/modules/v2d_hoi_object_reconstruction/assets/basketball_example/front_stereo_camera_left/1771445450920045044.jpeg @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:e7580c0e180685bf1a31710eae3595cb06aa0e02f97b734c0676601b6c38f820 +size 85532 diff --git a/third-party/video_to_data/reconstruction/modules/v2d_hoi_object_reconstruction/assets/basketball_example/front_stereo_camera_left/1771445451253366044.jpeg b/third-party/video_to_data/reconstruction/modules/v2d_hoi_object_reconstruction/assets/basketball_example/front_stereo_camera_left/1771445451253366044.jpeg new file mode 100644 index 0000000000000000000000000000000000000000..35f76a94b7e3590fceedb2a2aa673235511b6a41 --- /dev/null +++ b/third-party/video_to_data/reconstruction/modules/v2d_hoi_object_reconstruction/assets/basketball_example/front_stereo_camera_left/1771445451253366044.jpeg @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:e114e1e3a38fb82c04ef7a105a2902de8bd705a725148b6a2745c1a3e0366d8d +size 87283 diff --git a/third-party/video_to_data/reconstruction/modules/v2d_hoi_object_reconstruction/assets/basketball_example/front_stereo_camera_left/1771445451586706044.jpeg b/third-party/video_to_data/reconstruction/modules/v2d_hoi_object_reconstruction/assets/basketball_example/front_stereo_camera_left/1771445451586706044.jpeg new file mode 100644 index 0000000000000000000000000000000000000000..f50b1119a9249ef84b576fcf0cc61b6255194dde --- /dev/null +++ b/third-party/video_to_data/reconstruction/modules/v2d_hoi_object_reconstruction/assets/basketball_example/front_stereo_camera_left/1771445451586706044.jpeg @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:f45f9d075e912e320113d5654bd2992513d779240042862e6b3413b9a9e9ad05 +size 87175 diff --git a/third-party/video_to_data/reconstruction/modules/v2d_hoi_object_reconstruction/assets/basketball_example/front_stereo_camera_left/1771445451920028056.jpeg b/third-party/video_to_data/reconstruction/modules/v2d_hoi_object_reconstruction/assets/basketball_example/front_stereo_camera_left/1771445451920028056.jpeg new file mode 100644 index 0000000000000000000000000000000000000000..f8e2ccf37e88c86221198c5a4cc1504189cbc029 --- /dev/null +++ b/third-party/video_to_data/reconstruction/modules/v2d_hoi_object_reconstruction/assets/basketball_example/front_stereo_camera_left/1771445451920028056.jpeg @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:6f6864a7f9e43d375a9bbc534610e808305ff6a44fe8d885cba5769b3b13af1f +size 83284 diff --git a/third-party/video_to_data/reconstruction/modules/v2d_hoi_object_reconstruction/assets/basketball_example/front_stereo_camera_left/1771445452253350056.jpeg b/third-party/video_to_data/reconstruction/modules/v2d_hoi_object_reconstruction/assets/basketball_example/front_stereo_camera_left/1771445452253350056.jpeg new file mode 100644 index 0000000000000000000000000000000000000000..f0eff3f4313c521b94ea165f00ab0eaa54d0c390 --- /dev/null +++ b/third-party/video_to_data/reconstruction/modules/v2d_hoi_object_reconstruction/assets/basketball_example/front_stereo_camera_left/1771445452253350056.jpeg @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:3a3891295f865d3aeba28dbb364c81258615d55d35505eba9e8a897f1fb02581 +size 83314 diff --git a/third-party/video_to_data/reconstruction/modules/v2d_hoi_object_reconstruction/assets/basketball_example/front_stereo_camera_left/1771445452586671056.jpeg b/third-party/video_to_data/reconstruction/modules/v2d_hoi_object_reconstruction/assets/basketball_example/front_stereo_camera_left/1771445452586671056.jpeg new file mode 100644 index 0000000000000000000000000000000000000000..fe4b4f28fed99c61b069267849a9bfe967d1b8e6 --- /dev/null +++ b/third-party/video_to_data/reconstruction/modules/v2d_hoi_object_reconstruction/assets/basketball_example/front_stereo_camera_left/1771445452586671056.jpeg @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:58f285225eb774eeac242c0da8220662f5c7f8b79e29aa9f6df5e378c8c74f88 +size 81557 diff --git a/third-party/video_to_data/reconstruction/modules/v2d_hoi_object_reconstruction/assets/basketball_example/front_stereo_camera_left/1771445452919988036.jpeg b/third-party/video_to_data/reconstruction/modules/v2d_hoi_object_reconstruction/assets/basketball_example/front_stereo_camera_left/1771445452919988036.jpeg new file mode 100644 index 0000000000000000000000000000000000000000..bf45b56873c9570efab349e14c20c021dfd34d1f --- /dev/null +++ b/third-party/video_to_data/reconstruction/modules/v2d_hoi_object_reconstruction/assets/basketball_example/front_stereo_camera_left/1771445452919988036.jpeg @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:cf997a493e9e03c8e2d1f9c8b08bfa1f760b1cff10a0a61610bfb72a24aa0294 +size 85573 diff --git a/third-party/video_to_data/reconstruction/modules/v2d_hoi_object_reconstruction/assets/basketball_example/front_stereo_camera_left/1771445453253327036.jpeg b/third-party/video_to_data/reconstruction/modules/v2d_hoi_object_reconstruction/assets/basketball_example/front_stereo_camera_left/1771445453253327036.jpeg new file mode 100644 index 0000000000000000000000000000000000000000..1ef98120e46cd90c69d5215a2f11a9a3020a1c21 --- /dev/null +++ b/third-party/video_to_data/reconstruction/modules/v2d_hoi_object_reconstruction/assets/basketball_example/front_stereo_camera_left/1771445453253327036.jpeg @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:ffabcec0e63333ce18a7f71201c281385b68cea4dff30d38b22f8051542533bf +size 85870 diff --git a/third-party/video_to_data/reconstruction/modules/v2d_hoi_object_reconstruction/assets/basketball_example/front_stereo_camera_left/1771445453586647036.jpeg b/third-party/video_to_data/reconstruction/modules/v2d_hoi_object_reconstruction/assets/basketball_example/front_stereo_camera_left/1771445453586647036.jpeg new file mode 100644 index 0000000000000000000000000000000000000000..b94d5531967898087137d7178b36cbaa9cd851af --- /dev/null +++ b/third-party/video_to_data/reconstruction/modules/v2d_hoi_object_reconstruction/assets/basketball_example/front_stereo_camera_left/1771445453586647036.jpeg @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:656c45a10a96e08f255eb7f99a2ba3ba3014ce9e9bcea2f22a04349655a0293f +size 85533 diff --git a/third-party/video_to_data/reconstruction/modules/v2d_hoi_object_reconstruction/assets/basketball_example/front_stereo_camera_left/1771445453919968052.jpeg b/third-party/video_to_data/reconstruction/modules/v2d_hoi_object_reconstruction/assets/basketball_example/front_stereo_camera_left/1771445453919968052.jpeg new file mode 100644 index 0000000000000000000000000000000000000000..b6138160e01454712bed7444aba103c6644bcbfb --- /dev/null +++ b/third-party/video_to_data/reconstruction/modules/v2d_hoi_object_reconstruction/assets/basketball_example/front_stereo_camera_left/1771445453919968052.jpeg @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:f4648f12e288939e6b96ddb14b035c5a80a4b8da167b72eef184d62a97280983 +size 85600 diff --git a/third-party/video_to_data/reconstruction/modules/v2d_hoi_object_reconstruction/assets/basketball_example/front_stereo_camera_left/1771445454253289052.jpeg b/third-party/video_to_data/reconstruction/modules/v2d_hoi_object_reconstruction/assets/basketball_example/front_stereo_camera_left/1771445454253289052.jpeg new file mode 100644 index 0000000000000000000000000000000000000000..f94fbb57908cd6625fcdb035a2e1a0878cbb4981 --- /dev/null +++ b/third-party/video_to_data/reconstruction/modules/v2d_hoi_object_reconstruction/assets/basketball_example/front_stereo_camera_left/1771445454253289052.jpeg @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:4a08a94d94c8c5116ca1449bcb6814df3d35bb86d40ff053c3a6696559b4dab6 +size 93551 diff --git a/third-party/video_to_data/reconstruction/modules/v2d_hoi_object_reconstruction/assets/basketball_example/front_stereo_camera_left/1771445454586628052.jpeg b/third-party/video_to_data/reconstruction/modules/v2d_hoi_object_reconstruction/assets/basketball_example/front_stereo_camera_left/1771445454586628052.jpeg new file mode 100644 index 0000000000000000000000000000000000000000..b70b2172aa22ce5c3b62542dd9e389a78bbad535 --- /dev/null +++ b/third-party/video_to_data/reconstruction/modules/v2d_hoi_object_reconstruction/assets/basketball_example/front_stereo_camera_left/1771445454586628052.jpeg @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:9151700d6fc8eb1e14b560d55bb3b39af7ec07d707a2bf8efdfe1ce3aacd2af5 +size 96134 diff --git a/third-party/video_to_data/reconstruction/modules/v2d_hoi_object_reconstruction/assets/basketball_example/front_stereo_camera_left/1771445454919948036.jpeg b/third-party/video_to_data/reconstruction/modules/v2d_hoi_object_reconstruction/assets/basketball_example/front_stereo_camera_left/1771445454919948036.jpeg new file mode 100644 index 0000000000000000000000000000000000000000..31d80f4ecace32c24931a7d365580179955cec79 --- /dev/null +++ b/third-party/video_to_data/reconstruction/modules/v2d_hoi_object_reconstruction/assets/basketball_example/front_stereo_camera_left/1771445454919948036.jpeg @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:92ea181169dab75d87ae4584a7394075f1b21519bba8216d985797e8e2d83f16 +size 95835 diff --git a/third-party/video_to_data/reconstruction/modules/v2d_hoi_object_reconstruction/assets/basketball_example/front_stereo_camera_left/1771445455253269036.jpeg b/third-party/video_to_data/reconstruction/modules/v2d_hoi_object_reconstruction/assets/basketball_example/front_stereo_camera_left/1771445455253269036.jpeg new file mode 100644 index 0000000000000000000000000000000000000000..bcdae53084abd6830e34477f0c0a838a07db1783 --- /dev/null +++ b/third-party/video_to_data/reconstruction/modules/v2d_hoi_object_reconstruction/assets/basketball_example/front_stereo_camera_left/1771445455253269036.jpeg @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:e7ab8bddbcc7ab48f42d5ebb1ed1dd8351b3e0466b44ac27a0e5ffeac6f969b0 +size 95289 diff --git a/third-party/video_to_data/reconstruction/modules/v2d_hoi_object_reconstruction/assets/basketball_example/front_stereo_camera_left/1771445455586590036.jpeg b/third-party/video_to_data/reconstruction/modules/v2d_hoi_object_reconstruction/assets/basketball_example/front_stereo_camera_left/1771445455586590036.jpeg new file mode 100644 index 0000000000000000000000000000000000000000..ee722a1326f3e436435a6d39b64cec2492f86dc7 --- /dev/null +++ b/third-party/video_to_data/reconstruction/modules/v2d_hoi_object_reconstruction/assets/basketball_example/front_stereo_camera_left/1771445455586590036.jpeg @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:205e1b93702feeec8273f3b48adb5a6086a5d2ce7b28e100c3e5d7a38455dd0c +size 98174 diff --git a/third-party/video_to_data/reconstruction/modules/v2d_hoi_object_reconstruction/assets/basketball_example/front_stereo_camera_left/1771445455919911028.jpeg b/third-party/video_to_data/reconstruction/modules/v2d_hoi_object_reconstruction/assets/basketball_example/front_stereo_camera_left/1771445455919911028.jpeg new file mode 100644 index 0000000000000000000000000000000000000000..71d4d31c666a2b767fb0c54a47e9967262bf376e --- /dev/null +++ b/third-party/video_to_data/reconstruction/modules/v2d_hoi_object_reconstruction/assets/basketball_example/front_stereo_camera_left/1771445455919911028.jpeg @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:642b8976b65f2a78c2633b5849b2c39e2674daf6a636098d04a2d1ed5dc917af +size 104347 diff --git a/third-party/video_to_data/reconstruction/modules/v2d_hoi_object_reconstruction/assets/basketball_example/front_stereo_camera_left/1771445456253250028.jpeg b/third-party/video_to_data/reconstruction/modules/v2d_hoi_object_reconstruction/assets/basketball_example/front_stereo_camera_left/1771445456253250028.jpeg new file mode 100644 index 0000000000000000000000000000000000000000..a19d62ef8553878024151807ba3f21760348c0bc --- /dev/null +++ b/third-party/video_to_data/reconstruction/modules/v2d_hoi_object_reconstruction/assets/basketball_example/front_stereo_camera_left/1771445456253250028.jpeg @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:f7dd05b1c8b6eba8d3481e9df103aa6b459b58d4ca321c27f7700ac2fdfcac5f +size 100997 diff --git a/third-party/video_to_data/reconstruction/modules/v2d_hoi_object_reconstruction/assets/basketball_example/front_stereo_camera_left/1771445456586570028.jpeg b/third-party/video_to_data/reconstruction/modules/v2d_hoi_object_reconstruction/assets/basketball_example/front_stereo_camera_left/1771445456586570028.jpeg new file mode 100644 index 0000000000000000000000000000000000000000..5bbe4cafe94e1ef70f1526d97928badcbd4c206d --- /dev/null +++ b/third-party/video_to_data/reconstruction/modules/v2d_hoi_object_reconstruction/assets/basketball_example/front_stereo_camera_left/1771445456586570028.jpeg @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:61558b2aad7c8789adb1f1b5053f95e99bfdc3755abe15e4828acc582b2f631e +size 98259 diff --git a/third-party/video_to_data/reconstruction/modules/v2d_hoi_object_reconstruction/assets/basketball_example/front_stereo_camera_left/1771445456919891032.jpeg b/third-party/video_to_data/reconstruction/modules/v2d_hoi_object_reconstruction/assets/basketball_example/front_stereo_camera_left/1771445456919891032.jpeg new file mode 100644 index 0000000000000000000000000000000000000000..750637479e69144c72409cef5b31d1c4057413b7 --- /dev/null +++ b/third-party/video_to_data/reconstruction/modules/v2d_hoi_object_reconstruction/assets/basketball_example/front_stereo_camera_left/1771445456919891032.jpeg @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:1cd38d69b0823000e130316e1fad8add4a42642907beef90f809775a84ade7d3 +size 96058 diff --git a/third-party/video_to_data/reconstruction/modules/v2d_hoi_object_reconstruction/assets/basketball_example/front_stereo_camera_left/1771445457253212032.jpeg b/third-party/video_to_data/reconstruction/modules/v2d_hoi_object_reconstruction/assets/basketball_example/front_stereo_camera_left/1771445457253212032.jpeg new file mode 100644 index 0000000000000000000000000000000000000000..13ec2114daf22805e802e386a05e44f58558e11a --- /dev/null +++ b/third-party/video_to_data/reconstruction/modules/v2d_hoi_object_reconstruction/assets/basketball_example/front_stereo_camera_left/1771445457253212032.jpeg @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:8aef58742f224ce289e48b4f6f36954a8670633f20c41fc8a288a88b1cdc4bcc +size 97251 diff --git a/third-party/video_to_data/reconstruction/modules/v2d_hoi_object_reconstruction/assets/basketball_example/front_stereo_camera_left/1771445457586533032.jpeg b/third-party/video_to_data/reconstruction/modules/v2d_hoi_object_reconstruction/assets/basketball_example/front_stereo_camera_left/1771445457586533032.jpeg new file mode 100644 index 0000000000000000000000000000000000000000..0502c1cd23cb346f8ebb902356407576397e505e --- /dev/null +++ b/third-party/video_to_data/reconstruction/modules/v2d_hoi_object_reconstruction/assets/basketball_example/front_stereo_camera_left/1771445457586533032.jpeg @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:24af6abeeeef70e97770bc93c7150d1666bad470ec65533a9e0c35fbf7aca4e7 +size 96204 diff --git a/third-party/video_to_data/reconstruction/modules/v2d_hoi_object_reconstruction/assets/basketball_example/front_stereo_camera_left/1771445457919874072.jpeg b/third-party/video_to_data/reconstruction/modules/v2d_hoi_object_reconstruction/assets/basketball_example/front_stereo_camera_left/1771445457919874072.jpeg new file mode 100644 index 0000000000000000000000000000000000000000..1dbea55bdbaca487dae48fd5546fe0ae884b4e9b --- /dev/null +++ b/third-party/video_to_data/reconstruction/modules/v2d_hoi_object_reconstruction/assets/basketball_example/front_stereo_camera_left/1771445457919874072.jpeg @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:982ce17c6ca76cf41e0e0b6c2e103cd4e8fb235fd23f0f190bd8c9ea0ee88fc6 +size 96752 diff --git a/third-party/video_to_data/reconstruction/modules/v2d_hoi_object_reconstruction/assets/basketball_example/front_stereo_camera_left/1771445458253196072.jpeg b/third-party/video_to_data/reconstruction/modules/v2d_hoi_object_reconstruction/assets/basketball_example/front_stereo_camera_left/1771445458253196072.jpeg new file mode 100644 index 0000000000000000000000000000000000000000..7a797d6361d569de62dd68242d50e8af80a59be0 --- /dev/null +++ b/third-party/video_to_data/reconstruction/modules/v2d_hoi_object_reconstruction/assets/basketball_example/front_stereo_camera_left/1771445458253196072.jpeg @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:87f900788e894b9229cc0899cee66ec44f18075b82369c885f055cf0b589c975 +size 94058 diff --git a/third-party/video_to_data/reconstruction/modules/v2d_hoi_object_reconstruction/assets/basketball_example/front_stereo_camera_left/1771445458586513072.jpeg b/third-party/video_to_data/reconstruction/modules/v2d_hoi_object_reconstruction/assets/basketball_example/front_stereo_camera_left/1771445458586513072.jpeg new file mode 100644 index 0000000000000000000000000000000000000000..71f22cf6a6fe340de3b78f431131f18134f7912a --- /dev/null +++ b/third-party/video_to_data/reconstruction/modules/v2d_hoi_object_reconstruction/assets/basketball_example/front_stereo_camera_left/1771445458586513072.jpeg @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:5514aa9b9496eee3a4feafa174a9ccc46b8e102def8131da2b71e1c7dd20582e +size 93355 diff --git a/third-party/video_to_data/reconstruction/modules/v2d_hoi_object_reconstruction/assets/basketball_example/front_stereo_camera_left/1771445458919833160.jpeg b/third-party/video_to_data/reconstruction/modules/v2d_hoi_object_reconstruction/assets/basketball_example/front_stereo_camera_left/1771445458919833160.jpeg new file mode 100644 index 0000000000000000000000000000000000000000..d3c8167163d2fe630698f1a39e40209b1f1eae5e --- /dev/null +++ b/third-party/video_to_data/reconstruction/modules/v2d_hoi_object_reconstruction/assets/basketball_example/front_stereo_camera_left/1771445458919833160.jpeg @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:33e9ee1d101ec90923e01be64aeb169f8272d33548e429802656ee7bda855d78 +size 93596 diff --git a/third-party/video_to_data/reconstruction/modules/v2d_hoi_object_reconstruction/assets/basketball_example/front_stereo_camera_left/1771445459253172160.jpeg b/third-party/video_to_data/reconstruction/modules/v2d_hoi_object_reconstruction/assets/basketball_example/front_stereo_camera_left/1771445459253172160.jpeg new file mode 100644 index 0000000000000000000000000000000000000000..9949f0d09a50de3e44d1e950c290343fadd3a6b0 --- /dev/null +++ b/third-party/video_to_data/reconstruction/modules/v2d_hoi_object_reconstruction/assets/basketball_example/front_stereo_camera_left/1771445459253172160.jpeg @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:6031c45eef0b368d333582efebe87dfc01050f938ce68b8d67b9b2c9395c20c5 +size 96798 diff --git a/third-party/video_to_data/reconstruction/modules/v2d_hoi_object_reconstruction/assets/basketball_example/front_stereo_camera_left/1771445459586493160.jpeg b/third-party/video_to_data/reconstruction/modules/v2d_hoi_object_reconstruction/assets/basketball_example/front_stereo_camera_left/1771445459586493160.jpeg new file mode 100644 index 0000000000000000000000000000000000000000..b9114be8e2b08d45291db0acc232d8f9f010ce89 --- /dev/null +++ b/third-party/video_to_data/reconstruction/modules/v2d_hoi_object_reconstruction/assets/basketball_example/front_stereo_camera_left/1771445459586493160.jpeg @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:d3474c58ecbf956fccbc55c54353949c3d409077d2078d091cf2498d7e39314d +size 95808 diff --git a/third-party/video_to_data/reconstruction/modules/v2d_hoi_object_reconstruction/assets/basketball_example/front_stereo_camera_left/1771445459919814032.jpeg b/third-party/video_to_data/reconstruction/modules/v2d_hoi_object_reconstruction/assets/basketball_example/front_stereo_camera_left/1771445459919814032.jpeg new file mode 100644 index 0000000000000000000000000000000000000000..25437e0eb97329848e26c41e4f4c45bb43b833c9 --- /dev/null +++ b/third-party/video_to_data/reconstruction/modules/v2d_hoi_object_reconstruction/assets/basketball_example/front_stereo_camera_left/1771445459919814032.jpeg @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:cfb815e3baef012165ce8234794c8acc0472ecb6cdc5563d402ff60c2a2aea52 +size 95253 diff --git a/third-party/video_to_data/reconstruction/modules/v2d_hoi_object_reconstruction/assets/basketball_example/front_stereo_camera_left/1771445460253134032.jpeg b/third-party/video_to_data/reconstruction/modules/v2d_hoi_object_reconstruction/assets/basketball_example/front_stereo_camera_left/1771445460253134032.jpeg new file mode 100644 index 0000000000000000000000000000000000000000..d9017e1b9649aaabba26e7fd8e221fcc86fa8ca9 --- /dev/null +++ b/third-party/video_to_data/reconstruction/modules/v2d_hoi_object_reconstruction/assets/basketball_example/front_stereo_camera_left/1771445460253134032.jpeg @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:2cce24c75816baa324a4c7197acf2e88c4f86cf0724eba84c4cd9bf26cd82413 +size 97714 diff --git a/third-party/video_to_data/reconstruction/modules/v2d_hoi_object_reconstruction/assets/basketball_example/front_stereo_camera_left/1771445460586455032.jpeg b/third-party/video_to_data/reconstruction/modules/v2d_hoi_object_reconstruction/assets/basketball_example/front_stereo_camera_left/1771445460586455032.jpeg new file mode 100644 index 0000000000000000000000000000000000000000..b4fe8d261553710cc62fcc4145e7d8e83777c6ea --- /dev/null +++ b/third-party/video_to_data/reconstruction/modules/v2d_hoi_object_reconstruction/assets/basketball_example/front_stereo_camera_left/1771445460586455032.jpeg @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:d1cd8b243c1872811e9bf7cca89fbdee7fe6bb99adfa9616d9e4c2657c2d6931 +size 100063 diff --git a/third-party/video_to_data/reconstruction/modules/v2d_hoi_object_reconstruction/assets/basketball_example/front_stereo_camera_left/1771445460919794128.jpeg b/third-party/video_to_data/reconstruction/modules/v2d_hoi_object_reconstruction/assets/basketball_example/front_stereo_camera_left/1771445460919794128.jpeg new file mode 100644 index 0000000000000000000000000000000000000000..f1000eb3e5c34a2b1c79ff90215e1d31190f5086 --- /dev/null +++ b/third-party/video_to_data/reconstruction/modules/v2d_hoi_object_reconstruction/assets/basketball_example/front_stereo_camera_left/1771445460919794128.jpeg @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:49acd3f9db7fa8b2cea160938d2f2c78c82280afb04592e9fc6053986bab71ef +size 102087 diff --git a/third-party/video_to_data/reconstruction/modules/v2d_hoi_object_reconstruction/assets/basketball_example/front_stereo_camera_left/1771445461253115128.jpeg b/third-party/video_to_data/reconstruction/modules/v2d_hoi_object_reconstruction/assets/basketball_example/front_stereo_camera_left/1771445461253115128.jpeg new file mode 100644 index 0000000000000000000000000000000000000000..c1e522e9f9d56c973f5ac009e9e5aee9c87043d2 --- /dev/null +++ b/third-party/video_to_data/reconstruction/modules/v2d_hoi_object_reconstruction/assets/basketball_example/front_stereo_camera_left/1771445461253115128.jpeg @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:d245dc0eaca7799efca85e884c4891b22851e2227579087b8a479b2e4422cfde +size 103305 diff --git a/third-party/video_to_data/reconstruction/modules/v2d_hoi_object_reconstruction/assets/basketball_example/front_stereo_camera_left/1771445461586435128.jpeg b/third-party/video_to_data/reconstruction/modules/v2d_hoi_object_reconstruction/assets/basketball_example/front_stereo_camera_left/1771445461586435128.jpeg new file mode 100644 index 0000000000000000000000000000000000000000..002bc2aaf8c7307323fbab5b5366b6d806986cfa --- /dev/null +++ b/third-party/video_to_data/reconstruction/modules/v2d_hoi_object_reconstruction/assets/basketball_example/front_stereo_camera_left/1771445461586435128.jpeg @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:38be4602ddea5fadbb3f60c7fcbe86cd0ba18736f95733764f6606fc26a8a9ae +size 95137 diff --git a/third-party/video_to_data/reconstruction/modules/v2d_hoi_object_reconstruction/assets/basketball_example/front_stereo_camera_left/1771445461919756112.jpeg b/third-party/video_to_data/reconstruction/modules/v2d_hoi_object_reconstruction/assets/basketball_example/front_stereo_camera_left/1771445461919756112.jpeg new file mode 100644 index 0000000000000000000000000000000000000000..e32d77b74a1133ab86d09e1802cc464fb835a723 --- /dev/null +++ b/third-party/video_to_data/reconstruction/modules/v2d_hoi_object_reconstruction/assets/basketball_example/front_stereo_camera_left/1771445461919756112.jpeg @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:1eabf719c91456e5fb83b1c2b8a6ce73e5608d9c2fe394656c3b0a6e2bf3d576 +size 101045 diff --git a/third-party/video_to_data/reconstruction/modules/v2d_hoi_object_reconstruction/assets/basketball_example/front_stereo_camera_left/1771445462253077112.jpeg b/third-party/video_to_data/reconstruction/modules/v2d_hoi_object_reconstruction/assets/basketball_example/front_stereo_camera_left/1771445462253077112.jpeg new file mode 100644 index 0000000000000000000000000000000000000000..b1014357fb5bd5f62f8f44765ec7b7c097f0a84a --- /dev/null +++ b/third-party/video_to_data/reconstruction/modules/v2d_hoi_object_reconstruction/assets/basketball_example/front_stereo_camera_left/1771445462253077112.jpeg @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:a848b9f0cef37bff324266dbc7261539b7f098f13a081f0395aca09ec520b554 +size 99170 diff --git a/third-party/video_to_data/reconstruction/modules/v2d_hoi_object_reconstruction/assets/basketball_example/front_stereo_camera_left/1771445462586416112.jpeg b/third-party/video_to_data/reconstruction/modules/v2d_hoi_object_reconstruction/assets/basketball_example/front_stereo_camera_left/1771445462586416112.jpeg new file mode 100644 index 0000000000000000000000000000000000000000..23d7b670622ef6b50608c74c8eefc663e7953e47 --- /dev/null +++ b/third-party/video_to_data/reconstruction/modules/v2d_hoi_object_reconstruction/assets/basketball_example/front_stereo_camera_left/1771445462586416112.jpeg @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:5ec0d6daa02abb332e62204be472b822c781bdaba7cb4543041bfed720b61057 +size 97818 diff --git a/third-party/video_to_data/reconstruction/modules/v2d_hoi_object_reconstruction/assets/basketball_example/front_stereo_camera_left/1771445462919736064.jpeg b/third-party/video_to_data/reconstruction/modules/v2d_hoi_object_reconstruction/assets/basketball_example/front_stereo_camera_left/1771445462919736064.jpeg new file mode 100644 index 0000000000000000000000000000000000000000..409475fafdbbd5cd079509cc1f776b7894a1cb72 --- /dev/null +++ b/third-party/video_to_data/reconstruction/modules/v2d_hoi_object_reconstruction/assets/basketball_example/front_stereo_camera_left/1771445462919736064.jpeg @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:03b0ae3cf8bf29f570189847b344a4b6bc68a1166bac17c2ac42cef3d648acee +size 95398 diff --git a/third-party/video_to_data/reconstruction/modules/v2d_hoi_object_reconstruction/assets/basketball_example/front_stereo_camera_left/1771445463253058064.jpeg b/third-party/video_to_data/reconstruction/modules/v2d_hoi_object_reconstruction/assets/basketball_example/front_stereo_camera_left/1771445463253058064.jpeg new file mode 100644 index 0000000000000000000000000000000000000000..5b3dc22abf36822a9ae6a3f0db4ef36df86b3b0d --- /dev/null +++ b/third-party/video_to_data/reconstruction/modules/v2d_hoi_object_reconstruction/assets/basketball_example/front_stereo_camera_left/1771445463253058064.jpeg @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:08c80fb91f2ed8624dcd3bda655700f0d225bc80becd1a26c1c87bae579f7cf9 +size 97339 diff --git a/third-party/video_to_data/reconstruction/modules/v2d_hoi_object_reconstruction/assets/basketball_example/front_stereo_camera_left/1771445463586380064.jpeg b/third-party/video_to_data/reconstruction/modules/v2d_hoi_object_reconstruction/assets/basketball_example/front_stereo_camera_left/1771445463586380064.jpeg new file mode 100644 index 0000000000000000000000000000000000000000..42a52f019def2f8134587bfe9208f00458568c8b --- /dev/null +++ b/third-party/video_to_data/reconstruction/modules/v2d_hoi_object_reconstruction/assets/basketball_example/front_stereo_camera_left/1771445463586380064.jpeg @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:99c4b2954978df04a2178ba7e2dc111774ce0aca68cc222300a57768eaf66cf0 +size 97760 diff --git a/third-party/video_to_data/reconstruction/modules/v2d_hoi_object_reconstruction/assets/basketball_example/front_stereo_camera_left/1771445463919699072.jpeg b/third-party/video_to_data/reconstruction/modules/v2d_hoi_object_reconstruction/assets/basketball_example/front_stereo_camera_left/1771445463919699072.jpeg new file mode 100644 index 0000000000000000000000000000000000000000..e97d01deec48712f2a89f7b8dd5aa76f1ef1c3aa --- /dev/null +++ b/third-party/video_to_data/reconstruction/modules/v2d_hoi_object_reconstruction/assets/basketball_example/front_stereo_camera_left/1771445463919699072.jpeg @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:04c8f8ee7f597c2e53a82e3250b60fc1b16cc96ea9f95ba2a7462b2d01352e2d +size 97772 diff --git a/third-party/video_to_data/reconstruction/modules/v2d_hoi_object_reconstruction/assets/basketball_example/front_stereo_camera_left/1771445464253041072.jpeg b/third-party/video_to_data/reconstruction/modules/v2d_hoi_object_reconstruction/assets/basketball_example/front_stereo_camera_left/1771445464253041072.jpeg new file mode 100644 index 0000000000000000000000000000000000000000..cfb8d4cdbbcff89c1a1cf068ae3a8b4d8c69cd34 --- /dev/null +++ b/third-party/video_to_data/reconstruction/modules/v2d_hoi_object_reconstruction/assets/basketball_example/front_stereo_camera_left/1771445464253041072.jpeg @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:5026e20228d248aa4390eae1be75d7cf80bc3bb6d0f9a0dd17d101756c29f9c1 +size 98097 diff --git a/third-party/video_to_data/reconstruction/modules/v2d_hoi_object_reconstruction/assets/basketball_example/front_stereo_camera_left/1771445464586358072.jpeg b/third-party/video_to_data/reconstruction/modules/v2d_hoi_object_reconstruction/assets/basketball_example/front_stereo_camera_left/1771445464586358072.jpeg new file mode 100644 index 0000000000000000000000000000000000000000..c8e02582501d6d244f6a51b075eec483cc43aa14 --- /dev/null +++ b/third-party/video_to_data/reconstruction/modules/v2d_hoi_object_reconstruction/assets/basketball_example/front_stereo_camera_left/1771445464586358072.jpeg @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:831a6454bc3d41f3ec530682cc465681334de3cb5beb9ebde69c07a8e0f380d4 +size 97649 diff --git a/third-party/video_to_data/reconstruction/modules/v2d_hoi_object_reconstruction/assets/basketball_example/front_stereo_camera_left/1771445464919679060.jpeg b/third-party/video_to_data/reconstruction/modules/v2d_hoi_object_reconstruction/assets/basketball_example/front_stereo_camera_left/1771445464919679060.jpeg new file mode 100644 index 0000000000000000000000000000000000000000..af209a75e21fd5dc7d35c3f68a6041b43d0cc8ea --- /dev/null +++ b/third-party/video_to_data/reconstruction/modules/v2d_hoi_object_reconstruction/assets/basketball_example/front_stereo_camera_left/1771445464919679060.jpeg @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:6b0bd4e66537843cafdaaff36d8f09249d858bfb9fe14fb98957593b56bc25d0 +size 97568 diff --git a/third-party/video_to_data/reconstruction/modules/v2d_hoi_object_reconstruction/assets/basketball_example/front_stereo_camera_left/1771445465253000060.jpeg b/third-party/video_to_data/reconstruction/modules/v2d_hoi_object_reconstruction/assets/basketball_example/front_stereo_camera_left/1771445465253000060.jpeg new file mode 100644 index 0000000000000000000000000000000000000000..ebb17a3e20d92538505646ed728b3537a69cc41f --- /dev/null +++ b/third-party/video_to_data/reconstruction/modules/v2d_hoi_object_reconstruction/assets/basketball_example/front_stereo_camera_left/1771445465253000060.jpeg @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:042622a23dea6011bfca7858d164107d1c94369ae2aaa651eaf6c31372aaac6c +size 96787 diff --git a/third-party/video_to_data/reconstruction/modules/v2d_hoi_object_reconstruction/assets/basketball_example/front_stereo_camera_left/1771445465586339060.jpeg b/third-party/video_to_data/reconstruction/modules/v2d_hoi_object_reconstruction/assets/basketball_example/front_stereo_camera_left/1771445465586339060.jpeg new file mode 100644 index 0000000000000000000000000000000000000000..4f50e9a9a1c1e85b123c4172e1a3a89a976e8b63 --- /dev/null +++ b/third-party/video_to_data/reconstruction/modules/v2d_hoi_object_reconstruction/assets/basketball_example/front_stereo_camera_left/1771445465586339060.jpeg @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:a9e855964279d6c837d29d5a7d266faae847977141a0a4ec91780be1c6ad6a1b +size 96103 diff --git a/third-party/video_to_data/reconstruction/modules/v2d_hoi_object_reconstruction/assets/basketball_example/front_stereo_camera_left/1771445465919659184.jpeg b/third-party/video_to_data/reconstruction/modules/v2d_hoi_object_reconstruction/assets/basketball_example/front_stereo_camera_left/1771445465919659184.jpeg new file mode 100644 index 0000000000000000000000000000000000000000..0718c2f4eaa6dcc209a6bec73c416f9cb2ea64f9 --- /dev/null +++ b/third-party/video_to_data/reconstruction/modules/v2d_hoi_object_reconstruction/assets/basketball_example/front_stereo_camera_left/1771445465919659184.jpeg @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:d651cd770fa16950ac4799202f70a57d6468767ab6fd619c514e1d6aa5ce6de5 +size 96774 diff --git a/third-party/video_to_data/reconstruction/modules/v2d_hoi_object_reconstruction/assets/basketball_example/front_stereo_camera_left/1771445466252980184.jpeg b/third-party/video_to_data/reconstruction/modules/v2d_hoi_object_reconstruction/assets/basketball_example/front_stereo_camera_left/1771445466252980184.jpeg new file mode 100644 index 0000000000000000000000000000000000000000..c4141e7437660da1cc24cadcd3e642463986654f --- /dev/null +++ b/third-party/video_to_data/reconstruction/modules/v2d_hoi_object_reconstruction/assets/basketball_example/front_stereo_camera_left/1771445466252980184.jpeg @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:34cc081c05712cfbe540b17c1caf8a86caa7170bf7fe3deed48d221c6e437511 +size 96446 diff --git a/third-party/video_to_data/reconstruction/modules/v2d_hoi_object_reconstruction/assets/basketball_example/front_stereo_camera_right/1771445398921412053.jpeg b/third-party/video_to_data/reconstruction/modules/v2d_hoi_object_reconstruction/assets/basketball_example/front_stereo_camera_right/1771445398921412053.jpeg new file mode 100644 index 0000000000000000000000000000000000000000..b76e4559b1e5e5908f4214445aa164151ce03640 --- /dev/null +++ b/third-party/video_to_data/reconstruction/modules/v2d_hoi_object_reconstruction/assets/basketball_example/front_stereo_camera_right/1771445398921412053.jpeg @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:5a8c2288af32f67dd0a85de1e6115c4b348a8d52e74313b9ef9f008047f98602 +size 100147 diff --git a/third-party/video_to_data/reconstruction/modules/v2d_hoi_object_reconstruction/assets/basketball_example/front_stereo_camera_right/1771445399254733053.jpeg b/third-party/video_to_data/reconstruction/modules/v2d_hoi_object_reconstruction/assets/basketball_example/front_stereo_camera_right/1771445399254733053.jpeg new file mode 100644 index 0000000000000000000000000000000000000000..c4c07e87a8800576d1d20b84fd91a473ca5a65e7 --- /dev/null +++ b/third-party/video_to_data/reconstruction/modules/v2d_hoi_object_reconstruction/assets/basketball_example/front_stereo_camera_right/1771445399254733053.jpeg @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:3d8f3f962d350552ad3d4e694727f786a3f25995c18ae9ba16efe74d4dd52655 +size 99367 diff --git a/third-party/video_to_data/reconstruction/modules/v2d_hoi_object_reconstruction/assets/basketball_example/front_stereo_camera_right/1771445399588055053.jpeg b/third-party/video_to_data/reconstruction/modules/v2d_hoi_object_reconstruction/assets/basketball_example/front_stereo_camera_right/1771445399588055053.jpeg new file mode 100644 index 0000000000000000000000000000000000000000..94819c1fb4b87c4a04023b0d941384c09c2da6bb --- /dev/null +++ b/third-party/video_to_data/reconstruction/modules/v2d_hoi_object_reconstruction/assets/basketball_example/front_stereo_camera_right/1771445399588055053.jpeg @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:c97fc17bf86b39aa50e96b6000b051ce34c3ba62c466be67738542c0011d6040 +size 97853 diff --git a/third-party/video_to_data/reconstruction/modules/v2d_hoi_object_reconstruction/assets/basketball_example/front_stereo_camera_right/1771445399921377045.jpeg b/third-party/video_to_data/reconstruction/modules/v2d_hoi_object_reconstruction/assets/basketball_example/front_stereo_camera_right/1771445399921377045.jpeg new file mode 100644 index 0000000000000000000000000000000000000000..189a321455afa46c7e0610b82b9931e918e79427 --- /dev/null +++ b/third-party/video_to_data/reconstruction/modules/v2d_hoi_object_reconstruction/assets/basketball_example/front_stereo_camera_right/1771445399921377045.jpeg @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:29803ec6c68d670f52d71ebd5368abc9c8eb473df1f038ceda3b98c5c24a6ea2 +size 98259 diff --git a/third-party/video_to_data/reconstruction/modules/v2d_hoi_object_reconstruction/assets/basketball_example/front_stereo_camera_right/1771445400254693045.jpeg b/third-party/video_to_data/reconstruction/modules/v2d_hoi_object_reconstruction/assets/basketball_example/front_stereo_camera_right/1771445400254693045.jpeg new file mode 100644 index 0000000000000000000000000000000000000000..94af2d642551b5c7d0588bcc8d8932e70788d27a --- /dev/null +++ b/third-party/video_to_data/reconstruction/modules/v2d_hoi_object_reconstruction/assets/basketball_example/front_stereo_camera_right/1771445400254693045.jpeg @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:d5ea6965b035264d3b2695a55e54a823b1e51d7548bceccb3a4f5dfeaa9dd2bc +size 100211 diff --git a/third-party/video_to_data/reconstruction/modules/v2d_hoi_object_reconstruction/assets/basketball_example/front_stereo_camera_right/1771445400588032045.jpeg b/third-party/video_to_data/reconstruction/modules/v2d_hoi_object_reconstruction/assets/basketball_example/front_stereo_camera_right/1771445400588032045.jpeg new file mode 100644 index 0000000000000000000000000000000000000000..74ff2219dd9de489ec74fffb12c7c9a4e3037a4e --- /dev/null +++ b/third-party/video_to_data/reconstruction/modules/v2d_hoi_object_reconstruction/assets/basketball_example/front_stereo_camera_right/1771445400588032045.jpeg @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:7b3701c991886148cdec6b4ce3c92cf6971ea82070cf98f743d7e1fdaa539c2b +size 99453 diff --git a/third-party/video_to_data/reconstruction/modules/v2d_hoi_object_reconstruction/assets/basketball_example/front_stereo_camera_right/1771445400921353081.jpeg b/third-party/video_to_data/reconstruction/modules/v2d_hoi_object_reconstruction/assets/basketball_example/front_stereo_camera_right/1771445400921353081.jpeg new file mode 100644 index 0000000000000000000000000000000000000000..cb5f56574b3dbe4e12435e91ae43e69cc4cbdb16 --- /dev/null +++ b/third-party/video_to_data/reconstruction/modules/v2d_hoi_object_reconstruction/assets/basketball_example/front_stereo_camera_right/1771445400921353081.jpeg @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:7b6ccc3eb2f1b0e432a835e42d25f5ec4558347a05a247aaa31e6188e734fb0f +size 103129 diff --git a/third-party/video_to_data/reconstruction/modules/v2d_hoi_object_reconstruction/assets/basketball_example/front_stereo_camera_right/1771445401254674081.jpeg b/third-party/video_to_data/reconstruction/modules/v2d_hoi_object_reconstruction/assets/basketball_example/front_stereo_camera_right/1771445401254674081.jpeg new file mode 100644 index 0000000000000000000000000000000000000000..6f8ee8da6ddadb09232316e7b92a4ab539538cba --- /dev/null +++ b/third-party/video_to_data/reconstruction/modules/v2d_hoi_object_reconstruction/assets/basketball_example/front_stereo_camera_right/1771445401254674081.jpeg @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:23a547c81926dbca98e58e2de8a22f71a2af8ac075320436ea3684577c3ebe97 +size 103587 diff --git a/third-party/video_to_data/reconstruction/modules/v2d_hoi_object_reconstruction/assets/basketball_example/front_stereo_camera_right/1771445401587995081.jpeg b/third-party/video_to_data/reconstruction/modules/v2d_hoi_object_reconstruction/assets/basketball_example/front_stereo_camera_right/1771445401587995081.jpeg new file mode 100644 index 0000000000000000000000000000000000000000..ac29d29e100f27aa8c1c004b6117f285b99b1fa9 --- /dev/null +++ b/third-party/video_to_data/reconstruction/modules/v2d_hoi_object_reconstruction/assets/basketball_example/front_stereo_camera_right/1771445401587995081.jpeg @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:9cf6659f3578d5d5fb5e63d54ec7733b8f5af1101ffd60cd4d2715dfea78e1ee +size 103880 diff --git a/third-party/video_to_data/reconstruction/modules/v2d_hoi_object_reconstruction/assets/basketball_example/front_stereo_camera_right/1771445401921334060.jpeg b/third-party/video_to_data/reconstruction/modules/v2d_hoi_object_reconstruction/assets/basketball_example/front_stereo_camera_right/1771445401921334060.jpeg new file mode 100644 index 0000000000000000000000000000000000000000..65c95c1663190b646cad68ae2eadd9156cb10018 --- /dev/null +++ b/third-party/video_to_data/reconstruction/modules/v2d_hoi_object_reconstruction/assets/basketball_example/front_stereo_camera_right/1771445401921334060.jpeg @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:8a0f82d3901e3a7c4215367f8ac5b3d38279b9c7a5e42d31087777e4b8262d71 +size 102359 diff --git a/third-party/video_to_data/reconstruction/modules/v2d_hoi_object_reconstruction/assets/basketball_example/front_stereo_camera_right/1771445402254654060.jpeg b/third-party/video_to_data/reconstruction/modules/v2d_hoi_object_reconstruction/assets/basketball_example/front_stereo_camera_right/1771445402254654060.jpeg new file mode 100644 index 0000000000000000000000000000000000000000..d83402e5065b1973f834464a67e0c9661953d3b9 --- /dev/null +++ b/third-party/video_to_data/reconstruction/modules/v2d_hoi_object_reconstruction/assets/basketball_example/front_stereo_camera_right/1771445402254654060.jpeg @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:a47a4e2b8016b115a2030b8dbc5d3fb68faf17028abc04d228f184d3e197a604 +size 102403 diff --git a/third-party/video_to_data/reconstruction/modules/v2d_hoi_object_reconstruction/assets/basketball_example/front_stereo_camera_right/1771445402587975060.jpeg b/third-party/video_to_data/reconstruction/modules/v2d_hoi_object_reconstruction/assets/basketball_example/front_stereo_camera_right/1771445402587975060.jpeg new file mode 100644 index 0000000000000000000000000000000000000000..e50c950ec2c136a0b732ff1474b067c608554f88 --- /dev/null +++ b/third-party/video_to_data/reconstruction/modules/v2d_hoi_object_reconstruction/assets/basketball_example/front_stereo_camera_right/1771445402587975060.jpeg @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:8f36a723da68db14aa6ee3aea727f7b48934a3edf62567b3e39df7c633c95c49 +size 102481 diff --git a/third-party/video_to_data/reconstruction/modules/v2d_hoi_object_reconstruction/assets/basketball_example/front_stereo_camera_right/1771445402921296020.jpeg b/third-party/video_to_data/reconstruction/modules/v2d_hoi_object_reconstruction/assets/basketball_example/front_stereo_camera_right/1771445402921296020.jpeg new file mode 100644 index 0000000000000000000000000000000000000000..7c31dc2c91e97173cfd8cfad29210dd8846cef0d --- /dev/null +++ b/third-party/video_to_data/reconstruction/modules/v2d_hoi_object_reconstruction/assets/basketball_example/front_stereo_camera_right/1771445402921296020.jpeg @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:2f9dab5c0c177d36b9c60eb01c889c420329f6c2bbf4d30eb0977cda588f4c16 +size 106992 diff --git a/third-party/video_to_data/reconstruction/modules/v2d_hoi_object_reconstruction/assets/basketball_example/front_stereo_camera_right/1771445403254617020.jpeg b/third-party/video_to_data/reconstruction/modules/v2d_hoi_object_reconstruction/assets/basketball_example/front_stereo_camera_right/1771445403254617020.jpeg new file mode 100644 index 0000000000000000000000000000000000000000..f1426074357508da658b2f454fbbe7ef47856603 --- /dev/null +++ b/third-party/video_to_data/reconstruction/modules/v2d_hoi_object_reconstruction/assets/basketball_example/front_stereo_camera_right/1771445403254617020.jpeg @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:53c5a4547cdb83af36e096abc973d28ab78734cb80f28c716c12b21d2cdaf791 +size 101568 diff --git a/third-party/video_to_data/reconstruction/modules/v2d_hoi_object_reconstruction/assets/basketball_example/front_stereo_camera_right/1771445403587955020.jpeg b/third-party/video_to_data/reconstruction/modules/v2d_hoi_object_reconstruction/assets/basketball_example/front_stereo_camera_right/1771445403587955020.jpeg new file mode 100644 index 0000000000000000000000000000000000000000..210c3031deeb3890e6f37b1b956c7c22b3d1f155 --- /dev/null +++ b/third-party/video_to_data/reconstruction/modules/v2d_hoi_object_reconstruction/assets/basketball_example/front_stereo_camera_right/1771445403587955020.jpeg @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:51d1553d36b0c8fe6c4f1c408b67691ed370e0e40cf8f3bcacada65982f190cc +size 100933 diff --git a/third-party/video_to_data/reconstruction/modules/v2d_hoi_object_reconstruction/assets/basketball_example/front_stereo_camera_right/1771445403921276017.jpeg b/third-party/video_to_data/reconstruction/modules/v2d_hoi_object_reconstruction/assets/basketball_example/front_stereo_camera_right/1771445403921276017.jpeg new file mode 100644 index 0000000000000000000000000000000000000000..21210e7ef05d9d75d6197fa90b9a108a2be67102 --- /dev/null +++ b/third-party/video_to_data/reconstruction/modules/v2d_hoi_object_reconstruction/assets/basketball_example/front_stereo_camera_right/1771445403921276017.jpeg @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:a25a74cf373dd1bc7061da7a558fffe4ca1216e6ebb9d118b0555492e955d842 +size 99002 diff --git a/third-party/video_to_data/reconstruction/modules/v2d_hoi_object_reconstruction/assets/basketball_example/front_stereo_camera_right/1771445404254597017.jpeg b/third-party/video_to_data/reconstruction/modules/v2d_hoi_object_reconstruction/assets/basketball_example/front_stereo_camera_right/1771445404254597017.jpeg new file mode 100644 index 0000000000000000000000000000000000000000..8e9ae8158296e495c19c0e0e02f7f7773e8d9446 --- /dev/null +++ b/third-party/video_to_data/reconstruction/modules/v2d_hoi_object_reconstruction/assets/basketball_example/front_stereo_camera_right/1771445404254597017.jpeg @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:2c536f3b6eca420ffcd5504c35f03635ce3f3abf362f11fe133fce96180b1fd7 +size 101938 diff --git a/third-party/video_to_data/reconstruction/modules/v2d_hoi_object_reconstruction/assets/basketball_example/front_stereo_camera_right/1771445404587918017.jpeg b/third-party/video_to_data/reconstruction/modules/v2d_hoi_object_reconstruction/assets/basketball_example/front_stereo_camera_right/1771445404587918017.jpeg new file mode 100644 index 0000000000000000000000000000000000000000..ec8fdcd053f97749c72482492b593f72fedb1e49 --- /dev/null +++ b/third-party/video_to_data/reconstruction/modules/v2d_hoi_object_reconstruction/assets/basketball_example/front_stereo_camera_right/1771445404587918017.jpeg @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:58093cf1a70c38bfa3bc591b67a9f1997a473bb173e65d281d13fd7cbcd31101 +size 99078 diff --git a/third-party/video_to_data/reconstruction/modules/v2d_hoi_object_reconstruction/assets/basketball_example/front_stereo_camera_right/1771445404921238120.jpeg b/third-party/video_to_data/reconstruction/modules/v2d_hoi_object_reconstruction/assets/basketball_example/front_stereo_camera_right/1771445404921238120.jpeg new file mode 100644 index 0000000000000000000000000000000000000000..619ae5d4555a8813c78e9975165e19d32d2187a4 --- /dev/null +++ b/third-party/video_to_data/reconstruction/modules/v2d_hoi_object_reconstruction/assets/basketball_example/front_stereo_camera_right/1771445404921238120.jpeg @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:06f66139786b6be59d82fe5c8a2b081e38d99bae109896e12ce7c93119c4e61e +size 89970 diff --git a/third-party/video_to_data/reconstruction/modules/v2d_hoi_object_reconstruction/assets/basketball_example/front_stereo_camera_right/1771445405254580120.jpeg b/third-party/video_to_data/reconstruction/modules/v2d_hoi_object_reconstruction/assets/basketball_example/front_stereo_camera_right/1771445405254580120.jpeg new file mode 100644 index 0000000000000000000000000000000000000000..6d718d27ef08a179c3f1bc802b4d4901f46be0c5 --- /dev/null +++ b/third-party/video_to_data/reconstruction/modules/v2d_hoi_object_reconstruction/assets/basketball_example/front_stereo_camera_right/1771445405254580120.jpeg @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:da73d47d4b00dc540278570f9afaa9d0e277c863093d8fdc97870dcb1aca07cc +size 89423 diff --git a/third-party/video_to_data/reconstruction/modules/v2d_hoi_object_reconstruction/assets/basketball_example/front_stereo_camera_right/1771445405587902120.jpeg b/third-party/video_to_data/reconstruction/modules/v2d_hoi_object_reconstruction/assets/basketball_example/front_stereo_camera_right/1771445405587902120.jpeg new file mode 100644 index 0000000000000000000000000000000000000000..e163329bded7ef9a608d87f397975ca525e51c05 --- /dev/null +++ b/third-party/video_to_data/reconstruction/modules/v2d_hoi_object_reconstruction/assets/basketball_example/front_stereo_camera_right/1771445405587902120.jpeg @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:b1c278c156dd774a7eab5ff9d2e410e31e66f7da842f18070db9687828cef452 +size 85096 diff --git a/third-party/video_to_data/reconstruction/modules/v2d_hoi_object_reconstruction/assets/basketball_example/front_stereo_camera_right/1771445405921219052.jpeg b/third-party/video_to_data/reconstruction/modules/v2d_hoi_object_reconstruction/assets/basketball_example/front_stereo_camera_right/1771445405921219052.jpeg new file mode 100644 index 0000000000000000000000000000000000000000..b691ab98c8fee00ab91d5de5e72954027872cbc3 --- /dev/null +++ b/third-party/video_to_data/reconstruction/modules/v2d_hoi_object_reconstruction/assets/basketball_example/front_stereo_camera_right/1771445405921219052.jpeg @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:4c6bcf6f72130ad07d3ebb90dad953e1ec75e7f3949aa2732a83eeca305c867e +size 93284 diff --git a/third-party/video_to_data/reconstruction/modules/v2d_hoi_object_reconstruction/assets/basketball_example/front_stereo_camera_right/1771445406254540052.jpeg b/third-party/video_to_data/reconstruction/modules/v2d_hoi_object_reconstruction/assets/basketball_example/front_stereo_camera_right/1771445406254540052.jpeg new file mode 100644 index 0000000000000000000000000000000000000000..330dbe982a6647b077b81cd91f79336db219e00e --- /dev/null +++ b/third-party/video_to_data/reconstruction/modules/v2d_hoi_object_reconstruction/assets/basketball_example/front_stereo_camera_right/1771445406254540052.jpeg @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:a9450fd58b3bcaeb2df34d40fac4d007da51a7abc24166bf69c89ac5320b9727 +size 90976 diff --git a/third-party/video_to_data/reconstruction/modules/v2d_hoi_object_reconstruction/assets/basketball_example/front_stereo_camera_right/1771445406587879052.jpeg b/third-party/video_to_data/reconstruction/modules/v2d_hoi_object_reconstruction/assets/basketball_example/front_stereo_camera_right/1771445406587879052.jpeg new file mode 100644 index 0000000000000000000000000000000000000000..4e6c919b73d5966cbaf38b10f074bf57478a4f9b --- /dev/null +++ b/third-party/video_to_data/reconstruction/modules/v2d_hoi_object_reconstruction/assets/basketball_example/front_stereo_camera_right/1771445406587879052.jpeg @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:78c4b20117b6b9c12c77271721e22c8c7fb2a2c4b76efb281e4af32d81382586 +size 88540 diff --git a/third-party/video_to_data/reconstruction/modules/v2d_hoi_object_reconstruction/assets/basketball_example/front_stereo_camera_right/1771445406921199016.jpeg b/third-party/video_to_data/reconstruction/modules/v2d_hoi_object_reconstruction/assets/basketball_example/front_stereo_camera_right/1771445406921199016.jpeg new file mode 100644 index 0000000000000000000000000000000000000000..132d024d53087e7c6718ddbd5abc840cb844b2a2 --- /dev/null +++ b/third-party/video_to_data/reconstruction/modules/v2d_hoi_object_reconstruction/assets/basketball_example/front_stereo_camera_right/1771445406921199016.jpeg @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:545e01956a1387500add79901d770f4e03e709e8d6a979f9a916a7ec6fbcadc5 +size 85769 diff --git a/third-party/video_to_data/reconstruction/modules/v2d_hoi_object_reconstruction/assets/basketball_example/front_stereo_camera_right/1771445407254520016.jpeg b/third-party/video_to_data/reconstruction/modules/v2d_hoi_object_reconstruction/assets/basketball_example/front_stereo_camera_right/1771445407254520016.jpeg new file mode 100644 index 0000000000000000000000000000000000000000..7f19492fdd37297ee0121892975126280e55a3da --- /dev/null +++ b/third-party/video_to_data/reconstruction/modules/v2d_hoi_object_reconstruction/assets/basketball_example/front_stereo_camera_right/1771445407254520016.jpeg @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:015660b54710c34cd98898eddf73663175812737408d17961a31ee1b7a516a31 +size 87829 diff --git a/third-party/video_to_data/reconstruction/modules/v2d_hoi_object_reconstruction/assets/basketball_example/front_stereo_camera_right/1771445407587841016.jpeg b/third-party/video_to_data/reconstruction/modules/v2d_hoi_object_reconstruction/assets/basketball_example/front_stereo_camera_right/1771445407587841016.jpeg new file mode 100644 index 0000000000000000000000000000000000000000..ecb3740c9eae2c84a5ded8449e3ae435acf33aff --- /dev/null +++ b/third-party/video_to_data/reconstruction/modules/v2d_hoi_object_reconstruction/assets/basketball_example/front_stereo_camera_right/1771445407587841016.jpeg @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:5e1759df36e75b66476b37d9418233e80ed0de426676a84d231835cf631103bb +size 85737 diff --git a/third-party/video_to_data/reconstruction/modules/v2d_hoi_object_reconstruction/assets/basketball_example/front_stereo_camera_right/1771445407921162033.jpeg b/third-party/video_to_data/reconstruction/modules/v2d_hoi_object_reconstruction/assets/basketball_example/front_stereo_camera_right/1771445407921162033.jpeg new file mode 100644 index 0000000000000000000000000000000000000000..5215934824747e62d53576e1c14b9fe928b45806 --- /dev/null +++ b/third-party/video_to_data/reconstruction/modules/v2d_hoi_object_reconstruction/assets/basketball_example/front_stereo_camera_right/1771445407921162033.jpeg @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:b2ec4eb9c9505e3007c738e3b7b97fa91cebf38b0aa3f13ebc4b8cbd49a9483a +size 86351 diff --git a/third-party/video_to_data/reconstruction/modules/v2d_hoi_object_reconstruction/assets/basketball_example/front_stereo_camera_right/1771445408254500033.jpeg b/third-party/video_to_data/reconstruction/modules/v2d_hoi_object_reconstruction/assets/basketball_example/front_stereo_camera_right/1771445408254500033.jpeg new file mode 100644 index 0000000000000000000000000000000000000000..372a7324548acf105c5dd3c32155fc47dd7fb920 --- /dev/null +++ b/third-party/video_to_data/reconstruction/modules/v2d_hoi_object_reconstruction/assets/basketball_example/front_stereo_camera_right/1771445408254500033.jpeg @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:fe9d422f4abd3bcbdd64a49aca1ca396eef121e66475222a03f141c7d1320321 +size 87444 diff --git a/third-party/video_to_data/reconstruction/modules/v2d_hoi_object_reconstruction/assets/basketball_example/front_stereo_camera_right/1771445408587821033.jpeg b/third-party/video_to_data/reconstruction/modules/v2d_hoi_object_reconstruction/assets/basketball_example/front_stereo_camera_right/1771445408587821033.jpeg new file mode 100644 index 0000000000000000000000000000000000000000..27c34fadcf56ee87761557c4d97548c84e28bdcc --- /dev/null +++ b/third-party/video_to_data/reconstruction/modules/v2d_hoi_object_reconstruction/assets/basketball_example/front_stereo_camera_right/1771445408587821033.jpeg @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:a0d299b0b255a7948857a0d01a865f835d4bfa89deb6b8d530a803a07012ee29 +size 84261 diff --git a/third-party/video_to_data/reconstruction/modules/v2d_hoi_object_reconstruction/assets/basketball_example/front_stereo_camera_right/1771445408921142024.jpeg b/third-party/video_to_data/reconstruction/modules/v2d_hoi_object_reconstruction/assets/basketball_example/front_stereo_camera_right/1771445408921142024.jpeg new file mode 100644 index 0000000000000000000000000000000000000000..2c1caa9f07a8c1bb7ead9cec4980f96c0503cd48 --- /dev/null +++ b/third-party/video_to_data/reconstruction/modules/v2d_hoi_object_reconstruction/assets/basketball_example/front_stereo_camera_right/1771445408921142024.jpeg @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:10c4138ae3689fc3824036fba74b1969d746eabb38ddea55e9767922cd57aba5 +size 88253 diff --git a/third-party/video_to_data/reconstruction/modules/v2d_hoi_object_reconstruction/assets/basketball_example/front_stereo_camera_right/1771445409254463024.jpeg b/third-party/video_to_data/reconstruction/modules/v2d_hoi_object_reconstruction/assets/basketball_example/front_stereo_camera_right/1771445409254463024.jpeg new file mode 100644 index 0000000000000000000000000000000000000000..d9d6f2775019c9f8ffeca9fbb2ed5e4431e8a40b --- /dev/null +++ b/third-party/video_to_data/reconstruction/modules/v2d_hoi_object_reconstruction/assets/basketball_example/front_stereo_camera_right/1771445409254463024.jpeg @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:e94d4cc6cfbc73ef3bf21a690922dd0c960864ddd992d2e9b665357786034c26 +size 85576 diff --git a/third-party/video_to_data/reconstruction/modules/v2d_hoi_object_reconstruction/assets/basketball_example/front_stereo_camera_right/1771445409587802024.jpeg b/third-party/video_to_data/reconstruction/modules/v2d_hoi_object_reconstruction/assets/basketball_example/front_stereo_camera_right/1771445409587802024.jpeg new file mode 100644 index 0000000000000000000000000000000000000000..8262c9f91d641161e7abc5db8caa4cfdb8e65c38 --- /dev/null +++ b/third-party/video_to_data/reconstruction/modules/v2d_hoi_object_reconstruction/assets/basketball_example/front_stereo_camera_right/1771445409587802024.jpeg @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:6a0b5da1a39462d1e8fd9ebe69feb4d930c83551588d6dd71dddaa0614c459af +size 87076 diff --git a/third-party/video_to_data/reconstruction/modules/v2d_hoi_object_reconstruction/assets/basketball_example/front_stereo_camera_right/1771445409921122020.jpeg b/third-party/video_to_data/reconstruction/modules/v2d_hoi_object_reconstruction/assets/basketball_example/front_stereo_camera_right/1771445409921122020.jpeg new file mode 100644 index 0000000000000000000000000000000000000000..51d93f40e697fb9a976900e4121fd0b530cb90f9 --- /dev/null +++ b/third-party/video_to_data/reconstruction/modules/v2d_hoi_object_reconstruction/assets/basketball_example/front_stereo_camera_right/1771445409921122020.jpeg @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:4fbaa4f608dc5d7182d564916366f4bee9a5438a88a5f0060d38c7786af2c048 +size 84194 diff --git a/third-party/video_to_data/reconstruction/modules/v2d_hoi_object_reconstruction/assets/basketball_example/front_stereo_camera_right/1771445410254443020.jpeg b/third-party/video_to_data/reconstruction/modules/v2d_hoi_object_reconstruction/assets/basketball_example/front_stereo_camera_right/1771445410254443020.jpeg new file mode 100644 index 0000000000000000000000000000000000000000..a583b0d6f76b7dc22507bfd4dcfbdeaeb908c77a --- /dev/null +++ b/third-party/video_to_data/reconstruction/modules/v2d_hoi_object_reconstruction/assets/basketball_example/front_stereo_camera_right/1771445410254443020.jpeg @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:2830bcb7d8bfe19f1766346df2e18d40bc680a8d52ded29fb840f6d382695d02 +size 83596 diff --git a/third-party/video_to_data/reconstruction/modules/v2d_hoi_object_reconstruction/assets/basketball_example/front_stereo_camera_right/1771445410587765020.jpeg b/third-party/video_to_data/reconstruction/modules/v2d_hoi_object_reconstruction/assets/basketball_example/front_stereo_camera_right/1771445410587765020.jpeg new file mode 100644 index 0000000000000000000000000000000000000000..00c386574cbfae03f350ce20701948809be3a5a8 --- /dev/null +++ b/third-party/video_to_data/reconstruction/modules/v2d_hoi_object_reconstruction/assets/basketball_example/front_stereo_camera_right/1771445410587765020.jpeg @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:5fdcb903d880adb8f66e9068d9aa0d0a1058d73cce2a9ae77628ab7626180008 +size 85096 diff --git a/third-party/video_to_data/reconstruction/modules/v2d_hoi_object_reconstruction/assets/basketball_example/front_stereo_camera_right/1771445410921087145.jpeg b/third-party/video_to_data/reconstruction/modules/v2d_hoi_object_reconstruction/assets/basketball_example/front_stereo_camera_right/1771445410921087145.jpeg new file mode 100644 index 0000000000000000000000000000000000000000..e9222ba81d89958d33422274b41a39fc3f512126 --- /dev/null +++ b/third-party/video_to_data/reconstruction/modules/v2d_hoi_object_reconstruction/assets/basketball_example/front_stereo_camera_right/1771445410921087145.jpeg @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:df359eccb1669968d19ae0e87532e01698eb1ce1849b0857cd2f2d072feb2c23 +size 82691 diff --git a/third-party/video_to_data/reconstruction/modules/v2d_hoi_object_reconstruction/assets/basketball_example/front_stereo_camera_right/1771445411254427145.jpeg b/third-party/video_to_data/reconstruction/modules/v2d_hoi_object_reconstruction/assets/basketball_example/front_stereo_camera_right/1771445411254427145.jpeg new file mode 100644 index 0000000000000000000000000000000000000000..42110d37862495c755dae8d35afa42a619592c45 --- /dev/null +++ b/third-party/video_to_data/reconstruction/modules/v2d_hoi_object_reconstruction/assets/basketball_example/front_stereo_camera_right/1771445411254427145.jpeg @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:a572e9c4ed89f903a2095d32e475c54b0c397acb04ad67d440ac2cc1c6425f56 +size 83409 diff --git a/third-party/video_to_data/reconstruction/modules/v2d_hoi_object_reconstruction/assets/basketball_example/front_stereo_camera_right/1771445411587744145.jpeg b/third-party/video_to_data/reconstruction/modules/v2d_hoi_object_reconstruction/assets/basketball_example/front_stereo_camera_right/1771445411587744145.jpeg new file mode 100644 index 0000000000000000000000000000000000000000..ebbe032cddf2b071a77499000b31aed52730bce8 --- /dev/null +++ b/third-party/video_to_data/reconstruction/modules/v2d_hoi_object_reconstruction/assets/basketball_example/front_stereo_camera_right/1771445411587744145.jpeg @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:a6a4123997747f3ec7dc6ed4416e60988d4fcdd80902454919d838ce5d4b1f10 +size 84647 diff --git a/third-party/video_to_data/reconstruction/modules/v2d_hoi_object_reconstruction/assets/basketball_example/front_stereo_camera_right/1771445411921065005.jpeg b/third-party/video_to_data/reconstruction/modules/v2d_hoi_object_reconstruction/assets/basketball_example/front_stereo_camera_right/1771445411921065005.jpeg new file mode 100644 index 0000000000000000000000000000000000000000..5c7cd2dc3ea4b48d41d6dea58a82e287a1cac156 --- /dev/null +++ b/third-party/video_to_data/reconstruction/modules/v2d_hoi_object_reconstruction/assets/basketball_example/front_stereo_camera_right/1771445411921065005.jpeg @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:f19ed6faec9c90634650ccef4ad7a09561bac14ef05c04bc1dc0e6715962cd12 +size 83698 diff --git a/third-party/video_to_data/reconstruction/modules/v2d_hoi_object_reconstruction/assets/basketball_example/front_stereo_camera_right/1771445412254386005.jpeg b/third-party/video_to_data/reconstruction/modules/v2d_hoi_object_reconstruction/assets/basketball_example/front_stereo_camera_right/1771445412254386005.jpeg new file mode 100644 index 0000000000000000000000000000000000000000..bd7328afaf4d23e05002754619c3c1b8b9746fd6 --- /dev/null +++ b/third-party/video_to_data/reconstruction/modules/v2d_hoi_object_reconstruction/assets/basketball_example/front_stereo_camera_right/1771445412254386005.jpeg @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:66340d9bd126ed84b4336f8adf1d37c80cc2cd96c13e48b657ae194f2eae4957 +size 88359 diff --git a/third-party/video_to_data/reconstruction/modules/v2d_hoi_object_reconstruction/assets/basketball_example/front_stereo_camera_right/1771445412587707005.jpeg b/third-party/video_to_data/reconstruction/modules/v2d_hoi_object_reconstruction/assets/basketball_example/front_stereo_camera_right/1771445412587707005.jpeg new file mode 100644 index 0000000000000000000000000000000000000000..f585b30b80507aff35509a0648511b6d6566becd --- /dev/null +++ b/third-party/video_to_data/reconstruction/modules/v2d_hoi_object_reconstruction/assets/basketball_example/front_stereo_camera_right/1771445412587707005.jpeg @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:6588a88fda3e490782b6c6da5df091e3968689e8fe8eff639dc6c4d50738ed8d +size 86579 diff --git a/third-party/video_to_data/reconstruction/modules/v2d_hoi_object_reconstruction/assets/basketball_example/front_stereo_camera_right/1771445412921046057.jpeg b/third-party/video_to_data/reconstruction/modules/v2d_hoi_object_reconstruction/assets/basketball_example/front_stereo_camera_right/1771445412921046057.jpeg new file mode 100644 index 0000000000000000000000000000000000000000..b22693e3bd3afdfdbd52e8dc00002a536b3142e5 --- /dev/null +++ b/third-party/video_to_data/reconstruction/modules/v2d_hoi_object_reconstruction/assets/basketball_example/front_stereo_camera_right/1771445412921046057.jpeg @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:4b9bdf739f9a57c5c3407ea2cd4c8791bc85e964d81c1bcfb0245f3ee8580145 +size 86469 diff --git a/third-party/video_to_data/reconstruction/modules/v2d_hoi_object_reconstruction/assets/basketball_example/front_stereo_camera_right/1771445413254366057.jpeg b/third-party/video_to_data/reconstruction/modules/v2d_hoi_object_reconstruction/assets/basketball_example/front_stereo_camera_right/1771445413254366057.jpeg new file mode 100644 index 0000000000000000000000000000000000000000..3fc28158f59bcebe999e07c9ae1bb11f859034b0 --- /dev/null +++ b/third-party/video_to_data/reconstruction/modules/v2d_hoi_object_reconstruction/assets/basketball_example/front_stereo_camera_right/1771445413254366057.jpeg @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:c744b3cbff4696a82677a79055e50ac41bca76d832743456db26416b5a43d1e7 +size 84247 diff --git a/third-party/video_to_data/reconstruction/modules/v2d_hoi_object_reconstruction/assets/basketball_example/front_stereo_camera_right/1771445413587687057.jpeg b/third-party/video_to_data/reconstruction/modules/v2d_hoi_object_reconstruction/assets/basketball_example/front_stereo_camera_right/1771445413587687057.jpeg new file mode 100644 index 0000000000000000000000000000000000000000..8426e1d24be6aa9c0fa8c9f18a80f3458a8af751 --- /dev/null +++ b/third-party/video_to_data/reconstruction/modules/v2d_hoi_object_reconstruction/assets/basketball_example/front_stereo_camera_right/1771445413587687057.jpeg @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:3b0919bee1e095fa3c311c37911a0bdfa49f00aab88c1906ae3cfdd0b548d0c6 +size 85236 diff --git a/third-party/video_to_data/reconstruction/modules/v2d_hoi_object_reconstruction/assets/basketball_example/front_stereo_camera_right/1771445413921008097.jpeg b/third-party/video_to_data/reconstruction/modules/v2d_hoi_object_reconstruction/assets/basketball_example/front_stereo_camera_right/1771445413921008097.jpeg new file mode 100644 index 0000000000000000000000000000000000000000..d20fd70d2115cd47a0410f971bc0d14ae7160cce --- /dev/null +++ b/third-party/video_to_data/reconstruction/modules/v2d_hoi_object_reconstruction/assets/basketball_example/front_stereo_camera_right/1771445413921008097.jpeg @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:def39e777ef0ada9e782c9ab2cf7040cb55a274dd04b602d14abfd4f709182d8 +size 85003 diff --git a/third-party/video_to_data/reconstruction/modules/v2d_hoi_object_reconstruction/assets/basketball_example/front_stereo_camera_right/1771445414254347097.jpeg b/third-party/video_to_data/reconstruction/modules/v2d_hoi_object_reconstruction/assets/basketball_example/front_stereo_camera_right/1771445414254347097.jpeg new file mode 100644 index 0000000000000000000000000000000000000000..69054c71e00a9a35d57a60ef9d21398ce81cd901 --- /dev/null +++ b/third-party/video_to_data/reconstruction/modules/v2d_hoi_object_reconstruction/assets/basketball_example/front_stereo_camera_right/1771445414254347097.jpeg @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:d77ddb90d632952b3d33f9f361ddb1fd3c81bffda5177e80d7f51eaf23dcc397 +size 84320 diff --git a/third-party/video_to_data/reconstruction/modules/v2d_hoi_object_reconstruction/assets/basketball_example/front_stereo_camera_right/1771445414587667097.jpeg b/third-party/video_to_data/reconstruction/modules/v2d_hoi_object_reconstruction/assets/basketball_example/front_stereo_camera_right/1771445414587667097.jpeg new file mode 100644 index 0000000000000000000000000000000000000000..089dc216edb25637e9d9a9c537a6b95777df45a1 --- /dev/null +++ b/third-party/video_to_data/reconstruction/modules/v2d_hoi_object_reconstruction/assets/basketball_example/front_stereo_camera_right/1771445414587667097.jpeg @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:ec7797de78d1305222cb4bcc72f6d4091e7f8ebc7b19d09611475b3e3d2ba449 +size 85581 diff --git a/third-party/video_to_data/reconstruction/modules/v2d_hoi_object_reconstruction/assets/basketball_example/front_stereo_camera_right/1771445414920988148.jpeg b/third-party/video_to_data/reconstruction/modules/v2d_hoi_object_reconstruction/assets/basketball_example/front_stereo_camera_right/1771445414920988148.jpeg new file mode 100644 index 0000000000000000000000000000000000000000..49b1c1cb1c7c3db74ff8a74eb9f7ba8e9d39d78c --- /dev/null +++ b/third-party/video_to_data/reconstruction/modules/v2d_hoi_object_reconstruction/assets/basketball_example/front_stereo_camera_right/1771445414920988148.jpeg @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:376bf30213573d1b079f59332c2b53f364be9ecfb3d36244fdc43add90af411c +size 87632 diff --git a/third-party/video_to_data/reconstruction/modules/v2d_hoi_object_reconstruction/assets/basketball_example/front_stereo_camera_right/1771445415254309148.jpeg b/third-party/video_to_data/reconstruction/modules/v2d_hoi_object_reconstruction/assets/basketball_example/front_stereo_camera_right/1771445415254309148.jpeg new file mode 100644 index 0000000000000000000000000000000000000000..9de66bc1359aadb0dff4e24dec7920fafbe35e75 --- /dev/null +++ b/third-party/video_to_data/reconstruction/modules/v2d_hoi_object_reconstruction/assets/basketball_example/front_stereo_camera_right/1771445415254309148.jpeg @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:6315a2d6c553c6c6656616b1dafefd92fb9cd32a924b2743cdbe94ddf7318bb1 +size 89730 diff --git a/third-party/video_to_data/reconstruction/modules/v2d_hoi_object_reconstruction/assets/basketball_example/front_stereo_camera_right/1771445415587630148.jpeg b/third-party/video_to_data/reconstruction/modules/v2d_hoi_object_reconstruction/assets/basketball_example/front_stereo_camera_right/1771445415587630148.jpeg new file mode 100644 index 0000000000000000000000000000000000000000..479d71a710850e2fe04f27aa12baea52353689b8 --- /dev/null +++ b/third-party/video_to_data/reconstruction/modules/v2d_hoi_object_reconstruction/assets/basketball_example/front_stereo_camera_right/1771445415587630148.jpeg @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:9f072c29f0d93a65e259bf2d9e16c6e4927d49c732ea4a4261b0f6983e2b2668 +size 92010 diff --git a/third-party/video_to_data/reconstruction/modules/v2d_hoi_object_reconstruction/assets/basketball_example/front_stereo_camera_right/1771445415920969076.jpeg b/third-party/video_to_data/reconstruction/modules/v2d_hoi_object_reconstruction/assets/basketball_example/front_stereo_camera_right/1771445415920969076.jpeg new file mode 100644 index 0000000000000000000000000000000000000000..ef89a74e80dbdcd561a9eda9d0a162e1ee658b8f --- /dev/null +++ b/third-party/video_to_data/reconstruction/modules/v2d_hoi_object_reconstruction/assets/basketball_example/front_stereo_camera_right/1771445415920969076.jpeg @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:4aa0ccf5e13241b59857f13bdc1f9915abcd141aaa4b6d80099fed5411d3c228 +size 92419 diff --git a/third-party/video_to_data/reconstruction/modules/v2d_hoi_object_reconstruction/assets/basketball_example/front_stereo_camera_right/1771445416254290076.jpeg b/third-party/video_to_data/reconstruction/modules/v2d_hoi_object_reconstruction/assets/basketball_example/front_stereo_camera_right/1771445416254290076.jpeg new file mode 100644 index 0000000000000000000000000000000000000000..8af85556de7862c823dfed98e8f299de8c1f5459 --- /dev/null +++ b/third-party/video_to_data/reconstruction/modules/v2d_hoi_object_reconstruction/assets/basketball_example/front_stereo_camera_right/1771445416254290076.jpeg @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:9ada0b085b38f2eaa838b8d7ca29746d8d2e540e34fd2628d1032aa7dafe98e8 +size 94840 diff --git a/third-party/video_to_data/reconstruction/modules/v2d_hoi_object_reconstruction/assets/basketball_example/front_stereo_camera_right/1771445416587612076.jpeg b/third-party/video_to_data/reconstruction/modules/v2d_hoi_object_reconstruction/assets/basketball_example/front_stereo_camera_right/1771445416587612076.jpeg new file mode 100644 index 0000000000000000000000000000000000000000..1ab3a5b2c079f8781d7bb118d11a200a71023a02 --- /dev/null +++ b/third-party/video_to_data/reconstruction/modules/v2d_hoi_object_reconstruction/assets/basketball_example/front_stereo_camera_right/1771445416587612076.jpeg @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:03108541ffe3d8c5685cd6c936c2abac2294dc8f4aa0582e4c4637b06cf3a44f +size 95682 diff --git a/third-party/video_to_data/reconstruction/modules/v2d_hoi_object_reconstruction/assets/basketball_example/front_stereo_camera_right/1771445416920934060.jpeg b/third-party/video_to_data/reconstruction/modules/v2d_hoi_object_reconstruction/assets/basketball_example/front_stereo_camera_right/1771445416920934060.jpeg new file mode 100644 index 0000000000000000000000000000000000000000..0cb21432a57bd83207c6b51a8caf390dec311060 --- /dev/null +++ b/third-party/video_to_data/reconstruction/modules/v2d_hoi_object_reconstruction/assets/basketball_example/front_stereo_camera_right/1771445416920934060.jpeg @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:9b26e69408db25b424f0846e9eb05a92252806c6d153f8d4f6e74c38e758ce66 +size 99532 diff --git a/third-party/video_to_data/reconstruction/modules/v2d_hoi_object_reconstruction/assets/basketball_example/front_stereo_camera_right/1771445417254255060.jpeg b/third-party/video_to_data/reconstruction/modules/v2d_hoi_object_reconstruction/assets/basketball_example/front_stereo_camera_right/1771445417254255060.jpeg new file mode 100644 index 0000000000000000000000000000000000000000..3b6be8729a8f149c8b4eec5708e5da84f69f2639 --- /dev/null +++ b/third-party/video_to_data/reconstruction/modules/v2d_hoi_object_reconstruction/assets/basketball_example/front_stereo_camera_right/1771445417254255060.jpeg @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:9b40b6ff47d15d51e502f506ac0ee7b3f1b0fb9468057ef174ab5c9bdcd7b79a +size 97370 diff --git a/third-party/video_to_data/reconstruction/modules/v2d_hoi_object_reconstruction/assets/basketball_example/front_stereo_camera_right/1771445417587591060.jpeg b/third-party/video_to_data/reconstruction/modules/v2d_hoi_object_reconstruction/assets/basketball_example/front_stereo_camera_right/1771445417587591060.jpeg new file mode 100644 index 0000000000000000000000000000000000000000..83d47a83b3f2ee259ea800da9811792fc919c853 --- /dev/null +++ b/third-party/video_to_data/reconstruction/modules/v2d_hoi_object_reconstruction/assets/basketball_example/front_stereo_camera_right/1771445417587591060.jpeg @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:c9f4b303d1879129be89f0587a3cf477f9da544084be6b75527ffec7ed2508fb +size 96082 diff --git a/third-party/video_to_data/reconstruction/modules/v2d_hoi_object_reconstruction/assets/basketball_example/front_stereo_camera_right/1771445417920911064.jpeg b/third-party/video_to_data/reconstruction/modules/v2d_hoi_object_reconstruction/assets/basketball_example/front_stereo_camera_right/1771445417920911064.jpeg new file mode 100644 index 0000000000000000000000000000000000000000..6c9af45c794af9b9bee00aa8a7fcf7285353f991 --- /dev/null +++ b/third-party/video_to_data/reconstruction/modules/v2d_hoi_object_reconstruction/assets/basketball_example/front_stereo_camera_right/1771445417920911064.jpeg @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:318ed1ce5bbea4f4cc46936b19917158815197ba74d3c252204dc0bf08711e75 +size 97301 diff --git a/third-party/video_to_data/reconstruction/modules/v2d_hoi_object_reconstruction/assets/basketball_example/front_stereo_camera_right/1771445418254232064.jpeg b/third-party/video_to_data/reconstruction/modules/v2d_hoi_object_reconstruction/assets/basketball_example/front_stereo_camera_right/1771445418254232064.jpeg new file mode 100644 index 0000000000000000000000000000000000000000..11de791c1f216d912fd529d359d55bb4346e2def --- /dev/null +++ b/third-party/video_to_data/reconstruction/modules/v2d_hoi_object_reconstruction/assets/basketball_example/front_stereo_camera_right/1771445418254232064.jpeg @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:2fa96ff0d934542a78d7e66aadfb79f9953a701f106a75b92034fbf025508902 +size 97645 diff --git a/third-party/video_to_data/reconstruction/modules/v2d_hoi_object_reconstruction/assets/basketball_example/front_stereo_camera_right/1771445418587553064.jpeg b/third-party/video_to_data/reconstruction/modules/v2d_hoi_object_reconstruction/assets/basketball_example/front_stereo_camera_right/1771445418587553064.jpeg new file mode 100644 index 0000000000000000000000000000000000000000..e2825e73e5c88e5a8ac25f476188e5a37ea25ba0 --- /dev/null +++ b/third-party/video_to_data/reconstruction/modules/v2d_hoi_object_reconstruction/assets/basketball_example/front_stereo_camera_right/1771445418587553064.jpeg @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:643d9abecc093486f2306c227d7f1a8f2478181d119946282587af13fd528fdc +size 101064 diff --git a/third-party/video_to_data/reconstruction/modules/v2d_hoi_object_reconstruction/assets/basketball_example/front_stereo_camera_right/1771445418920892064.jpeg b/third-party/video_to_data/reconstruction/modules/v2d_hoi_object_reconstruction/assets/basketball_example/front_stereo_camera_right/1771445418920892064.jpeg new file mode 100644 index 0000000000000000000000000000000000000000..1f803c84524cd3d86f8c21cd738084d6293bdf09 --- /dev/null +++ b/third-party/video_to_data/reconstruction/modules/v2d_hoi_object_reconstruction/assets/basketball_example/front_stereo_camera_right/1771445418920892064.jpeg @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:5101c5cb446f1d4b1d41ce16853839c302304b6a1e49d407498085c52d8dc17e +size 100009 diff --git a/third-party/video_to_data/reconstruction/modules/v2d_hoi_object_reconstruction/assets/basketball_example/front_stereo_camera_right/1771445419254212064.jpeg b/third-party/video_to_data/reconstruction/modules/v2d_hoi_object_reconstruction/assets/basketball_example/front_stereo_camera_right/1771445419254212064.jpeg new file mode 100644 index 0000000000000000000000000000000000000000..5d831af3ef1a52e80d2eb2b1db81def55aefbc7c --- /dev/null +++ b/third-party/video_to_data/reconstruction/modules/v2d_hoi_object_reconstruction/assets/basketball_example/front_stereo_camera_right/1771445419254212064.jpeg @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:e1162bdf670a7b1b3e4f7e6c510ddb3ae5ef6963b521e74359d523670e7e4992 +size 95840 diff --git a/third-party/video_to_data/reconstruction/modules/v2d_hoi_object_reconstruction/assets/basketball_example/front_stereo_camera_right/1771445419587533064.jpeg b/third-party/video_to_data/reconstruction/modules/v2d_hoi_object_reconstruction/assets/basketball_example/front_stereo_camera_right/1771445419587533064.jpeg new file mode 100644 index 0000000000000000000000000000000000000000..1ff01a01725afd1bfc31a38a2461b388c051c87c --- /dev/null +++ b/third-party/video_to_data/reconstruction/modules/v2d_hoi_object_reconstruction/assets/basketball_example/front_stereo_camera_right/1771445419587533064.jpeg @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:ffb1f614c6c8c43dc9de1a9bceaadd078e0e14372f8acf579b52acbf82975e8b +size 97732 diff --git a/third-party/video_to_data/reconstruction/modules/v2d_hoi_object_reconstruction/assets/basketball_example/front_stereo_camera_right/1771445419920854112.jpeg b/third-party/video_to_data/reconstruction/modules/v2d_hoi_object_reconstruction/assets/basketball_example/front_stereo_camera_right/1771445419920854112.jpeg new file mode 100644 index 0000000000000000000000000000000000000000..2cb47f8d829e069e7f0d99173cb731a3c45ef3ec --- /dev/null +++ b/third-party/video_to_data/reconstruction/modules/v2d_hoi_object_reconstruction/assets/basketball_example/front_stereo_camera_right/1771445419920854112.jpeg @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:3b1ba42f0ea1436eee8008334c87841a6df67abd29942c0932fc4f0226ea5b66 +size 97913 diff --git a/third-party/video_to_data/reconstruction/modules/v2d_hoi_object_reconstruction/assets/basketball_example/front_stereo_camera_right/1771445420254175112.jpeg b/third-party/video_to_data/reconstruction/modules/v2d_hoi_object_reconstruction/assets/basketball_example/front_stereo_camera_right/1771445420254175112.jpeg new file mode 100644 index 0000000000000000000000000000000000000000..de304874bc612d8be450d6146dd1479a51343cb4 --- /dev/null +++ b/third-party/video_to_data/reconstruction/modules/v2d_hoi_object_reconstruction/assets/basketball_example/front_stereo_camera_right/1771445420254175112.jpeg @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:74c01e46d42db1c6b454b7f7b5c8e1bba56923bb0f6c25f7e75e61c4224e0d79 +size 97281 diff --git a/third-party/video_to_data/reconstruction/modules/v2d_hoi_object_reconstruction/assets/basketball_example/front_stereo_camera_right/1771445420587514112.jpeg b/third-party/video_to_data/reconstruction/modules/v2d_hoi_object_reconstruction/assets/basketball_example/front_stereo_camera_right/1771445420587514112.jpeg new file mode 100644 index 0000000000000000000000000000000000000000..c34046ce78ad957e2409bca8ef84971a025d4668 --- /dev/null +++ b/third-party/video_to_data/reconstruction/modules/v2d_hoi_object_reconstruction/assets/basketball_example/front_stereo_camera_right/1771445420587514112.jpeg @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:217ab0d71d2d15795b1f3a1a4ae1381cc93551855f1f74f7aced126a8fd4fb70 +size 95559 diff --git a/third-party/video_to_data/reconstruction/modules/v2d_hoi_object_reconstruction/assets/basketball_example/front_stereo_camera_right/1771445420920834172.jpeg b/third-party/video_to_data/reconstruction/modules/v2d_hoi_object_reconstruction/assets/basketball_example/front_stereo_camera_right/1771445420920834172.jpeg new file mode 100644 index 0000000000000000000000000000000000000000..a53ff20bc3de26e3382c24f9ee48d2aeb0efd293 --- /dev/null +++ b/third-party/video_to_data/reconstruction/modules/v2d_hoi_object_reconstruction/assets/basketball_example/front_stereo_camera_right/1771445420920834172.jpeg @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:39ab69d0c0a4ada3bb8ed5dbf28c7ee6ea3627931d0b7a2a40330277899dbf97 +size 96805 diff --git a/third-party/video_to_data/reconstruction/modules/v2d_hoi_object_reconstruction/assets/basketball_example/front_stereo_camera_right/1771445421254155172.jpeg b/third-party/video_to_data/reconstruction/modules/v2d_hoi_object_reconstruction/assets/basketball_example/front_stereo_camera_right/1771445421254155172.jpeg new file mode 100644 index 0000000000000000000000000000000000000000..449595e60df4150566ec0e12482a37d7a2f06a12 --- /dev/null +++ b/third-party/video_to_data/reconstruction/modules/v2d_hoi_object_reconstruction/assets/basketball_example/front_stereo_camera_right/1771445421254155172.jpeg @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:285e63bba6f37034c84fd6b08549bba48ed46c2d92b93c5978d6864e9d6502d9 +size 97192 diff --git a/third-party/video_to_data/reconstruction/modules/v2d_hoi_object_reconstruction/assets/basketball_example/front_stereo_camera_right/1771445421587476172.jpeg b/third-party/video_to_data/reconstruction/modules/v2d_hoi_object_reconstruction/assets/basketball_example/front_stereo_camera_right/1771445421587476172.jpeg new file mode 100644 index 0000000000000000000000000000000000000000..83cbf0c5af4fe548d9547b90ed90820ebc7418b0 --- /dev/null +++ b/third-party/video_to_data/reconstruction/modules/v2d_hoi_object_reconstruction/assets/basketball_example/front_stereo_camera_right/1771445421587476172.jpeg @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:3cba478c196f7e7e883a432db722e41713d1ce32467668a203d018ce09407719 +size 97722 diff --git a/third-party/video_to_data/reconstruction/modules/v2d_hoi_object_reconstruction/assets/basketball_example/front_stereo_camera_right/1771445421920797045.jpeg b/third-party/video_to_data/reconstruction/modules/v2d_hoi_object_reconstruction/assets/basketball_example/front_stereo_camera_right/1771445421920797045.jpeg new file mode 100644 index 0000000000000000000000000000000000000000..2daa02645627ae42e2461f550838c0fb58d39798 --- /dev/null +++ b/third-party/video_to_data/reconstruction/modules/v2d_hoi_object_reconstruction/assets/basketball_example/front_stereo_camera_right/1771445421920797045.jpeg @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:ba9f6452f6f8479f972971470c9319e605aff0309f9f82f51c3f7ca6273bb8b5 +size 98668 diff --git a/third-party/video_to_data/reconstruction/modules/v2d_hoi_object_reconstruction/assets/basketball_example/front_stereo_camera_right/1771445422254137045.jpeg b/third-party/video_to_data/reconstruction/modules/v2d_hoi_object_reconstruction/assets/basketball_example/front_stereo_camera_right/1771445422254137045.jpeg new file mode 100644 index 0000000000000000000000000000000000000000..98d48979dfb5a7731bc4e73ac63810aa4776d0f1 --- /dev/null +++ b/third-party/video_to_data/reconstruction/modules/v2d_hoi_object_reconstruction/assets/basketball_example/front_stereo_camera_right/1771445422254137045.jpeg @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:f94bc7d8521428ee78b181f950b0de908d916186f6e5eb7b3ebc6b52cff1ba4c +size 96949 diff --git a/third-party/video_to_data/reconstruction/modules/v2d_hoi_object_reconstruction/assets/basketball_example/front_stereo_camera_right/1771445422587458045.jpeg b/third-party/video_to_data/reconstruction/modules/v2d_hoi_object_reconstruction/assets/basketball_example/front_stereo_camera_right/1771445422587458045.jpeg new file mode 100644 index 0000000000000000000000000000000000000000..c6aae78deb48c11f22c5cdb603e393e5943cb2f0 --- /dev/null +++ b/third-party/video_to_data/reconstruction/modules/v2d_hoi_object_reconstruction/assets/basketball_example/front_stereo_camera_right/1771445422587458045.jpeg @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:59cadeb65b4e2c2724b214648ca82cd227c4f379dd5c67530d83732fcae54527 +size 95801 diff --git a/third-party/video_to_data/reconstruction/modules/v2d_hoi_object_reconstruction/assets/basketball_example/front_stereo_camera_right/1771445422920780053.jpeg b/third-party/video_to_data/reconstruction/modules/v2d_hoi_object_reconstruction/assets/basketball_example/front_stereo_camera_right/1771445422920780053.jpeg new file mode 100644 index 0000000000000000000000000000000000000000..3a117a0eb4388b4f87a57be2040a684a3202ef42 --- /dev/null +++ b/third-party/video_to_data/reconstruction/modules/v2d_hoi_object_reconstruction/assets/basketball_example/front_stereo_camera_right/1771445422920780053.jpeg @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:d6308731a3be09e4cb94e9db8a2dfc8ea7bca153e51c2d2ad9b5d0189a33d5fa +size 95941 diff --git a/third-party/video_to_data/reconstruction/modules/v2d_hoi_object_reconstruction/assets/basketball_example/front_stereo_camera_right/1771445423254102053.jpeg b/third-party/video_to_data/reconstruction/modules/v2d_hoi_object_reconstruction/assets/basketball_example/front_stereo_camera_right/1771445423254102053.jpeg new file mode 100644 index 0000000000000000000000000000000000000000..b4c47d3400c9e27c44411273fb9819e3836e425b --- /dev/null +++ b/third-party/video_to_data/reconstruction/modules/v2d_hoi_object_reconstruction/assets/basketball_example/front_stereo_camera_right/1771445423254102053.jpeg @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:b52bebcab5842129d25d3a9b8a8c238a6e956e704bd18fa3c0caa385a605b2ad +size 95797 diff --git a/third-party/video_to_data/reconstruction/modules/v2d_hoi_object_reconstruction/assets/basketball_example/front_stereo_camera_right/1771445423587437053.jpeg b/third-party/video_to_data/reconstruction/modules/v2d_hoi_object_reconstruction/assets/basketball_example/front_stereo_camera_right/1771445423587437053.jpeg new file mode 100644 index 0000000000000000000000000000000000000000..c0540e42e713c5e40b34ae6014bb141fc4f6c7ec --- /dev/null +++ b/third-party/video_to_data/reconstruction/modules/v2d_hoi_object_reconstruction/assets/basketball_example/front_stereo_camera_right/1771445423587437053.jpeg @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:8d2c68ae4287ed0281472fabd8d531be6f04f74c778665c7afd68534c336a4b4 +size 96665 diff --git a/third-party/video_to_data/reconstruction/modules/v2d_hoi_object_reconstruction/assets/basketball_example/front_stereo_camera_right/1771445423920757037.jpeg b/third-party/video_to_data/reconstruction/modules/v2d_hoi_object_reconstruction/assets/basketball_example/front_stereo_camera_right/1771445423920757037.jpeg new file mode 100644 index 0000000000000000000000000000000000000000..8a5af488ad945f402ec16706e9fd2afa11d548a2 --- /dev/null +++ b/third-party/video_to_data/reconstruction/modules/v2d_hoi_object_reconstruction/assets/basketball_example/front_stereo_camera_right/1771445423920757037.jpeg @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:7e2e5b5f607190065cb1a9330bb675990fc8ed9e87268d08c1699d78834aadcf +size 98356 diff --git a/third-party/video_to_data/reconstruction/modules/v2d_hoi_object_reconstruction/assets/basketball_example/front_stereo_camera_right/1771445424254078037.jpeg b/third-party/video_to_data/reconstruction/modules/v2d_hoi_object_reconstruction/assets/basketball_example/front_stereo_camera_right/1771445424254078037.jpeg new file mode 100644 index 0000000000000000000000000000000000000000..67bd856c8eb21d5a819bdb2b951f2cb74ff70be1 --- /dev/null +++ b/third-party/video_to_data/reconstruction/modules/v2d_hoi_object_reconstruction/assets/basketball_example/front_stereo_camera_right/1771445424254078037.jpeg @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:d0b4054de1724acea7aa6e8fa13f0cbd950b5e6eccaadd179e5ef9e2278625fe +size 99065 diff --git a/third-party/video_to_data/reconstruction/modules/v2d_hoi_object_reconstruction/assets/basketball_example/front_stereo_camera_right/1771445424587399037.jpeg b/third-party/video_to_data/reconstruction/modules/v2d_hoi_object_reconstruction/assets/basketball_example/front_stereo_camera_right/1771445424587399037.jpeg new file mode 100644 index 0000000000000000000000000000000000000000..177cefffa7998d1d4838ba9fc70eef27b13fd791 --- /dev/null +++ b/third-party/video_to_data/reconstruction/modules/v2d_hoi_object_reconstruction/assets/basketball_example/front_stereo_camera_right/1771445424587399037.jpeg @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:fa1ef323ec672c714281a03c9edf1548ee26b8456c847ca585667c620f5ee428 +size 97657 diff --git a/third-party/video_to_data/reconstruction/modules/v2d_hoi_object_reconstruction/assets/basketball_example/front_stereo_camera_right/1771445424920720053.jpeg b/third-party/video_to_data/reconstruction/modules/v2d_hoi_object_reconstruction/assets/basketball_example/front_stereo_camera_right/1771445424920720053.jpeg new file mode 100644 index 0000000000000000000000000000000000000000..a94b2d76f40cd08d22edf9fd95177c8148cfa81f --- /dev/null +++ b/third-party/video_to_data/reconstruction/modules/v2d_hoi_object_reconstruction/assets/basketball_example/front_stereo_camera_right/1771445424920720053.jpeg @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:37fb5d30fed0a92710058f4b3963fb99035beba6904834e9debaa1653178b926 +size 96112 diff --git a/third-party/video_to_data/reconstruction/modules/v2d_hoi_object_reconstruction/assets/basketball_example/front_stereo_camera_right/1771445425254058053.jpeg b/third-party/video_to_data/reconstruction/modules/v2d_hoi_object_reconstruction/assets/basketball_example/front_stereo_camera_right/1771445425254058053.jpeg new file mode 100644 index 0000000000000000000000000000000000000000..9a82776900e2f277ca00b6469bb9cf9b8a60d681 --- /dev/null +++ b/third-party/video_to_data/reconstruction/modules/v2d_hoi_object_reconstruction/assets/basketball_example/front_stereo_camera_right/1771445425254058053.jpeg @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:9958bc1ba68ba53abbd0a22305f7440239a9d566e2abbe35cb5c9dc1b0150829 +size 96820 diff --git a/third-party/video_to_data/reconstruction/modules/v2d_hoi_object_reconstruction/assets/basketball_example/front_stereo_camera_right/1771445425587379053.jpeg b/third-party/video_to_data/reconstruction/modules/v2d_hoi_object_reconstruction/assets/basketball_example/front_stereo_camera_right/1771445425587379053.jpeg new file mode 100644 index 0000000000000000000000000000000000000000..6b06c2147e78f7662b1127a0fb378e023aa8b4b0 --- /dev/null +++ b/third-party/video_to_data/reconstruction/modules/v2d_hoi_object_reconstruction/assets/basketball_example/front_stereo_camera_right/1771445425587379053.jpeg @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:1c35c082acfe5d46a172f32ea986ad67fc7a79a1aba787ed8fc637db39e22936 +size 96013 diff --git a/third-party/video_to_data/reconstruction/modules/v2d_hoi_object_reconstruction/assets/basketball_example/front_stereo_camera_right/1771445425920700017.jpeg b/third-party/video_to_data/reconstruction/modules/v2d_hoi_object_reconstruction/assets/basketball_example/front_stereo_camera_right/1771445425920700017.jpeg new file mode 100644 index 0000000000000000000000000000000000000000..d50282238f9c4855fc9a3fecacc4898a03ac221a --- /dev/null +++ b/third-party/video_to_data/reconstruction/modules/v2d_hoi_object_reconstruction/assets/basketball_example/front_stereo_camera_right/1771445425920700017.jpeg @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:547d30e42dc7fd3d760534fcc8e64b401b9e1aacb1b6ff10e0cb22391e5eebd0 +size 94692 diff --git a/third-party/video_to_data/reconstruction/modules/v2d_hoi_object_reconstruction/assets/basketball_example/front_stereo_camera_right/1771445426254021017.jpeg b/third-party/video_to_data/reconstruction/modules/v2d_hoi_object_reconstruction/assets/basketball_example/front_stereo_camera_right/1771445426254021017.jpeg new file mode 100644 index 0000000000000000000000000000000000000000..4516d3f45654b83597891f33e24ed7a5a1d31a0d --- /dev/null +++ b/third-party/video_to_data/reconstruction/modules/v2d_hoi_object_reconstruction/assets/basketball_example/front_stereo_camera_right/1771445426254021017.jpeg @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:b8456f1a5d203f280b4e6df4617fad73fcd4f186b9f8546e4c27d471d22d5cf2 +size 94119 diff --git a/third-party/video_to_data/reconstruction/modules/v2d_hoi_object_reconstruction/assets/basketball_example/front_stereo_camera_right/1771445426587341017.jpeg b/third-party/video_to_data/reconstruction/modules/v2d_hoi_object_reconstruction/assets/basketball_example/front_stereo_camera_right/1771445426587341017.jpeg new file mode 100644 index 0000000000000000000000000000000000000000..154961b2737951a1d508a4d55b3eff1637856e4d --- /dev/null +++ b/third-party/video_to_data/reconstruction/modules/v2d_hoi_object_reconstruction/assets/basketball_example/front_stereo_camera_right/1771445426587341017.jpeg @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:26c4ee9ab6f0f7ac2cf0833635ce6deb67e583875dce4304c264e2c10d2f5686 +size 93500 diff --git a/third-party/video_to_data/reconstruction/modules/v2d_hoi_object_reconstruction/assets/basketball_example/front_stereo_camera_right/1771445426920680020.jpeg b/third-party/video_to_data/reconstruction/modules/v2d_hoi_object_reconstruction/assets/basketball_example/front_stereo_camera_right/1771445426920680020.jpeg new file mode 100644 index 0000000000000000000000000000000000000000..534df3a3c7e8023644b2c5d78570ca77fddca337 --- /dev/null +++ b/third-party/video_to_data/reconstruction/modules/v2d_hoi_object_reconstruction/assets/basketball_example/front_stereo_camera_right/1771445426920680020.jpeg @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:22c0100143e02d6c6f31eb4ea47dbf396a24aa01d766896d56e35a8b4ce6266f +size 93860 diff --git a/third-party/video_to_data/reconstruction/modules/v2d_hoi_object_reconstruction/assets/basketball_example/front_stereo_camera_right/1771445427254001020.jpeg b/third-party/video_to_data/reconstruction/modules/v2d_hoi_object_reconstruction/assets/basketball_example/front_stereo_camera_right/1771445427254001020.jpeg new file mode 100644 index 0000000000000000000000000000000000000000..c866818fb12bb7ca543bee9d7c61cd4b89f746ca --- /dev/null +++ b/third-party/video_to_data/reconstruction/modules/v2d_hoi_object_reconstruction/assets/basketball_example/front_stereo_camera_right/1771445427254001020.jpeg @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:8910defa2ffb7cd0755155e8f73a1ad81dfd01e3a2510b1a0645a9857adb996f +size 93233 diff --git a/third-party/video_to_data/reconstruction/modules/v2d_hoi_object_reconstruction/assets/basketball_example/front_stereo_camera_right/1771445427587322020.jpeg b/third-party/video_to_data/reconstruction/modules/v2d_hoi_object_reconstruction/assets/basketball_example/front_stereo_camera_right/1771445427587322020.jpeg new file mode 100644 index 0000000000000000000000000000000000000000..1062ef1ab80ed03936e2e44f269a5eeca9436666 --- /dev/null +++ b/third-party/video_to_data/reconstruction/modules/v2d_hoi_object_reconstruction/assets/basketball_example/front_stereo_camera_right/1771445427587322020.jpeg @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:aa05438c2bb3f62684d0c345587f5c9e0c20332ab3eb1de710854dc0ad042ec1 +size 93635 diff --git a/third-party/video_to_data/reconstruction/modules/v2d_hoi_object_reconstruction/assets/basketball_example/front_stereo_camera_right/1771445427920643017.jpeg b/third-party/video_to_data/reconstruction/modules/v2d_hoi_object_reconstruction/assets/basketball_example/front_stereo_camera_right/1771445427920643017.jpeg new file mode 100644 index 0000000000000000000000000000000000000000..d650a5f9713e5d6e19dbe4849e91175927ba799d --- /dev/null +++ b/third-party/video_to_data/reconstruction/modules/v2d_hoi_object_reconstruction/assets/basketball_example/front_stereo_camera_right/1771445427920643017.jpeg @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:1e4be9c83342dee6181a2ea419c3bcee3cd3e6980ff5b4883cbfc9fbc9056faa +size 93528 diff --git a/third-party/video_to_data/reconstruction/modules/v2d_hoi_object_reconstruction/assets/basketball_example/front_stereo_camera_right/1771445428253983017.jpeg b/third-party/video_to_data/reconstruction/modules/v2d_hoi_object_reconstruction/assets/basketball_example/front_stereo_camera_right/1771445428253983017.jpeg new file mode 100644 index 0000000000000000000000000000000000000000..9bacd8cc09bf666dae6385c1f8d45193fb1a3e25 --- /dev/null +++ b/third-party/video_to_data/reconstruction/modules/v2d_hoi_object_reconstruction/assets/basketball_example/front_stereo_camera_right/1771445428253983017.jpeg @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:f9647f1c4fab5f53c17422fc391836665d1608a5bb7b496631f63c753748850f +size 93294 diff --git a/third-party/video_to_data/reconstruction/modules/v2d_hoi_object_reconstruction/assets/basketball_example/front_stereo_camera_right/1771445428587305017.jpeg b/third-party/video_to_data/reconstruction/modules/v2d_hoi_object_reconstruction/assets/basketball_example/front_stereo_camera_right/1771445428587305017.jpeg new file mode 100644 index 0000000000000000000000000000000000000000..66e4bb5af0868665cefdf8044532853725579ad7 --- /dev/null +++ b/third-party/video_to_data/reconstruction/modules/v2d_hoi_object_reconstruction/assets/basketball_example/front_stereo_camera_right/1771445428587305017.jpeg @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:0bf56a0bc39a8ad338d685c9bef8dce217ed31dcd1759cecbdb5e3c6a48ac73f +size 93434 diff --git a/third-party/video_to_data/reconstruction/modules/v2d_hoi_object_reconstruction/assets/basketball_example/front_stereo_camera_right/1771445428920627008.jpeg b/third-party/video_to_data/reconstruction/modules/v2d_hoi_object_reconstruction/assets/basketball_example/front_stereo_camera_right/1771445428920627008.jpeg new file mode 100644 index 0000000000000000000000000000000000000000..6e921f7a4bbba7199f9b28bbc9c0d6fbabed0782 --- /dev/null +++ b/third-party/video_to_data/reconstruction/modules/v2d_hoi_object_reconstruction/assets/basketball_example/front_stereo_camera_right/1771445428920627008.jpeg @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:46252999eefe795b69b655fddcfaf61a3cdfa525d068a10e4003b82a875f32ae +size 92905 diff --git a/third-party/video_to_data/reconstruction/modules/v2d_hoi_object_reconstruction/assets/basketball_example/front_stereo_camera_right/1771445429253944008.jpeg b/third-party/video_to_data/reconstruction/modules/v2d_hoi_object_reconstruction/assets/basketball_example/front_stereo_camera_right/1771445429253944008.jpeg new file mode 100644 index 0000000000000000000000000000000000000000..7e59edc1b2e36d648944a782b2d1f310684645f0 --- /dev/null +++ b/third-party/video_to_data/reconstruction/modules/v2d_hoi_object_reconstruction/assets/basketball_example/front_stereo_camera_right/1771445429253944008.jpeg @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:c7cfed60dce314c3e1ceef6fa7251598669c1d2f726ad09ba6560e3871c78be1 +size 92792 diff --git a/third-party/video_to_data/reconstruction/modules/v2d_hoi_object_reconstruction/assets/basketball_example/front_stereo_camera_right/1771445429587264008.jpeg b/third-party/video_to_data/reconstruction/modules/v2d_hoi_object_reconstruction/assets/basketball_example/front_stereo_camera_right/1771445429587264008.jpeg new file mode 100644 index 0000000000000000000000000000000000000000..e4385353cb4b4f8805323e74ece7dda21d385506 --- /dev/null +++ b/third-party/video_to_data/reconstruction/modules/v2d_hoi_object_reconstruction/assets/basketball_example/front_stereo_camera_right/1771445429587264008.jpeg @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:566457610fc96ef80a6357a96ea1892f603a7ec24ed96fb8dcacb2799175d562 +size 91836 diff --git a/third-party/video_to_data/reconstruction/modules/v2d_hoi_object_reconstruction/assets/basketball_example/front_stereo_camera_right/1771445429920603020.jpeg b/third-party/video_to_data/reconstruction/modules/v2d_hoi_object_reconstruction/assets/basketball_example/front_stereo_camera_right/1771445429920603020.jpeg new file mode 100644 index 0000000000000000000000000000000000000000..ea7d441c6384847eb90fd2e477e0a14f9f93e13f --- /dev/null +++ b/third-party/video_to_data/reconstruction/modules/v2d_hoi_object_reconstruction/assets/basketball_example/front_stereo_camera_right/1771445429920603020.jpeg @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:b0a39e5dfd6d437165f280483996abb83947179996a819ab9b8f03a1db9735fd +size 90632 diff --git a/third-party/video_to_data/reconstruction/modules/v2d_hoi_object_reconstruction/assets/basketball_example/front_stereo_camera_right/1771445430253924020.jpeg b/third-party/video_to_data/reconstruction/modules/v2d_hoi_object_reconstruction/assets/basketball_example/front_stereo_camera_right/1771445430253924020.jpeg new file mode 100644 index 0000000000000000000000000000000000000000..e91334a039bceed3dcad0ea2149c7c41d250b3e2 --- /dev/null +++ b/third-party/video_to_data/reconstruction/modules/v2d_hoi_object_reconstruction/assets/basketball_example/front_stereo_camera_right/1771445430253924020.jpeg @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:36dd9b8710b46d4f85e3758eaf441b27a5c589be4409c32117aa86afbbdcec02 +size 91200 diff --git a/third-party/video_to_data/reconstruction/modules/v2d_hoi_object_reconstruction/assets/basketball_example/front_stereo_camera_right/1771445430587245020.jpeg b/third-party/video_to_data/reconstruction/modules/v2d_hoi_object_reconstruction/assets/basketball_example/front_stereo_camera_right/1771445430587245020.jpeg new file mode 100644 index 0000000000000000000000000000000000000000..d54da580cf9ef1d847ba046bd451f029900dfaf7 --- /dev/null +++ b/third-party/video_to_data/reconstruction/modules/v2d_hoi_object_reconstruction/assets/basketball_example/front_stereo_camera_right/1771445430587245020.jpeg @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:63410dab1157726ce8832b9a28237816ef4b179ffb957ebd33f66b4d134b8b87 +size 92033 diff --git a/third-party/video_to_data/reconstruction/modules/v2d_hoi_object_reconstruction/assets/basketball_example/front_stereo_camera_right/1771445430920566129.jpeg b/third-party/video_to_data/reconstruction/modules/v2d_hoi_object_reconstruction/assets/basketball_example/front_stereo_camera_right/1771445430920566129.jpeg new file mode 100644 index 0000000000000000000000000000000000000000..157a76aea238a30f7c48f08ff587662399c75423 --- /dev/null +++ b/third-party/video_to_data/reconstruction/modules/v2d_hoi_object_reconstruction/assets/basketball_example/front_stereo_camera_right/1771445430920566129.jpeg @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:51eb2048c74645d243c5f9f7f50605c1b2f64c571941ecaea14b7bad7fd3301e +size 89218 diff --git a/third-party/video_to_data/reconstruction/modules/v2d_hoi_object_reconstruction/assets/basketball_example/front_stereo_camera_right/1771445431253886129.jpeg b/third-party/video_to_data/reconstruction/modules/v2d_hoi_object_reconstruction/assets/basketball_example/front_stereo_camera_right/1771445431253886129.jpeg new file mode 100644 index 0000000000000000000000000000000000000000..dda97284aff27a1eef4af80a90033f36651c2f94 --- /dev/null +++ b/third-party/video_to_data/reconstruction/modules/v2d_hoi_object_reconstruction/assets/basketball_example/front_stereo_camera_right/1771445431253886129.jpeg @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:59c252a4c5f810839899159fafd178040cf5f9f18926b5ca65e8ff82f5a7af65 +size 92435 diff --git a/third-party/video_to_data/reconstruction/modules/v2d_hoi_object_reconstruction/assets/basketball_example/front_stereo_camera_right/1771445431587225129.jpeg b/third-party/video_to_data/reconstruction/modules/v2d_hoi_object_reconstruction/assets/basketball_example/front_stereo_camera_right/1771445431587225129.jpeg new file mode 100644 index 0000000000000000000000000000000000000000..deb921e201c9509d2b7f09d638dc6341207cb1fc --- /dev/null +++ b/third-party/video_to_data/reconstruction/modules/v2d_hoi_object_reconstruction/assets/basketball_example/front_stereo_camera_right/1771445431587225129.jpeg @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:ebf790c18561c84942f3b0a9ce04001e19ba0edb3525beaad0e637da3db7b741 +size 92946 diff --git a/third-party/video_to_data/reconstruction/modules/v2d_hoi_object_reconstruction/assets/basketball_example/front_stereo_camera_right/1771445431920546008.jpeg b/third-party/video_to_data/reconstruction/modules/v2d_hoi_object_reconstruction/assets/basketball_example/front_stereo_camera_right/1771445431920546008.jpeg new file mode 100644 index 0000000000000000000000000000000000000000..642f589c55d33180f675ca9270edd46b45d4b9c5 --- /dev/null +++ b/third-party/video_to_data/reconstruction/modules/v2d_hoi_object_reconstruction/assets/basketball_example/front_stereo_camera_right/1771445431920546008.jpeg @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:d4d0c1697603cf049093185937a0b13772aae686d6a7784cc9f5e42fccccd3c1 +size 93261 diff --git a/third-party/video_to_data/reconstruction/modules/v2d_hoi_object_reconstruction/assets/basketball_example/front_stereo_camera_right/1771445432253867008.jpeg b/third-party/video_to_data/reconstruction/modules/v2d_hoi_object_reconstruction/assets/basketball_example/front_stereo_camera_right/1771445432253867008.jpeg new file mode 100644 index 0000000000000000000000000000000000000000..8e137e2c042b116ce7be0a130b334900bb0d409b --- /dev/null +++ b/third-party/video_to_data/reconstruction/modules/v2d_hoi_object_reconstruction/assets/basketball_example/front_stereo_camera_right/1771445432253867008.jpeg @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:89129ec889319038876c890cf8eba9e335edaa926c2034d604d397b6f0e7859a +size 93383 diff --git a/third-party/video_to_data/reconstruction/modules/v2d_hoi_object_reconstruction/assets/basketball_example/front_stereo_camera_right/1771445432587187008.jpeg b/third-party/video_to_data/reconstruction/modules/v2d_hoi_object_reconstruction/assets/basketball_example/front_stereo_camera_right/1771445432587187008.jpeg new file mode 100644 index 0000000000000000000000000000000000000000..cf54f020b5071b3676a4bca3bd6674f96929a899 --- /dev/null +++ b/third-party/video_to_data/reconstruction/modules/v2d_hoi_object_reconstruction/assets/basketball_example/front_stereo_camera_right/1771445432587187008.jpeg @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:cc317f3af8d732abfb1e0abec7e45c709998a6a88650510681782fd7cac8704d +size 93261 diff --git a/third-party/video_to_data/reconstruction/modules/v2d_hoi_object_reconstruction/assets/basketball_example/front_stereo_camera_right/1771445432920526012.jpeg b/third-party/video_to_data/reconstruction/modules/v2d_hoi_object_reconstruction/assets/basketball_example/front_stereo_camera_right/1771445432920526012.jpeg new file mode 100644 index 0000000000000000000000000000000000000000..369ceee64b5b074f4008b21df73657c18a841dc0 --- /dev/null +++ b/third-party/video_to_data/reconstruction/modules/v2d_hoi_object_reconstruction/assets/basketball_example/front_stereo_camera_right/1771445432920526012.jpeg @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:95a48ddb23ea750775921f597962d5534845f96d8b63cc861920836f08f6ff5b +size 93159 diff --git a/third-party/video_to_data/reconstruction/modules/v2d_hoi_object_reconstruction/assets/basketball_example/front_stereo_camera_right/1771445433253847012.jpeg b/third-party/video_to_data/reconstruction/modules/v2d_hoi_object_reconstruction/assets/basketball_example/front_stereo_camera_right/1771445433253847012.jpeg new file mode 100644 index 0000000000000000000000000000000000000000..9a705b54c8c82e57342974d3f04900c705180007 --- /dev/null +++ b/third-party/video_to_data/reconstruction/modules/v2d_hoi_object_reconstruction/assets/basketball_example/front_stereo_camera_right/1771445433253847012.jpeg @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:c9433c4252e23238dbff91b5b9318140f934706145c022ba74fea99f81f0dff3 +size 92999 diff --git a/third-party/video_to_data/reconstruction/modules/v2d_hoi_object_reconstruction/assets/basketball_example/front_stereo_camera_right/1771445433587168012.jpeg b/third-party/video_to_data/reconstruction/modules/v2d_hoi_object_reconstruction/assets/basketball_example/front_stereo_camera_right/1771445433587168012.jpeg new file mode 100644 index 0000000000000000000000000000000000000000..47c25f92b5eb0d30fafa904ae30be40d973fbb58 --- /dev/null +++ b/third-party/video_to_data/reconstruction/modules/v2d_hoi_object_reconstruction/assets/basketball_example/front_stereo_camera_right/1771445433587168012.jpeg @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:65a93d170e4a024776e4bdfeddaf38dcb5a977e2269880a1a691ccfac2ca581b +size 92821 diff --git a/third-party/video_to_data/reconstruction/modules/v2d_hoi_object_reconstruction/assets/basketball_example/front_stereo_camera_right/1771445433920489104.jpeg b/third-party/video_to_data/reconstruction/modules/v2d_hoi_object_reconstruction/assets/basketball_example/front_stereo_camera_right/1771445433920489104.jpeg new file mode 100644 index 0000000000000000000000000000000000000000..e93aa4b666c526625cd88bd349dd62bb877cf619 --- /dev/null +++ b/third-party/video_to_data/reconstruction/modules/v2d_hoi_object_reconstruction/assets/basketball_example/front_stereo_camera_right/1771445433920489104.jpeg @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:f0c5097ed06bae8251c3152ee2d2dd4409cfe5b4dfe26dfc32e5fac6982566d0 +size 92252 diff --git a/third-party/video_to_data/reconstruction/modules/v2d_hoi_object_reconstruction/assets/basketball_example/front_stereo_camera_right/1771445434253809104.jpeg b/third-party/video_to_data/reconstruction/modules/v2d_hoi_object_reconstruction/assets/basketball_example/front_stereo_camera_right/1771445434253809104.jpeg new file mode 100644 index 0000000000000000000000000000000000000000..4e0ddda20a558a451e24acdd857c2961fad88194 --- /dev/null +++ b/third-party/video_to_data/reconstruction/modules/v2d_hoi_object_reconstruction/assets/basketball_example/front_stereo_camera_right/1771445434253809104.jpeg @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:a66d19bb04ea0c4015abf5c5296512fb1f1363c566f4874ed9f8954c22b03c1a +size 91951 diff --git a/third-party/video_to_data/reconstruction/modules/v2d_hoi_object_reconstruction/assets/basketball_example/front_stereo_camera_right/1771445434587151104.jpeg b/third-party/video_to_data/reconstruction/modules/v2d_hoi_object_reconstruction/assets/basketball_example/front_stereo_camera_right/1771445434587151104.jpeg new file mode 100644 index 0000000000000000000000000000000000000000..21a74c17f6891931bfc2cf06421525529eb0efec --- /dev/null +++ b/third-party/video_to_data/reconstruction/modules/v2d_hoi_object_reconstruction/assets/basketball_example/front_stereo_camera_right/1771445434587151104.jpeg @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:e8b33a8968701c53f25d966bbd0e5ae2d3ae4ea81570ca6368b32b539aafcb2a +size 92618 diff --git a/third-party/video_to_data/reconstruction/modules/v2d_hoi_object_reconstruction/assets/basketball_example/front_stereo_camera_right/1771445434920473056.jpeg b/third-party/video_to_data/reconstruction/modules/v2d_hoi_object_reconstruction/assets/basketball_example/front_stereo_camera_right/1771445434920473056.jpeg new file mode 100644 index 0000000000000000000000000000000000000000..4feb3c790ea205ce109329be9a5e6e54c368f428 --- /dev/null +++ b/third-party/video_to_data/reconstruction/modules/v2d_hoi_object_reconstruction/assets/basketball_example/front_stereo_camera_right/1771445434920473056.jpeg @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:0f94cd517ac3877f93dce3cc5d5f77f344072ca7b94215fd0bf486d0f6f96ced +size 92933 diff --git a/third-party/video_to_data/reconstruction/modules/v2d_hoi_object_reconstruction/assets/basketball_example/front_stereo_camera_right/1771445435253790056.jpeg b/third-party/video_to_data/reconstruction/modules/v2d_hoi_object_reconstruction/assets/basketball_example/front_stereo_camera_right/1771445435253790056.jpeg new file mode 100644 index 0000000000000000000000000000000000000000..4b26d38806ae11bd01e415ba157a2556921427c2 --- /dev/null +++ b/third-party/video_to_data/reconstruction/modules/v2d_hoi_object_reconstruction/assets/basketball_example/front_stereo_camera_right/1771445435253790056.jpeg @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:b77f90c0dc8b20bf531731be2d8eff39ea4bfa78e6407a16d35de049e4b8ab6f +size 93397 diff --git a/third-party/video_to_data/reconstruction/modules/v2d_hoi_object_reconstruction/assets/basketball_example/front_stereo_camera_right/1771445435587110056.jpeg b/third-party/video_to_data/reconstruction/modules/v2d_hoi_object_reconstruction/assets/basketball_example/front_stereo_camera_right/1771445435587110056.jpeg new file mode 100644 index 0000000000000000000000000000000000000000..8f4483a3ba353296cee86c5bcadd56bc8ec2fddd --- /dev/null +++ b/third-party/video_to_data/reconstruction/modules/v2d_hoi_object_reconstruction/assets/basketball_example/front_stereo_camera_right/1771445435587110056.jpeg @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:0aef1f8a49bbbe0c4655314481ad005cbcf7bf60bb96ec43f3d3a15fcc062941 +size 93676 diff --git a/third-party/video_to_data/reconstruction/modules/v2d_hoi_object_reconstruction/assets/basketball_example/front_stereo_camera_right/1771445435920431020.jpeg b/third-party/video_to_data/reconstruction/modules/v2d_hoi_object_reconstruction/assets/basketball_example/front_stereo_camera_right/1771445435920431020.jpeg new file mode 100644 index 0000000000000000000000000000000000000000..7785deb25d6e256b5e0110e96c15f5683a7caba1 --- /dev/null +++ b/third-party/video_to_data/reconstruction/modules/v2d_hoi_object_reconstruction/assets/basketball_example/front_stereo_camera_right/1771445435920431020.jpeg @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:5e597b12859ca65a8c8aae760e46470f31f586d4c4adcdcbcc8811828cb36d0c +size 94446 diff --git a/third-party/video_to_data/reconstruction/modules/v2d_hoi_object_reconstruction/assets/basketball_example/front_stereo_camera_right/1771445436253770020.jpeg b/third-party/video_to_data/reconstruction/modules/v2d_hoi_object_reconstruction/assets/basketball_example/front_stereo_camera_right/1771445436253770020.jpeg new file mode 100644 index 0000000000000000000000000000000000000000..550f2b74db2c8d2a7b443be491d0bb17aa811a07 --- /dev/null +++ b/third-party/video_to_data/reconstruction/modules/v2d_hoi_object_reconstruction/assets/basketball_example/front_stereo_camera_right/1771445436253770020.jpeg @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:e77e1f33088b69161d2f86070c182cb317f90f6f593c38cceb3dfe0f4ef57476 +size 94939 diff --git a/third-party/video_to_data/reconstruction/modules/v2d_hoi_object_reconstruction/assets/basketball_example/front_stereo_camera_right/1771445436587091020.jpeg b/third-party/video_to_data/reconstruction/modules/v2d_hoi_object_reconstruction/assets/basketball_example/front_stereo_camera_right/1771445436587091020.jpeg new file mode 100644 index 0000000000000000000000000000000000000000..e5ab17fcbd567f246f736e51e45ddc4124f30eb7 --- /dev/null +++ b/third-party/video_to_data/reconstruction/modules/v2d_hoi_object_reconstruction/assets/basketball_example/front_stereo_camera_right/1771445436587091020.jpeg @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:c26383b8d17805d87e512af571da6eac3ad3ea9d3cfa8261399a40764a4f72d6 +size 95428 diff --git a/third-party/video_to_data/reconstruction/modules/v2d_hoi_object_reconstruction/assets/basketball_example/front_stereo_camera_right/1771445436920411032.jpeg b/third-party/video_to_data/reconstruction/modules/v2d_hoi_object_reconstruction/assets/basketball_example/front_stereo_camera_right/1771445436920411032.jpeg new file mode 100644 index 0000000000000000000000000000000000000000..cea45b960706b1a3871acaee5ccaa97a691f71cb --- /dev/null +++ b/third-party/video_to_data/reconstruction/modules/v2d_hoi_object_reconstruction/assets/basketball_example/front_stereo_camera_right/1771445436920411032.jpeg @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:e022b6d2cd57a343f2cf3f25ba9260d5ddfd91be12e580180ccc9988759239e7 +size 94886 diff --git a/third-party/video_to_data/reconstruction/modules/v2d_hoi_object_reconstruction/assets/basketball_example/front_stereo_camera_right/1771445437253732032.jpeg b/third-party/video_to_data/reconstruction/modules/v2d_hoi_object_reconstruction/assets/basketball_example/front_stereo_camera_right/1771445437253732032.jpeg new file mode 100644 index 0000000000000000000000000000000000000000..3d555e42b5879f3c09ca02f53f55cb86ece80318 --- /dev/null +++ b/third-party/video_to_data/reconstruction/modules/v2d_hoi_object_reconstruction/assets/basketball_example/front_stereo_camera_right/1771445437253732032.jpeg @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:d35a2e3502f7b75f7a92d6f469b7e5ffa3e13b43a5f15bf7c5e2cefd0ee6739f +size 94455 diff --git a/third-party/video_to_data/reconstruction/modules/v2d_hoi_object_reconstruction/assets/basketball_example/front_stereo_camera_right/1771445437587071032.jpeg b/third-party/video_to_data/reconstruction/modules/v2d_hoi_object_reconstruction/assets/basketball_example/front_stereo_camera_right/1771445437587071032.jpeg new file mode 100644 index 0000000000000000000000000000000000000000..68a98e5004b741dae1f26d695ac4ff3dc842cc3d --- /dev/null +++ b/third-party/video_to_data/reconstruction/modules/v2d_hoi_object_reconstruction/assets/basketball_example/front_stereo_camera_right/1771445437587071032.jpeg @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:4abd01d614767ed1ceaf13221f44cae9889056be4494468fb3213f1a84976bef +size 94463 diff --git a/third-party/video_to_data/reconstruction/modules/v2d_hoi_object_reconstruction/assets/basketball_example/front_stereo_camera_right/1771445437920392040.jpeg b/third-party/video_to_data/reconstruction/modules/v2d_hoi_object_reconstruction/assets/basketball_example/front_stereo_camera_right/1771445437920392040.jpeg new file mode 100644 index 0000000000000000000000000000000000000000..6fd27d9d6ac28ad42c99c6e11d2420e0a083565e --- /dev/null +++ b/third-party/video_to_data/reconstruction/modules/v2d_hoi_object_reconstruction/assets/basketball_example/front_stereo_camera_right/1771445437920392040.jpeg @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:855658f771466025b5f4d585ac8b86d4da514acb8fe43e4b217bff9d523efd2b +size 95669 diff --git a/third-party/video_to_data/reconstruction/modules/v2d_hoi_object_reconstruction/assets/basketball_example/front_stereo_camera_right/1771445438253712040.jpeg b/third-party/video_to_data/reconstruction/modules/v2d_hoi_object_reconstruction/assets/basketball_example/front_stereo_camera_right/1771445438253712040.jpeg new file mode 100644 index 0000000000000000000000000000000000000000..78e5e3067b40fdfeb1f94efe0cc95d4bea38f401 --- /dev/null +++ b/third-party/video_to_data/reconstruction/modules/v2d_hoi_object_reconstruction/assets/basketball_example/front_stereo_camera_right/1771445438253712040.jpeg @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:13c672a22f248405d95361f01a2fcd04c6479de58ca81d80d15bd9092a120c39 +size 98242 diff --git a/third-party/video_to_data/reconstruction/modules/v2d_hoi_object_reconstruction/assets/basketball_example/front_stereo_camera_right/1771445438587033040.jpeg b/third-party/video_to_data/reconstruction/modules/v2d_hoi_object_reconstruction/assets/basketball_example/front_stereo_camera_right/1771445438587033040.jpeg new file mode 100644 index 0000000000000000000000000000000000000000..6bdd3dab17db1f85d6957922b519819876856241 --- /dev/null +++ b/third-party/video_to_data/reconstruction/modules/v2d_hoi_object_reconstruction/assets/basketball_example/front_stereo_camera_right/1771445438587033040.jpeg @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:79bde418ebfd8ed39f969a4a5c28f8e6a15b51fad19bdc38251476bb218ab3d1 +size 102091 diff --git a/third-party/video_to_data/reconstruction/modules/v2d_hoi_object_reconstruction/assets/basketball_example/front_stereo_camera_right/1771445438920354028.jpeg b/third-party/video_to_data/reconstruction/modules/v2d_hoi_object_reconstruction/assets/basketball_example/front_stereo_camera_right/1771445438920354028.jpeg new file mode 100644 index 0000000000000000000000000000000000000000..3a7af41a9b91c03ee1f4b918bfe3cce526a24b87 --- /dev/null +++ b/third-party/video_to_data/reconstruction/modules/v2d_hoi_object_reconstruction/assets/basketball_example/front_stereo_camera_right/1771445438920354028.jpeg @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:6d357baf31a7f3c2b7ee4c7a6d3bcbbd5ebd1f6024ad7bcfb79557dc1f94caba +size 101285 diff --git a/third-party/video_to_data/reconstruction/modules/v2d_hoi_object_reconstruction/assets/basketball_example/front_stereo_camera_right/1771445439253693028.jpeg b/third-party/video_to_data/reconstruction/modules/v2d_hoi_object_reconstruction/assets/basketball_example/front_stereo_camera_right/1771445439253693028.jpeg new file mode 100644 index 0000000000000000000000000000000000000000..725a9bc5a2922ad40b0156eda29b93a859b558e9 --- /dev/null +++ b/third-party/video_to_data/reconstruction/modules/v2d_hoi_object_reconstruction/assets/basketball_example/front_stereo_camera_right/1771445439253693028.jpeg @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:7400eda7928806cb71cc6aa5fc893044c00a3f59999c4b4f6610508a4944f150 +size 100630 diff --git a/third-party/video_to_data/reconstruction/modules/v2d_hoi_object_reconstruction/assets/basketball_example/front_stereo_camera_right/1771445439587014028.jpeg b/third-party/video_to_data/reconstruction/modules/v2d_hoi_object_reconstruction/assets/basketball_example/front_stereo_camera_right/1771445439587014028.jpeg new file mode 100644 index 0000000000000000000000000000000000000000..3ae22708a8c88d5744ebfe518f3ad8d3928b026b --- /dev/null +++ b/third-party/video_to_data/reconstruction/modules/v2d_hoi_object_reconstruction/assets/basketball_example/front_stereo_camera_right/1771445439587014028.jpeg @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:37ac6723233e9fece1e30bb5b32ab2e023e71d53f8ac412ec81103c17f9a57a1 +size 99558 diff --git a/third-party/video_to_data/reconstruction/modules/v2d_hoi_object_reconstruction/assets/basketball_example/front_stereo_camera_right/1771445439920336052.jpeg b/third-party/video_to_data/reconstruction/modules/v2d_hoi_object_reconstruction/assets/basketball_example/front_stereo_camera_right/1771445439920336052.jpeg new file mode 100644 index 0000000000000000000000000000000000000000..ff6de8192243c69fdd8a046e25177fe8912c90cf --- /dev/null +++ b/third-party/video_to_data/reconstruction/modules/v2d_hoi_object_reconstruction/assets/basketball_example/front_stereo_camera_right/1771445439920336052.jpeg @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:d3acc1babfefa7e1bfc15d0f6b4bc865ce7104d4e4c9608e6cddadef5cfb4b1a +size 98553 diff --git a/third-party/video_to_data/reconstruction/modules/v2d_hoi_object_reconstruction/assets/basketball_example/front_stereo_camera_right/1771445440253658052.jpeg b/third-party/video_to_data/reconstruction/modules/v2d_hoi_object_reconstruction/assets/basketball_example/front_stereo_camera_right/1771445440253658052.jpeg new file mode 100644 index 0000000000000000000000000000000000000000..471218ac199771cfceb2c23832ef56f14deb42b3 --- /dev/null +++ b/third-party/video_to_data/reconstruction/modules/v2d_hoi_object_reconstruction/assets/basketball_example/front_stereo_camera_right/1771445440253658052.jpeg @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:e845bbb1f4058646830eb3514810eb88355c285ac551537c36ffb590db257323 +size 83039 diff --git a/third-party/video_to_data/reconstruction/modules/v2d_hoi_object_reconstruction/assets/basketball_example/front_stereo_camera_right/1771445440586997052.jpeg b/third-party/video_to_data/reconstruction/modules/v2d_hoi_object_reconstruction/assets/basketball_example/front_stereo_camera_right/1771445440586997052.jpeg new file mode 100644 index 0000000000000000000000000000000000000000..117eb3623712051629d6b3d1e54d9ea5a25368f4 --- /dev/null +++ b/third-party/video_to_data/reconstruction/modules/v2d_hoi_object_reconstruction/assets/basketball_example/front_stereo_camera_right/1771445440586997052.jpeg @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:8824d58959c4de774dd99c7e9bd2571da3588ddb0bd9f111362c6b1c026d25f2 +size 95338 diff --git a/third-party/video_to_data/reconstruction/modules/v2d_hoi_object_reconstruction/assets/basketball_example/front_stereo_camera_right/1771445440920315080.jpeg b/third-party/video_to_data/reconstruction/modules/v2d_hoi_object_reconstruction/assets/basketball_example/front_stereo_camera_right/1771445440920315080.jpeg new file mode 100644 index 0000000000000000000000000000000000000000..832fdcdcf33afd18e8feed1cf8dc3f113ddde3e8 --- /dev/null +++ b/third-party/video_to_data/reconstruction/modules/v2d_hoi_object_reconstruction/assets/basketball_example/front_stereo_camera_right/1771445440920315080.jpeg @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:6fb634e44f3872a08b4bccdde89a4fed8c25baa82218b43c9f129e271240177d +size 95004 diff --git a/third-party/video_to_data/reconstruction/modules/v2d_hoi_object_reconstruction/assets/basketball_example/front_stereo_camera_right/1771445441253635080.jpeg b/third-party/video_to_data/reconstruction/modules/v2d_hoi_object_reconstruction/assets/basketball_example/front_stereo_camera_right/1771445441253635080.jpeg new file mode 100644 index 0000000000000000000000000000000000000000..e0f302bc715b34b33f77cee2ad0fe2bf06e5eb80 --- /dev/null +++ b/third-party/video_to_data/reconstruction/modules/v2d_hoi_object_reconstruction/assets/basketball_example/front_stereo_camera_right/1771445441253635080.jpeg @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:ddd1aac7fed727d8c8e8a6a851ea4bf253651919993869e274883c2cc1ec1fd2 +size 98168 diff --git a/third-party/video_to_data/reconstruction/modules/v2d_hoi_object_reconstruction/assets/basketball_example/front_stereo_camera_right/1771445441586956080.jpeg b/third-party/video_to_data/reconstruction/modules/v2d_hoi_object_reconstruction/assets/basketball_example/front_stereo_camera_right/1771445441586956080.jpeg new file mode 100644 index 0000000000000000000000000000000000000000..64bff6ee6a6a0b549bfa05035753e236adff7cf8 --- /dev/null +++ b/third-party/video_to_data/reconstruction/modules/v2d_hoi_object_reconstruction/assets/basketball_example/front_stereo_camera_right/1771445441586956080.jpeg @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:b82e7d4a9575057f04f0f1f55a32a72ed6934f26f6611bacddc4b5bcdb717965 +size 93009 diff --git a/third-party/video_to_data/reconstruction/modules/v2d_hoi_object_reconstruction/assets/basketball_example/front_stereo_camera_right/1771445441920277064.jpeg b/third-party/video_to_data/reconstruction/modules/v2d_hoi_object_reconstruction/assets/basketball_example/front_stereo_camera_right/1771445441920277064.jpeg new file mode 100644 index 0000000000000000000000000000000000000000..360c6fdaed83fb14b988f8ce5fa4b9103188a3e0 --- /dev/null +++ b/third-party/video_to_data/reconstruction/modules/v2d_hoi_object_reconstruction/assets/basketball_example/front_stereo_camera_right/1771445441920277064.jpeg @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:545f267d47855da9c93e795aeed288ff8d812b5e94b97264ff4c28032e394e6c +size 98841