File size: 5,878 Bytes
a863b67 | 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 | """Running Flow4RT on a video or a list of frames.
Frame reading and resizing follow `load_images` / `crop_img` of DUSt3R
(https://github.com/naver/dust3r, Copyright (C) 2024-present Naver Corporation, CC BY-NC-SA 4.0).
"""
import os
from typing import Dict, List, Sequence, Union
import cv2
import numpy as np
import PIL.Image
import torch
from PIL.ImageOps import exif_transpose
from .model import Flow4RT
from .model.geometry import focal_length_from_pointmap
IMAGE_EXTENSIONS = (".jpg", ".jpeg", ".png")
VIDEO_EXTENSIONS = (".mp4", ".avi", ".mov")
Frames = Union[str, Sequence[Union[str, PIL.Image.Image]]]
# --------------------------------------------------------------------------------------
# Input
# --------------------------------------------------------------------------------------
def read_frames(inputs: Frames, max_frames: int = None, stride: int = 1, start: int = 0) -> List[PIL.Image.Image]:
"""Reads RGB frames from a video file, a directory of images, or a list of image paths /
PIL images. Frames are taken as `[start::stride][:max_frames]`."""
if isinstance(inputs, str) and inputs.lower().endswith(VIDEO_EXTENSIONS):
cap = cv2.VideoCapture(inputs)
if not cap.isOpened():
raise IOError(f"Cannot open video {inputs}")
frames = []
idx = 0
while True:
ok, frame = cap.read()
if not ok:
break
if idx >= start and (idx - start) % stride == 0:
frames.append(PIL.Image.fromarray(cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)))
if max_frames is not None and len(frames) >= max_frames:
break
idx += 1
cap.release()
return frames
if isinstance(inputs, str):
if not os.path.isdir(inputs):
raise ValueError(f"{inputs} is neither a video nor a directory")
inputs = sorted(os.path.join(inputs, f) for f in os.listdir(inputs) if f.lower().endswith(IMAGE_EXTENSIONS))
inputs = list(inputs)[start::stride][:max_frames]
return [exif_transpose(f if isinstance(f, PIL.Image.Image) else PIL.Image.open(f)).convert("RGB") for f in inputs]
def resize_frame(img: PIL.Image.Image, long_edge: int = 518, patch_size: int = Flow4RT.PATCH_SIZE,
crop: bool = False) -> PIL.Image.Image:
"""Resizes the long edge to `long_edge`, then brings both sides to multiples of `patch_size`
by resizing (default) or by a center crop."""
S = max(img.size)
interp = PIL.Image.LANCZOS if S > long_edge else PIL.Image.BICUBIC
img = img.resize(tuple(int(round(x * long_edge / S)) for x in img.size), interp)
W, H = img.size
halfw, halfh = (W // patch_size) * patch_size // 2, (H // patch_size) * patch_size // 2
if crop:
cx, cy = W // 2, H // 2
return img.crop((cx - halfw, cy - halfh, cx + halfw, cy + halfh))
return img.resize((2 * halfw, 2 * halfh), PIL.Image.LANCZOS)
def frames_to_tensor(frames: Sequence[PIL.Image.Image], long_edge: int = 518, crop: bool = False) -> torch.Tensor:
"""PIL frames -> (V, 3, H, W) tensor in [-1, 1] at the model resolution."""
imgs = [np.asarray(resize_frame(f, long_edge, crop=crop), dtype=np.float32) / 255.0 for f in frames]
return (torch.from_numpy(np.stack(imgs)).permute(0, 3, 1, 2) - 0.5) / 0.5
# --------------------------------------------------------------------------------------
# Inference
# --------------------------------------------------------------------------------------
def load_model(path: str, device: Union[str, torch.device] = "cuda") -> Flow4RT:
return Flow4RT.from_pretrained(path, device=device)
@torch.no_grad()
def predict(model: Flow4RT, images: torch.Tensor, anchor: int = 0, amp: bool = True) -> Dict[str, torch.Tensor]:
"""Runs Flow4RT on all frames in a single forward pass, with every frame paired with the
anchor frame. The world coordinate frame is the camera of the anchor frame.
Args:
images: (V, 3, H, W) in [-1, 1], e.g. from `frames_to_tensor`.
Returns a dict of tensors (on the model device):
images (V, H, W, 3) input frames in [0, 1]
pts3d (V, H, W, 3) pointmap of frame i in its own camera
depth (V, H, W) z of `pts3d`
conf (V, H, W) confidence of `pts3d`
rigidity (V, H, W) rigidity map of frame i w.r.t. the anchor (sums to 1 per frame)
cam2world (V, 4, 4) camera-to-world pose of frame i
points (V, H, W, 3) pointmap of frame i in world coordinates (reconstruction)
tracks (V, H, W, 3) the anchor frame's pixels at the time of frame i, in world
coordinates (world-space 3D tracks / scene flow)
focal (V,) focal length in pixels, from `pts3d`
"""
device = next(model.parameters()).device
V = images.shape[0]
views = {
"img": images[None].to(device),
"target_idx": torch.full((1, V), anchor, dtype=torch.long, device=device),
}
dtype = torch.bfloat16 if device.type != "cuda" or torch.cuda.is_bf16_supported() else torch.float16
with torch.autocast(device_type=device.type, dtype=dtype, enabled=amp):
pred_src, pred_tgt = model(views) # frame i toward the anchor; the anchor toward frame i
def get(pred, key):
return pred[key][0].float()
return {
"images": ((images.permute(0, 2, 3, 1) + 1) / 2).to(device),
"pts3d": get(pred_src, "pts3d"),
"depth": get(pred_src, "pts3d")[..., 2],
"conf": get(pred_src, "conf"),
"rigidity": get(pred_src, "rigidity"),
"cam2world": get(pred_src, "camera_pose"),
"points": get(pred_src, "pts3d_v"),
"tracks": get(pred_tgt, "pts3d_t"),
"focal": focal_length_from_pointmap(get(pred_src, "pts3d")),
}
|