from __future__ import annotations import numpy as np def default_camera_intrinsics(width: int, height: int) -> np.ndarray: focal = float(max(height, width) * 0.95) cx, cy = (width - 1) * 0.5, (height - 1) * 0.5 return np.array([[focal, 0, cx], [0, focal, cy], [0, 0, 1]], dtype=np.float32) def pixel_intrinsics_from_model( intrinsics: np.ndarray | None, width: int, height: int, ) -> np.ndarray: if intrinsics is None: return default_camera_intrinsics(width, height) pixel_intrinsics = intrinsics.astype(np.float32).copy() if abs(float(pixel_intrinsics[0, 0])) < 10: pixel_intrinsics[0, 0] *= width pixel_intrinsics[0, 2] *= width pixel_intrinsics[1, 1] *= height pixel_intrinsics[1, 2] *= height return pixel_intrinsics def prepare_depth_for_backprojection( depth: np.ndarray, mask: np.ndarray, is_metric_depth: bool, ) -> tuple[np.ndarray, str]: depth_float = depth.astype(np.float32).copy() if is_metric_depth: return depth_float, "metric" valid = (mask > 0) & np.isfinite(depth_float) if valid.sum() < 1000: return depth_float, "relative-raw" ys, xs = np.where(valid) floor_depth = depth_float[ys, xs] if floor_depth.size >= 1000: corr = np.corrcoef(floor_depth, ys.astype(np.float32))[0, 1] if np.isfinite(corr) and corr > 0: depth_float = 1.0 - depth_float floor_depth = depth_float[ys, xs] lo, hi = np.percentile(floor_depth[np.isfinite(floor_depth)], [2, 98]) if hi - lo < 1e-6: return depth_float, "relative-raw" normalized = np.clip((depth_float - lo) / (hi - lo), 0.0, 1.0) return (0.8 + normalized * 3.2).astype(np.float32), "relative-normalized" def backproject_depth( depth: np.ndarray, intrinsics: np.ndarray, ) -> np.ndarray: h, w = depth.shape[:2] yy, xx = np.mgrid[0:h, 0:w] fx = max(float(intrinsics[0, 0]), 1e-6) fy = max(float(intrinsics[1, 1]), 1e-6) cx = float(intrinsics[0, 2]) cy = float(intrinsics[1, 2]) return np.dstack(( (xx - cx) * depth / fx, (yy - cy) * depth / fy, depth, )).astype(np.float32)