mirror of
https://github.com/nerfstudio-project/nerfstudio.git
synced 2026-12-05 07:18:57 +08:00
Rename repo to nerfactory (#204)
* Rename to nerfactory * Fix missing files
This commit is contained in:
1 parent
8db05d8299
commit
6dc704c551
187 files changed
+259775
-259761
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,127 @@
|
||||
# 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.
|
||||
"""
|
||||
|
||||
import copy
|
||||
from dataclasses import dataclass
|
||||
from typing import List, Tuple
|
||||
|
||||
import torch
|
||||
from nerfactory.cameras.cameras import Camera, get_camera, get_intrinsics_from_intrinsics_matrix
|
||||
from nerfactory.cameras.utils import get_interpolated_poses_many
|
||||
|
||||
import nerfactory.cameras.utils as camera_utils
|
||||
|
||||
|
||||
@dataclass
|
||||
class CameraPath:
|
||||
"""A camera path."""
|
||||
|
||||
cameras: List[Camera]
|
||||
|
||||
|
||||
def get_interpolated_camera_path(camera_a: Camera, camera_b: Camera, steps: int) -> CameraPath:
|
||||
"""Generate a camera path between two cameras.
|
||||
|
||||
Args:
|
||||
camera_a: The first camera.
|
||||
camera_b: The second camera.
|
||||
steps: The number of steps to interpolate between the two cameras.
|
||||
|
||||
Returns:
|
||||
CameraPath: A camera 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]
|
||||
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)
|
||||
|
||||
|
||||
def get_spiral_path(
|
||||
camera: Camera,
|
||||
steps: int = 30,
|
||||
radius: float = None,
|
||||
radiuses: Tuple[float] = None,
|
||||
rots: int = 2,
|
||||
zrate: float = 0.5,
|
||||
) -> CameraPath:
|
||||
"""
|
||||
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:
|
||||
CameraPath: 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.")
|
||||
|
||||
# TODO: don't hardcode this. pass this in
|
||||
up = camera.camera_to_world[:3, 2] # scene is z up
|
||||
# up = camera.camera_to_world[:3, 1] # this will rotate 90 degrees
|
||||
focal = min(camera.fx, camera.fy)
|
||||
target = torch.tensor([0, 0, -focal], device=camera.device) # camera looking in -z direction
|
||||
|
||||
c2wh_global = camera.get_camera_to_world_h()
|
||||
|
||||
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)
|
||||
ones = torch.tensor([0, 0, 0, 1], device=c2w.device)[None]
|
||||
c2wh = torch.cat([c2w, ones], dim=0)
|
||||
local_c2whs.append(c2wh)
|
||||
|
||||
cameras = []
|
||||
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)
|
||||
|
||||
return CameraPath(cameras=cameras)
|
||||
@@ -0,0 +1,408 @@
|
||||
# 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
|
||||
"""
|
||||
from abc import abstractmethod
|
||||
from typing import Optional, Type
|
||||
|
||||
import torch
|
||||
from torch.nn.functional import normalize
|
||||
from torchtyping import TensorType
|
||||
|
||||
from nerfactory.cameras.rays import RayBundle
|
||||
from nerfactory.utils.misc import is_not_none
|
||||
|
||||
|
||||
class Camera:
|
||||
"""Base Camera. Intended to be subclassed"""
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
camera_to_world: Optional[TensorType[3, 4]] = torch.eye(4)[:3],
|
||||
camera_index: int = None,
|
||||
) -> None:
|
||||
self.camera_to_world = camera_to_world
|
||||
self.camera_index = camera_index
|
||||
|
||||
@property
|
||||
def device(self):
|
||||
"""Returns the device that the camera is on."""
|
||||
return self.camera_to_world.device
|
||||
|
||||
@abstractmethod
|
||||
def get_num_intrinsics_params(self) -> int:
|
||||
"""
|
||||
Returns:
|
||||
int: number of optimizable intrinsic parameters
|
||||
"""
|
||||
return
|
||||
|
||||
@abstractmethod
|
||||
def get_intrinsics(self) -> torch.Tensor:
|
||||
"""
|
||||
Returns:
|
||||
torch.Tensor: Intrinsics matrix
|
||||
"""
|
||||
return
|
||||
|
||||
def get_camera_to_world(self) -> TensorType[3, 4]:
|
||||
"""
|
||||
Returns:
|
||||
TensorType[3, 4]: Camera to world transformation
|
||||
"""
|
||||
return self.camera_to_world
|
||||
|
||||
def get_camera_to_world_h(self) -> TensorType[4, 4]:
|
||||
"""
|
||||
Returns:
|
||||
TensorType[4, 4]: 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:
|
||||
int: Image height
|
||||
"""
|
||||
return
|
||||
|
||||
@abstractmethod
|
||||
def get_image_width(self) -> int:
|
||||
"""
|
||||
Returns:
|
||||
int: Image width
|
||||
"""
|
||||
return
|
||||
|
||||
@abstractmethod
|
||||
def rescale_output_resolution(self, scaling_factor: float) -> None:
|
||||
"""Rescales the camera intrinsics for output resolution.
|
||||
|
||||
Args:
|
||||
scaling_factor (float): Scaling factor
|
||||
|
||||
Returns:
|
||||
None
|
||||
"""
|
||||
return
|
||||
|
||||
def get_image_coords(self, pixel_offset: float = 0.5) -> TensorType["image_height", "image_width", 2]:
|
||||
"""
|
||||
Args:
|
||||
pixel_offset (float): Offset for each pixel. Defaults to center of pixel (0.5)
|
||||
|
||||
Returns:
|
||||
TensorType["image_height", "image_width", 2]: Grid of image coordinates.
|
||||
"""
|
||||
image_height = self.get_image_height()
|
||||
image_width = self.get_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],
|
||||
) -> 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
|
||||
|
||||
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 is_not_none(self.camera_index):
|
||||
ray_bundle.set_camera_indices(camera_index=self.camera_index)
|
||||
return ray_bundle
|
||||
|
||||
|
||||
class PinholeCamera(Camera):
|
||||
"""Pinhole camera model."""
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
cx: float,
|
||||
cy: float,
|
||||
fx: float,
|
||||
fy: float,
|
||||
camera_to_world: Optional[TensorType[3, 4]] = torch.eye(4)[:3],
|
||||
camera_index: int = None,
|
||||
):
|
||||
super().__init__(camera_to_world, 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,
|
||||
)
|
||||
return K
|
||||
|
||||
def get_intrinsics(self) -> torch.Tensor:
|
||||
return torch.tensor([self.cx, self.cy, self.fx, self.fy])
|
||||
|
||||
@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
|
||||
) # (..., 1, 3) * (..., 3, 3) -> (..., 3)
|
||||
directions = normalize(directions, dim=-1)
|
||||
origins = camera_to_world[..., :3, 3] # (..., 3)
|
||||
|
||||
## 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))
|
||||
pixel_area = dx * dy
|
||||
|
||||
return RayBundle(origins=origins, directions=directions, pixel_area=pixel_area[..., None])
|
||||
|
||||
|
||||
class SimplePinholeCamera(PinholeCamera):
|
||||
"""Simple Pinhole Camera model."""
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
cx: float,
|
||||
cy: float,
|
||||
f: float,
|
||||
camera_to_world: Optional[TensorType[3, 4]] = torch.eye(4)[:3],
|
||||
camera_index: int = None,
|
||||
):
|
||||
super().__init__(cx, cy, f, f, camera_to_world, camera_index)
|
||||
|
||||
@classmethod
|
||||
def fx_index(cls):
|
||||
return 2
|
||||
|
||||
@classmethod
|
||||
def fy_index(cls):
|
||||
return 2
|
||||
|
||||
|
||||
class EquirectangularCamera(Camera):
|
||||
"""Equirectangular (360 degree) camera model."""
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
height: int,
|
||||
width: int,
|
||||
camera_to_world: Optional[TensorType[3, 4]] = torch.eye(4)[:3],
|
||||
camera_index: int = None,
|
||||
):
|
||||
super().__init__(camera_to_world, 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])
|
||||
|
||||
def rescale_output_resolution(self, scaling_factor: float) -> None:
|
||||
self.height *= scaling_factor
|
||||
self.width *= scaling_factor
|
||||
|
||||
@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, s_theta * s_phi, c_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, torch.sin(d_theta_min) * s_phi, c_phi], -1), dim=-1
|
||||
)
|
||||
dirx_max = normalize(
|
||||
torch.cat([torch.cos(d_theta_max) * s_phi, torch.sin(d_theta_max) * s_phi, c_phi], -1), dim=-1
|
||||
)
|
||||
diry_min = normalize(
|
||||
torch.cat([c_theta * torch.sin(d_phi_min), s_theta * torch.sin(d_phi_min), torch.cos(d_phi_min)], -1),
|
||||
dim=-1,
|
||||
)
|
||||
diry_max = normalize(
|
||||
torch.cat([c_theta * torch.sin(d_phi_max), s_theta * torch.sin(d_phi_max), torch.cos(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)
|
||||
|
||||
|
||||
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]:
|
||||
"""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
|
||||
@@ -0,0 +1,262 @@
|
||||
# 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 Optional
|
||||
|
||||
import torch
|
||||
from torchtyping import TensorType
|
||||
|
||||
from nerfactory.utils.math import Gaussians, conical_frustum_to_gaussian
|
||||
from nerfactory.utils.misc import is_not_none
|
||||
from nerfactory.utils.tensor_dataclass import TensorDataclass
|
||||
|
||||
|
||||
@dataclass
|
||||
class Frustums(TensorDataclass):
|
||||
"""Describes region of space as a frustum.
|
||||
|
||||
Args:
|
||||
origins (TensorType[..., 3]): xyz coordinate for ray origin.
|
||||
directions (TensorType[..., 3]): Direction of ray.
|
||||
starts (TensorType[..., num_samples, 1]): Where the frustum starts along a ray.
|
||||
ends (TensorType[..., num_samples, 1]): Where the frustum ends along a ray.
|
||||
pixel_area (TensorType[..., 1]): Projected area of pixel a distance 1 away from origin.
|
||||
"""
|
||||
|
||||
origins: TensorType[..., 3]
|
||||
directions: TensorType[..., 3]
|
||||
starts: TensorType[..., 1]
|
||||
ends: TensorType[..., 1]
|
||||
pixel_area: TensorType[..., 1]
|
||||
|
||||
def get_positions(self) -> TensorType[..., 3]:
|
||||
"""Calulates "center" position of frustum. Not weighted by mass.
|
||||
|
||||
Returns:
|
||||
TensorType[..., 3]: xyz positions.
|
||||
"""
|
||||
return self.origins + self.directions * (self.starts + self.ends) / 2
|
||||
|
||||
def get_gaussian_blob(self) -> Gaussians:
|
||||
"""Calculates of guassian approximation of conical frustum.
|
||||
|
||||
Resturns:
|
||||
Gaussians: 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:
|
||||
Frustums: 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
|
||||
|
||||
Args:
|
||||
frustums (Frustums): Frustums along ray.
|
||||
camera_indices (TensorType[..., 1]): Camera index.
|
||||
valid_mask (TensorType[..., 1]): Rays that are valid.
|
||||
deltas (TensorType[..., 1]): "width" of each sample.
|
||||
ts (TensorType[..., 1]): sample-camera distance of each sample.
|
||||
"""
|
||||
|
||||
frustums: Frustums
|
||||
camera_indices: TensorType[..., 1] = None
|
||||
valid_mask: TensorType[..., 1] = None
|
||||
deltas: TensorType[..., 1] = None
|
||||
|
||||
def get_weights(self, densities: TensorType[..., "num_samples", 1]) -> TensorType[..., "num_samples", 1]:
|
||||
"""Return weights based on predicted densities
|
||||
|
||||
Args:
|
||||
densities (TensorType[..., "num_samples", 1]): Predicted densities for samples along ray
|
||||
|
||||
Returns:
|
||||
TensorType[..., "num_samples", 1]: Weights for each sample
|
||||
"""
|
||||
|
||||
delta_density = self.deltas * densities
|
||||
alphas = 1 - torch.exp(-delta_density)
|
||||
|
||||
# mip-nerf version of transmittance calculation:
|
||||
transmittance = torch.cumsum(delta_density[..., :-1, :], dim=-2)
|
||||
transmittance = torch.cat(
|
||||
[torch.zeros((*transmittance.shape[:1], 1, 1)).to(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"""
|
||||
self.valid_mask = valid_mask
|
||||
|
||||
def apply_masks(self) -> "RaySamples":
|
||||
"""Use valid_mask to mask samples.
|
||||
|
||||
Returns:
|
||||
RaySamples: New set of masked samples.
|
||||
"""
|
||||
if is_not_none(self.valid_mask):
|
||||
return self[self.valid_mask[..., 0]]
|
||||
return self
|
||||
|
||||
|
||||
@dataclass
|
||||
class RayBundle(TensorDataclass):
|
||||
"""A bundle of ray parameters.
|
||||
|
||||
Args:
|
||||
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 (TensorType[..., 1]): Camera indices
|
||||
nears (TensorType[..., 1]): Distance along ray to start sampling
|
||||
fars (TensorType[..., 1]): Rays Distance along ray to stop sampling
|
||||
valid_mask (TensorType[..., 1]): Rays that are valid
|
||||
"""
|
||||
|
||||
origins: TensorType["num_rays", 3]
|
||||
directions: TensorType["num_rays", 3]
|
||||
pixel_area: TensorType["num_rays", 1]
|
||||
camera_indices: Optional[TensorType["num_rays", 1]] = None
|
||||
nears: Optional[TensorType["num_rays", 1]] = None
|
||||
fars: Optional[TensorType["num_rays", 1]] = None
|
||||
valid_mask: Optional[TensorType["num_rays", 1]] = None
|
||||
num_rays_per_chunk: int = None
|
||||
|
||||
def move_to_device(self, device: torch.device) -> None:
|
||||
"""Move bundle data to a device.
|
||||
|
||||
Args:
|
||||
device (torch.device): Device to move tensors to.
|
||||
"""
|
||||
self.origins = self.origins.to(device)
|
||||
self.directions = self.directions.to(device)
|
||||
if is_not_none(self.camera_indices):
|
||||
self.camera_indices = self.camera_indices.to(device)
|
||||
|
||||
def set_camera_indices(self, camera_index: int) -> None:
|
||||
"""Sets all of the the camera indices to a specific camera index.
|
||||
|
||||
Args:
|
||||
camera_index (int): 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 (int): Number of rays in output RayBundle
|
||||
|
||||
Returns:
|
||||
RayBundle: 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 (int): Start index of RayBundle chunk.
|
||||
end_idx (int): End index of RayBundle chunk.
|
||||
|
||||
Returns:
|
||||
RayBundle: Flattened RayBundle with end_idx-start_idx rays.
|
||||
|
||||
"""
|
||||
return self.flatten()[start_idx:end_idx]
|
||||
|
||||
def get_ray_samples(
|
||||
self, bin_starts: TensorType[..., "num_samples", 1], bin_ends: TensorType[..., "num_samples", 1]
|
||||
) -> RaySamples:
|
||||
"""Produces samples for each ray by projection points along the ray direction.
|
||||
|
||||
|
||||
Args:
|
||||
bin_starts (TensorType[..., "num_samples", 1]): Distance from origin to start of bin.
|
||||
bin_ends (TensorType[..., "num_samples", 1]): Distance from origin to end of bin.
|
||||
|
||||
Returns:
|
||||
RaySamples: 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 # [..., N_samples, 1]
|
||||
deltas = dists * torch.norm(self.directions[:, :], dim=-1)[..., None, None]
|
||||
|
||||
if is_not_none(self.camera_indices):
|
||||
camera_indices = self.camera_indices[..., None]
|
||||
else:
|
||||
camera_indices = None
|
||||
|
||||
frustums = Frustums(
|
||||
origins=self.origins[..., None, :], # [..., 1, 3]
|
||||
directions=self.directions[..., None, :], # [..., 1, 3]
|
||||
starts=bin_starts, # [..., N_samples, 1]
|
||||
ends=bin_ends, # [..., N_samples, 1]
|
||||
pixel_area=self.pixel_area[..., None, :], # [..., 1, 1]
|
||||
).to(device)
|
||||
|
||||
ray_samples = RaySamples(
|
||||
frustums=frustums,
|
||||
camera_indices=camera_indices, # [..., 1, 1]
|
||||
valid_mask=valid_mask, # [..., N_samples, 1]
|
||||
deltas=deltas, # [..., N_samples, 1]
|
||||
)
|
||||
|
||||
return ray_samples
|
||||
@@ -0,0 +1,316 @@
|
||||
# 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
|
||||
|
||||
import numpy as np
|
||||
import torch
|
||||
|
||||
_EPS = np.finfo(float).eps * 4.0
|
||||
|
||||
|
||||
def unit_vector(data, axis=None, out=None):
|
||||
"""Return ndarray normalized by length, i.e. Euclidean norm, along axis.
|
||||
>>> v0 = np.random.random(3)
|
||||
>>> v1 = unit_vector(v0)
|
||||
>>> np.allclose(v1, v0 / np.linalg.norm(v0))
|
||||
True
|
||||
>>> v0 = np.random.rand(5, 4, 3)
|
||||
>>> v1 = unit_vector(v0, axis=-1)
|
||||
>>> v2 = v0 / np.expand_dims(np.sqrt(np.sum(v0*v0, axis=2)), 2)
|
||||
>>> np.allclose(v1, v2)
|
||||
True
|
||||
>>> v1 = unit_vector(v0, axis=1)
|
||||
>>> v2 = v0 / np.expand_dims(np.sqrt(np.sum(v0*v0, axis=1)), 1)
|
||||
>>> np.allclose(v1, v2)
|
||||
True
|
||||
>>> v1 = np.empty((5, 4, 3))
|
||||
>>> unit_vector(v0, axis=1, out=v1)
|
||||
>>> np.allclose(v1, v2)
|
||||
True
|
||||
>>> list(unit_vector([]))
|
||||
[]
|
||||
>>> list(unit_vector([1]))
|
||||
[1.0]
|
||||
"""
|
||||
if out is None:
|
||||
data = np.array(data, dtype=np.float64, copy=True)
|
||||
if data.ndim == 1:
|
||||
data /= math.sqrt(np.dot(data, data))
|
||||
return data
|
||||
else:
|
||||
if out is not data:
|
||||
out[:] = np.array(data, copy=False)
|
||||
data = out
|
||||
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
|
||||
if out is None:
|
||||
return data
|
||||
|
||||
|
||||
def quaternion_from_matrix(matrix, isprecise=False):
|
||||
"""Return quaternion from rotation matrix.
|
||||
If isprecise is True, the input matrix is assumed to be a precise rotation
|
||||
matrix and a faster algorithm is used.
|
||||
>>> q = quaternion_from_matrix(np.identity(4), True)
|
||||
>>> np.allclose(q, [1, 0, 0, 0])
|
||||
True
|
||||
>>> q = quaternion_from_matrix(np.diag([1, -1, -1, 1]))
|
||||
>>> np.allclose(q, [0, 1, 0, 0]) or np.allclose(q, [0, -1, 0, 0])
|
||||
True
|
||||
>>> R = rotation_matrix(0.123, (1, 2, 3))
|
||||
>>> q = quaternion_from_matrix(R, True)
|
||||
>>> np.allclose(q, [0.9981095, 0.0164262, 0.0328524, 0.0492786])
|
||||
True
|
||||
>>> R = [[-0.545, 0.797, 0.260, 0], [0.733, 0.603, -0.313, 0],
|
||||
... [-0.407, 0.021, -0.913, 0], [0, 0, 0, 1]]
|
||||
>>> q = quaternion_from_matrix(R)
|
||||
>>> np.allclose(q, [0.19069, 0.43736, 0.87485, -0.083611])
|
||||
True
|
||||
>>> R = [[0.395, 0.362, 0.843, 0], [-0.626, 0.796, -0.056, 0],
|
||||
... [-0.677, -0.498, 0.529, 0], [0, 0, 0, 1]]
|
||||
>>> q = quaternion_from_matrix(R)
|
||||
>>> np.allclose(q, [0.82336615, -0.13610694, 0.46344705, -0.29792603])
|
||||
True
|
||||
>>> R = random_rotation_matrix()
|
||||
>>> q = quaternion_from_matrix(R)
|
||||
>>> is_same_transform(R, quaternion_matrix(q))
|
||||
True
|
||||
>>> R = euler_matrix(0.0, 0.0, np.pi/2.0)
|
||||
>>> np.allclose(quaternion_from_matrix(R, isprecise=False),
|
||||
... quaternion_from_matrix(R, isprecise=True))
|
||||
True
|
||||
"""
|
||||
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[[3, 0, 1, 2], np.argmax(w)]
|
||||
if q[0] < 0.0:
|
||||
np.negative(q, q)
|
||||
return q
|
||||
|
||||
|
||||
def quaternion_slerp(quat0, quat1, fraction, spin=0, shortestpath=True):
|
||||
"""Return spherical linear interpolation between two quaternions.
|
||||
>>> q0 = random_quaternion()
|
||||
>>> q1 = random_quaternion()
|
||||
>>> q = quaternion_slerp(q0, q1, 0)
|
||||
>>> np.allclose(q, q0)
|
||||
True
|
||||
>>> q = quaternion_slerp(q0, q1, 1, 1)
|
||||
>>> np.allclose(q, q1)
|
||||
True
|
||||
>>> q = quaternion_slerp(q0, q1, 0.5)
|
||||
>>> angle = math.acos(np.dot(q0, q))
|
||||
>>> (np.allclose(2, math.acos(np.dot(q0, q1)) / angle) or
|
||||
np.allclose(2, math.acos(-np.dot(q0, q1)) / angle))
|
||||
True
|
||||
"""
|
||||
q0 = unit_vector(quat0[:4])
|
||||
q1 = unit_vector(quat1[:4])
|
||||
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):
|
||||
"""Return homogeneous rotation matrix from quaternion.
|
||||
>>> M = quaternion_matrix([0.99810947, 0.06146124, 0, 0])
|
||||
>>> np.allclose(M, rotation_matrix(0.123, [1, 0, 0]))
|
||||
True
|
||||
>>> M = quaternion_matrix([1, 0, 0, 0])
|
||||
>>> np.allclose(M, np.identity(4))
|
||||
True
|
||||
>>> M = quaternion_matrix([0, 1, 0, 0])
|
||||
>>> np.allclose(M, np.diag([1, -1, -1, 1]))
|
||||
True
|
||||
"""
|
||||
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=10):
|
||||
"""Return interpolation of poses with specified number of steps.
|
||||
Args:
|
||||
poseA
|
||||
poseB
|
||||
Return:
|
||||
list of poses
|
||||
"""
|
||||
|
||||
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=10):
|
||||
"""
|
||||
Interpolate between two camera poses.
|
||||
Args:
|
||||
Returns:
|
||||
"""
|
||||
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(list_of_poses, list_of_Ks, steps_per_transition=10):
|
||||
"""
|
||||
Args:
|
||||
list_of_poses
|
||||
steps
|
||||
distances_per_step
|
||||
Returns:
|
||||
"""
|
||||
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)
|
||||
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
|
||||
|
||||
|
||||
def get_swirl_poses(pose):
|
||||
"""
|
||||
Returns a swirl around the camera poses.
|
||||
# TODO(ethan): add parameters and make this work
|
||||
"""
|
||||
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):
|
||||
"""Returns a normalized vector."""
|
||||
return x / torch.linalg.norm(x)
|
||||
|
||||
|
||||
def viewmatrix(lookat, up, pos):
|
||||
"""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:
|
||||
torch.Tensor: 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
|
||||
Reference in new issue
Block a user