mirror of
https://github.com/nerfstudio-project/nerfstudio.git
synced 2026-12-01 13:28:59 +08:00
Rename to nerfstudio (#589)
This commit is contained in:
1 parent
fae01d3ca6
commit
1f83ad03db
210 files changed
+3400
-3413
No files matched your search
@@ -0,0 +1,13 @@
|
||||
# Copyright 2022 The Plenoptix Team. All rights reserved.
|
||||
#
|
||||
# Licensed under the Apache License, Version 2.0 (the "License");
|
||||
# you may not use this file except in compliance with the License.
|
||||
# You may obtain a copy of the License at
|
||||
#
|
||||
# http://www.apache.org/licenses/LICENSE-2.0
|
||||
#
|
||||
# Unless required by applicable law or agreed to in writing, software
|
||||
# distributed under the License is distributed on an "AS IS" BASIS,
|
||||
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
# See the License for the specific language governing permissions and
|
||||
# limitations under the License.
|
||||
@@ -0,0 +1,140 @@
|
||||
# Copyright 2022 The Plenoptix Team. All rights reserved.
|
||||
#
|
||||
# Licensed under the Apache License, Version 2.0 (the "License");
|
||||
# you may not use this file except in compliance with the License.
|
||||
# You may obtain a copy of the License at
|
||||
#
|
||||
# http://www.apache.org/licenses/LICENSE-2.0
|
||||
#
|
||||
# Unless required by applicable law or agreed to in writing, software
|
||||
# distributed under the License is distributed on an "AS IS" BASIS,
|
||||
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
# See the License for the specific language governing permissions and
|
||||
# limitations under the License.
|
||||
|
||||
"""
|
||||
Code for camera paths.
|
||||
"""
|
||||
|
||||
from typing import Any, Dict, Optional, Tuple
|
||||
|
||||
import torch
|
||||
|
||||
import nerfstudio.cameras.utils as camera_utils
|
||||
import nerfstudio.utils.poses as pose_utils
|
||||
from nerfstudio.cameras.cameras import Cameras
|
||||
from nerfstudio.cameras.utils import get_interpolated_poses_many
|
||||
from nerfstudio.viewer.server.utils import three_js_perspective_camera_focal_length
|
||||
|
||||
|
||||
def get_interpolated_camera_path(cameras: Cameras, steps: int) -> Cameras:
|
||||
"""Generate a camera path between two cameras.
|
||||
|
||||
Args:
|
||||
cameras: Cameras object containing intrinsics of all cameras.
|
||||
steps: The number of steps to interpolate between the two cameras.
|
||||
|
||||
Returns:
|
||||
A new set of cameras along a path.
|
||||
"""
|
||||
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 = 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: Cameras,
|
||||
steps: int = 30,
|
||||
radius: Optional[float] = None,
|
||||
radiuses: Optional[Tuple[float]] = None,
|
||||
rots: int = 2,
|
||||
zrate: float = 0.5,
|
||||
) -> Cameras:
|
||||
"""
|
||||
Returns a list of camera in a sprial trajectory.
|
||||
|
||||
Args:
|
||||
camera: The camera to start the spiral from.
|
||||
steps: The number of cameras in the generated path.
|
||||
radius: The radius of the spiral for all xyz directions.
|
||||
radiuses: The list of radii for the spiral in xyz directions.
|
||||
rots: The number of rotations to apply to the camera.
|
||||
zrate: How much to change the z position of the camera.
|
||||
|
||||
Returns:
|
||||
A spiral camera path.
|
||||
"""
|
||||
|
||||
assert radius is not None or radiuses is not None, "Either radius or radiuses must be specified."
|
||||
if radius is not None and radiuses is None:
|
||||
rad = torch.tensor([radius] * 3, device=camera.device)
|
||||
elif radiuses is not None and radius is None:
|
||||
rad = torch.tensor(radiuses, device=camera.device)
|
||||
else:
|
||||
raise ValueError("Only one of radius or radiuses must be specified.")
|
||||
|
||||
up = camera.camera_to_worlds[0, :3, 2] # scene is z up
|
||||
focal = torch.min(camera.fx[0], camera.fy[0])
|
||||
target = torch.tensor([0, 0, -focal], device=camera.device) # camera looking in -z direction
|
||||
|
||||
c2w = camera.camera_to_worlds[0]
|
||||
c2wh_global = pose_utils.to4x4(c2w)
|
||||
|
||||
local_c2whs = []
|
||||
for theta in torch.linspace(0.0, 2.0 * torch.pi * rots, steps + 1)[:-1]:
|
||||
center = (
|
||||
torch.tensor([torch.cos(theta), -torch.sin(theta), -torch.sin(theta * zrate)], device=camera.device) * rad
|
||||
)
|
||||
lookat = center - target
|
||||
c2w = camera_utils.viewmatrix(lookat, up, center)
|
||||
c2wh = pose_utils.to4x4(c2w)
|
||||
local_c2whs.append(c2wh)
|
||||
|
||||
new_c2ws = []
|
||||
for local_c2wh in local_c2whs:
|
||||
c2wh = torch.matmul(c2wh_global, local_c2wh)
|
||||
new_c2ws.append(c2wh[:3, :4])
|
||||
new_c2ws = torch.stack(new_c2ws, dim=0)
|
||||
|
||||
return Cameras(fx=camera.fx[0], fy=camera.fy[0], cx=camera.cx, cy=camera.cy, camera_to_worlds=new_c2ws)
|
||||
|
||||
|
||||
def get_path_from_json(camera_path: Dict[str, Any]) -> Cameras:
|
||||
"""Takes a camera path dictionary and returns a trajectory as a Camera instance.
|
||||
|
||||
Args:
|
||||
camera_path: A dictionary of the camera path information coming from the viewer.
|
||||
|
||||
Returns:
|
||||
A Cameras instance with the camera path.
|
||||
"""
|
||||
|
||||
image_height = camera_path["render_height"]
|
||||
image_width = camera_path["render_width"]
|
||||
|
||||
c2ws = []
|
||||
fxs = []
|
||||
fys = []
|
||||
for camera in camera_path["camera_path"]:
|
||||
# pose
|
||||
c2w = torch.tensor(camera["camera_to_world"]).view(4, 4)[:3]
|
||||
c2ws.append(c2w)
|
||||
# field of view
|
||||
fov = camera["fov"]
|
||||
focal_length = three_js_perspective_camera_focal_length(fov, image_height)
|
||||
fxs.append(focal_length)
|
||||
fys.append(focal_length)
|
||||
|
||||
camera_to_worlds = torch.stack(c2ws, dim=0)
|
||||
fx = torch.tensor(fxs)
|
||||
fy = torch.tensor(fys)
|
||||
return Cameras(
|
||||
fx=fx,
|
||||
fy=fy,
|
||||
cx=image_width / 2,
|
||||
cy=image_height / 2,
|
||||
camera_to_worlds=camera_to_worlds,
|
||||
)
|
||||
@@ -0,0 +1,313 @@
|
||||
# Copyright 2022 The Plenoptix Team. All rights reserved.
|
||||
#
|
||||
# Licensed under the Apache License, Version 2.0 (the "License");
|
||||
# you may not use this file except in compliance with the License.
|
||||
# You may obtain a copy of the License at
|
||||
#
|
||||
# http://www.apache.org/licenses/LICENSE-2.0
|
||||
#
|
||||
# Unless required by applicable law or agreed to in writing, software
|
||||
# distributed under the License is distributed on an "AS IS" BASIS,
|
||||
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
# See the License for the specific language governing permissions and
|
||||
# limitations under the License.
|
||||
|
||||
"""
|
||||
Camera Models
|
||||
"""
|
||||
import base64
|
||||
import math
|
||||
from enum import Enum, auto
|
||||
from typing import Dict, Optional, Union
|
||||
|
||||
import cv2
|
||||
import torch
|
||||
import torchvision
|
||||
from torch.nn.functional import normalize
|
||||
from torchtyping import TensorType
|
||||
|
||||
from nerfstudio.cameras import utils as camera_utils
|
||||
from nerfstudio.cameras.rays import RayBundle
|
||||
|
||||
|
||||
class CameraType(Enum):
|
||||
"""Supported camera types."""
|
||||
|
||||
PERSPECTIVE = auto()
|
||||
FISHEYE = auto()
|
||||
|
||||
|
||||
CAMERA_MODEL_TO_TYPE = {
|
||||
"SIMPLE_PINHOLE": CameraType.PERSPECTIVE,
|
||||
"PINHOLE": CameraType.PERSPECTIVE,
|
||||
"SIMPLE_RADIAL": CameraType.PERSPECTIVE,
|
||||
"RADIAL": CameraType.PERSPECTIVE,
|
||||
"OPENCV": CameraType.PERSPECTIVE,
|
||||
"OPENCV_FISHEYE": CameraType.FISHEYE,
|
||||
}
|
||||
|
||||
|
||||
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_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.
|
||||
width: Image width.
|
||||
height: Image height.
|
||||
distortion_params: OpenCV 6 radial distortion coefficients.
|
||||
camera_type: Type of camera model.
|
||||
"""
|
||||
|
||||
def __init__(
|
||||
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,
|
||||
width: Optional[int] = None,
|
||||
height: Optional[int] = None,
|
||||
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) if height is None else height
|
||||
self._image_widths = int(self.cx * 2) if width is None else width
|
||||
self.camera_type = camera_type
|
||||
|
||||
@property
|
||||
def device(self):
|
||||
"""Returns the device that the camera is on."""
|
||||
return self.camera_to_worlds.device
|
||||
|
||||
@property
|
||||
def size(self) -> int:
|
||||
"""Returns the number of cameras."""
|
||||
return self._num_cameras
|
||||
|
||||
@property
|
||||
def image_height(self) -> int:
|
||||
"""Returns the height of the images."""
|
||||
return self._image_heights
|
||||
|
||||
@property
|
||||
def image_width(self) -> int:
|
||||
"""Returns the height of the images."""
|
||||
return self._image_widths
|
||||
|
||||
def to(self, device: Union[torch.device, str]) -> "Cameras":
|
||||
"""
|
||||
Args:
|
||||
device: Device to move the camera onto
|
||||
|
||||
Returns:
|
||||
Cameras on the specified device.
|
||||
"""
|
||||
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,
|
||||
width=self.image_width,
|
||||
height=self.image_height,
|
||||
distortion_params=distortion_params,
|
||||
camera_type=self.camera_type,
|
||||
)
|
||||
|
||||
def get_image_coords(self, pixel_offset: float = 0.5) -> TensorType["height", "width", 2]:
|
||||
"""
|
||||
Args:
|
||||
pixel_offset: Offset for each pixel. Defaults to center of pixel (0.5)
|
||||
|
||||
Returns:
|
||||
Grid of image coordinates.
|
||||
"""
|
||||
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
|
||||
|
||||
def generate_rays(
|
||||
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:
|
||||
"""Generates rays for the given camera indices.
|
||||
|
||||
TODO - add support for intrinsics delta.
|
||||
TODO - add support for distortions.
|
||||
|
||||
Args:
|
||||
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:
|
||||
Rays for the given camera indices and coords.
|
||||
"""
|
||||
|
||||
if isinstance(camera_indices, torch.Tensor):
|
||||
camera_indices = camera_indices.to(self.device)
|
||||
|
||||
if coords is None:
|
||||
coords = self.get_image_coords().to(self.device)
|
||||
|
||||
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
|
||||
|
||||
coord = torch.stack([(x - cx) / fx, -(y - cy) / fy], -1)
|
||||
coord_x_offset = torch.stack([(x - cx + 1) / fx, -(y - cy) / fy], -1)
|
||||
coord_y_offset = torch.stack([(x - cx) / fx, -(y - cy + 1) / fy], -1)
|
||||
|
||||
coord_stack = torch.stack([coord, coord_x_offset, coord_y_offset], dim=0)
|
||||
|
||||
distortion_params = None
|
||||
if self.distortion_params is not None:
|
||||
distortion_params = self.distortion_params[camera_indices]
|
||||
if distortion_params_delta is not None:
|
||||
distortion_params = distortion_params + distortion_params_delta
|
||||
elif distortion_params_delta is not None:
|
||||
distortion_params = distortion_params_delta
|
||||
|
||||
if distortion_params is not None:
|
||||
coord_stack = camera_utils.radial_and_tangential_undistort(coord_stack, distortion_params)
|
||||
|
||||
if self.camera_type == CameraType.PERSPECTIVE:
|
||||
directions_stack = torch.stack(
|
||||
[coord_stack[..., 0], coord_stack[..., 1], -torch.ones_like(coord_stack[..., 1])], dim=-1
|
||||
)
|
||||
elif self.camera_type == CameraType.FISHEYE:
|
||||
theta = torch.sqrt(torch.sum(coord_stack**2, dim=-1))
|
||||
theta = torch.clip(theta, 0.0, math.pi)
|
||||
|
||||
sin_theta = torch.sin(theta)
|
||||
directions_stack = torch.stack(
|
||||
[
|
||||
coord_stack[..., 0] * sin_theta / theta,
|
||||
coord_stack[..., 1] * sin_theta / theta,
|
||||
-torch.cos(theta),
|
||||
],
|
||||
dim=-1,
|
||||
)
|
||||
else:
|
||||
raise ValueError(f"Camera type {self.camera_type} not supported.")
|
||||
|
||||
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_stack = normalize(directions_stack, dim=-1)
|
||||
|
||||
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)[..., None]
|
||||
|
||||
if not isinstance(camera_indices, torch.Tensor):
|
||||
ray_bundle_camera_indices = torch.Tensor([camera_indices]).broadcast_to(pixel_area.shape).to(self.device)
|
||||
else:
|
||||
ray_bundle_camera_indices = camera_indices.view(pixel_area.shape)
|
||||
|
||||
return RayBundle(
|
||||
origins=origins,
|
||||
directions=directions,
|
||||
pixel_area=pixel_area,
|
||||
camera_indices=ray_bundle_camera_indices,
|
||||
)
|
||||
|
||||
def to_json(
|
||||
self,
|
||||
camera_idx: int,
|
||||
image: Optional[TensorType["height", "width", 2]] = None,
|
||||
max_size: Optional[int] = None,
|
||||
) -> Dict:
|
||||
"""Convert a camera to a json dictionary.
|
||||
|
||||
Args:
|
||||
camera_idx: Index of the camera to convert.
|
||||
image: An image in range [0, 1] that is encoded to a base64 string.
|
||||
max_size: Max size to resize the image to if present.
|
||||
|
||||
Returns:
|
||||
A JSON representation of the camera
|
||||
"""
|
||||
json_ = {
|
||||
"type": "PinholeCamera",
|
||||
"cx": self.cx,
|
||||
"cy": self.cy,
|
||||
"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().type(torch.uint8)
|
||||
if max_size is not None:
|
||||
image_uint8 = image_uint8.permute(2, 0, 1)
|
||||
image_uint8 = torchvision.transforms.functional.resize(image_uint8, max_size) # type: ignore
|
||||
image_uint8 = image_uint8.permute(1, 2, 0)
|
||||
image_uint8 = image_uint8.cpu().numpy()
|
||||
data = cv2.imencode(".jpg", image_uint8)[1].tobytes()
|
||||
json_["image"] = str("data:image/jpeg;base64," + base64.b64encode(data).decode("ascii"))
|
||||
return json_
|
||||
|
||||
def get_intrinsics_matrices(self) -> TensorType["num_cameras", 3, 3]:
|
||||
"""Returns the intrinsic matrices for each camera.
|
||||
|
||||
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:
|
||||
"""Rescale the output resolution of the cameras.
|
||||
|
||||
Args:
|
||||
scaling_factor: Scaling factor to apply to the output resolution.
|
||||
"""
|
||||
self.fx = self.fx * scaling_factor
|
||||
self.fy = self.fy * scaling_factor
|
||||
self.cx = self.cx * scaling_factor
|
||||
self.cy = self.cy * scaling_factor
|
||||
self._image_heights = int(self._image_heights * scaling_factor)
|
||||
self._image_widths = int(self._image_widths * scaling_factor)
|
||||
@@ -0,0 +1,265 @@
|
||||
# Copyright 2022 The Plenoptix Team. All rights reserved.
|
||||
#
|
||||
# Licensed under the Apache License, Version 2.0 (the "License");
|
||||
# you may not use this file except in compliance with the License.
|
||||
# You may obtain a copy of the License at
|
||||
#
|
||||
# http://www.apache.org/licenses/LICENSE-2.0
|
||||
#
|
||||
# Unless required by applicable law or agreed to in writing, software
|
||||
# distributed under the License is distributed on an "AS IS" BASIS,
|
||||
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
# See the License for the specific language governing permissions and
|
||||
# limitations under the License.
|
||||
|
||||
"""
|
||||
Some ray datastructures.
|
||||
"""
|
||||
import random
|
||||
from dataclasses import dataclass
|
||||
from typing import Callable, Dict, Optional
|
||||
|
||||
import torch
|
||||
from torchtyping import TensorType
|
||||
|
||||
from nerfstudio.utils.math import Gaussians, conical_frustum_to_gaussian
|
||||
from nerfstudio.utils.tensor_dataclass import TensorDataclass
|
||||
|
||||
|
||||
@dataclass
|
||||
class Frustums(TensorDataclass):
|
||||
"""Describes region of space as a frustum."""
|
||||
|
||||
origins: TensorType["bs":..., 3]
|
||||
"""xyz coordinate for ray origin."""
|
||||
directions: TensorType["bs":..., 3]
|
||||
"""Direction of ray."""
|
||||
starts: TensorType["bs":..., 1]
|
||||
"""Where the frustum starts along a ray."""
|
||||
ends: TensorType["bs":..., 1]
|
||||
"""Where the frustum ends along a ray."""
|
||||
pixel_area: TensorType["bs":..., 1]
|
||||
"""Projected area of pixel a distance 1 away from origin."""
|
||||
|
||||
def get_positions(self) -> TensorType[..., 3]:
|
||||
"""Calulates "center" position of frustum. Not weighted by mass.
|
||||
|
||||
Returns:
|
||||
xyz positions.
|
||||
"""
|
||||
return self.origins + self.directions * (self.starts + self.ends) / 2
|
||||
|
||||
def get_gaussian_blob(self) -> Gaussians:
|
||||
"""Calculates guassian approximation of conical frustum.
|
||||
|
||||
Resturns:
|
||||
Conical frustums approximated by gaussian distribution.
|
||||
"""
|
||||
# Cone radius is set such that the square pixel_area matches the cone area.
|
||||
cone_radius = torch.sqrt(self.pixel_area) / 1.7724538509055159 # r = sqrt(pixel_area / pi)
|
||||
return conical_frustum_to_gaussian(
|
||||
origins=self.origins,
|
||||
directions=self.directions,
|
||||
starts=self.starts,
|
||||
ends=self.ends,
|
||||
radius=cone_radius,
|
||||
)
|
||||
|
||||
@classmethod
|
||||
def get_mock_frustum(cls, device="cpu") -> "Frustums":
|
||||
"""Helper function to generate a placeholder frustum.
|
||||
|
||||
Returns:
|
||||
A size 1 frustum with meaningless values.
|
||||
"""
|
||||
return Frustums(
|
||||
origins=torch.ones((1, 3)).to(device),
|
||||
directions=torch.ones((1, 3)).to(device),
|
||||
starts=torch.ones((1, 1)).to(device),
|
||||
ends=torch.ones((1, 1)).to(device),
|
||||
pixel_area=torch.ones((1, 1)).to(device),
|
||||
)
|
||||
|
||||
|
||||
@dataclass
|
||||
class RaySamples(TensorDataclass):
|
||||
"""Samples along a ray"""
|
||||
|
||||
frustums: Frustums
|
||||
"""Frustums along ray."""
|
||||
camera_indices: Optional[TensorType["bs":..., 1]] = None
|
||||
"""Camera index."""
|
||||
valid_mask: Optional[TensorType["bs":..., 1]] = None
|
||||
"""Rays that are valid."""
|
||||
deltas: Optional[TensorType["bs":..., 1]] = None
|
||||
""""width" of each sample."""
|
||||
spacing_starts: Optional[TensorType["bs":..., "num_samples", 1]] = None
|
||||
"""Start of normalized bin edges along ray [0,1], before warping is applied, ie. linear in disparity sampling."""
|
||||
spacing_ends: Optional[TensorType["bs":..., "num_samples", 1]] = None
|
||||
"""Start of normalized bin edges along ray [0,1], before warping is applied, ie. linear in disparity sampling."""
|
||||
spacing_to_euclidean_fn: Optional[Callable] = None
|
||||
"""Function to convert bins to euclidean distance."""
|
||||
metadata: Optional[Dict[str, TensorType["bs":..., "latent_dims"]]] = None
|
||||
"""addtional information relevant to generating ray samples"""
|
||||
|
||||
def get_weights(self, densities: TensorType[..., "num_samples", 1]) -> TensorType[..., "num_samples", 1]:
|
||||
"""Return weights based on predicted densities
|
||||
|
||||
Args:
|
||||
densities: Predicted densities for samples along ray
|
||||
|
||||
Returns:
|
||||
Weights for each sample
|
||||
"""
|
||||
|
||||
delta_density = self.deltas * densities
|
||||
alphas = 1 - torch.exp(-delta_density)
|
||||
|
||||
# TODO: put both versions of the transmittance calculation somewhere
|
||||
# mip-nerf version of transmittance calculation:
|
||||
transmittance = torch.cumsum(delta_density[..., :-1, :], dim=-2)
|
||||
transmittance = torch.cat(
|
||||
[torch.zeros((*transmittance.shape[:1], 1, 1), device=densities.device), transmittance], dim=-2
|
||||
)
|
||||
transmittance = torch.exp(-transmittance) # [..., "num_samples"]
|
||||
|
||||
# most nerf codebases do the following:
|
||||
# transmittance = torch.cat(
|
||||
# [torch.ones((*alphas.shape[:1], 1)).to(densities.device), 1.0 - alphas + 1e-10], dim=-1
|
||||
# )
|
||||
# transmittance = torch.cumprod(transmittance, dim=-1)[..., :-1] # [..., "num_samples"]
|
||||
|
||||
weights = alphas * transmittance # [..., "num_samples"]
|
||||
|
||||
return weights
|
||||
|
||||
def set_valid_mask(self, valid_mask: TensorType[..., "num_samples"]) -> None:
|
||||
"""Sets valid mask
|
||||
|
||||
Args:
|
||||
valid_mask: the mask to use
|
||||
"""
|
||||
self.valid_mask = valid_mask
|
||||
|
||||
def apply_masks(self) -> "RaySamples":
|
||||
"""Use valid_mask to mask samples.
|
||||
|
||||
Returns:
|
||||
New set of masked samples.
|
||||
"""
|
||||
if self.valid_mask is not None:
|
||||
return self[self.valid_mask[..., 0]]
|
||||
return self
|
||||
|
||||
|
||||
@dataclass
|
||||
class RayBundle(TensorDataclass):
|
||||
"""A bundle of ray parameters."""
|
||||
|
||||
# TODO(ethan): make sure the sizes with ... are correct
|
||||
origins: TensorType[..., 3]
|
||||
"""Ray origins (XYZ)"""
|
||||
directions: TensorType[..., 3]
|
||||
"""Unit ray direction vector"""
|
||||
pixel_area: TensorType[..., 1]
|
||||
"""Projected area of pixel a distance 1 away from origin"""
|
||||
camera_indices: Optional[TensorType[..., 1]] = None
|
||||
"""Camera indices"""
|
||||
nears: Optional[TensorType[..., 1]] = None
|
||||
"""Distance along ray to start sampling"""
|
||||
fars: Optional[TensorType[..., 1]] = None
|
||||
"""Rays Distance along ray to stop sampling"""
|
||||
valid_mask: Optional[TensorType[..., 1, bool]] = None
|
||||
"""Rays that are valid"""
|
||||
metadata: Optional[Dict[str, TensorType["num_rays", "latent_dims"]]] = None
|
||||
"""Additional metadata or data needed for interpolation, will mimic shape of rays"""
|
||||
|
||||
def set_camera_indices(self, camera_index: int) -> None:
|
||||
"""Sets all of the the camera indices to a specific camera index.
|
||||
|
||||
Args:
|
||||
camera_index: Camera index.
|
||||
"""
|
||||
self.camera_indices = torch.ones_like(self.origins[..., 0:1]).long() * camera_index
|
||||
|
||||
def __len__(self):
|
||||
num_rays = torch.numel(self.origins) // self.origins.shape[-1]
|
||||
return num_rays
|
||||
|
||||
def sample(self, num_rays: int) -> "RayBundle":
|
||||
"""Returns a RayBundle as a subset of rays.
|
||||
|
||||
Args:
|
||||
num_rays: Number of rays in output RayBundle
|
||||
|
||||
Returns:
|
||||
RayBundle with subset of rays.
|
||||
"""
|
||||
assert num_rays <= len(self)
|
||||
indices = random.sample(range(len(self)), k=num_rays)
|
||||
return self[indices]
|
||||
|
||||
def get_row_major_sliced_ray_bundle(self, start_idx: int, end_idx: int) -> "RayBundle":
|
||||
"""Flattens RayBundle and extracts chunk given start and end indicies.
|
||||
|
||||
Args:
|
||||
start_idx: Start index of RayBundle chunk.
|
||||
end_idx: End index of RayBundle chunk.
|
||||
|
||||
Returns:
|
||||
Flattened RayBundle with end_idx-start_idx rays.
|
||||
|
||||
"""
|
||||
return self.flatten()[start_idx:end_idx]
|
||||
|
||||
def get_ray_samples(
|
||||
self,
|
||||
bin_starts: TensorType["bs":..., "num_samples", 1],
|
||||
bin_ends: TensorType["bs":..., "num_samples", 1],
|
||||
spacing_starts: Optional[TensorType["bs":..., "num_samples", 1]],
|
||||
spacing_ends: Optional[TensorType["bs":..., "num_samples", 1]],
|
||||
spacing_to_euclidean_fn: Optional[Callable],
|
||||
) -> RaySamples:
|
||||
"""Produces samples for each ray by projection points along the ray direction. Currently samples uniformly.
|
||||
|
||||
Args:
|
||||
bin_starts: Distance from origin to start of bin.
|
||||
bin_ends: Distance from origin to end of bin.
|
||||
|
||||
Returns:
|
||||
Samples projected along ray.
|
||||
"""
|
||||
device = self.origins.device
|
||||
|
||||
valid_mask = torch.ones((bin_starts.shape), dtype=torch.bool, device=device)
|
||||
|
||||
dists = bin_ends - bin_starts # [..., num_samples, 1]
|
||||
deltas = dists * torch.norm(self.directions[:, :], dim=-1)[..., None, None]
|
||||
|
||||
if self.camera_indices is not None:
|
||||
camera_indices = self.camera_indices[..., None]
|
||||
else:
|
||||
camera_indices = None
|
||||
|
||||
shaped_raybundle_fields = self[..., None]
|
||||
|
||||
frustums = Frustums(
|
||||
origins=shaped_raybundle_fields.origins, # [..., 1, 3]
|
||||
directions=shaped_raybundle_fields.directions, # [..., 1, 3]
|
||||
starts=bin_starts, # [..., num_samples, 1]
|
||||
ends=bin_ends, # [..., num_samples, 1]
|
||||
pixel_area=shaped_raybundle_fields.pixel_area, # [..., 1, 1]
|
||||
).to(device)
|
||||
|
||||
ray_samples = RaySamples(
|
||||
frustums=frustums,
|
||||
camera_indices=camera_indices, # [..., 1, 1]
|
||||
valid_mask=valid_mask, # [..., num_samples, 1]
|
||||
deltas=deltas, # [..., num_samples, 1]
|
||||
spacing_starts=spacing_starts, # [..., num_samples, 1]
|
||||
spacing_ends=spacing_ends, # [..., num_samples, 1]
|
||||
spacing_to_euclidean_fn=spacing_to_euclidean_fn,
|
||||
metadata=shaped_raybundle_fields.metadata,
|
||||
)
|
||||
|
||||
return ray_samples
|
||||
@@ -0,0 +1,477 @@
|
||||
# Copyright 2022 The Plenoptix Team. All rights reserved.
|
||||
#
|
||||
# Licensed under the Apache License, Version 2.0 (the "License");
|
||||
# you may not use this file except in compliance with the License.
|
||||
# You may obtain a copy of the License at
|
||||
#
|
||||
# http://www.apache.org/licenses/LICENSE-2.0
|
||||
#
|
||||
# Unless required by applicable law or agreed to in writing, software
|
||||
# distributed under the License is distributed on an "AS IS" BASIS,
|
||||
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
# See the License for the specific language governing permissions and
|
||||
# limitations under the License.
|
||||
|
||||
# pylint: skip-file
|
||||
"""
|
||||
Camera transformation helper code.
|
||||
"""
|
||||
|
||||
import math
|
||||
from turtle import width
|
||||
from typing import List, Literal, Optional, Tuple
|
||||
|
||||
import numpy as np
|
||||
import torch
|
||||
from torchtyping import TensorType
|
||||
|
||||
_EPS = np.finfo(float).eps * 4.0
|
||||
|
||||
|
||||
def unit_vector(data, axis: Optional[int] = None) -> np.ndarray:
|
||||
"""Return ndarray normalized by length, i.e. Euclidean norm, along axis.
|
||||
|
||||
Args:
|
||||
axis: the axis along which to normalize into unit vector
|
||||
out: where to write out the data to. If None, returns a new np ndarray
|
||||
"""
|
||||
data = np.array(data, dtype=np.float64, copy=True)
|
||||
if data.ndim == 1:
|
||||
data /= math.sqrt(np.dot(data, data))
|
||||
return data
|
||||
length = np.atleast_1d(np.sum(data * data, axis))
|
||||
np.sqrt(length, length)
|
||||
if axis is not None:
|
||||
length = np.expand_dims(length, axis)
|
||||
data /= length
|
||||
return data
|
||||
|
||||
|
||||
def quaternion_from_matrix(matrix, isprecise: bool = False) -> np.ndarray:
|
||||
"""Return quaternion from rotation matrix.
|
||||
|
||||
Args:
|
||||
matrix: rotation matrix to obtain quaternion
|
||||
isprecise: if True, input matrix is assumed to be precise rotation matrix and a faster algorithm is used.
|
||||
"""
|
||||
M = np.array(matrix, dtype=np.float64, copy=False)[:4, :4]
|
||||
if isprecise:
|
||||
q = np.empty((4,))
|
||||
t = np.trace(M)
|
||||
if t > M[3, 3]:
|
||||
q[0] = t
|
||||
q[3] = M[1, 0] - M[0, 1]
|
||||
q[2] = M[0, 2] - M[2, 0]
|
||||
q[1] = M[2, 1] - M[1, 2]
|
||||
else:
|
||||
i, j, k = 1, 2, 3
|
||||
if M[1, 1] > M[0, 0]:
|
||||
i, j, k = 2, 3, 1
|
||||
if M[2, 2] > M[i, i]:
|
||||
i, j, k = 3, 1, 2
|
||||
t = M[i, i] - (M[j, j] + M[k, k]) + M[3, 3]
|
||||
q[i] = t
|
||||
q[j] = M[i, j] + M[j, i]
|
||||
q[k] = M[k, i] + M[i, k]
|
||||
q[3] = M[k, j] - M[j, k]
|
||||
q *= 0.5 / math.sqrt(t * M[3, 3])
|
||||
else:
|
||||
m00 = M[0, 0]
|
||||
m01 = M[0, 1]
|
||||
m02 = M[0, 2]
|
||||
m10 = M[1, 0]
|
||||
m11 = M[1, 1]
|
||||
m12 = M[1, 2]
|
||||
m20 = M[2, 0]
|
||||
m21 = M[2, 1]
|
||||
m22 = M[2, 2]
|
||||
# symmetric matrix K
|
||||
K = np.array(
|
||||
[
|
||||
[m00 - m11 - m22, 0.0, 0.0, 0.0],
|
||||
[m01 + m10, m11 - m00 - m22, 0.0, 0.0],
|
||||
[m02 + m20, m12 + m21, m22 - m00 - m11, 0.0],
|
||||
[m21 - m12, m02 - m20, m10 - m01, m00 + m11 + m22],
|
||||
]
|
||||
)
|
||||
K /= 3.0
|
||||
# quaternion is eigenvector of K that corresponds to largest eigenvalue
|
||||
w, V = np.linalg.eigh(K)
|
||||
q = V[np.array([3, 0, 1, 2]), np.argmax(w)]
|
||||
if q[0] < 0.0:
|
||||
np.negative(q, q)
|
||||
return q
|
||||
|
||||
|
||||
def quaternion_slerp(quat0, quat1, fraction: float, spin: int = 0, shortestpath: bool = True) -> np.ndarray:
|
||||
"""Return spherical linear interpolation between two quaternions.
|
||||
Args:
|
||||
quat0: first quaternion
|
||||
quat1: second quaternion
|
||||
fraction: how much to interpolate between quat0 vs quat1 (if 0, closer to quat0; if 1, closer to quat1)
|
||||
spin: how much of an additional spin to place on the interpolation
|
||||
shortestpath: whether to return the short or long path to rotation
|
||||
"""
|
||||
q0 = unit_vector(quat0[:4])
|
||||
q1 = unit_vector(quat1[:4])
|
||||
if q0 is None or q1 is None:
|
||||
raise ValueError("Input quaternions invalid.")
|
||||
if fraction == 0.0:
|
||||
return q0
|
||||
elif fraction == 1.0:
|
||||
return q1
|
||||
d = np.dot(q0, q1)
|
||||
if abs(abs(d) - 1.0) < _EPS:
|
||||
return q0
|
||||
if shortestpath and d < 0.0:
|
||||
# invert rotation
|
||||
d = -d
|
||||
np.negative(q1, q1)
|
||||
angle = math.acos(d) + spin * math.pi
|
||||
if abs(angle) < _EPS:
|
||||
return q0
|
||||
isin = 1.0 / math.sin(angle)
|
||||
q0 *= math.sin((1.0 - fraction) * angle) * isin
|
||||
q1 *= math.sin(fraction * angle) * isin
|
||||
q0 += q1
|
||||
return q0
|
||||
|
||||
|
||||
def quaternion_matrix(quaternion) -> np.ndarray:
|
||||
"""Return homogeneous rotation matrix from quaternion.
|
||||
|
||||
Args:
|
||||
quaternion: value to convert to matrix
|
||||
"""
|
||||
q = np.array(quaternion, dtype=np.float64, copy=True)
|
||||
n = np.dot(q, q)
|
||||
if n < _EPS:
|
||||
return np.identity(4)
|
||||
q *= math.sqrt(2.0 / n)
|
||||
q = np.outer(q, q)
|
||||
return np.array(
|
||||
[
|
||||
[1.0 - q[2, 2] - q[3, 3], q[1, 2] - q[3, 0], q[1, 3] + q[2, 0], 0.0],
|
||||
[q[1, 2] + q[3, 0], 1.0 - q[1, 1] - q[3, 3], q[2, 3] - q[1, 0], 0.0],
|
||||
[q[1, 3] - q[2, 0], q[2, 3] + q[1, 0], 1.0 - q[1, 1] - q[2, 2], 0.0],
|
||||
[0.0, 0.0, 0.0, 1.0],
|
||||
]
|
||||
)
|
||||
|
||||
|
||||
def get_interpolated_poses(poseA, poseB, steps: int = 10) -> List[float]:
|
||||
"""Return interpolation of poses with specified number of steps.
|
||||
Args:
|
||||
poseA: first pose
|
||||
poseB: second pose
|
||||
steps: number of steps the interpolated pose path should contain
|
||||
"""
|
||||
|
||||
quatA = quaternion_from_matrix(poseA[:3, :3])
|
||||
quatB = quaternion_from_matrix(poseB[:3, :3])
|
||||
|
||||
ts = np.linspace(0, 1, steps)
|
||||
quats = [quaternion_slerp(quatA, quatB, t) for t in ts]
|
||||
trans = [(1 - t) * poseA[:3, 3] + t * poseB[:3, 3] for t in ts]
|
||||
|
||||
posesAB = []
|
||||
for quat, tran in zip(quats, trans):
|
||||
pose = np.identity(4)
|
||||
pose[:3, :3] = quaternion_matrix(quat)[:3, :3]
|
||||
pose[:3, 3] = tran
|
||||
posesAB.append(pose)
|
||||
return posesAB
|
||||
|
||||
|
||||
def get_interpolated_K(KA, KB, steps: int = 10) -> TensorType[3, 4]:
|
||||
"""
|
||||
Returns interpolated path between two camera poses with specified number of steps.
|
||||
|
||||
Args:
|
||||
KA: camera matrix 1
|
||||
KB: camera matrix 2
|
||||
steps: number of steps the interpolated pose path should contain
|
||||
"""
|
||||
Ks = []
|
||||
ts = np.linspace(0, 1, steps)
|
||||
for t in ts:
|
||||
newK = KA * (1.0 - t) + KB * t
|
||||
Ks.append(newK)
|
||||
return Ks
|
||||
|
||||
|
||||
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:
|
||||
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(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(Ks[idx], Ks[idx + 1], steps_per_transition)
|
||||
return torch.stack(traj, dim=0), torch.stack(Ks, dim=0)
|
||||
|
||||
|
||||
def get_swirl_poses(pose):
|
||||
"""
|
||||
Returns a swirl around the camera poses.
|
||||
# TODO(ethan): add parameters and make this work + add docstrings + return type
|
||||
"""
|
||||
N_frames = 30 * 4
|
||||
dx = np.linspace(0, 0.03, N_frames)
|
||||
dy = np.linspace(0, -0.1, N_frames)
|
||||
dz = np.linspace(0, 0.5, N_frames)
|
||||
poses = np.tile(pose, (N_frames, 1, 1))
|
||||
for i in range(N_frames):
|
||||
poses[i, 0, 3] += dx[i]
|
||||
poses[i, 1, 3] += dy[i]
|
||||
poses[i, 2, 3] += dz[i]
|
||||
return poses
|
||||
|
||||
|
||||
def normalize(x) -> TensorType[...]:
|
||||
"""Returns a normalized vector."""
|
||||
return x / torch.linalg.norm(x)
|
||||
|
||||
|
||||
def viewmatrix(lookat, up, pos) -> TensorType[...]:
|
||||
"""Returns a camera transformation matrix.
|
||||
|
||||
Args:
|
||||
lookat: The direction the camera is looking.
|
||||
up: The upward direction of the camera.
|
||||
pos: The position of the camera.
|
||||
|
||||
Returns:
|
||||
A camera transformation matrix.
|
||||
"""
|
||||
vec2 = normalize(lookat)
|
||||
vec1_avg = normalize(up)
|
||||
vec0 = normalize(torch.cross(vec1_avg, vec2))
|
||||
vec1 = normalize(torch.cross(vec2, vec0))
|
||||
m = torch.stack([vec0, vec1, vec2, pos], 1)
|
||||
return m
|
||||
|
||||
|
||||
def get_distortion_params(
|
||||
k1: float = 0.0,
|
||||
k2: float = 0.0,
|
||||
k3: float = 0.0,
|
||||
k4: float = 0.0,
|
||||
p1: float = 0.0,
|
||||
p2: float = 0.0,
|
||||
) -> TensorType[...]:
|
||||
"""Returns a distortion parameters matrix.
|
||||
|
||||
Args:
|
||||
k1: The first radial distortion parameter.
|
||||
k2: The second radial distortion parameter.
|
||||
k3: The third radial distortion parameter.
|
||||
k4: The fourth radial distortion parameter.
|
||||
p1: The first tangential distortion parameter.
|
||||
p2: The second tangential distortion parameter.
|
||||
Returns:
|
||||
torch.Tensor: A distortion parameters matrix.
|
||||
"""
|
||||
return torch.Tensor([k1, k2, k3, k4, p1, p2])
|
||||
|
||||
|
||||
def radial_and_tangential_undistort(
|
||||
coords: TensorType["num_coords":..., 2],
|
||||
distortion_params: TensorType["num_coords":..., 6],
|
||||
eps: float = 1e-9,
|
||||
max_iterations=10,
|
||||
) -> TensorType["num_coords":..., 2]:
|
||||
"""Computes undistorted coords given opencv distortion parameters.
|
||||
Addapted from MultiNeRF
|
||||
https://github.com/google-research/multinerf/blob/b02228160d3179300c7d499dca28cb9ca3677f32/internal/camera_utils.py#L477-L509
|
||||
|
||||
Args:
|
||||
coords: The distorted coordinates.
|
||||
distortion_params: The distortion parameters [k1, k2, k3, k4, p1, p2].
|
||||
eps: The epsilon for the convergence.
|
||||
max_iterations: The maximum number of iterations to perform.
|
||||
|
||||
Returns:
|
||||
The undistorted coordinates.
|
||||
"""
|
||||
|
||||
# Initialize from the distorted point.
|
||||
x = torch.clone(coords[..., 0])
|
||||
y = torch.clone(coords[..., 1])
|
||||
|
||||
for _ in range(max_iterations):
|
||||
fx, fy, fx_x, fx_y, fy_x, fy_y = _compute_residual_and_jacobian(
|
||||
x=x, y=y, xd=coords[..., 0], yd=coords[..., 1], distortion_params=distortion_params
|
||||
)
|
||||
denominator = fy_x * fx_y - fx_x * fy_y
|
||||
x_numerator = fx * fy_y - fy * fx_y
|
||||
y_numerator = fy * fx_x - fx * fy_x
|
||||
step_x = torch.where(torch.abs(denominator) > eps, x_numerator / denominator, torch.zeros_like(denominator))
|
||||
step_y = torch.where(torch.abs(denominator) > eps, y_numerator / denominator, torch.zeros_like(denominator))
|
||||
|
||||
x = x + step_x
|
||||
y = y + step_y
|
||||
|
||||
return torch.stack([x, y], dim=-1)
|
||||
|
||||
|
||||
def _compute_residual_and_jacobian(
|
||||
x: TensorType["num_coords":...],
|
||||
y: TensorType["num_coords":...],
|
||||
xd: TensorType["num_coords":...],
|
||||
yd: TensorType["num_coords":...],
|
||||
distortion_params: TensorType["num_coords":..., 6],
|
||||
) -> Tuple[
|
||||
TensorType["num_coords":...],
|
||||
TensorType["num_coords":...],
|
||||
TensorType["num_coords":...],
|
||||
TensorType["num_coords":...],
|
||||
TensorType["num_coords":...],
|
||||
TensorType["num_coords":...],
|
||||
]:
|
||||
"""Auxiliary function of radial_and_tangential_undistort() that computes residuals and jacobians.
|
||||
Adapted from MultiNeRF:
|
||||
https://github.com/google-research/multinerf/blob/b02228160d3179300c7d499dca28cb9ca3677f32/internal/camera_utils.py#L427-L474
|
||||
|
||||
Args:
|
||||
x: The updated x coordinates.
|
||||
y: The updated y coordinates.
|
||||
xd: The distorted x coordinates.
|
||||
yd: The distorted y coordinates.
|
||||
distortion_params: The distortion parameters [k1, k2, k3, k4, p1, p2].
|
||||
|
||||
Returns:
|
||||
The residuals (fx, fy) and jacobians (fx_x, fx_y, fy_x, fy_y).
|
||||
"""
|
||||
|
||||
k1 = distortion_params[..., 0]
|
||||
k2 = distortion_params[..., 1]
|
||||
k3 = distortion_params[..., 2]
|
||||
k4 = distortion_params[..., 3]
|
||||
p1 = distortion_params[..., 4]
|
||||
p2 = distortion_params[..., 5]
|
||||
|
||||
# let r(x, y) = x^2 + y^2;
|
||||
# d(x, y) = 1 + k1 * r(x, y) + k2 * r(x, y) ^2 + k3 * r(x, y)^3 +
|
||||
# k4 * r(x, y)^4;
|
||||
r = x * x + y * y
|
||||
d = 1.0 + r * (k1 + r * (k2 + r * (k3 + r * k4)))
|
||||
|
||||
# The perfect projection is:
|
||||
# xd = x * d(x, y) + 2 * p1 * x * y + p2 * (r(x, y) + 2 * x^2);
|
||||
# yd = y * d(x, y) + 2 * p2 * x * y + p1 * (r(x, y) + 2 * y^2);
|
||||
#
|
||||
# Let's define
|
||||
#
|
||||
# fx(x, y) = x * d(x, y) + 2 * p1 * x * y + p2 * (r(x, y) + 2 * x^2) - xd;
|
||||
# fy(x, y) = y * d(x, y) + 2 * p2 * x * y + p1 * (r(x, y) + 2 * y^2) - yd;
|
||||
#
|
||||
# We are looking for a solution that satisfies
|
||||
# fx(x, y) = fy(x, y) = 0;
|
||||
fx = d * x + 2 * p1 * x * y + p2 * (r + 2 * x * x) - xd
|
||||
fy = d * y + 2 * p2 * x * y + p1 * (r + 2 * y * y) - yd
|
||||
|
||||
# Compute derivative of d over [x, y]
|
||||
d_r = k1 + r * (2.0 * k2 + r * (3.0 * k3 + r * 4.0 * k4))
|
||||
d_x = 2.0 * x * d_r
|
||||
d_y = 2.0 * y * d_r
|
||||
|
||||
# Compute derivative of fx over x and y.
|
||||
fx_x = d + d_x * x + 2.0 * p1 * y + 6.0 * p2 * x
|
||||
fx_y = d_y * x + 2.0 * p1 * x + 2.0 * p2 * y
|
||||
|
||||
# Compute derivative of fy over x and y.
|
||||
fy_x = d_x * y + 2.0 * p2 * y + 2.0 * p1 * x
|
||||
fy_y = d + d_y * y + 2.0 * p2 * x + 6.0 * p1 * y
|
||||
|
||||
return fx, fy, fx_x, fx_y, fy_x, fy_y
|
||||
|
||||
|
||||
def rotation_matrix(a: TensorType[3], b: TensorType[3]) -> TensorType[3, 3]:
|
||||
"""Compute the rotation matrix that rotates vector a to vector b.
|
||||
|
||||
Args:
|
||||
a: The vector to rotate.
|
||||
b: The vector to rotate to.
|
||||
Returns:
|
||||
The rotation matrix.
|
||||
"""
|
||||
a = a / torch.linalg.norm(a)
|
||||
b = b / torch.linalg.norm(b)
|
||||
v = torch.cross(a, b)
|
||||
c = torch.dot(a, b)
|
||||
# If vectors are exactly opposite, we add a little noise to one of them
|
||||
if c < -1 + 1e-8:
|
||||
eps = (torch.rand(3) - 0.5) * 0.01
|
||||
return rotmat(a + eps, b)
|
||||
s = torch.linalg.norm(v)
|
||||
skew_sym_mat = torch.Tensor(
|
||||
[
|
||||
[0, -v[2], v[1]],
|
||||
[v[2], 0, -v[0]],
|
||||
[-v[1], v[0], 0],
|
||||
]
|
||||
)
|
||||
return torch.eye(3) + skew_sym_mat + skew_sym_mat @ skew_sym_mat * ((1 - c) / (s**2 + 1e-8))
|
||||
|
||||
|
||||
def auto_orient_poses(
|
||||
poses: TensorType["num_poses":..., 4, 4], method: Literal["pca", "up"] = "up"
|
||||
) -> TensorType["num_poses":..., 3, 4]:
|
||||
"""Orients and centers the poses. We provide two methods for orientation: pca and up.
|
||||
|
||||
pca: Orient the poses so that the principal component of the points is aligned with the axes.
|
||||
This method works well when all of the cameras are in the same plane.
|
||||
|
||||
up: Orient the poses so that the average up vector is aligned with the z axis.
|
||||
This method works well when images are not at arbitrary angles.
|
||||
|
||||
Args:
|
||||
poses: The poses to orient.
|
||||
method: The method to use for orientation. Either "pca" or "up".
|
||||
|
||||
Returns:
|
||||
The oriented poses.
|
||||
"""
|
||||
|
||||
translation = poses[..., :3, 3]
|
||||
|
||||
mean_translation = torch.mean(translation, dim=0)
|
||||
translation = translation - mean_translation
|
||||
|
||||
if method == "pca":
|
||||
_, eigvec = torch.linalg.eigh(translation.T @ translation)
|
||||
eigvec = torch.flip(eigvec, dims=(-1,))
|
||||
|
||||
if torch.linalg.det(eigvec) < 0:
|
||||
eigvec[:, 2] = -eigvec[:, 2]
|
||||
|
||||
transform = torch.cat([eigvec, eigvec @ -mean_translation[..., None]], dim=-1)
|
||||
oriented_poses = transform @ poses
|
||||
|
||||
if oriented_poses.mean(axis=0)[2, 1] < 0:
|
||||
oriented_poses[:, 1:3] = -1 * oriented_poses[:, 1:3]
|
||||
elif method == "up":
|
||||
up = torch.mean(poses[:, :3, 1], dim=0)
|
||||
up = up / torch.linalg.norm(up)
|
||||
|
||||
rotation = rotation_matrix(up, torch.Tensor([0, 0, 1]))
|
||||
transform = torch.cat([rotation, rotation @ -mean_translation[..., None]], dim=-1)
|
||||
oriented_poses = transform @ poses
|
||||
|
||||
return oriented_poses
|
||||
Reference in new issue
Block a user