mirror of
https://github.com/nerfstudio-project/nerfstudio.git
synced 2026-12-05 15:28:49 +08:00
Camera Refactor (#301)
* Start camera refactor * Training runs, but transforms incorrect * Cameras render correctly in viewer. * Fix eval * cleanup * cleanup
This commit is contained in:
1 parent
6bdb26c3a4
commit
04d0165a24
15 files changed
+334
-614
No files matched your search
@@ -16,30 +16,16 @@
|
||||
Code for camera paths.
|
||||
"""
|
||||
|
||||
import copy
|
||||
from dataclasses import dataclass
|
||||
from typing import List, Optional, Tuple
|
||||
from typing import Optional, Tuple
|
||||
|
||||
import torch
|
||||
|
||||
import nerfactory.cameras.utils as camera_utils
|
||||
from nerfactory.cameras.cameras import (
|
||||
Camera,
|
||||
PinholeCamera,
|
||||
get_camera,
|
||||
get_intrinsics_from_intrinsics_matrix,
|
||||
)
|
||||
from nerfactory.cameras.cameras import Cameras
|
||||
from nerfactory.cameras.utils import get_interpolated_poses_many
|
||||
|
||||
|
||||
@dataclass
|
||||
class CameraPath:
|
||||
"""A camera path."""
|
||||
|
||||
cameras: List[Camera]
|
||||
|
||||
|
||||
def get_interpolated_camera_path(camera_a: PinholeCamera, camera_b: PinholeCamera, steps: int) -> CameraPath:
|
||||
def get_interpolated_camera_path(cameras: Cameras, steps: int) -> Cameras:
|
||||
"""Generate a camera path between two cameras.
|
||||
|
||||
Args:
|
||||
@@ -48,38 +34,24 @@ def get_interpolated_camera_path(camera_a: PinholeCamera, camera_b: PinholeCamer
|
||||
steps: The number of steps to interpolate between the two cameras.
|
||||
|
||||
Returns:
|
||||
CameraPath: A camera path.
|
||||
A new set of cameras along a path.
|
||||
"""
|
||||
device = camera_a.device
|
||||
Ka = camera_a.get_intrinsics_matrix().cpu().numpy()
|
||||
pose_a = camera_a.get_camera_to_world_h().cpu().numpy()
|
||||
Kb = camera_b.get_intrinsics_matrix().cpu().numpy()
|
||||
pose_b = camera_b.get_camera_to_world_h().cpu().numpy()
|
||||
poses = [pose_a, pose_b]
|
||||
Ks = [Ka, Kb]
|
||||
Ks = cameras.get_intrinsics_matrices().cpu().numpy()
|
||||
poses = cameras.camera_to_worlds().cpu().numpy()
|
||||
poses, Ks = get_interpolated_poses_many(poses, Ks, steps_per_transition=steps)
|
||||
|
||||
cameras = []
|
||||
for pose, K in zip(poses, Ks):
|
||||
intrinsics = get_intrinsics_from_intrinsics_matrix(K).to(device).float()
|
||||
# TODO: this makes cx and cy an integer, but this code should be fixed
|
||||
# it was added to avoid floating point errors when rescaling and the image resolution
|
||||
# being different per rendered image in a camera path
|
||||
intrinsics[:2] = torch.round(intrinsics[:2])
|
||||
camera_to_world = torch.from_numpy(pose[:3]).to(device).float()
|
||||
camera = get_camera(intrinsics, camera_to_world, camera_index=camera_a.camera_index)
|
||||
cameras.append(camera)
|
||||
return CameraPath(cameras=cameras)
|
||||
cameras = Cameras(fx=Ks[:, 0, 0], fy=Ks[:, 1, 1], cx=Ks[0, 0, 2], cy=Ks[0, 1, 2], camera_to_worlds=poses)
|
||||
return cameras
|
||||
|
||||
|
||||
def get_spiral_path(
|
||||
camera: PinholeCamera,
|
||||
camera: Cameras,
|
||||
steps: int = 30,
|
||||
radius: Optional[float] = None,
|
||||
radiuses: Optional[Tuple[float]] = None,
|
||||
rots: int = 2,
|
||||
zrate: float = 0.5,
|
||||
) -> CameraPath:
|
||||
) -> Cameras:
|
||||
"""
|
||||
Returns a list of camera in a sprial trajectory.
|
||||
|
||||
@@ -92,7 +64,7 @@ def get_spiral_path(
|
||||
zrate: How much to change the z position of the camera.
|
||||
|
||||
Returns:
|
||||
CameraPath: A spiral camera path.
|
||||
A spiral camera path.
|
||||
"""
|
||||
|
||||
assert radius is not None or radiuses is not None, "Either radius or radiuses must be specified."
|
||||
@@ -104,12 +76,14 @@ def get_spiral_path(
|
||||
raise ValueError("Only one of radius or radiuses must be specified.")
|
||||
|
||||
# TODO: don't hardcode this. pass this in
|
||||
up = camera.camera_to_world[:3, 2] # scene is z up
|
||||
up = camera.camera_to_worlds[0, :3, 2] # scene is z up
|
||||
# up = camera.camera_to_world[:3, 1] # this will rotate 90 degrees
|
||||
focal = min(camera.fx, camera.fy)
|
||||
focal = torch.min(camera.fx[0], camera.fy[0])
|
||||
target = torch.tensor([0, 0, -focal], device=camera.device) # camera looking in -z direction
|
||||
|
||||
c2wh_global = camera.get_camera_to_world_h()
|
||||
c2w = camera.camera_to_worlds[0]
|
||||
ones = torch.tensor([0, 0, 0, 1], device=c2w.device)[None]
|
||||
c2wh_global = torch.cat([c2w, ones], dim=0)
|
||||
|
||||
local_c2whs = []
|
||||
for theta in torch.linspace(0.0, 2.0 * torch.pi * rots, steps + 1)[:-1]:
|
||||
@@ -122,11 +96,9 @@ def get_spiral_path(
|
||||
c2wh = torch.cat([c2w, ones], dim=0)
|
||||
local_c2whs.append(c2wh)
|
||||
|
||||
cameras = []
|
||||
new_c2ws = []
|
||||
for local_c2wh in local_c2whs:
|
||||
cam = copy.deepcopy(camera)
|
||||
c2wh = torch.matmul(c2wh_global, local_c2wh)
|
||||
cam.camera_to_world = c2wh[:3, :4]
|
||||
cameras.append(cam)
|
||||
new_c2ws.append(c2wh[:3, :4])
|
||||
|
||||
return CameraPath(cameras=cameras)
|
||||
return Cameras(fx=camera.fx[0], fy=camera.fy[0], cx=camera.cx, cy=camera.cy, camera_to_worlds=new_c2ws)
|
||||
+160
-409
@@ -16,8 +16,8 @@
|
||||
Camera Models
|
||||
"""
|
||||
import base64
|
||||
from abc import abstractmethod
|
||||
from typing import Dict, Optional, Tuple, Type
|
||||
from enum import Enum, auto
|
||||
from typing import Dict, Optional, Tuple, Union
|
||||
|
||||
import cv2
|
||||
import numpy as np
|
||||
@@ -28,87 +28,96 @@ from torchtyping import TensorType
|
||||
from nerfactory.cameras.rays import RayBundle
|
||||
|
||||
|
||||
class Camera:
|
||||
"""Base Camera. Intended to be subclassed.
|
||||
class CameraType(Enum):
|
||||
"""Supported camera types."""
|
||||
|
||||
PERSPECTIVE = auto
|
||||
FISHEYE = auto
|
||||
|
||||
|
||||
class Cameras:
|
||||
"""Dataset inputs for the image dataset and the ray generator.
|
||||
|
||||
Note: currently only supports cameras with the same principal points and types.
|
||||
|
||||
Args:
|
||||
camera_to_world: Camera to world transformation
|
||||
camera_index: Camera index
|
||||
camera_to_worlds: Tensor of per-image c2w matrices, in [R | t] format.
|
||||
fx: Focal length x.
|
||||
fy: Focal length y.
|
||||
cx: Principal point x.
|
||||
cy: Principal point y.
|
||||
distortion_params: OpenCV 6 radial distortion coefficients.
|
||||
camera_type: Type of camera model.
|
||||
"""
|
||||
|
||||
def __init__(
|
||||
self, camera_to_world: TensorType[3, 4] = torch.eye(4)[:3], camera_index: Optional[int] = None
|
||||
) -> None:
|
||||
self.camera_to_world = camera_to_world
|
||||
self.camera_index = camera_index
|
||||
self,
|
||||
camera_to_worlds: TensorType["num_cameras", 3, 4],
|
||||
fx: Union[TensorType["num_cameras"], float],
|
||||
fy: Union[TensorType["num_cameras"], float],
|
||||
cx: float,
|
||||
cy: float,
|
||||
distortion_params: Optional[TensorType["num_cameras", 6]] = None,
|
||||
camera_type: CameraType = CameraType.PERSPECTIVE,
|
||||
):
|
||||
self._num_cameras = camera_to_worlds.shape[0]
|
||||
self.camera_to_worlds = camera_to_worlds
|
||||
if not isinstance(fx, torch.Tensor):
|
||||
fx = torch.Tensor([fx])
|
||||
if not isinstance(fy, torch.Tensor):
|
||||
fy = torch.Tensor([fy])
|
||||
self.fx = fx.broadcast_to((self._num_cameras)).to(self.device)
|
||||
self.fy = fy.broadcast_to((self._num_cameras)).to(self.device)
|
||||
self.cx = cx
|
||||
self.cy = cy
|
||||
if distortion_params is not None:
|
||||
self.distortion_params = distortion_params.broadcast_to((self._num_cameras, 6))
|
||||
else:
|
||||
self.distortion_params = None
|
||||
self._image_heights = int(self.cy * 2)
|
||||
self._image_widths = int(self.cx * 2)
|
||||
self.camera_type = camera_type
|
||||
|
||||
@property
|
||||
def device(self):
|
||||
"""Returns the device that the camera is on."""
|
||||
return self.camera_to_world.device
|
||||
return self.camera_to_worlds.device
|
||||
|
||||
@abstractmethod
|
||||
def get_num_intrinsics_params(self) -> int:
|
||||
"""
|
||||
Returns:
|
||||
number of optimizable intrinsic parameters
|
||||
"""
|
||||
return
|
||||
@property
|
||||
def size(self) -> int:
|
||||
"""Returns the number of cameras."""
|
||||
return self._num_cameras
|
||||
|
||||
@abstractmethod
|
||||
def get_intrinsics(self) -> torch.Tensor:
|
||||
"""
|
||||
Returns:
|
||||
Intrinsics matrix
|
||||
"""
|
||||
return
|
||||
@property
|
||||
def image_height(self) -> int:
|
||||
"""Returns the height of the images."""
|
||||
return self._image_heights
|
||||
|
||||
def get_camera_to_world(self) -> TensorType[3, 4]:
|
||||
"""
|
||||
Returns:
|
||||
Camera to world transformation
|
||||
"""
|
||||
return self.camera_to_world
|
||||
@property
|
||||
def image_width(self) -> int:
|
||||
"""Returns the height of the images."""
|
||||
return self._image_widths
|
||||
|
||||
def get_camera_to_world_h(self) -> TensorType[4, 4]:
|
||||
def to(self, device: Union[torch.device, str]) -> "Cameras":
|
||||
"""
|
||||
Returns:
|
||||
Camera to world transformation with homogeneous coordinates
|
||||
"""
|
||||
c2w = self.camera_to_world
|
||||
ones = torch.tensor([0, 0, 0, 1], device=c2w.device)[None]
|
||||
c2w = torch.cat([c2w, ones], dim=0)
|
||||
return c2w
|
||||
|
||||
@abstractmethod
|
||||
def get_image_height(self) -> int:
|
||||
"""
|
||||
Returns:
|
||||
Image height
|
||||
"""
|
||||
return
|
||||
|
||||
@abstractmethod
|
||||
def get_image_width(self) -> int:
|
||||
"""
|
||||
Returns:
|
||||
Image width
|
||||
"""
|
||||
return
|
||||
|
||||
@abstractmethod
|
||||
def rescale_output_resolution(self, scaling_factor: float) -> None:
|
||||
"""Rescales the camera intrinsics for output resolution.
|
||||
|
||||
Args:
|
||||
scaling_factor: Scaling factor
|
||||
Device to move the camera to.
|
||||
|
||||
Returns:
|
||||
None
|
||||
Cameras: Cameras on the specified device.
|
||||
"""
|
||||
return
|
||||
distortion_params = self.distortion_params.to(device) if self.distortion_params is not None else None
|
||||
return Cameras(
|
||||
camera_to_worlds=self.camera_to_worlds.to(device),
|
||||
fx=self.fx.to(device),
|
||||
fy=self.fy.to(device),
|
||||
cx=self.cx,
|
||||
cy=self.cy,
|
||||
distortion_params=distortion_params,
|
||||
camera_type=self.camera_type,
|
||||
)
|
||||
|
||||
def get_image_coords(self, pixel_offset: float = 0.5) -> TensorType["image_height", "image_width", 2]:
|
||||
def get_image_coords(self, pixel_offset: float = 0.5) -> TensorType["height", "width", 2]:
|
||||
"""
|
||||
Args:
|
||||
pixel_offset (float): Offset for each pixel. Defaults to center of pixel (0.5)
|
||||
@@ -116,203 +125,105 @@ class Camera:
|
||||
Returns:
|
||||
TensorType["image_height", "image_width", 2]: Grid of image coordinates.
|
||||
"""
|
||||
image_height = self.get_image_height()
|
||||
image_width = self.get_image_width()
|
||||
image_height = self.image_height
|
||||
image_width = self.image_width
|
||||
image_coords = torch.meshgrid(torch.arange(image_height), torch.arange(image_width), indexing="ij")
|
||||
image_coords = torch.stack(image_coords, dim=-1) + pixel_offset # stored as (y, x) coordinates
|
||||
return image_coords
|
||||
|
||||
@classmethod
|
||||
@abstractmethod
|
||||
def generate_rays(
|
||||
cls,
|
||||
intrinsics: TensorType[..., "num_intrinsics_params"],
|
||||
camera_to_world: TensorType[..., 3, 4],
|
||||
coords: TensorType[..., 2],
|
||||
self,
|
||||
camera_indices: Union[TensorType["num_rays":...], int],
|
||||
coords: Optional[TensorType["num_rays":..., 2]] = None,
|
||||
camera_to_world_delta: Optional[TensorType["num_rays":..., 3, 4]] = None,
|
||||
distortion_params_delta: Optional[TensorType["num_rays":..., 6]] = None,
|
||||
) -> RayBundle:
|
||||
"""
|
||||
Args:
|
||||
intrinsics (TensorType[..., "num_intrinsics_params"]): Camera intrinsics
|
||||
camera_to_world (TensorType[..., 3, 4]): Camera to world transformation matrix
|
||||
coords (TensorType[..., 2]): Image grid coordinates
|
||||
"""Generates rays for the given camera indices.
|
||||
|
||||
Returns:
|
||||
RayBundle: A bundle of rays for each grid coordinate.
|
||||
"""
|
||||
return
|
||||
|
||||
def get_camera_ray_bundle(self, device=None) -> RayBundle:
|
||||
"""Generate rays for the camera.
|
||||
|
||||
Returns:
|
||||
Rays: Camera rays of shape [height, width]
|
||||
"""
|
||||
if device is None:
|
||||
device = self.camera_to_world.device
|
||||
height = self.get_image_height()
|
||||
width = self.get_image_width()
|
||||
intrinsics = (
|
||||
self.get_intrinsics().unsqueeze(0).repeat(height, width, 1).to(device)
|
||||
) # (num_rays, num_intrinsics_params)
|
||||
camera_to_world = self.camera_to_world.unsqueeze(0).repeat(height, width, 1, 1).to(device) # (num_rays, 3, 4)
|
||||
coords = self.get_image_coords().to(device)
|
||||
ray_bundle = self.generate_rays(intrinsics, camera_to_world, coords)
|
||||
if self.camera_index is not None:
|
||||
ray_bundle.set_camera_indices(camera_index=self.camera_index)
|
||||
return ray_bundle
|
||||
|
||||
@abstractmethod
|
||||
def to_json(
|
||||
self,
|
||||
image: Optional[TensorType["image_height", "image_width", 2]] = None,
|
||||
resize_shape: Optional[Tuple[int, int]] = None,
|
||||
) -> Dict:
|
||||
"""Converts the camera to a json dictionary.
|
||||
TODO - add support for intrinsics delta.
|
||||
TODO - add support for distortions.
|
||||
|
||||
Args:
|
||||
image: An image in range [0, 1] that is encoded to a base64 string. Defaults to None.
|
||||
camera_indices: Indices of the cameras to generate rays for.
|
||||
coords: Coordinates of the pixels to generate rays for. If None, the full image will be rendered.
|
||||
camera_to_world_delta: Optional delta for the camera to world matrices.
|
||||
distortion_params_delta: Optional delta for the distortion parameters.
|
||||
|
||||
Returns:
|
||||
A JSON representation of the camera
|
||||
Rays for the given camera indices and coords.
|
||||
"""
|
||||
raise NotImplementedError
|
||||
|
||||
@staticmethod
|
||||
def from_json(json_: Dict) -> "Camera": # pylint:disable=no-self-use
|
||||
"""Converts a json dictionary to the camera object.
|
||||
if coords is None:
|
||||
coords = self.get_image_coords().to(self.device)
|
||||
|
||||
Args:
|
||||
json_: The json dictionary.
|
||||
assert coords is not None
|
||||
y = coords[..., 0] # (..., 1)
|
||||
x = coords[..., 1] # (..., 1)
|
||||
fx, fy = self.fx[camera_indices], self.fy[camera_indices]
|
||||
cx, cy = self.cx, self.cy
|
||||
|
||||
Returns:
|
||||
The camera object instantiated from the json dictionary.
|
||||
"""
|
||||
raise NotImplementedError
|
||||
|
||||
|
||||
class PinholeCamera(Camera):
|
||||
"""Pinhole camera model.
|
||||
|
||||
Args:
|
||||
fx: Focal length in x direction
|
||||
fy: Focal length in y direction
|
||||
cx: Principal point in x direction
|
||||
cy: Principal point in y direction
|
||||
camera_to_world: Camera to world transformation
|
||||
camera_index: Camera index. Defaults to None.
|
||||
"""
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
cx: float,
|
||||
cy: float,
|
||||
fx: float,
|
||||
fy: float,
|
||||
camera_to_world: TensorType[3, 4] = torch.eye(4)[:3],
|
||||
camera_index: Optional[int] = None,
|
||||
):
|
||||
super().__init__(camera_to_world=camera_to_world, camera_index=camera_index)
|
||||
self.cx = cx
|
||||
self.cy = cy
|
||||
self.fx = fx
|
||||
self.fy = fy
|
||||
|
||||
def get_num_intrinsics_params(self) -> int:
|
||||
return 4
|
||||
|
||||
def get_image_width(self) -> int:
|
||||
return int(self.cx * 2.0)
|
||||
|
||||
def get_image_height(self) -> int:
|
||||
return int(self.cy * 2.0)
|
||||
|
||||
def get_intrinsics_matrix(self) -> TensorType[3, 3]:
|
||||
"""
|
||||
Returns:
|
||||
TensorType[3, 3]: Pinhole camera intrinsics matrix
|
||||
"""
|
||||
K = torch.tensor(
|
||||
[[self.fx, 0.0, self.cx], [0.0, self.fy, self.cy], [0, 0, 1.0]],
|
||||
dtype=torch.float32,
|
||||
directions = normalize(torch.stack([(x - cx) / fx, -(y - cy) / fy, -torch.ones_like(x)], -1), dim=-1)
|
||||
directions_x_offset = normalize(
|
||||
torch.stack([(x - cx + 1) / fx, -(y - cy) / fy, -torch.ones_like(x)], -1), dim=-1
|
||||
)
|
||||
directions_y_offset = normalize(
|
||||
torch.stack([(x - cx) / fx, -(y - cy + 1) / fy, -torch.ones_like(x)], -1), dim=-1
|
||||
)
|
||||
return K
|
||||
|
||||
def get_intrinsics(self) -> torch.Tensor:
|
||||
return torch.tensor([self.cx, self.cy, self.fx, self.fy])
|
||||
directions_stack = torch.stack([directions, directions_x_offset, directions_y_offset], dim=0)
|
||||
|
||||
@classmethod
|
||||
def fx_index(cls) -> int:
|
||||
"""Returns the index of the fx parameter in the intrinsics vector
|
||||
TODO(ethan): redo this in a better way.
|
||||
Ideally we can dynamically grab the focal length parameters depending on
|
||||
Simple vs. not Simple Pinhole Model.
|
||||
|
||||
Returns:
|
||||
x focal length index
|
||||
"""
|
||||
return 2
|
||||
|
||||
@classmethod
|
||||
def fy_index(cls) -> int:
|
||||
"""Returns the index of the fy parameter in the intrinsics vector
|
||||
|
||||
Returns:
|
||||
y focal length index
|
||||
"""
|
||||
return 3
|
||||
|
||||
def rescale_output_resolution(self, scaling_factor: float) -> None:
|
||||
self.cx *= scaling_factor
|
||||
self.cy *= scaling_factor
|
||||
self.fx *= scaling_factor
|
||||
self.fy *= scaling_factor
|
||||
|
||||
@classmethod
|
||||
def generate_rays(
|
||||
cls,
|
||||
intrinsics: TensorType[..., "num_intrinsics_params"],
|
||||
camera_to_world: TensorType[..., 3, 4],
|
||||
coords: TensorType[..., 2],
|
||||
) -> RayBundle:
|
||||
|
||||
cx = intrinsics[..., 0:1]
|
||||
cy = intrinsics[..., 1:2]
|
||||
fx = intrinsics[..., cls.fx_index() : cls.fx_index() + 1]
|
||||
fy = intrinsics[..., cls.fy_index() : cls.fy_index() + 1]
|
||||
y = coords[..., 0:1] # (..., 1)
|
||||
x = coords[..., 1:2] # (..., 1)
|
||||
original_directions = torch.cat([(x - cx) / fx, -(y - cy) / fy, -torch.ones_like(x)], -1) # (..., 3)
|
||||
rotation = camera_to_world[..., :3, :3] # (..., 3, 3)
|
||||
directions = torch.sum(
|
||||
original_directions[..., None, :] * rotation, dim=-1
|
||||
c2w = self.camera_to_worlds[camera_indices]
|
||||
if camera_to_world_delta is not None:
|
||||
c2w = c2w + camera_to_world_delta
|
||||
rotation = c2w[..., :3, :3] # (..., 3, 3)
|
||||
directions_stack = torch.sum(
|
||||
directions_stack[..., None, :] * rotation, dim=-1
|
||||
) # (..., 1, 3) * (..., 3, 3) -> (..., 3)
|
||||
directions = normalize(directions, dim=-1)
|
||||
origins = camera_to_world[..., :3, 3] # (..., 3)
|
||||
directions_stack = normalize(directions_stack, dim=-1)
|
||||
|
||||
## Calculate pixel area directly
|
||||
dirx_min = normalize(torch.cat([(x - cx - 0.5) / fx, -(y - cy) / fy, -torch.ones_like(x)], -1), dim=-1)
|
||||
dirx_max = normalize(torch.cat([(x - cx + 0.5) / fx, -(y - cy) / fy, -torch.ones_like(x)], -1), dim=-1)
|
||||
diry_min = normalize(torch.cat([(x - cx) / fx, -(y - cy - 0.5) / fy, -torch.ones_like(x)], -1), dim=-1)
|
||||
diry_max = normalize(torch.cat([(x - cx) / fx, -(y - cy + 0.5) / fy, -torch.ones_like(x)], -1), dim=-1)
|
||||
dx = torch.sqrt(torch.sum((dirx_max - dirx_min) ** 2, dim=-1))
|
||||
dy = torch.sqrt(torch.sum((diry_max - diry_min) ** 2, dim=-1))
|
||||
distortion_params = None
|
||||
if self.distortion_params is not None:
|
||||
if distortion_params_delta is not None:
|
||||
distortion_params = self.distortion_params[camera_indices] + distortion_params_delta
|
||||
elif distortion_params_delta is not None:
|
||||
distortion_params = distortion_params_delta
|
||||
|
||||
if distortion_params is not None:
|
||||
raise NotImplementedError("Camera distortion not implemented.")
|
||||
|
||||
origins = c2w[..., :3, 3] # (..., 3)
|
||||
directions = directions_stack[0]
|
||||
|
||||
dx = torch.sqrt(torch.sum((directions - directions_stack[1]) ** 2, dim=-1))
|
||||
dy = torch.sqrt(torch.sum((directions - directions_stack[2]) ** 2, dim=-1))
|
||||
pixel_area = dx * dy
|
||||
|
||||
return RayBundle(origins=origins, directions=directions, pixel_area=pixel_area[..., None])
|
||||
|
||||
def to_json(
|
||||
self,
|
||||
image: Optional[TensorType["image_height", "image_width", 2]] = None,
|
||||
camera_idx: int,
|
||||
image: Optional[TensorType["height", "width", 2]] = None,
|
||||
resize_shape: Optional[Tuple[int, int]] = None,
|
||||
) -> Dict:
|
||||
"""Convert a camera to a json dictionary.
|
||||
|
||||
Args:
|
||||
camera_idx (int): Index of the camera to convert.
|
||||
image: An image in range [0, 1] that is encoded to a base64 string. Defaults to None.
|
||||
resize_shape: Shape to resize the image to. Defaults to None.
|
||||
|
||||
Returns:
|
||||
A JSON representation of the camera
|
||||
"""
|
||||
json_ = {
|
||||
"type": "PinholeCamera",
|
||||
"cx": self.cx,
|
||||
"cy": self.cy,
|
||||
"fx": self.fx,
|
||||
"fy": self.fy,
|
||||
"camera_to_world": self.camera_to_world.tolist(),
|
||||
"camera_index": self.camera_index,
|
||||
"fx": self.fx[camera_idx].tolist(),
|
||||
"fy": self.fy[camera_idx].tolist(),
|
||||
"camera_to_world": self.camera_to_worlds[camera_idx].tolist(),
|
||||
"camera_index": camera_idx,
|
||||
}
|
||||
if image is not None:
|
||||
image_uint8 = (image * 255).detach().cpu().numpy().astype(np.uint8)
|
||||
@@ -322,187 +233,27 @@ class PinholeCamera(Camera):
|
||||
json_["image"] = str("data:image/png;base64," + base64.b64encode(data).decode("ascii"))
|
||||
return json_
|
||||
|
||||
@staticmethod
|
||||
def from_json(json_: Dict) -> "PinholeCamera": # pylint:disable=no-self-use
|
||||
raise NotImplementedError
|
||||
def get_intrinsics_matrices(self) -> TensorType["num_cameras", 3, 3]:
|
||||
"""Returns the intrinsic matrices for each camera.
|
||||
|
||||
|
||||
class SimplePinholeCamera(PinholeCamera):
|
||||
"""Simple Pinhole Camera model.
|
||||
|
||||
Args:
|
||||
cx: Principal point x direction
|
||||
cy: Principal point y direction
|
||||
f: Focal length
|
||||
camera_to_world: Camera to world transformation matrix
|
||||
camera_index: Camera index. Defaults to None.
|
||||
"""
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
cx: float,
|
||||
cy: float,
|
||||
f: float,
|
||||
camera_to_world: TensorType[3, 4] = torch.eye(4)[:3],
|
||||
camera_index: Optional[int] = None,
|
||||
):
|
||||
super().__init__(cx, cy, f, f, camera_to_world=camera_to_world, camera_index=camera_index)
|
||||
|
||||
@classmethod
|
||||
def fx_index(cls):
|
||||
return 2
|
||||
|
||||
@classmethod
|
||||
def fy_index(cls):
|
||||
return 2
|
||||
|
||||
@staticmethod
|
||||
def from_json(json_: Dict) -> "SimplePinholeCamera": # pylint:disable=no-self-use
|
||||
raise NotImplementedError
|
||||
|
||||
|
||||
class EquirectangularCamera(Camera):
|
||||
"""Equirectangular (360 degree) camera model.
|
||||
|
||||
Args:
|
||||
height: Height of the image
|
||||
width: Width of the image
|
||||
camera_to_world: Camera to world transformation matrix
|
||||
camera_index: Camera index. Defaults to None.
|
||||
"""
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
height: int,
|
||||
width: int,
|
||||
camera_to_world: TensorType[3, 4] = torch.eye(4)[:3],
|
||||
camera_index: Optional[int] = None,
|
||||
):
|
||||
super().__init__(camera_to_world=camera_to_world, camera_index=camera_index)
|
||||
self.height = height
|
||||
self.width = width
|
||||
|
||||
def get_num_intrinsics_params(self):
|
||||
return 2
|
||||
|
||||
def get_image_width(self):
|
||||
return self.width
|
||||
|
||||
def get_image_height(self):
|
||||
return self.height
|
||||
|
||||
def get_intrinsics(self) -> torch.Tensor:
|
||||
return torch.tensor([self.height, self.width])
|
||||
Returns:
|
||||
Pinhole camera intrinsics matrices
|
||||
"""
|
||||
K = torch.zeros((self.size, 3, 3), dtype=torch.float32)
|
||||
K[:, 0, 0] = self.fx
|
||||
K[:, 1, 1] = self.fy
|
||||
K[:, 0, 2] = self.cx
|
||||
K[:, 1, 2] = self.cy
|
||||
K[:, 2, 2] = 1.0
|
||||
return K
|
||||
|
||||
def rescale_output_resolution(self, scaling_factor: float) -> None:
|
||||
self.height *= scaling_factor
|
||||
self.width *= scaling_factor
|
||||
"""Rescale the output resolution of the cameras.
|
||||
|
||||
@classmethod
|
||||
def generate_rays(
|
||||
cls,
|
||||
intrinsics: TensorType[..., 2],
|
||||
camera_to_world: TensorType[..., 3, 4],
|
||||
coords: TensorType[..., 2],
|
||||
) -> RayBundle:
|
||||
|
||||
y = coords[..., 0:1] # (num_rays, 1)
|
||||
x = coords[..., 1:2] # (num_rays, 1)
|
||||
|
||||
height = intrinsics[..., 0:1]
|
||||
width = intrinsics[..., 1:2]
|
||||
|
||||
phi = y / height * torch.pi
|
||||
theta = -x / width * 2 * torch.pi
|
||||
|
||||
d_phi_min = (y + 0.5) / height * torch.pi
|
||||
d_phi_max = (y - 0.5) / height * torch.pi
|
||||
d_theta_min = -(x - 0.5) / width * 2 * torch.pi
|
||||
d_theta_max = -(x + 0.5) / width * 2 * torch.pi
|
||||
|
||||
s_phi = torch.sin(phi)
|
||||
c_phi = torch.cos(phi)
|
||||
s_theta = torch.sin(theta)
|
||||
c_theta = torch.cos(theta)
|
||||
|
||||
directions = torch.cat([c_theta * s_phi, c_phi, s_theta * s_phi], dim=-1)
|
||||
origins = camera_to_world[..., :3, 3] # (num_rays, 3)
|
||||
|
||||
## Calculate area directly
|
||||
dirx_min = normalize(
|
||||
torch.cat([torch.cos(d_theta_min) * s_phi, c_phi, torch.sin(d_theta_min) * s_phi], -1), dim=-1
|
||||
)
|
||||
dirx_max = normalize(
|
||||
torch.cat([torch.cos(d_theta_max) * s_phi, c_phi, torch.sin(d_theta_max) * s_phi], -1), dim=-1
|
||||
)
|
||||
diry_min = normalize(
|
||||
torch.cat([c_theta * torch.sin(d_phi_min), torch.cos(d_phi_min), s_theta * torch.sin(d_phi_min)], -1),
|
||||
dim=-1,
|
||||
)
|
||||
diry_max = normalize(
|
||||
torch.cat([c_theta * torch.sin(d_phi_max), torch.cos(d_phi_max), s_theta * torch.sin(d_phi_max)], -1),
|
||||
dim=-1,
|
||||
)
|
||||
dx = torch.sqrt(torch.sum((dirx_max - dirx_min) ** 2, dim=-1))
|
||||
dy = torch.sqrt(torch.sum((diry_max - diry_min) ** 2, dim=-1))
|
||||
pixel_area = dx * dy
|
||||
return RayBundle(origins=origins, directions=directions, pixel_area=pixel_area[..., None])
|
||||
|
||||
def to_json(
|
||||
self,
|
||||
image: Optional[TensorType["image_height", "image_width", 2]] = None,
|
||||
resize_shape: Optional[Tuple[int, int]] = None,
|
||||
) -> Dict:
|
||||
raise NotImplementedError
|
||||
|
||||
@staticmethod
|
||||
def from_json(json_: Dict) -> "SimplePinholeCamera": # pylint:disable=no-self-use
|
||||
raise NotImplementedError
|
||||
|
||||
|
||||
def get_intrinsics_from_intrinsics_matrix(intrinsics_matrix: TensorType[3, 3]):
|
||||
"""
|
||||
Return a flat intrinsics tensor.
|
||||
"""
|
||||
fx = intrinsics_matrix[0, 0]
|
||||
fy = intrinsics_matrix[1, 1]
|
||||
cx = intrinsics_matrix[0, 2]
|
||||
cy = intrinsics_matrix[1, 2]
|
||||
if fx == fy:
|
||||
return torch.tensor([cx, cy, fx])
|
||||
return torch.tensor([cx, cy, fx, fy])
|
||||
|
||||
|
||||
def get_camera_model(num_intrinsics_params: int) -> Type[Camera]:
|
||||
# TODO: we should specify the type in the dataloading pipeline instead of relying on number of intrinsics
|
||||
# to make the choice
|
||||
"""Returns the camera model given the specified number of intrinsics parameters.
|
||||
|
||||
Args:
|
||||
num_intrinsics_params (int): Number of intrinsic parametes.
|
||||
|
||||
Returns:
|
||||
Camera: Camera model
|
||||
"""
|
||||
if num_intrinsics_params == 2:
|
||||
return EquirectangularCamera
|
||||
if num_intrinsics_params == 3:
|
||||
return SimplePinholeCamera
|
||||
if num_intrinsics_params == 4:
|
||||
return PinholeCamera
|
||||
raise NotImplementedError
|
||||
|
||||
|
||||
def get_camera(intrinsics: TensorType["num_intrinsics"], camera_to_world: TensorType[3, 4], camera_index=None):
|
||||
"""Returns a transformed camera.
|
||||
|
||||
Args:
|
||||
intrinsics (TensorType["num_intrinsics"]): Intrinsics tensor.
|
||||
camera_to_world (TensorType[3, 4]): Camera to world transformation.
|
||||
camera_index (int): Camera index.
|
||||
"""
|
||||
assert len(intrinsics.shape) == 1, "The intrinsics object should be a flat tensor."
|
||||
num_intrinsics_params = len(intrinsics)
|
||||
camera_class = get_camera_model(num_intrinsics_params)
|
||||
camera = camera_class(*intrinsics.tolist(), camera_to_world=camera_to_world, camera_index=camera_index)
|
||||
return camera
|
||||
Args:
|
||||
scaling_factor: Scaling factor to apply to the output resolution.
|
||||
"""
|
||||
self.fx *= scaling_factor
|
||||
self.fy *= scaling_factor
|
||||
self.cx *= scaling_factor
|
||||
self.cy *= scaling_factor
|
||||
+19
-11
@@ -18,9 +18,11 @@ Camera transformation helper code.
|
||||
"""
|
||||
|
||||
import math
|
||||
from typing import Tuple
|
||||
|
||||
import numpy as np
|
||||
import torch
|
||||
from torchtyping import TensorType
|
||||
|
||||
_EPS = np.finfo(float).eps * 4.0
|
||||
|
||||
@@ -257,24 +259,30 @@ def get_interpolated_K(KA, KB, steps=10):
|
||||
return Ks
|
||||
|
||||
|
||||
def get_interpolated_poses_many(list_of_poses, list_of_Ks, steps_per_transition=10):
|
||||
"""
|
||||
def get_interpolated_poses_many(
|
||||
poses: TensorType["num_poses", 3, 4],
|
||||
Ks: TensorType["num_poses", 3, 3],
|
||||
steps_per_transition=10,
|
||||
) -> Tuple[TensorType["num_poses", 3, 4], TensorType["num_poses", 3, 3]]:
|
||||
"""Return interpolated poses for many camera poses.
|
||||
|
||||
Args:
|
||||
list_of_poses
|
||||
steps
|
||||
distances_per_step
|
||||
poses: list of camera poses
|
||||
Ks: list of camera intrinsics
|
||||
steps_per_transition: number of steps per transition
|
||||
|
||||
Returns:
|
||||
tuple of new poses and intrinsics
|
||||
"""
|
||||
traj = []
|
||||
Ks = []
|
||||
for idx in range(len(list_of_poses) - 1):
|
||||
poseA = list_of_poses[idx]
|
||||
poseB = list_of_poses[idx + 1]
|
||||
# steps = int(np.linalg.norm(poseA[:3,3] - poseB[:3,3], ord=2) / distance_per_step)
|
||||
for idx in range(poses.shape[0] - 1):
|
||||
poseA = poses[idx]
|
||||
poseB = poses[idx + 1]
|
||||
posesAB = get_interpolated_poses(poseA, poseB, steps=steps_per_transition)
|
||||
traj += posesAB
|
||||
Ks += get_interpolated_K(list_of_Ks[idx], list_of_Ks[idx + 1], steps_per_transition)
|
||||
return traj, Ks
|
||||
Ks += get_interpolated_K(Ks[idx], Ks[idx + 1], steps_per_transition)
|
||||
return torch.stack(traj, dim=0), torch.stack(Ks, dim=0)
|
||||
|
||||
|
||||
def get_swirl_poses(pose):
|
||||
|
||||
Reference in new issue
Block a user