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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env python3
|
| 2 |
+
"""Extract TransPhy3D sequences and import them into FiftyOne.
|
| 3 |
+
|
| 4 |
+
Pipeline
|
| 5 |
+
--------
|
| 6 |
+
1. Read WebDataset tar files from the TransPhy3D test split.
|
| 7 |
+
2. Extract per-frame assets to ``data/processed/{sequence_id}/``.
|
| 8 |
+
3. Assemble RGB frames into ``rgb.mp4`` with ffmpeg.
|
| 9 |
+
4. Create FiftyOne video samples with frame-level annotations.
|
| 10 |
+
|
| 11 |
+
Processed layout per sequence::
|
| 12 |
+
|
| 13 |
+
rgb.mp4
|
| 14 |
+
depth/{frame_id:08d}.png
|
| 15 |
+
normal/{frame_id:08d}.png
|
| 16 |
+
depth_json/{frame_id:08d}.json
|
| 17 |
+
metadata/{frame_id:08d}.json
|
| 18 |
+
|
| 19 |
+
FiftyOne stores depth and normals as :class:`fiftyone.core.labels.Heatmap`
|
| 20 |
+
fields that reference PNG files on disk via absolute ``map_path`` values.
|
| 21 |
+
|
| 22 |
+
Typical usage::
|
| 23 |
+
|
| 24 |
+
conda activate fiftyone
|
| 25 |
+
python import_transphy3d.py --overwrite
|
| 26 |
+
|
| 27 |
+
For grouped video + 3D reconstruction import, run :mod:`reconstruct_scenes`
|
| 28 |
+
after this script has produced processed assets.
|
| 29 |
+
|
| 30 |
+
Depth decoding (also used by reconstruction)::
|
| 31 |
+
|
| 32 |
+
depth_metric = png_uint16 / 65535 * max_depth
|
| 33 |
+
"""
|
| 34 |
+
|
| 35 |
+
from __future__ import annotations
|
| 36 |
+
|
| 37 |
+
import argparse
|
| 38 |
+
import json
|
| 39 |
+
import re
|
| 40 |
+
import shutil
|
| 41 |
+
import subprocess
|
| 42 |
+
import tarfile
|
| 43 |
+
from collections import defaultdict
|
| 44 |
+
from pathlib import Path
|
| 45 |
+
|
| 46 |
+
import fiftyone as fo
|
| 47 |
+
from tqdm import tqdm
|
| 48 |
+
|
| 49 |
+
MEMBER_RE = re.compile(
|
| 50 |
+
r"^(.+?)_(\d+)\.(depth\.json|depth\.png|image\.png|metadata\.json|normal\.png)$"
|
| 51 |
+
)
|
| 52 |
+
|
| 53 |
+
|
| 54 |
+
def parse_member(name: str) -> tuple[str, int, str] | None:
|
| 55 |
+
"""Parse a tar member name into ``(sequence_id, frame_id, extension)``."""
|
| 56 |
+
match = MEMBER_RE.match(name)
|
| 57 |
+
if not match:
|
| 58 |
+
return None
|
| 59 |
+
prefix, frame_id, ext = match.groups()
|
| 60 |
+
return prefix, int(frame_id), ext
|
| 61 |
+
|
| 62 |
+
|
| 63 |
+
def scene_type(sequence_id: str) -> str:
|
| 64 |
+
"""Map a sequence id to a coarse scene category label."""
|
| 65 |
+
if "table_with_robot" in sequence_id:
|
| 66 |
+
return "table_with_robot"
|
| 67 |
+
return "materials"
|
| 68 |
+
|
| 69 |
+
|
| 70 |
+
def sequence_id_from_tar(tar_path: Path) -> str:
|
| 71 |
+
"""Infer the sequence id prefix from the first valid tar member name."""
|
| 72 |
+
with tarfile.open(tar_path) as tf:
|
| 73 |
+
for name in tf.getnames():
|
| 74 |
+
parsed = parse_member(name)
|
| 75 |
+
if parsed is not None:
|
| 76 |
+
return parsed[0]
|
| 77 |
+
raise ValueError(f"Could not determine sequence id for {tar_path}")
|
| 78 |
+
|
| 79 |
+
|
| 80 |
+
def tar_sequence_map(tar_dir: Path) -> dict[str, Path]:
|
| 81 |
+
"""Map sequence ids to their source tar paths."""
|
| 82 |
+
mapping: dict[str, Path] = {}
|
| 83 |
+
for tar_path in sorted(tar_dir.glob("*.tar")):
|
| 84 |
+
mapping[sequence_id_from_tar(tar_path)] = tar_path
|
| 85 |
+
return mapping
|
| 86 |
+
|
| 87 |
+
|
| 88 |
+
def load_tar_frames(tar_path: Path) -> dict[int, dict[str, bytes]]:
|
| 89 |
+
"""Load all frame payloads from one WebDataset tar file."""
|
| 90 |
+
frames: dict[int, dict[str, bytes]] = defaultdict(dict)
|
| 91 |
+
with tarfile.open(tar_path) as tf:
|
| 92 |
+
for member in tf.getmembers():
|
| 93 |
+
parsed = parse_member(member.name)
|
| 94 |
+
if parsed is None:
|
| 95 |
+
continue
|
| 96 |
+
_, frame_id, ext = parsed
|
| 97 |
+
frames[frame_id][ext] = tf.extractfile(member).read()
|
| 98 |
+
return dict(frames)
|
| 99 |
+
|
| 100 |
+
|
| 101 |
+
def frame_asset_paths(seq_dir: Path, frame_id: int) -> dict[str, Path]:
|
| 102 |
+
"""Return absolute paths for one frame's extracted on-disk assets."""
|
| 103 |
+
stem = f"{frame_id:08d}"
|
| 104 |
+
return {
|
| 105 |
+
"depth": (seq_dir / "depth" / f"{stem}.png").resolve(),
|
| 106 |
+
"normal": (seq_dir / "normal" / f"{stem}.png").resolve(),
|
| 107 |
+
"depth_json": (seq_dir / "depth_json" / f"{stem}.json").resolve(),
|
| 108 |
+
"metadata_json": (seq_dir / "metadata" / f"{stem}.json").resolve(),
|
| 109 |
+
}
|
| 110 |
+
|
| 111 |
+
|
| 112 |
+
def load_frame_calibration(paths: dict[str, Path]) -> tuple[float, dict]:
|
| 113 |
+
"""Load ``max_depth`` and parsed ``metadata.json`` for one frame."""
|
| 114 |
+
depth_info = json.loads(paths["depth_json"].read_text())
|
| 115 |
+
metadata = json.loads(paths["metadata_json"].read_text())
|
| 116 |
+
return depth_info["max_depth"], metadata
|
| 117 |
+
|
| 118 |
+
|
| 119 |
+
def calibration_frame_fields(
|
| 120 |
+
frame_id: int,
|
| 121 |
+
sequence_id: str,
|
| 122 |
+
max_depth: float,
|
| 123 |
+
metadata: dict,
|
| 124 |
+
) -> dict:
|
| 125 |
+
"""Build parsed calibration fields for one video frame."""
|
| 126 |
+
cameras = metadata["camera_matrices"]
|
| 127 |
+
return {
|
| 128 |
+
"frame_id": metadata.get("frame_id", frame_id),
|
| 129 |
+
"sequence_id": metadata.get("sequence_id", sequence_id),
|
| 130 |
+
"max_depth": max_depth,
|
| 131 |
+
"camera_extrinsics": cameras["extrinsics"],
|
| 132 |
+
"camera_intrinsics": cameras["intrinsics"],
|
| 133 |
+
}
|
| 134 |
+
|
| 135 |
+
|
| 136 |
+
def frame_field_update(
|
| 137 |
+
frame_id: int,
|
| 138 |
+
sequence_id: str,
|
| 139 |
+
paths: dict[str, Path],
|
| 140 |
+
max_depth: float,
|
| 141 |
+
metadata: dict,
|
| 142 |
+
) -> dict:
|
| 143 |
+
"""Build the full FiftyOne frame-field payload for one video frame."""
|
| 144 |
+
return {
|
| 145 |
+
**calibration_frame_fields(frame_id, sequence_id, max_depth, metadata),
|
| 146 |
+
"depth_map": fo.Heatmap(map_path=str(paths["depth"]), range=[0, 65535]),
|
| 147 |
+
"normal_map": fo.Heatmap(map_path=str(paths["normal"])),
|
| 148 |
+
}
|
| 149 |
+
|
| 150 |
+
|
| 151 |
+
def sorted_frame_ids(seq_dir: Path) -> list[int]:
|
| 152 |
+
"""Return sorted frame ids inferred from extracted depth PNG filenames."""
|
| 153 |
+
return sorted(int(path.stem) for path in (seq_dir / "depth").glob("*.png"))
|
| 154 |
+
|
| 155 |
+
|
| 156 |
+
def write_rgb_video(frames: dict[int, dict[str, bytes]], output_path: Path, fps: int) -> None:
|
| 157 |
+
"""Assemble extracted ``image.png`` frames into an H.264 ``rgb.mp4`` file."""
|
| 158 |
+
output_path.parent.mkdir(parents=True, exist_ok=True)
|
| 159 |
+
frame_ids = sorted(frames)
|
| 160 |
+
temp_dir = output_path.parent / "_rgb_frames_tmp"
|
| 161 |
+
if temp_dir.exists():
|
| 162 |
+
shutil.rmtree(temp_dir)
|
| 163 |
+
temp_dir.mkdir(parents=True, exist_ok=True)
|
| 164 |
+
|
| 165 |
+
try:
|
| 166 |
+
for idx, frame_id in enumerate(frame_ids):
|
| 167 |
+
(temp_dir / f"frame_{idx:06d}.png").write_bytes(frames[frame_id]["image.png"])
|
| 168 |
+
|
| 169 |
+
subprocess.run(
|
| 170 |
+
[
|
| 171 |
+
"ffmpeg",
|
| 172 |
+
"-y",
|
| 173 |
+
"-hide_banner",
|
| 174 |
+
"-loglevel",
|
| 175 |
+
"error",
|
| 176 |
+
"-framerate",
|
| 177 |
+
str(fps),
|
| 178 |
+
"-i",
|
| 179 |
+
str(temp_dir / "frame_%06d.png"),
|
| 180 |
+
"-c:v",
|
| 181 |
+
"libx264",
|
| 182 |
+
"-pix_fmt",
|
| 183 |
+
"yuv420p",
|
| 184 |
+
str(output_path),
|
| 185 |
+
],
|
| 186 |
+
check=True,
|
| 187 |
+
)
|
| 188 |
+
finally:
|
| 189 |
+
shutil.rmtree(temp_dir, ignore_errors=True)
|
| 190 |
+
|
| 191 |
+
|
| 192 |
+
def write_frame_assets(
|
| 193 |
+
frames: dict[int, dict[str, bytes]],
|
| 194 |
+
seq_dir: Path,
|
| 195 |
+
*,
|
| 196 |
+
write_png: bool = True,
|
| 197 |
+
write_json: bool = True,
|
| 198 |
+
) -> None:
|
| 199 |
+
"""Write selected per-frame assets for one sequence to disk."""
|
| 200 |
+
subdirs = []
|
| 201 |
+
if write_png:
|
| 202 |
+
subdirs.extend(("depth", "normal"))
|
| 203 |
+
if write_json:
|
| 204 |
+
subdirs.extend(("depth_json", "metadata"))
|
| 205 |
+
for name in subdirs:
|
| 206 |
+
(seq_dir / name).mkdir(parents=True, exist_ok=True)
|
| 207 |
+
|
| 208 |
+
for frame_id in sorted(frames):
|
| 209 |
+
frame = frames[frame_id]
|
| 210 |
+
paths = frame_asset_paths(seq_dir, frame_id)
|
| 211 |
+
if write_png:
|
| 212 |
+
paths["depth"].write_bytes(frame["depth.png"])
|
| 213 |
+
paths["normal"].write_bytes(frame["normal.png"])
|
| 214 |
+
if write_json:
|
| 215 |
+
paths["depth_json"].write_bytes(frame["depth.json"])
|
| 216 |
+
paths["metadata_json"].write_bytes(frame["metadata.json"])
|
| 217 |
+
|
| 218 |
+
|
| 219 |
+
def build_video_sample_from_disk(
|
| 220 |
+
sequence_id: str,
|
| 221 |
+
processed_root: Path,
|
| 222 |
+
source_tar: str,
|
| 223 |
+
) -> fo.Sample:
|
| 224 |
+
"""Build a FiftyOne video sample from already extracted processed assets."""
|
| 225 |
+
seq_dir = processed_root / sequence_id
|
| 226 |
+
video_path = (seq_dir / "rgb.mp4").resolve()
|
| 227 |
+
if not video_path.exists():
|
| 228 |
+
raise FileNotFoundError(f"Missing RGB video for sequence {sequence_id}: {video_path}")
|
| 229 |
+
|
| 230 |
+
frame_ids = sorted_frame_ids(seq_dir)
|
| 231 |
+
if not frame_ids:
|
| 232 |
+
raise ValueError(f"No extracted depth frames found for sequence {sequence_id}")
|
| 233 |
+
|
| 234 |
+
sample = fo.Sample(filepath=str(video_path))
|
| 235 |
+
sample["sequence_id"] = sequence_id
|
| 236 |
+
sample["source_tar"] = source_tar
|
| 237 |
+
sample["frame_count"] = len(frame_ids)
|
| 238 |
+
sample["scene_type"] = scene_type(sequence_id)
|
| 239 |
+
sample["tags"] = ["test"]
|
| 240 |
+
|
| 241 |
+
for frame_idx, frame_id in enumerate(frame_ids, start=1):
|
| 242 |
+
paths = frame_asset_paths(seq_dir, frame_id)
|
| 243 |
+
max_depth, metadata = load_frame_calibration(paths)
|
| 244 |
+
sample.frames[frame_idx] = fo.Frame(
|
| 245 |
+
**frame_field_update(frame_id, sequence_id, paths, max_depth, metadata)
|
| 246 |
+
)
|
| 247 |
+
|
| 248 |
+
return sample
|
| 249 |
+
|
| 250 |
+
|
| 251 |
+
def build_video_sample(
|
| 252 |
+
sequence_id: str,
|
| 253 |
+
tar_path: Path,
|
| 254 |
+
processed_root: Path,
|
| 255 |
+
fps: int,
|
| 256 |
+
) -> fo.Sample:
|
| 257 |
+
"""Extract one tar, write processed assets, and build a FiftyOne video sample."""
|
| 258 |
+
frames = load_tar_frames(tar_path)
|
| 259 |
+
if not frames:
|
| 260 |
+
raise ValueError(f"No frames found in {tar_path}")
|
| 261 |
+
|
| 262 |
+
seq_dir = processed_root / sequence_id
|
| 263 |
+
write_frame_assets(frames, seq_dir)
|
| 264 |
+
write_rgb_video(frames, seq_dir / "rgb.mp4", fps=fps)
|
| 265 |
+
return build_video_sample_from_disk(sequence_id, processed_root, tar_path.name)
|
| 266 |
+
|
| 267 |
+
|
| 268 |
+
def backfill_json_files(tar_dir: Path, processed_root: Path) -> None:
|
| 269 |
+
"""Write ``depth_json/`` and ``metadata/`` files for every tar in ``tar_dir``."""
|
| 270 |
+
for sequence_id, tar_path in tqdm(tar_sequence_map(tar_dir).items(), desc="Writing JSON files"):
|
| 271 |
+
write_frame_assets(
|
| 272 |
+
load_tar_frames(tar_path),
|
| 273 |
+
processed_root / sequence_id,
|
| 274 |
+
write_png=False,
|
| 275 |
+
)
|
| 276 |
+
|
| 277 |
+
|
| 278 |
+
def refresh_calibration_fields(
|
| 279 |
+
tar_dir: Path,
|
| 280 |
+
processed_root: Path,
|
| 281 |
+
dataset_name: str,
|
| 282 |
+
) -> fo.Dataset:
|
| 283 |
+
"""Refresh on-disk JSON files and update parsed calibration frame fields."""
|
| 284 |
+
backfill_json_files(tar_dir, processed_root)
|
| 285 |
+
|
| 286 |
+
dataset = fo.load_dataset(dataset_name)
|
| 287 |
+
for sample in tqdm(dataset, desc="Updating calibration fields"):
|
| 288 |
+
seq_dir = processed_root / sample["sequence_id"]
|
| 289 |
+
frame_updates = {}
|
| 290 |
+
for frame_idx, frame_id in enumerate(sorted_frame_ids(seq_dir), start=1):
|
| 291 |
+
paths = frame_asset_paths(seq_dir, frame_id)
|
| 292 |
+
max_depth, metadata = load_frame_calibration(paths)
|
| 293 |
+
frame_updates[frame_idx] = calibration_frame_fields(
|
| 294 |
+
frame_id,
|
| 295 |
+
sample["sequence_id"],
|
| 296 |
+
max_depth,
|
| 297 |
+
metadata,
|
| 298 |
+
)
|
| 299 |
+
|
| 300 |
+
sample.frames.update(frame_updates)
|
| 301 |
+
sample.save()
|
| 302 |
+
|
| 303 |
+
return dataset
|
| 304 |
+
|
| 305 |
+
|
| 306 |
+
def import_dataset(
|
| 307 |
+
tar_dir: Path,
|
| 308 |
+
processed_root: Path,
|
| 309 |
+
dataset_name: str,
|
| 310 |
+
fps: int,
|
| 311 |
+
overwrite: bool,
|
| 312 |
+
) -> fo.Dataset:
|
| 313 |
+
"""Extract all tars and create a persistent FiftyOne video dataset."""
|
| 314 |
+
tar_map = tar_sequence_map(tar_dir)
|
| 315 |
+
if not tar_map:
|
| 316 |
+
raise FileNotFoundError(f"No tar files found in {tar_dir}")
|
| 317 |
+
|
| 318 |
+
if dataset_name in fo.list_datasets():
|
| 319 |
+
if not overwrite:
|
| 320 |
+
raise ValueError(
|
| 321 |
+
f"Dataset '{dataset_name}' already exists. Pass --overwrite to replace it."
|
| 322 |
+
)
|
| 323 |
+
fo.delete_dataset(dataset_name)
|
| 324 |
+
|
| 325 |
+
dataset = fo.Dataset(dataset_name)
|
| 326 |
+
dataset.persistent = True
|
| 327 |
+
|
| 328 |
+
samples = [
|
| 329 |
+
build_video_sample(sequence_id, tar_path, processed_root, fps)
|
| 330 |
+
for sequence_id, tar_path in tqdm(tar_map.items(), desc="Processing sequences")
|
| 331 |
+
]
|
| 332 |
+
dataset.add_samples(samples)
|
| 333 |
+
dataset.compute_metadata()
|
| 334 |
+
return dataset
|
| 335 |
+
|
| 336 |
+
|
| 337 |
+
def print_dataset_summary(dataset: fo.Dataset) -> None:
|
| 338 |
+
"""Print a short import summary for the created or updated dataset."""
|
| 339 |
+
frame_counts = dataset.values("frame_count")
|
| 340 |
+
preview = frame_counts[:3] if frame_counts else []
|
| 341 |
+
print(f"Dataset: {dataset.name}")
|
| 342 |
+
print(f"Samples: {len(dataset)}")
|
| 343 |
+
print(f"Media type: {dataset.media_type}")
|
| 344 |
+
print(f"Frames per sample (first 3): {preview}")
|
| 345 |
+
print(f"Total frame documents: {dataset.count('frames')}")
|
| 346 |
+
print(f"Sample fields: {list(dataset.get_field_schema().keys())}")
|
| 347 |
+
print(f"Frame fields: {list(dataset.get_frame_field_schema().keys())}")
|
| 348 |
+
|
| 349 |
+
|
| 350 |
+
def main() -> None:
|
| 351 |
+
parser = argparse.ArgumentParser(description=__doc__)
|
| 352 |
+
parser.add_argument(
|
| 353 |
+
"--tar-dir",
|
| 354 |
+
type=Path,
|
| 355 |
+
default=Path("data/tars/test"),
|
| 356 |
+
help="Directory containing downloaded WebDataset tar files",
|
| 357 |
+
)
|
| 358 |
+
parser.add_argument(
|
| 359 |
+
"--processed-root",
|
| 360 |
+
type=Path,
|
| 361 |
+
default=Path("data/processed"),
|
| 362 |
+
help="Directory where extracted PNG/JSON assets and rgb.mp4 files are written",
|
| 363 |
+
)
|
| 364 |
+
parser.add_argument(
|
| 365 |
+
"--dataset-name",
|
| 366 |
+
default="TransPhy3D",
|
| 367 |
+
help="Name of the FiftyOne dataset to create or update",
|
| 368 |
+
)
|
| 369 |
+
parser.add_argument(
|
| 370 |
+
"--fps",
|
| 371 |
+
type=int,
|
| 372 |
+
default=30,
|
| 373 |
+
help="FPS used when assembling rgb.mp4 from extracted PNG frames",
|
| 374 |
+
)
|
| 375 |
+
parser.add_argument(
|
| 376 |
+
"--overwrite",
|
| 377 |
+
action="store_true",
|
| 378 |
+
help="Replace an existing FiftyOne dataset with the same name",
|
| 379 |
+
)
|
| 380 |
+
parser.add_argument(
|
| 381 |
+
"--update-json-only",
|
| 382 |
+
action="store_true",
|
| 383 |
+
help="Refresh on-disk JSON files and update calibration frame fields",
|
| 384 |
+
)
|
| 385 |
+
parser.add_argument(
|
| 386 |
+
"--extract-json-only",
|
| 387 |
+
action="store_true",
|
| 388 |
+
help="Write depth_json/ and metadata/ files to disk only",
|
| 389 |
+
)
|
| 390 |
+
args = parser.parse_args()
|
| 391 |
+
|
| 392 |
+
if args.extract_json_only and args.update_json_only:
|
| 393 |
+
parser.error("Choose only one of --extract-json-only or --update-json-only")
|
| 394 |
+
|
| 395 |
+
if args.extract_json_only:
|
| 396 |
+
backfill_json_files(args.tar_dir, args.processed_root)
|
| 397 |
+
print(f"Wrote JSON files under {args.processed_root}")
|
| 398 |
+
return
|
| 399 |
+
|
| 400 |
+
if args.update_json_only:
|
| 401 |
+
dataset = refresh_calibration_fields(args.tar_dir, args.processed_root, args.dataset_name)
|
| 402 |
+
else:
|
| 403 |
+
dataset = import_dataset(
|
| 404 |
+
args.tar_dir,
|
| 405 |
+
args.processed_root,
|
| 406 |
+
args.dataset_name,
|
| 407 |
+
args.fps,
|
| 408 |
+
args.overwrite,
|
| 409 |
+
)
|
| 410 |
+
|
| 411 |
+
print_dataset_summary(dataset)
|
| 412 |
+
|
| 413 |
+
|
| 414 |
+
if __name__ == "__main__":
|
| 415 |
+
main()
|
reconstruct_scenes.py
ADDED
|
@@ -0,0 +1,436 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env python3
|
| 2 |
+
"""Build merged RGB point clouds and grouped FiftyOne scenes for TransPhy3D.
|
| 3 |
+
|
| 4 |
+
Pipeline
|
| 5 |
+
--------
|
| 6 |
+
1. Read per-frame depth PNGs, ``depth.json``, and ``metadata.json`` from disk.
|
| 7 |
+
2. Match each depth frame to the corresponding RGB frame in ``rgb.mp4``.
|
| 8 |
+
3. Back-project depth pixels into a shared world coordinate system.
|
| 9 |
+
4. Color each 3D point from the RGB image.
|
| 10 |
+
5. Merge all frames into one point cloud per sequence.
|
| 11 |
+
6. Export ``scene.pcd`` and a FiftyOne ``scene.fo3d`` scene file.
|
| 12 |
+
|
| 13 |
+
Optionally builds a grouped FiftyOne dataset with two linked slices per
|
| 14 |
+
sequence: ``video`` (RGB video + frame annotations) and ``reconstruction``
|
| 15 |
+
(merged point cloud in ``scene.fo3d``).
|
| 16 |
+
|
| 17 |
+
Run with the ``fiftyone`` conda environment::
|
| 18 |
+
|
| 19 |
+
conda activate fiftyone
|
| 20 |
+
python reconstruct_scenes.py --build-dataset --overwrite
|
| 21 |
+
|
| 22 |
+
Math reference
|
| 23 |
+
--------------
|
| 24 |
+
Depth decoding::
|
| 25 |
+
|
| 26 |
+
Z = png_value / 65535 * max_depth
|
| 27 |
+
|
| 28 |
+
Pinhole back-projection::
|
| 29 |
+
|
| 30 |
+
X = (u - cx) * Z / fx
|
| 31 |
+
Y = (v - cy) * Z / fy
|
| 32 |
+
|
| 33 |
+
World coordinates::
|
| 34 |
+
|
| 35 |
+
[Xw, Yw, Zw, 1]^T = T @ [X, Y, Z, 1]^T
|
| 36 |
+
"""
|
| 37 |
+
|
| 38 |
+
from __future__ import annotations
|
| 39 |
+
|
| 40 |
+
import argparse
|
| 41 |
+
import json
|
| 42 |
+
from pathlib import Path
|
| 43 |
+
|
| 44 |
+
import cv2
|
| 45 |
+
import fiftyone as fo
|
| 46 |
+
import numpy as np
|
| 47 |
+
import open3d as o3d
|
| 48 |
+
from PIL import Image
|
| 49 |
+
from tqdm import tqdm
|
| 50 |
+
|
| 51 |
+
from import_transphy3d import (
|
| 52 |
+
build_video_sample_from_disk,
|
| 53 |
+
scene_type,
|
| 54 |
+
sorted_frame_ids,
|
| 55 |
+
tar_sequence_map,
|
| 56 |
+
)
|
| 57 |
+
|
| 58 |
+
|
| 59 |
+
def pixel_intrinsics(k_norm: list[list[float]], width: int, height: int) -> np.ndarray:
|
| 60 |
+
"""Convert normalized camera intrinsics to a pixel-space ``K`` matrix."""
|
| 61 |
+
k = np.eye(3, dtype=np.float64)
|
| 62 |
+
k[0, 0] = k_norm[0][0] * width
|
| 63 |
+
k[1, 1] = k_norm[1][1] * height
|
| 64 |
+
k[0, 2] = k_norm[0][2] * width
|
| 65 |
+
k[1, 2] = k_norm[1][2] * height
|
| 66 |
+
return k
|
| 67 |
+
|
| 68 |
+
|
| 69 |
+
def decode_depth(depth_path: Path, max_depth: float) -> np.ndarray:
|
| 70 |
+
"""Decode a 16-bit depth PNG into metric depth values."""
|
| 71 |
+
depth_u16 = np.array(Image.open(depth_path), dtype=np.uint16)
|
| 72 |
+
return depth_u16.astype(np.float64) / 65535.0 * max_depth
|
| 73 |
+
|
| 74 |
+
|
| 75 |
+
def load_frame_calibration(seq_dir: Path, frame_id: int) -> tuple[float, np.ndarray, np.ndarray]:
|
| 76 |
+
"""Load metric depth scale and camera matrices for one frame."""
|
| 77 |
+
stem = f"{frame_id:08d}"
|
| 78 |
+
max_depth = json.loads((seq_dir / "depth_json" / f"{stem}.json").read_text())["max_depth"]
|
| 79 |
+
cameras = json.loads((seq_dir / "metadata" / f"{stem}.json").read_text())["camera_matrices"]
|
| 80 |
+
extrinsics = np.array(cameras["extrinsics"], dtype=np.float64)
|
| 81 |
+
intrinsics = np.array(cameras["intrinsics"], dtype=np.float64)
|
| 82 |
+
return max_depth, extrinsics, intrinsics
|
| 83 |
+
|
| 84 |
+
|
| 85 |
+
def subsample_valid_depth(
|
| 86 |
+
depth: np.ndarray,
|
| 87 |
+
stride: int,
|
| 88 |
+
) -> tuple[np.ndarray, np.ndarray, np.ndarray]:
|
| 89 |
+
"""Return subsampled pixel coordinates and depth values with valid measurements."""
|
| 90 |
+
v_coords, u_coords = np.mgrid[0 : depth.shape[0] : stride, 0 : depth.shape[1] : stride]
|
| 91 |
+
depths = depth[v_coords, u_coords]
|
| 92 |
+
valid = np.isfinite(depths) & (depths > 0)
|
| 93 |
+
return u_coords, v_coords, depths, valid
|
| 94 |
+
|
| 95 |
+
|
| 96 |
+
def camera_to_world(
|
| 97 |
+
u: np.ndarray,
|
| 98 |
+
v: np.ndarray,
|
| 99 |
+
depth: np.ndarray,
|
| 100 |
+
k: np.ndarray,
|
| 101 |
+
extrinsics: np.ndarray,
|
| 102 |
+
*,
|
| 103 |
+
z_sign: float,
|
| 104 |
+
use_inverse: bool,
|
| 105 |
+
) -> np.ndarray:
|
| 106 |
+
"""Back-project pixel coordinates into world-space 3D points."""
|
| 107 |
+
x = (u - k[0, 2]) * depth / k[0, 0]
|
| 108 |
+
y = (v - k[1, 2]) * depth / k[1, 1]
|
| 109 |
+
z = z_sign * depth
|
| 110 |
+
pts_cam = np.stack([x, y, z, np.ones_like(z)], axis=1)
|
| 111 |
+
transform = np.linalg.inv(extrinsics) if use_inverse else extrinsics
|
| 112 |
+
return (transform @ pts_cam.T).T[:, :3]
|
| 113 |
+
|
| 114 |
+
|
| 115 |
+
def backproject_pixels(
|
| 116 |
+
depth: np.ndarray,
|
| 117 |
+
rgb: np.ndarray,
|
| 118 |
+
k: np.ndarray,
|
| 119 |
+
extrinsics: np.ndarray,
|
| 120 |
+
*,
|
| 121 |
+
stride: int,
|
| 122 |
+
z_sign: float,
|
| 123 |
+
use_inverse: bool,
|
| 124 |
+
) -> tuple[np.ndarray, np.ndarray]:
|
| 125 |
+
"""Back-project a depth/RGB frame pair into colored world points."""
|
| 126 |
+
u_coords, v_coords, depths, valid = subsample_valid_depth(depth, stride)
|
| 127 |
+
if not np.any(valid):
|
| 128 |
+
return np.empty((0, 3)), np.empty((0, 3))
|
| 129 |
+
|
| 130 |
+
u = u_coords[valid].astype(np.float64)
|
| 131 |
+
v = v_coords[valid].astype(np.float64)
|
| 132 |
+
d = depths[valid]
|
| 133 |
+
points = camera_to_world(u, v, d, k, extrinsics, z_sign=z_sign, use_inverse=use_inverse)
|
| 134 |
+
colors = rgb[v_coords[valid], u_coords[valid]].astype(np.float64) / 255.0
|
| 135 |
+
return points, colors
|
| 136 |
+
|
| 137 |
+
|
| 138 |
+
def reprojection_error(
|
| 139 |
+
points_world: np.ndarray,
|
| 140 |
+
u_orig: np.ndarray,
|
| 141 |
+
v_orig: np.ndarray,
|
| 142 |
+
k: np.ndarray,
|
| 143 |
+
extrinsics: np.ndarray,
|
| 144 |
+
*,
|
| 145 |
+
z_sign: float,
|
| 146 |
+
use_inverse: bool,
|
| 147 |
+
) -> float:
|
| 148 |
+
"""Mean pixel reprojection error for a candidate camera convention."""
|
| 149 |
+
transform = extrinsics if use_inverse else np.linalg.inv(extrinsics)
|
| 150 |
+
pts_cam = (transform @ np.hstack([points_world, np.ones((len(points_world), 1))]).T).T[:, :3]
|
| 151 |
+
valid = pts_cam[:, 2] > 1e-6
|
| 152 |
+
if not np.any(valid):
|
| 153 |
+
return np.inf
|
| 154 |
+
|
| 155 |
+
u_proj = k[0, 0] * pts_cam[valid, 0] / pts_cam[valid, 2] + k[0, 2]
|
| 156 |
+
v_proj = k[1, 1] * pts_cam[valid, 1] / pts_cam[valid, 2] + k[1, 2]
|
| 157 |
+
return float(np.hypot(u_proj - u_orig[valid], v_proj - v_orig[valid]).mean())
|
| 158 |
+
|
| 159 |
+
|
| 160 |
+
def choose_backprojection_convention(
|
| 161 |
+
depth: np.ndarray,
|
| 162 |
+
k: np.ndarray,
|
| 163 |
+
extrinsics: np.ndarray,
|
| 164 |
+
*,
|
| 165 |
+
stride: int,
|
| 166 |
+
) -> tuple[float, bool]:
|
| 167 |
+
"""Pick the camera convention with the lowest reprojection error."""
|
| 168 |
+
u_coords, v_coords, depths, valid = subsample_valid_depth(depth, max(stride, 4))
|
| 169 |
+
u_sample = u_coords[valid][:5000].astype(np.float64)
|
| 170 |
+
v_sample = v_coords[valid][:5000].astype(np.float64)
|
| 171 |
+
d_sample = depths[valid][:5000]
|
| 172 |
+
|
| 173 |
+
best_error = np.inf
|
| 174 |
+
best_z_sign = 1.0
|
| 175 |
+
best_use_inverse = False
|
| 176 |
+
|
| 177 |
+
for z_sign in (1.0, -1.0):
|
| 178 |
+
for use_inverse in (False, True):
|
| 179 |
+
points = camera_to_world(
|
| 180 |
+
u_sample,
|
| 181 |
+
v_sample,
|
| 182 |
+
d_sample,
|
| 183 |
+
k,
|
| 184 |
+
extrinsics,
|
| 185 |
+
z_sign=z_sign,
|
| 186 |
+
use_inverse=use_inverse,
|
| 187 |
+
)
|
| 188 |
+
err = reprojection_error(
|
| 189 |
+
points,
|
| 190 |
+
u_sample,
|
| 191 |
+
v_sample,
|
| 192 |
+
k,
|
| 193 |
+
extrinsics,
|
| 194 |
+
z_sign=z_sign,
|
| 195 |
+
use_inverse=use_inverse,
|
| 196 |
+
)
|
| 197 |
+
if err < best_error:
|
| 198 |
+
best_error = err
|
| 199 |
+
best_z_sign = z_sign
|
| 200 |
+
best_use_inverse = use_inverse
|
| 201 |
+
|
| 202 |
+
return best_z_sign, best_use_inverse
|
| 203 |
+
|
| 204 |
+
|
| 205 |
+
def reconstruct_sequence(
|
| 206 |
+
seq_dir: Path,
|
| 207 |
+
*,
|
| 208 |
+
stride: int,
|
| 209 |
+
voxel_size: float,
|
| 210 |
+
max_depth_ratio: float,
|
| 211 |
+
) -> tuple[Path, Path, int]:
|
| 212 |
+
"""Reconstruct one sequence into a merged RGB-colored point cloud."""
|
| 213 |
+
frame_ids = sorted_frame_ids(seq_dir)
|
| 214 |
+
if not frame_ids:
|
| 215 |
+
raise ValueError(f"No depth frames found in {seq_dir / 'depth'}")
|
| 216 |
+
|
| 217 |
+
video_path = seq_dir / "rgb.mp4"
|
| 218 |
+
cap = cv2.VideoCapture(str(video_path))
|
| 219 |
+
if not cap.isOpened():
|
| 220 |
+
raise RuntimeError(f"Could not open video: {video_path}")
|
| 221 |
+
|
| 222 |
+
all_points: list[np.ndarray] = []
|
| 223 |
+
all_colors: list[np.ndarray] = []
|
| 224 |
+
z_sign = 1.0
|
| 225 |
+
use_inverse = False
|
| 226 |
+
k: np.ndarray | None = None
|
| 227 |
+
|
| 228 |
+
try:
|
| 229 |
+
for frame_index, frame_id in enumerate(frame_ids):
|
| 230 |
+
ok, frame_bgr = cap.read()
|
| 231 |
+
if not ok:
|
| 232 |
+
raise RuntimeError(f"Could not read frame {frame_index} from {video_path}")
|
| 233 |
+
|
| 234 |
+
rgb = cv2.cvtColor(frame_bgr, cv2.COLOR_BGR2RGB)
|
| 235 |
+
max_depth, extrinsics, intrinsics = load_frame_calibration(seq_dir, frame_id)
|
| 236 |
+
depth = decode_depth(seq_dir / "depth" / f"{frame_id:08d}.png", max_depth)
|
| 237 |
+
depth[depth > max_depth * max_depth_ratio] = 0
|
| 238 |
+
|
| 239 |
+
if k is None:
|
| 240 |
+
height, width = rgb.shape[:2]
|
| 241 |
+
k = pixel_intrinsics(intrinsics.tolist(), width, height)
|
| 242 |
+
z_sign, use_inverse = choose_backprojection_convention(
|
| 243 |
+
depth,
|
| 244 |
+
k,
|
| 245 |
+
extrinsics,
|
| 246 |
+
stride=stride,
|
| 247 |
+
)
|
| 248 |
+
|
| 249 |
+
points, colors = backproject_pixels(
|
| 250 |
+
depth,
|
| 251 |
+
rgb,
|
| 252 |
+
k,
|
| 253 |
+
extrinsics,
|
| 254 |
+
stride=stride,
|
| 255 |
+
z_sign=z_sign,
|
| 256 |
+
use_inverse=use_inverse,
|
| 257 |
+
)
|
| 258 |
+
if len(points):
|
| 259 |
+
all_points.append(points)
|
| 260 |
+
all_colors.append(colors)
|
| 261 |
+
finally:
|
| 262 |
+
cap.release()
|
| 263 |
+
|
| 264 |
+
if not all_points:
|
| 265 |
+
raise ValueError(f"No valid depth points reconstructed for {seq_dir.name}")
|
| 266 |
+
|
| 267 |
+
pcd = o3d.geometry.PointCloud()
|
| 268 |
+
pcd.points = o3d.utility.Vector3dVector(np.vstack(all_points))
|
| 269 |
+
pcd.colors = o3d.utility.Vector3dVector(np.vstack(all_colors))
|
| 270 |
+
if voxel_size > 0:
|
| 271 |
+
pcd = pcd.voxel_down_sample(voxel_size)
|
| 272 |
+
|
| 273 |
+
pcd_path = (seq_dir / "scene.pcd").resolve()
|
| 274 |
+
fo3d_path = (seq_dir / "scene.fo3d").resolve()
|
| 275 |
+
o3d.io.write_point_cloud(str(pcd_path), pcd)
|
| 276 |
+
|
| 277 |
+
scene = fo.Scene(camera=fo.PerspectiveCamera(up="Z"))
|
| 278 |
+
cloud = fo.PointCloud("reconstruction", str(pcd_path), flag_for_projection=True)
|
| 279 |
+
cloud.default_material.point_size = 2
|
| 280 |
+
scene.add(cloud)
|
| 281 |
+
scene.write(str(fo3d_path))
|
| 282 |
+
|
| 283 |
+
return pcd_path, fo3d_path, len(pcd.points)
|
| 284 |
+
|
| 285 |
+
|
| 286 |
+
def build_grouped_dataset(
|
| 287 |
+
processed_root: Path,
|
| 288 |
+
tar_dir: Path,
|
| 289 |
+
target_dataset_name: str,
|
| 290 |
+
overwrite: bool,
|
| 291 |
+
) -> fo.Dataset:
|
| 292 |
+
"""Create a grouped FiftyOne dataset with video and reconstruction slices."""
|
| 293 |
+
if target_dataset_name in fo.list_datasets():
|
| 294 |
+
if not overwrite:
|
| 295 |
+
raise ValueError(
|
| 296 |
+
f"Dataset '{target_dataset_name}' already exists. "
|
| 297 |
+
"Pass --overwrite to replace it."
|
| 298 |
+
)
|
| 299 |
+
fo.delete_dataset(target_dataset_name)
|
| 300 |
+
|
| 301 |
+
target = fo.Dataset(target_dataset_name)
|
| 302 |
+
target.persistent = True
|
| 303 |
+
target.add_group_field("group", default="video")
|
| 304 |
+
|
| 305 |
+
samples = []
|
| 306 |
+
for sequence_id, tar_path in tqdm(tar_sequence_map(tar_dir).items(), desc="Building grouped dataset"):
|
| 307 |
+
seq_dir = processed_root / sequence_id
|
| 308 |
+
fo3d_path = (seq_dir / "scene.fo3d").resolve()
|
| 309 |
+
if not fo3d_path.exists():
|
| 310 |
+
raise FileNotFoundError(f"Missing reconstruction for {sequence_id}")
|
| 311 |
+
|
| 312 |
+
group = fo.Group()
|
| 313 |
+
video = build_video_sample_from_disk(sequence_id, processed_root, tar_path.name)
|
| 314 |
+
video["group"] = group.element("video")
|
| 315 |
+
|
| 316 |
+
reconstruction = fo.Sample(
|
| 317 |
+
filepath=str(fo3d_path),
|
| 318 |
+
group=group.element("reconstruction"),
|
| 319 |
+
)
|
| 320 |
+
reconstruction["sequence_id"] = sequence_id
|
| 321 |
+
reconstruction["scene_type"] = scene_type(sequence_id)
|
| 322 |
+
reconstruction["point_cloud_path"] = str((seq_dir / "scene.pcd").resolve())
|
| 323 |
+
reconstruction["tags"] = ["test", "reconstruction"]
|
| 324 |
+
samples.extend([video, reconstruction])
|
| 325 |
+
|
| 326 |
+
target.add_samples(samples)
|
| 327 |
+
target.compute_metadata()
|
| 328 |
+
return target
|
| 329 |
+
|
| 330 |
+
|
| 331 |
+
def list_sequence_dirs(processed_root: Path, sequence: str | None) -> list[Path]:
|
| 332 |
+
"""Return sequence directories to reconstruct."""
|
| 333 |
+
if sequence:
|
| 334 |
+
seq_dir = processed_root / sequence
|
| 335 |
+
if not seq_dir.is_dir():
|
| 336 |
+
raise FileNotFoundError(f"Sequence directory not found: {seq_dir}")
|
| 337 |
+
return [seq_dir]
|
| 338 |
+
return sorted(path for path in processed_root.iterdir() if path.is_dir())
|
| 339 |
+
|
| 340 |
+
|
| 341 |
+
def print_grouped_summary(dataset: fo.Dataset) -> None:
|
| 342 |
+
"""Print a short summary after building the grouped dataset."""
|
| 343 |
+
print(f"Grouped dataset: {dataset.name}")
|
| 344 |
+
print(f"Groups: {len(dataset)}")
|
| 345 |
+
print(f"Slices: {dataset.group_slices}")
|
| 346 |
+
print(f"Media types: {dataset.group_media_types}")
|
| 347 |
+
print(f"Total frame documents: {dataset.count('frames')}")
|
| 348 |
+
|
| 349 |
+
|
| 350 |
+
def main() -> None:
|
| 351 |
+
parser = argparse.ArgumentParser(description=__doc__)
|
| 352 |
+
parser.add_argument(
|
| 353 |
+
"--processed-root",
|
| 354 |
+
type=Path,
|
| 355 |
+
default=Path("data/processed"),
|
| 356 |
+
help="Root directory containing per-sequence processed assets",
|
| 357 |
+
)
|
| 358 |
+
parser.add_argument(
|
| 359 |
+
"--tar-dir",
|
| 360 |
+
type=Path,
|
| 361 |
+
default=Path("data/tars/test"),
|
| 362 |
+
help="Directory of source WebDataset tar files",
|
| 363 |
+
)
|
| 364 |
+
parser.add_argument(
|
| 365 |
+
"--sequence",
|
| 366 |
+
default=None,
|
| 367 |
+
help="Reconstruct a single sequence id instead of all sequences",
|
| 368 |
+
)
|
| 369 |
+
parser.add_argument(
|
| 370 |
+
"--stride",
|
| 371 |
+
type=int,
|
| 372 |
+
default=4,
|
| 373 |
+
help="Pixel subsampling stride during back-projection",
|
| 374 |
+
)
|
| 375 |
+
parser.add_argument(
|
| 376 |
+
"--voxel-size",
|
| 377 |
+
type=float,
|
| 378 |
+
default=0.01,
|
| 379 |
+
help="Open3D voxel size for downsampling; 0 disables downsampling",
|
| 380 |
+
)
|
| 381 |
+
parser.add_argument(
|
| 382 |
+
"--max-depth-ratio",
|
| 383 |
+
type=float,
|
| 384 |
+
default=0.999,
|
| 385 |
+
help="Zero depths above max_depth * ratio to remove far-plane saturation",
|
| 386 |
+
)
|
| 387 |
+
parser.add_argument(
|
| 388 |
+
"--build-dataset",
|
| 389 |
+
action="store_true",
|
| 390 |
+
help="After reconstruction, build the grouped FiftyOne dataset",
|
| 391 |
+
)
|
| 392 |
+
parser.add_argument(
|
| 393 |
+
"--build-dataset-only",
|
| 394 |
+
action="store_true",
|
| 395 |
+
help="Skip reconstruction and only build the grouped FiftyOne dataset",
|
| 396 |
+
)
|
| 397 |
+
parser.add_argument(
|
| 398 |
+
"--target-dataset",
|
| 399 |
+
default="TransPhy3D",
|
| 400 |
+
help="Name of the grouped FiftyOne dataset to create",
|
| 401 |
+
)
|
| 402 |
+
parser.add_argument(
|
| 403 |
+
"--overwrite",
|
| 404 |
+
action="store_true",
|
| 405 |
+
help="Replace an existing FiftyOne dataset with the same name",
|
| 406 |
+
)
|
| 407 |
+
args = parser.parse_args()
|
| 408 |
+
|
| 409 |
+
if args.build_dataset and args.build_dataset_only:
|
| 410 |
+
parser.error("Choose only one of --build-dataset or --build-dataset-only")
|
| 411 |
+
|
| 412 |
+
if not args.build_dataset_only:
|
| 413 |
+
for seq_dir in tqdm(
|
| 414 |
+
list_sequence_dirs(args.processed_root, args.sequence),
|
| 415 |
+
desc="Reconstructing sequences",
|
| 416 |
+
):
|
| 417 |
+
_, fo3d_path, n_points = reconstruct_sequence(
|
| 418 |
+
seq_dir,
|
| 419 |
+
stride=args.stride,
|
| 420 |
+
voxel_size=args.voxel_size,
|
| 421 |
+
max_depth_ratio=args.max_depth_ratio,
|
| 422 |
+
)
|
| 423 |
+
print(f"{seq_dir.name}: {n_points:,} points -> {fo3d_path.name}")
|
| 424 |
+
|
| 425 |
+
if args.build_dataset or args.build_dataset_only:
|
| 426 |
+
dataset = build_grouped_dataset(
|
| 427 |
+
args.processed_root,
|
| 428 |
+
args.tar_dir,
|
| 429 |
+
args.target_dataset,
|
| 430 |
+
args.overwrite,
|
| 431 |
+
)
|
| 432 |
+
print_grouped_summary(dataset)
|
| 433 |
+
|
| 434 |
+
|
| 435 |
+
if __name__ == "__main__":
|
| 436 |
+
main()
|