"""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")), }