from functools import partial from typing import Optional, Tuple import numpy as np import torch import torch.nn.functional as F def normalized_view_plane_uv( width: int, height: int, aspect_ratio: float = None, dtype: torch.dtype = None, device: torch.device = None, ) -> torch.Tensor: """Normalized view-plane UVs spanning the image diagonal.""" if aspect_ratio is None: aspect_ratio = width / height span_x = aspect_ratio / (1 + aspect_ratio**2) ** 0.5 span_y = 1 / (1 + aspect_ratio**2) ** 0.5 u = torch.linspace( -span_x * (width - 1) / width, span_x * (width - 1) / width, width, dtype=dtype, device=device, ) v = torch.linspace( -span_y * (height - 1) / height, span_y * (height - 1) / height, height, dtype=dtype, device=device, ) u, v = torch.meshgrid(u, v, indexing="xy") return torch.stack([u, v], dim=-1) def solve_optimal_focal_shift(uv: np.ndarray, xyz: np.ndarray): """Solve min ||focal * (xy / (z + shift)) - uv||^2.""" from scipy.optimize import least_squares uv = uv.reshape(-1, 2) xy = xyz[..., :2].reshape(-1, 2) z = xyz[..., 2].reshape(-1) def fn(uv: np.ndarray, xy: np.ndarray, z: np.ndarray, shift: np.ndarray): xy_proj = xy / (z + shift)[:, None] f = (xy_proj * uv).sum() / np.square(xy_proj).sum() return (f * xy_proj - uv).ravel() solution = least_squares(partial(fn, uv, xy, z), x0=0, ftol=1e-3, method="lm") optim_shift = solution["x"].squeeze().astype(np.float32) xy_proj = xy / (z + optim_shift)[:, None] optim_focal = (xy_proj * uv).sum() / np.square(xy_proj).sum() return optim_shift, optim_focal def solve_optimal_shift(uv: np.ndarray, xyz: np.ndarray, focal: float): """Solve min ||focal * (xy / (z + shift)) - uv||^2 for a fixed focal.""" from scipy.optimize import least_squares uv = uv.reshape(-1, 2) xy = xyz[..., :2].reshape(-1, 2) z = xyz[..., 2].reshape(-1) def fn(uv: np.ndarray, xy: np.ndarray, z: np.ndarray, shift: np.ndarray): xy_proj = xy / (z + shift)[:, None] return (focal * xy_proj - uv).ravel() solution = least_squares(partial(fn, uv, xy, z), x0=0, ftol=1e-3, method="lm") return solution["x"].squeeze().astype(np.float32) def recover_global_focal_shift( points_all: torch.Tensor, mask_all: Optional[torch.Tensor] = None, focal: Optional[torch.Tensor] = None, downsample_size: Tuple[int, int] = (64, 64), ): """Estimate one global focal and one Z shift per batch from all frames. Args: points_all: `(B, S, H, W, 3)` camera-space point maps mask_all: optional `(B, S, H, W)` validity mask focal: optional `(B, 1)` known focal; if set only shift is solved downsample_size: `(height, width)` used for the least-squares solve Returns: focal: `(B, 1)` focal relative to the half-diagonal of the image shift: `(B,)` additive depth shift """ batch_size, num_frames, height, width, _ = points_all.shape device = points_all.device dtype = points_all.dtype uv = normalized_view_plane_uv(width, height, dtype=dtype, device=device) uv_lr = F.interpolate( uv.permute(2, 0, 1).unsqueeze(0), downsample_size, mode="nearest" )[0].permute(1, 2, 0) uv_lr_np = uv_lr.cpu().numpy().reshape(-1, 2) points_lr = F.interpolate( points_all.reshape(batch_size * num_frames, height, width, 3).permute(0, 3, 1, 2), downsample_size, mode="nearest", ).permute(0, 2, 3, 1) points_lr = points_lr.reshape(batch_size, num_frames, -1, 3) if mask_all is not None: mask_lr = ( F.interpolate( mask_all.reshape(batch_size * num_frames, 1, height, width).float(), downsample_size, mode="nearest", ).reshape(batch_size, num_frames, -1) > 0 ) else: mask_lr = torch.ones( batch_size, num_frames, downsample_size[0] * downsample_size[1], dtype=torch.bool, device=device, ) focals = [] shifts = [] for batch_idx in range(batch_size): points_b = points_lr[batch_idx][mask_lr[batch_idx]] uv_b = np.tile(uv_lr_np[None], (num_frames, 1, 1)) uv_b = uv_b[mask_lr[batch_idx].cpu().numpy()] if points_b.shape[0] < 10: focals.append(torch.ones(1, device=device, dtype=dtype)) shifts.append(torch.zeros((), device=device, dtype=dtype)) continue points_np = points_b.detach().cpu().numpy() if focal is None: shift_np, focal_np = solve_optimal_focal_shift(uv_b, points_np) focals.append(torch.tensor([float(focal_np)], device=device, dtype=dtype)) else: shift_np = solve_optimal_shift(uv_b, points_np, float(focal[batch_idx].item())) focals.append(focal[batch_idx].reshape(1).to(device=device, dtype=dtype)) shifts.append(torch.tensor(float(shift_np), device=device, dtype=dtype)) return torch.stack(focals, dim=0), torch.stack(shifts, dim=0) def pixel_intrinsics_from_focal( focal: torch.Tensor, height: int, width: int, num_frames: int, ) -> torch.Tensor: """Convert half-diagonal-relative focal to a pixel-space pinhole K. `fx = fy = focal * 0.5 * sqrt(H^2 + W^2)`, principal point at the image center. Returns `(B, S, 3, 3)`. """ if focal.ndim == 1: focal = focal.unsqueeze(-1) half_diag = 0.5 * (float(height) ** 2 + float(width) ** 2) ** 0.5 f_px = focal * half_diag batch_size = f_px.shape[0] intrinsics = f_px.new_zeros(batch_size, num_frames, 3, 3) intrinsics[..., 0, 0] = f_px intrinsics[..., 1, 1] = f_px intrinsics[..., 0, 2] = width / 2.0 intrinsics[..., 1, 2] = height / 2.0 intrinsics[..., 2, 2] = 1.0 return intrinsics