File size: 4,595 Bytes
9c890d3 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 | """Prepare videos, arrays, or calibrated NPZ inputs for SCALE4D inference."""
from __future__ import annotations
import json
from pathlib import Path
import cv2
import numpy as np
import torch
from evaluation.ucpe_inputs import ClipInput
def array_clip(
rgbs: np.ndarray | torch.Tensor,
*,
query_uv: np.ndarray | torch.Tensor | None = None,
query_times: np.ndarray | torch.Tensor | None = None,
cameras_to_world: np.ndarray | torch.Tensor | None = None,
intrinsics: np.ndarray | torch.Tensor | None = None,
world_up: np.ndarray | torch.Tensor | None = None,
grid_size: int = 16,
metadata: dict | None = None,
) -> ClipInput:
rgbs = torch.as_tensor(rgbs).cpu()
if rgbs.ndim == 4:
rgbs = rgbs[None]
if rgbs.ndim != 5 or min(rgbs.shape) < 1:
raise ValueError("RGB must have shape (T, 3, H, W) or (V, T, 3, H, W)")
views, frames, _, height, width = rgbs.shape
if grid_size < 1:
raise ValueError("grid_size must be positive")
if query_uv is None:
ys, xs = torch.meshgrid(
torch.linspace(0, height - 1, grid_size),
torch.linspace(0, width - 1, grid_size),
indexing="ij",
)
query_uv = torch.stack([xs, ys], dim=-1).reshape(-1, 2)
query_uv = torch.as_tensor(query_uv).float().cpu()
count = len(query_uv)
query_times = (
torch.zeros(count, dtype=torch.int64)
if query_times is None
else torch.as_tensor(query_times).cpu()
)
if cameras_to_world is None:
cameras_to_world = torch.eye(4).expand(views, frames, 4, 4).clone()
synthetic_intrinsics = intrinsics is None
if intrinsics is None:
focal = float(max(height, width))
intrinsics = (
torch.tensor(
[[focal, 0, (width - 1) / 2], [0, focal, (height - 1) / 2], [0, 0, 1]]
)
.expand(views, frames, 3, 3)
.clone()
)
info = dict(metadata or {})
info.setdefault("dataset_type", "scale4d")
info.setdefault("camera_ids", list(range(views)))
info["camera_calibration"] = "synthetic" if synthetic_intrinsics else "provided"
result = ClipInput(
rgbs=rgbs,
cameras_to_world=torch.as_tensor(cameras_to_world).cpu(),
intrinsics=torch.as_tensor(intrinsics).cpu(),
query_uv=query_uv,
query_times=query_times,
query_views=torch.zeros(count, dtype=torch.int64),
world_up=None if world_up is None else torch.as_tensor(world_up).cpu(),
metadata=info,
)
result.validate()
return result
def video_clip(path: str | Path, frames: int = 48, grid_size: int = 16) -> ClipInput:
path = Path(path).expanduser()
capture = cv2.VideoCapture(str(path))
try:
total = int(capture.get(cv2.CAP_PROP_FRAME_COUNT))
if total < 1:
raise ValueError(f"Cannot read video frames: {path}")
indices = np.linspace(0, total - 1, frames).round().astype(np.int64)
images = []
for index in indices:
capture.set(cv2.CAP_PROP_POS_FRAMES, int(index))
ok, image = capture.read()
if not ok:
raise ValueError(f"Cannot decode frame {index} of {path}")
images.append(cv2.cvtColor(image, cv2.COLOR_BGR2RGB))
finally:
capture.release()
return array_clip(
np.stack(images).transpose(0, 3, 1, 2),
grid_size=grid_size,
metadata={
"dataset_type": "video",
"source_frame_indices": indices.tolist(),
},
)
def npz_clip(path: str | Path) -> ClipInput:
with np.load(Path(path).expanduser(), allow_pickle=False) as data:
metadata = (
json.loads(str(data["metadata_json"].item()))
if "metadata_json" in data
else {}
)
values = {
name: torch.from_numpy(data[name].copy())
for name in (
"rgbs",
"cameras_to_world",
"intrinsics",
"query_uv",
"query_times",
"query_views",
)
}
metadata.setdefault("dataset_type", "scale4d")
metadata.setdefault("camera_ids", list(range(values["rgbs"].shape[0])))
metadata.setdefault("camera_calibration", "provided")
result = ClipInput(
**values,
world_up=torch.from_numpy(data["world_up"].copy())
if "world_up" in data
else None,
metadata=metadata,
)
result.validate()
return result
|