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):