Serializing JSON code for drawable objects (and some documentation) (#222)

* some comments and starting serializing comments. on plane w/o formatter

* fixing pylint and black

* removed changes in file

* revert file

* addressing comments

* remove abstract

Co-authored-by: Ethan Weber <ethanweber@Ethans-MacBook-Pro.local>
This commit is contained in:
Ethan WeberandEthan Weber authored and GitHub committed 2022-07-28 13:55:58 -05:00
1 parent 44a7fa288c
commit d13a766b9e
13 files changed
+240 -106

No files matched your search

+114 -24
View File
@@ -15,9 +15,11 @@
"""
Camera Models
"""
import base64
from abc import abstractmethod
from typing import Optional, Type
from typing import Dict, Optional, Type
import cv2
import torch
from torch.nn.functional import normalize
from torchtyping import TensorType
@@ -27,12 +29,15 @@ from nerfactory.utils.misc import is_not_none
class Camera:
"""Base Camera. Intended to be subclassed"""
"""Base Camera. Intended to be subclassed.
Args:
camera_to_world: Camera to world transformation
camera_index: Camera index
"""
def __init__(
self,
camera_to_world: Optional[TensorType[3, 4]] = torch.eye(4)[:3],
camera_index: int = None,
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
@@ -46,7 +51,7 @@ class Camera:
def get_num_intrinsics_params(self) -> int:
"""
Returns:
int: number of optimizable intrinsic parameters
number of optimizable intrinsic parameters
"""
return
@@ -54,21 +59,21 @@ class Camera:
def get_intrinsics(self) -> torch.Tensor:
"""
Returns:
torch.Tensor: Intrinsics matrix
Intrinsics matrix
"""
return
def get_camera_to_world(self) -> TensorType[3, 4]:
"""
Returns:
TensorType[3, 4]: Camera to world transformation
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
Camera to world transformation with homogeneous coordinates
"""
c2w = self.camera_to_world
ones = torch.tensor([0, 0, 0, 1], device=c2w.device)[None]
@@ -79,7 +84,7 @@ class Camera:
def get_image_height(self) -> int:
"""
Returns:
int: Image height
Image height
"""
return
@@ -87,7 +92,7 @@ class Camera:
def get_image_width(self) -> int:
"""
Returns:
int: Image width
Image width
"""
return
@@ -96,7 +101,7 @@ class Camera:
"""Rescales the camera intrinsics for output resolution.
Args:
scaling_factor (float): Scaling factor
scaling_factor: Scaling factor
Returns:
None
@@ -156,9 +161,42 @@ class Camera:
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) -> Dict:
"""Converts the camera to a json dictionary.
Args:
image: An image that is encoded to a base64 string. Defaults to None.
Returns:
A JSON representation of the camera
"""
raise NotImplementedError
@staticmethod
def from_json(json_: Dict) -> "Camera": # pylint:disable=no-self-use
"""Converts a json dictionary to the camera object.
Args:
json_: The json dictionary.
Returns:
The camera object instantiated from the json dictionary.
"""
raise NotImplementedError
class PinholeCamera(Camera):
"""Pinhole camera model."""
"""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,
@@ -166,10 +204,10 @@ class PinholeCamera(Camera):
cy: float,
fx: float,
fy: float,
camera_to_world: Optional[TensorType[3, 4]] = torch.eye(4)[:3],
camera_index: int = None,
camera_to_world: TensorType[3, 4] = torch.eye(4)[:3],
camera_index: Optional[int] = None,
):
super().__init__(camera_to_world, camera_index)
super().__init__(camera_to_world=camera_to_world, camera_index=camera_index)
self.cx = cx
self.cy = cy
self.fx = fx
@@ -258,19 +296,48 @@ class PinholeCamera(Camera):
return RayBundle(origins=origins, directions=directions, pixel_area=pixel_area[..., None])
def to_json(self, image: Optional[TensorType["image_height", "image_width", 2]] = None) -> Dict:
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,
}
if image:
# move image to cpu if not already
# TODO: move to numpy
data = cv2.imencode(".png", image[:, :, ::-1])[1].tobytes()
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
class SimplePinholeCamera(PinholeCamera):
"""Simple Pinhole Camera model."""
"""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: Optional[TensorType[3, 4]] = torch.eye(4)[:3],
camera_index: int = None,
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_index)
super().__init__(cx, cy, f, f, camera_to_world=camera_to_world, camera_index=camera_index)
@classmethod
def fx_index(cls):
@@ -280,18 +347,32 @@ class SimplePinholeCamera(PinholeCamera):
def fy_index(cls):
return 2
def to_json(self, image: Optional[TensorType["image_height", "image_width", 2]] = None) -> Dict:
raise NotImplementedError
@staticmethod
def from_json(json_: Dict) -> "SimplePinholeCamera": # pylint:disable=no-self-use
raise NotImplementedError
class EquirectangularCamera(Camera):
"""Equirectangular (360 degree) camera model."""
"""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: Optional[TensorType[3, 4]] = torch.eye(4)[:3],
camera_index: int = None,
camera_to_world: TensorType[3, 4] = torch.eye(4)[:3],
camera_index: Optional[int] = None,
):
super().__init__(camera_to_world, camera_index)
super().__init__(camera_to_world=camera_to_world, camera_index=camera_index)
self.height = height
self.width = width
@@ -361,6 +442,13 @@ class EquirectangularCamera(Camera):
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) -> 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]):
"""
@@ -376,6 +464,8 @@ def get_intrinsics_from_intrinsics_matrix(intrinsics_matrix: TensorType[3, 3]):
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: