Initial ray generation and dataset code (#12)

* ray generator and cameras structure progress

* test renames

* added pass

* conflicts

* fixing some black errors

* reformated files

* merged master and .gitignore

* fixing linting

* removing old folder

* removed return False

* pylint fixes

* update

* updates

* update

* update

* update

* update

* update

* update

* update

* update

* update

* update
This commit is contained in:
Ethan Weber authored and GitHub committed 2022-04-12 15:08:16 -07:00
1 parent 1995afda57
commit 0b7dfcdc5d
21 files changed
+652 -139

No files matched your search

-60
View File
@@ -1,60 +0,0 @@
"""
Camera Models
"""
from dataclasses import dataclass
from torchtyping import TensorType
import torch
@dataclass
class Rays:
"""Camera rays. Can be arbitrary dimension"""
origin: TensorType[..., 3]
direction: TensorType[..., 3]
class Camera:
"""Base Camera. Intended to be subclassed"""
def __init__(self, height: int, width: int, camera_to_world: TensorType[4, 3]) -> None:
"""Initialize camera
Args:
height (int): Number of camera sensor rows
width (int): Number of camera sensor columns
camera_to_world (TensorType[4, 3]): Pose transorm for camera
"""
self.height = height
self.width = width
self.camera_to_world = camera_to_world
def generate_rays(self, coords: TensorType[..., 2]) -> Rays:
"""Generates camera rays associated to grid of pixel coordinates.
Args:
coords (TensorType[..., 2]): Pixel coordiantes
Returns:
Rays: Camera rays associated to pixel coordinates.
"""
raise NotImplementedError
def get_image_coords(self) -> TensorType["height", "width", 2]:
"""Get grid of image coordinates
Returns:
TensorType["height", "width", 2]: Image coordinates
"""
coords = torch.meshgrid(torch.arange(self.height), torch.arange(self.width))
coords = torch.stack(coords, dim=-1)
return coords
def generate_all_rays(self) -> Rays:
"""Generate rays for entire camera
Returns:
Rays: Camera rays of shape [height, width]
"""
coords = self.get_image_coords()
return self.generate_rays(coords)
+94
View File
@@ -0,0 +1,94 @@
"""
The dataset baseclass.
"""
from abc import abstractmethod
import torch
import imageio
from mattport.structures.cameras import Camera
class Dataset(torch.utils.data.Dataset):
"""_summary_
Args:
torch (_type_): _description_
"""
def __init__(self, data_directory: str, dataset_type: str, scene: str):
"""_summary_
Args:
data_directory (str): _description_
type (str): _description_
scene (str): _description_
"""
super().__init__()
self.data_directory = data_directory
self.dataset_type = dataset_type
self.scene = scene
# data to populate
self.image_filenames = []
self.cameras = []
def __len__(self):
return len(self.image_filenames)
def get_image(self, idx):
"""_summary_
Args:
idx (_type_): _description_
Raises:
NotImplementedError: _description_
"""
image_filename = self.image_filenames[idx]
image = imageio.imread(image_filename)
return image
@abstractmethod
def get_camera(self, idx) -> Camera:
"""_summary_
Args:
idx (_type_): _description_
Raises:
NotImplementedError: _description_
Returns:
Camera: _description_
"""
return self.cameras[idx]
def __getitem__(self, idx):
"""Returns the rays for the camera.
Args:
idx (_type_): _description_
Raises:
NotImplementedError: _description_
"""
# raise NotImplementedError
# TODO(ethan): we should have a dataset which always takes rays from the same camera
# or, it could take rays from multiple cameras
camera = self.cameras[idx]
rays = camera.generate_all_rays() # (H, W, 6)
camera_indices = torch.ones_like(rays[:, :, 0:1]) * idx
rgbs = self.get_image(idx) / 255.0
return {
"rays": rays,
"rgbs": rgbs,
"camera_indices": camera_indices
# question: do we want to have more information here?
}
# question... what do I want the dataset to return?
+55
View File
@@ -0,0 +1,55 @@
"""
For loading the blender dataset format.
"""
import os
import imageio
import numpy as np
from mattport.utils.io import load_from_json
def load_blender_data(basedir, half_res=False, testskip=1):
"""Processes the a blender dataset directory.
Some of this code comes from https://github.com/yenchenlin/nerf-pytorch/blob/master/load_blender.py#L37.
Args:
basedir (_type_): _description_
half_res (bool, optional): _description_. Defaults to False.
testskip (int, optional): _description_. Defaults to 1.
Returns:
_type_: _description_
"""
# pylint: disable=unused-argument
# pylint: disable-msg=too-many-locals
splits = ["train", "val", "test"]
metas = {}
for split in splits:
metas[split] = load_from_json(os.path.join(basedir, f"transforms_{split}.json"))
image_filenames = []
all_poses = []
for split in splits:
meta = metas[split]
poses = []
if split == "train" or testskip == 0:
skip = 1
else:
skip = testskip
for frame in meta["frames"][::skip]:
fname = os.path.join(basedir, frame["file_path"] + ".png")
image_filenames.append(fname)
poses.append(np.array(frame["transform_matrix"]))
poses = np.array(poses).astype(np.float32)
all_poses.append(poses)
poses = np.concatenate(all_poses, 0)
img_0 = imageio.imread(image_filenames[0])
H, W = img_0.shape[:2]
camera_angle_x = float(meta["camera_angle_x"])
focal = 0.5 * W / np.tan(0.5 * camera_angle_x)
return image_filenames, poses, focal, H, W
+4 -6
View File
@@ -4,7 +4,7 @@ Builds the dataset
import importlib
import logging
from mattport.nerf.dataset.dataset import Dataset
from mattport.nerf.dataset.base import Dataset
def build_dataset(config: dict) -> Dataset:
@@ -16,11 +16,9 @@ def build_dataset(config: dict) -> Dataset:
"""
# TODO(ethan): better handle this with configs
module = importlib.import_module("mattport.nerf.dataset.base")
dataset = module.Dataset(
data_directory=config.data_directory,
dataset_type=config.dataset_type,
scene=config.scene,
module = importlib.import_module("mattport.nerf.dataset.blender_dataset")
dataset = module.BlenderDataset(
data_directory=config.data_directory, dataset_type=config.dataset_type, scene=config.scene
)
logging.info(dataset)
return dataset
-62
View File
@@ -1,62 +0,0 @@
"""
The dataset baseclass.
"""
from abc import abstractmethod
import torch
from mattport.nerf.cameras import Camera
class Dataset(torch.utils.data.Dataset):
"""_summary_
Args:
torch (_type_): _description_
"""
def __init__(self, data_directory: str, dataset_type: str, scene: str):
"""_summary_
Args:
data_directory (str): _description_
type (str): _description_
scene (str): _description_
"""
super().__init__()
self.data_directory = data_directory
self.dataset_type = dataset_type
self.scene = scene
def __len__(self):
pass
@abstractmethod
def get_image(self, idx):
"""_summary_
Args:
idx (_type_): _description_
Raises:
NotImplementedError: _description_
"""
raise NotImplementedError
@abstractmethod
def get_camera(self, idx) -> Camera:
"""_summary_
Args:
idx (_type_): _description_
Raises:
NotImplementedError: _description_
Returns:
Camera: _description_
"""
raise NotImplementedError
def __getitem__(self, idx):
raise NotImplementedError
+53
View File
@@ -0,0 +1,53 @@
"""
Ray generator.
"""
from torch import nn
from torchtyping import TensorType
from mattport.structures.rays import RayBundle
from mattport.structures.cameras import get_camera_model
class RayGenerator(nn.Module):
"""torch.nn Module for generating rays.
This class will store the intrinsics and extrinsics parameters of the cameras."""
def __init__(
self,
intrinsics: TensorType["num_cameras", "num_intrinsics_params"],
camera_to_world: TensorType["num_cameras", 3, 4],
) -> None:
"""_summary_
Args:
intrinsics (TensorType["num_cameras", "num_intrinsics_params"]):
The intrinsics parameters.
camera_to_world (TensorType["num_cameras", 3, 4]): Camera to world transformation matrix.
"""
super().__init__()
self.num_cameras, self.num_intrinsics_params = intrinsics.shape
assert self.num_cameras >= 0
self.intrinsics = nn.Parameter(intrinsics, requires_grad=False)
self.camera_to_world = nn.Parameter(camera_to_world, requires_grad=False)
# TODO(ethan): add learnable parameters that are deltas on the intrinsics and camera_to_world parameters
def forward(self, ray_indices: TensorType["num_rays", 3]) -> RayBundle:
"""Index into the cameras to generate the rays.
Args:
x (_type_): _description_
"""
c = ray_indices[:, 0] # camera indices
i = ray_indices[:, 1] # row indices
j = ray_indices[:, 2] # col indices
intrinsics = self.intrinsics[c]
camera_to_world = self.camera_to_world[c]
# NOTE(ethan): we currently assume all images have the same height and width
camera_index = 0
camera_class = get_camera_model(self.num_intrinsics_params)
camera = camera_class(*self.intrinsics[camera_index].tolist())
image_coords = camera.get_image_coords()
coords = image_coords[i, j]
ray_bundle = camera_class.generate_rays(intrinsics=intrinsics, camera_to_world=camera_to_world, coords=coords)
ray_bundle.camera_indices = c
return ray_bundle
+1 -1
View File
@@ -7,7 +7,7 @@ import torch
from torch import nn
from torchtyping import TensorType
from mattport.nerf import cameras
from mattport.structures import cameras
RaySamples = NamedTuple(
"RaySamples", [("locations", TensorType[..., "num_samples", 3]), ("deltas", TensorType[..., "num_samples"])]
+1 -2
View File
@@ -18,11 +18,10 @@ class Trainer:
def setup_dataset(self):
"""_summary_"""
self.train_dataset = build_dataset(self.config.dataset)
self.test_dataset = build_dataset(self.config.dataset)
# self.test_dataset = build_dataset(self.config.dataset)
def setup_graph(self):
"""_summary_"""
# self.graph = Graph()
raise NotImplementedError
def setup_optimizer(self):
+219
View File
@@ -0,0 +1,219 @@
"""
Camera Models
"""
from abc import abstractmethod
from dataclasses import dataclass
from typing import Optional
import torch
from torch.nn.functional import normalize
from torchtyping import TensorType
from mattport.structures.rays import CameraRayBundle, RayBundle
@dataclass
class Rays:
"""Camera rays. Can be arbitrary dimension"""
origin: TensorType[..., 3]
direction: TensorType[..., 3]
class Camera:
"""Base Camera. Intended to be subclassed"""
def __init__(self, camera_to_world: Optional[TensorType[3, 4]] = torch.eye(4)[:3]) -> None:
self.camera_to_world = camera_to_world
@abstractmethod
def get_num_intrinsics_params(self) -> int:
"""_summary_
Returns:
int: _description_
"""
return
@abstractmethod
def get_intrinsics(self) -> torch.Tensor:
"""_summary_
Returns:
torch.Tensor: _description_
"""
return
def get_camera_to_world(self) -> TensorType[3, 4]:
"""_summary_
Returns:
TensorType[3, 4]: _description_
"""
return self.camera_to_world
@abstractmethod
def get_image_height(self):
"""_summary_"""
return
@abstractmethod
def get_image_width(self):
"""_summary_"""
return
def get_image_coords(self) -> TensorType["image_height", "image_width", 2]:
"""_summary_
Returns:
_type_: _description_
"""
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)
return image_coords
@classmethod
@abstractmethod
def generate_rays(
cls,
intrinsics: TensorType["num_rays", "num_intrinsics_params"],
camera_to_world: TensorType["num_rays", 3, 4],
coords: TensorType["image_height", "image_width", 2],
) -> RayBundle:
"""_summary_
Args:
intrinsics (TensorType["num_rays", "num_intrinsics_params"]): _description_
camera_to_world (TensorType["num_rays", 3, 4]): _description_
coords (TensorType["image_height", "image_width", 2]): _description_
Returns:
RayBundle: _description_
"""
return
def generate_camera_rays(self) -> CameraRayBundle:
"""Generate rays for the camera.
Returns:
Rays: Camera rays of shape [height, width]
"""
image_height = self.get_image_height()
image_width = self.get_image_width()
num_rays = image_height * image_width
intrinsics = self.get_intrinsics().unsqueeze(0).repeat(num_rays, 1) # (num_rays, num_intrinsics_params)
camera_to_world = self.camera_to_world.unsqueeze(0).repeat(num_rays, 1, 1) # (num_rays, 3, 4)
coords = self.get_image_coords().view(num_rays, 2) # (num_rays, 2)
ray_bundle = self.generate_rays(intrinsics, camera_to_world, coords)
camera_ray_bundle = ray_bundle.to_camera_ray_bundle(image_height, image_width)
return camera_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]
):
super().__init__(camera_to_world)
self.cx = cx
self.cy = cy
self.fx = fx
self.fy = fy
def get_num_intrinsics_params(self):
return 4
def get_image_width(self):
return int(self.cx * 2.0)
def get_image_height(self):
return int(self.cy * 2.0)
def get_intrinsics_matrix(self):
"""_summary_
Returns:
_type_: _description_
"""
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):
"""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:
_type_: _description_
"""
return 2
@classmethod
def fy_index(cls):
"""_summary_
Returns:
_type_: _description_
"""
return 3
@classmethod
def generate_rays(
cls,
intrinsics: TensorType["num_rays", "num_intrinsics_params"],
camera_to_world: TensorType["num_rays", 3, 4],
coords: TensorType["num_rays", 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] # (num_rays, 1)
x = coords[:, 1:2] # (num_rays, 1)
directions = torch.cat([(x - cx) / fx, -(y - cy) / fy, -torch.ones_like(x)], -1) # (num_rays, 3)
rotation = camera_to_world[:, :3, :3] # (num_rays, 3, 3)
directions = torch.bmm(rotation, directions.unsqueeze(-1)).squeeze(-1) # (num_rays, 3)
directions = normalize(directions, dim=-1)
origins = camera_to_world[:, :3, 3] # (num_rays, 3)
return RayBundle(origins=origins, directions=directions)
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]):
super().__init__(cx, cy, f, f, camera_to_world)
@classmethod
def fx_index(cls):
return 2
@classmethod
def fy_index(cls):
return 2
def get_camera_model(num_intrinsics_params):
"""Returns the camera model given the specified number of intrinsics parameters.
Args:
num_intrinsics_params (_type_): _description_
Returns:
_type_: _description_
"""
if num_intrinsics_params == 3:
return SimplePinholeCamera
raise NotImplementedError
+44
View File
@@ -0,0 +1,44 @@
"""
Some ray datastructures.
"""
from dataclasses import dataclass
from typing import Optional
from torchtyping import TensorType
@dataclass
class CameraRayBundle:
"""_summary_"""
origins: TensorType["image_height", "image_width", 3]
directions: TensorType["image_height", "image_width", 3]
camera_index: int = None
@dataclass
class RayBundle:
"""_summary_
Returns:
_type_: _description_
"""
origins: TensorType["num_rays", 3]
directions: TensorType["num_rays", 3]
camera_indices: Optional[TensorType["num_rays"]] = None
def to_camera_ray_bundle(self, image_height, image_width) -> CameraRayBundle:
"""_summary_
Args:
image_height (_type_): _description_
image_width (_type_): _description_
Returns:
CameraRayBundle: _description_
"""
camera_ray_bundle = CameraRayBundle(
origins=self.origins.view(image_height, image_width, 3),
directions=self.directions.view(image_height, image_width, 3),
)
return camera_ray_bundle
+82
View File
@@ -0,0 +1,82 @@
"""
Input/output utils.
"""
import json
import os
def load_from_json(filename: str):
"""_summary_
Args:
filename (str): _description_
Returns:
_type_: _description_
"""
assert filename.endswith(".json")
with open(filename, "r", encoding="UTF-8") as file:
return json.load(file)
def write_to_json(filename: str, content: dict):
"""_summary_
Args:
filename (str): _description_
content (dict): _description_
"""
assert filename.endswith(".json")
with open(filename, "w", encoding="UTF-8") as file:
json.dump(content, file)
def get_git_root(path, dirs=(".git",), default=None):
"""_summary_
"https://stackoverflow.com/questions/22081209/find-the-root-of-the-git-repository-where-the-file-lives
Args:
path (_type_): _description_
dirs (tuple, optional): _description_. Defaults to (".git",).
default (_type_, optional): _description_. Defaults to None.
Returns:
_type_: _description_
"""
prev, test = None, os.path.abspath(path)
while prev != test:
if any(os.path.isdir(os.path.join(test, directory)) for directory in dirs):
return test
prev, test = test, os.path.abspath(os.path.join(test, os.pardir))
return default
def get_absolute_path(path, proj_root_func=get_git_root):
"""
Returns the full, absolute path.
Relative paths are assumed to start at the repo directory.
"""
if path == "":
return ""
absolute_path = path
if absolute_path[0] != "/":
absolute_path = os.path.join(proj_root_func(path), absolute_path)
return absolute_path
def make_dir(filename_or_folder):
"""Make the directory for either the filename or folder.
Note that filename_or_folder currently needs to end in / for it to be recognized as a folder.
"""
if filename_or_folder[-1] != "/" and filename_or_folder.find(".") < 0:
folder = os.path.dirname(filename_or_folder + "/")
else:
folder = os.path.dirname(filename_or_folder)
if not os.path.exists(folder):
try:
os.makedirs(folder)
except Exception as e: # pylint: disable=broad-except
print(f"Couldn't create folder: {folder}. Maybe due to a parallel process?")
print(e)
return filename_or_folder