from dataclasses import dataclass import numpy as np from scipy.spatial.transform import Rotation, Slerp DECLARED_INTEGER_PROFILE = 'declared_integer_centers_v1' NUREC_PINHOLE_PROFILE = 'nurec_pinhole_pixel_edges_v1' DATASET_CAMERA_PROFILES = {'dcgaussian_native_pinhole_v1': NUREC_PINHOLE_PROFILE} @dataclass(frozen=True) class PinholeCamera: width: int height: int fx: float fy: float cx: float cy: float @classmethod def from_json(cls, value, *, calibration_profile=DECLARED_INTEGER_PROFILE): if value['pixel_coordinates'] != 'origin_top_left_centers_at_integers': raise ValueError('Unsupported pixel coordinate convention') if value['pose_convention'] != 'camera_to_world_column_vectors' or value['length_unit'] != 'meter': raise ValueError('Unsupported pose/unit convention') c = value['calibration'] principal = np.asarray(c['principal_point_pixels'], dtype=np.float64) if calibration_profile == NUREC_PINHOLE_PROFILE: if value.get('camera_id') != 'pinhole_front_v1': raise ValueError('NuRec pinhole profile requires pinhole_front_v1') principal = principal - .5 elif calibration_profile != DECLARED_INTEGER_PROFILE: raise ValueError(f'Unsupported calibration profile: {calibration_profile}') return cls(*value['resolution'], *c['focal_length_pixels'], *principal) def crop(self, left, top, right, bottom): if not (0 <= left < right <= self.width and 0 <= top < bottom <= self.height): raise ValueError('Crop is outside the source image') return PinholeCamera(right-left, bottom-top, self.fx, self.fy, self.cx-left, self.cy-top) def matrix(self, raster_center_offset=0.): return np.array([[self.fx, 0., self.cx+raster_center_offset], [0., self.fy, self.cy+raster_center_offset], [0., 0., 1.]], dtype=np.float64) def rays(self): y, x = np.indices((self.height, self.width), dtype=np.float64) rays = np.stack([(x-self.cx)/self.fx, (y-self.cy)/self.fy, np.ones_like(x)], axis=-1) return rays / np.linalg.norm(rays, axis=-1, keepdims=True) def project(self, points): points = np.asarray(points) return points[..., :2]/points[..., 2:3]*[self.fx, self.fy]+[self.cx, self.cy] def exposure_midpoint(frame): poses = np.asarray([frame['pose_start_camera_to_world'], frame['pose_end_camera_to_world']], dtype=np.float64) if poses.shape != (2, 4, 4) or not np.isfinite(poses).all(): raise ValueError('Invalid camera poses') pose = np.eye(4) pose[:3, :3] = Slerp([0., 1.], Rotation.from_matrix(poses[:, :3, :3]))([.5]).as_matrix()[0] pose[:3, 3] = poses[:, :3, 3].mean(axis=0) return pose