[WIP] dataloading cleanup (#332)

* testing; need to merge

* fixing wrong base file in models/base

* pushed input parser into datasets class to abstract away fetching data in dataloader

* slight name chage and all

* nits

* added dataparser

* added licnese
This commit is contained in:
evonneng authored and GitHub committed 2022-09-06 13:54:35 -07:00
1 parent e907bc5c71
commit 56113e6c75
29 files changed
+1048 -960

No files matched your search

+13
View File
@@ -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.
+282
View File
@@ -0,0 +1,282 @@
# 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.
"""
Data loader.
"""
from __future__ import annotations
import logging
from abc import abstractmethod
from typing import Dict, List, Optional, Tuple, Union
import torch
from torch import nn
from torch.nn import Parameter
from torch.utils.data.distributed import DistributedSampler
from nerfactory.cameras.rays import RayBundle
from nerfactory.configs import base as cfg
from nerfactory.datamanagers.dataloaders import (
CacheImageDataloader,
FixedIndicesEvalDataloader,
)
from nerfactory.datamanagers.datasets import InputDataset
from nerfactory.datamanagers.pixel_sampler import PixelSampler
from nerfactory.models.modules.ray_generator import RayGenerator
from nerfactory.utils.callbacks import TrainingCallback, TrainingCallbackAttributes
from nerfactory.utils.misc import IterableWrapper
class DataManager(nn.Module):
"""Generic data manager's abstract class
This version of the data manager is designed be a monolithic way to load data and latents,
especially since this may contain learnable parameters which need to be shared across the train
and test data managers. The idea is that we have setup methods for train and eval separately and
this can be a combined train/eval if you want.
Usage:
To get data, use the next_train and next_eval functions.
This data manager's next_train and next_eval methods will return 2 things:
1. A Raybundle: This will contain the rays we are sampling, with latents and
conditionals attached (everything needed at inference)
2. A "batch" of auxilury information: This will contain the mask, the ground truth
pixels, etc needed to actually train, score, etc the model
Rationale:
Because of this abstraction we've added, we can support more NeRF paradigms beyond the
vanilla nerf paradigm of single-scene, fixed-images, no-learnt-latents.
We can now support variable scenes, variable number of images, and arbitrary latents.
Train Methods:
setup_train: sets up for being used as train
iter_train: will be called on __iter__() for the train iterator
next_train: will be called on __next__() for the training iterator
get_train_iterable: utility that gets a clean pythonic iterator for your training data
Eval Methods:
setup_eval: sets up for being used as eval
iter_eval: will be called on __iter__() for the eval iterator
next_eval: will be called on __next__() for the eval iterator
get_eval_iterable: utility that gets a clean pythonic iterator for your eval data
Attributes:
train_count (int): the step number of our train iteration, needs to be incremented manually
eval_count (int): the step number of our eval iteration, needs to be incremented manually
train_input_dataset (InputDataset): the input dataset for the train dataset
eval_input_dataset (InputDataset): the input dataset for the eval dataset
Additional attributes specific to each subclass are defined in the setup_train and setup_eval
functions.
"""
train_input_dataset: Optional[InputDataset] = None
eval_input_dataset: Optional[InputDataset] = None
def __init__(self):
"""Constructor for the DataManager class.
Subclassed DataManagers will likely need to override this constructor.
If you aren't manually calling the setup_train and setup_eval functions from an overriden
constructor, that you call super().__init__() BEFORE you initialize any
nn.Modules or nn.Parameters, but AFTER you've already set all the attributes you need
for the setup functions."""
super().__init__()
self.train_count = 0
self.eval_count = 0
if self.train_input_dataset and self.train_input_dataset.inputs:
self.setup_train()
if self.eval_input_dataset and self.eval_input_dataset.inputs:
self.setup_eval()
def forward(self):
"""Blank forward method
This is an nn.Module, and so requires a forward() method normally, although in our case
we do not need a forward() method"""
raise NotImplementedError
def iter_train(self):
"""The __iter__ function for the train iterator.
This only exists to assist the get_train_iterable function, since we need to pass
in an __iter__ function for our trivial iterable that we are making."""
self.train_count = 0
def iter_eval(self):
"""The __iter__ function for the eval iterator.
This only exists to assist the get_eval_iterable function, since we need to pass
in an __iter__ function for our trivial iterable that we are making."""
self.eval_count = 0
def get_train_iterable(self, length=-1) -> IterableWrapper:
"""Gets a trivial pythonic iterator that will use the iter_train and next_train functions
as __iter__ and __next__ methods respectivley.
This basically is just a little utility if you want to do something like:
| for ray_bundle, batch in datamanager.get_train_iterable():
| <eval code here>
since the returned IterableWrapper is just an iterator with the __iter__ and __next__
methods (methods bound to our DataManager instance in this case) specified in the constructor.
"""
return IterableWrapper(self.iter_train, self.next_train, length)
def get_eval_iterable(self, length=-1) -> IterableWrapper:
"""Gets a trivial pythonic iterator that will use the iter_eval and next_eval functions
as __iter__ and __next__ methods respectivley.
This basically is just a little utility if you want to do something like:
| for ray_bundle, batch in datamanager.get_eval_iterable():
| <eval code here>
since the returned IterableWrapper is just an iterator with the __iter__ and __next__
methods (methods bound to our DataManager instance in this case) specified in the constructor.
"""
return IterableWrapper(self.iter_eval, self.next_eval, length)
@abstractmethod
def setup_train(self):
"""Sets up the data manager for training.
Here you will define any subclass specific object attributes from the attribute"""
raise NotImplementedError
@abstractmethod
def setup_eval(self):
"""Sets up the data manager for evaluation"""
raise NotImplementedError
@abstractmethod
def next_train(self) -> Tuple:
"""Returns the next batch of data from the train data manager.
This will be a tuple of all the information that this data manager outputs.
"""
raise NotImplementedError
@abstractmethod
def next_eval(self) -> Tuple:
"""Returns the next batch of data from the eval data manager.
This will be a tuple of all the information that this data manager outputs.
"""
raise NotImplementedError
def get_training_callbacks( # pylint:disable=no-self-use
self, training_callback_attributes: TrainingCallbackAttributes # pylint: disable=unused-argument
) -> List[TrainingCallback]:
"""Returns a list of callbacks to be used during training."""
return []
@abstractmethod
def get_param_groups(self) -> Dict[str, List[Parameter]]: # pylint: disable=no-self-use
"""Get the param groups for the data manager.
Returns:
A list of dictionaries containing the data manager's param groups.
"""
return {}
class VanillaDataManager(DataManager): # pylint: disable=abstract-method
"""Basic stored data manager implementation.
This is pretty much a port over from our old dataloading utilities, and is a little jank
under the hood. We may clean this up a little bit under the hood with more standard dataloading
components that can be strung together, but it can be just used as a black box for now since
only the constructor is likely to change in the future, or maybe passing in step number to the
next_train and next_eval functions."""
config: cfg.VanillaDataManagerConfig
def __init__(
self,
config: cfg.VanillaDataManagerConfig,
device: Union[torch.device, str] = "cpu",
test_mode: bool = False,
world_size: int = 1,
local_rank: int = 0,
**kwargs, # pylint: disable=unused-argument
):
self.config = config
self.device = device
self.world_size = world_size
self.local_rank = local_rank
self.sampler = None
if config.eval_dataparser is None:
logging.info("No eval dataset specified so using train dataset for eval.")
config.eval_dataparser = config.train_dataparser
self.train_input_dataset = InputDataset(config.train_dataparser, split="train")
self.eval_input_dataset = InputDataset(config.eval_dataparser, split="val" if not test_mode else "test")
super().__init__()
def setup_train(self):
"""Sets up the data loaders for training"""
assert self.train_input_dataset is not None
if self.world_size > 1:
self.sampler = DistributedSampler(
self.train_input_dataset, num_replicas=self.world_size, rank=self.local_rank, shuffle=True, seed=42
)
self.train_image_dataloader = CacheImageDataloader(
self.train_input_dataset,
num_images_to_sample_from=self.config.train_num_images_to_sample_from,
device=self.device,
num_workers=self.world_size * 4,
pin_memory=True,
sampler=self.sampler,
) # TODO(ethan): pass this in
else:
self.train_image_dataloader = CacheImageDataloader(
self.train_input_dataset,
num_images_to_sample_from=self.config.train_num_images_to_sample_from,
device=self.device,
)
self.iter_train_image_dataloader = iter(self.train_image_dataloader)
self.train_pixel_sampler = PixelSampler(self.config.train_num_rays_per_batch)
self.train_ray_generator = RayGenerator(self.train_input_dataset.inputs.cameras.to(self.device))
def setup_eval(self):
"""Sets up the data loader for evaluation"""
assert self.eval_input_dataset is not None
self.eval_dataloader = FixedIndicesEvalDataloader(
input_dataset=self.eval_input_dataset,
num_rays_per_chunk=self.config.eval_num_rays_per_chunk,
image_indices=self.config.eval_image_indices,
device=self.device,
num_workers=0 if self.world_size == 1 else self.world_size * 4,
)
def next_train(self) -> Tuple[RayBundle, Dict]:
"""Returns the next batch of data from the train dataloader.
The RayBundle can be shaped in whatever way."""
self.train_count += 1
image_batch = next(self.iter_train_image_dataloader)
batch = self.train_pixel_sampler.sample(image_batch)
ray_indices = batch["indices"]
ray_bundle = self.train_ray_generator(ray_indices)
return ray_bundle, batch
def next_eval(self) -> Tuple[RayBundle, Dict]:
"""Returns the next batch of data from the eval dataloader.
The RayBundle should be shaped like an image."""
self.eval_count += 1
assert self.eval_dataloader is not None, "Must setup eval dataloader before calling next_eval"
camera_ray_bundle, batch = next(self.eval_dataloader)
return camera_ray_bundle, batch
+238
View File
@@ -0,0 +1,238 @@
# 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 sampling images from a dataset of images.
"""
import random
from abc import abstractmethod
from typing import Dict, Optional, Tuple, Union
import torch
from torch.utils.data import default_collate
from torch.utils.data.dataloader import DataLoader
from nerfactory.cameras.cameras import Cameras
from nerfactory.cameras.rays import RayBundle
from nerfactory.datamanagers.datasets import InputDataset
from nerfactory.utils.misc import get_dict_to_torch
class CacheImageDataloader(DataLoader):
"""Collated image dataset that implements caching of images.
Creates batches of the InputDataset return type.
Args:
dataset (torch.utils.data.Dataset): Dataset to sample from.
num_samples_to_collate (int, optional): How many images to sample rays for each batch. Defaults to all images.
num_times_to_repeat_images (int): How often to collate new images. Defaults to every iteration.
device (Union[torch.device, str]): Device to perform computation. Defaults to "cpu".
"""
def __init__(
self,
dataset: InputDataset,
num_images_to_sample_from: int = -1,
num_times_to_repeat_images: int = 0,
device: Union[torch.device, str] = "cpu",
**kwargs,
):
self.dataset = dataset
self.num_times_to_repeat_images = num_times_to_repeat_images
self.cache_all_images = num_images_to_sample_from == -1
self.num_images_to_sample_from = len(self.dataset) if self.cache_all_images else num_images_to_sample_from
self.device = device
self.num_repeated = self.num_times_to_repeat_images # starting value
self.first_time = True
self.cached_collated_batch = None
if self.cache_all_images:
self.cached_collated_batch = self._get_collated_batch()
super().__init__(dataset=dataset, **kwargs)
def __getitem__(self, idx):
return self.dataset.__getitem__(idx)
def _get_batch_list(self):
"""Returns a list of batches from the dataset attribute."""
indices = random.sample(range(len(self.dataset)), k=self.num_images_to_sample_from)
batch_list = [self.dataset.__getitem__(idx) for idx in indices]
return batch_list
def _get_collated_batch(self):
"""Returns a collated batch."""
batch_list = self._get_batch_list()
collated_batch = default_collate(batch_list)
collated_batch = get_dict_to_torch(collated_batch, device=self.device)
return collated_batch
def __iter__(self):
while True:
if self.cache_all_images:
collated_batch = self.cached_collated_batch
elif self.first_time or (
self.num_times_to_repeat_images != -1 and self.num_repeated >= self.num_times_to_repeat_images
):
# trigger a reset
self.num_repeated = 0
collated_batch = self._get_collated_batch()
# possibly save a cached item
self.cached_collated_batch = collated_batch if self.num_times_to_repeat_images != 0 else None
self.first_time = False
else:
collated_batch = self.cached_collated_batch
self.num_repeated += 1
yield collated_batch
class EvalDataloader(DataLoader):
"""Evaluation dataloader base class
Args:
input_dataset: InputDataset to load data from
cameras: Cameras to use for generating rays
num_rays_per_chunk: Number of camera rays to generate per chunk
device: Device to load data to
"""
def __init__(
self,
input_dataset: InputDataset,
num_rays_per_chunk: int,
device: Union[torch.device, str] = "cpu",
**kwargs,
):
self.input_dataset = input_dataset
self.cameras = input_dataset.inputs.cameras.to(device)
self.num_rays_per_chunk = num_rays_per_chunk
self.device = device
self.kwargs = kwargs
super().__init__(dataset=input_dataset)
@abstractmethod
def __iter__(self):
"""Iterates over the dataset"""
return self
@abstractmethod
def __next__(self) -> Tuple[RayBundle, Dict]:
"""Returns the next batch of data"""
def get_camera(self, image_idx: int = 0) -> Cameras:
"""Get camera for the given image index
Args:
image_idx: Camera image index
"""
distortion_params = None
if self.cameras.distortion_params is not None:
distortion_params = self.cameras.distortion_params[image_idx]
camera = Cameras(
fx=self.cameras.fx[image_idx],
fy=self.cameras.fy[image_idx],
cx=self.cameras.cx,
cy=self.cameras.cy,
camera_to_worlds=self.cameras.camera_to_worlds[image_idx],
distortion_params=distortion_params,
camera_type=self.cameras.camera_type,
)
return camera
def get_data_from_image_idx(self, image_idx) -> Tuple[RayBundle, Dict]:
"""Returns the data for a specific image index."""
ray_bundle = self.cameras.generate_rays(camera_indices=image_idx)
ray_bundle.num_rays_per_chunk = self.num_rays_per_chunk
ray_bundle.camera_indices = torch.Tensor([image_idx])[..., None].int()
batch = self.input_dataset[image_idx]
batch = get_dict_to_torch(batch, device=self.device)
return ray_bundle, batch
class FixedIndicesEvalDataloader(EvalDataloader):
"""Dataloader that returns a fixed set of indices."""
def __init__(
self,
input_dataset: InputDataset,
num_rays_per_chunk: int,
image_indices: Optional[Tuple[int]] = None,
device: Union[torch.device, str] = "cpu",
**kwargs,
):
"""
Args:
input_dataset: InputDataset to load data from
cameras: Cameras to use for generating rays
num_rays_per_chunk: Number of camera rays to generate per chunk
image_indices: List of image indices to load data from. If None, then use all images.
device: Device to load data to
"""
super().__init__(input_dataset, num_rays_per_chunk, device, **kwargs)
if image_indices is None:
self.image_indices = list(range(len(input_dataset)))
else:
self.image_indices = image_indices
self.num_rays_per_chunk = num_rays_per_chunk
self.count = 0
def __iter__(self):
self.count = 0
return self
def __next__(self):
if self.count < len(self.image_indices):
image_idx = self.image_indices[self.count]
ray_bundle, batch = self.get_data_from_image_idx(image_idx)
ray_bundle.num_rays_per_chunk = self.num_rays_per_chunk
self.count += 1
return ray_bundle, batch
raise StopIteration
class RandIndicesEvalDataloader(EvalDataloader):
"""Dataloader that returns random images.
Args:
input_dataset: InputDataset to load data from
cameras: Cameras to use for generating rays
num_rays_per_chunk: Number of camera rays to generate per chunk
device: Device to load data to
"""
def __init__(
self,
input_dataset: InputDataset,
num_rays_per_chunk: int,
device: Union[torch.device, str] = "cpu",
**kwargs,
):
super().__init__(input_dataset, num_rays_per_chunk, device, **kwargs)
self.count = 0
def __iter__(self):
self.count = 0
return self
def __next__(self):
if self.count < 1:
image_indices = range(self.cameras.size)
image_idx = random.choice(image_indices)
ray_bundle, batch = self.get_data_from_image_idx(image_idx)
self.count += 1
return ray_bundle, batch
raise StopIteration
+106
View File
@@ -0,0 +1,106 @@
# 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.
"""A set of standard datasets."""
from __future__ import annotations
import dataclasses
import logging
from abc import abstractmethod
from dataclasses import dataclass
from pathlib import Path
from nerfactory.configs import base as cfg
from nerfactory.datamanagers.structs import DatasetInputs
from nerfactory.utils.io import get_absolute_path, load_from_pkl, write_to_pkl
from nerfactory.utils.misc import get_hash_str_from_dict
@dataclass
class DataParser:
"""A dataset."""
def __init__(self, config: cfg.DataParserConfig):
super().__init__()
self.config = config
@abstractmethod
def _generate_dataset_inputs(self, split: str = "train") -> DatasetInputs:
"""Returns the dataset inputs for the given split.
Args:
split: Which dataset split to generate.
Returns:
DatasetInputs
"""
def get_dataset_inputs(self, split: str = "train", use_preprocessing_cache: bool = False) -> DatasetInputs:
"""Returns the dataset inputs for the given split.
Args:
split: Which dataset split to generate.
use_preprocessing_cache: Whether to use the cached dataset inputs. Defaults to False.
Returns:
DatasetInputs
"""
if use_preprocessing_cache:
dataset_inputs = self._get_dataset_inputs_from_cache(split)
else:
dataset_inputs = self._generate_dataset_inputs(split)
return dataset_inputs
def _get_cache_filename(self, split: str) -> Path:
"""Creates a cache filename from the dataset inputs arguments.
Args:
split: Which dataset split to generate filename for.
Returns:
filename for cache.
"""
dataset_config_hash = get_hash_str_from_dict(dataclasses.asdict(self))
dataset_config_hash_filename = get_absolute_path(
f"cache/dataset_inputs/{dataset_config_hash}-{split}.pkl"
).parent.mkdir()
assert dataset_config_hash_filename is not None, "dataset hash is None"
return dataset_config_hash_filename
def save_dataset_inputs_to_cache(self, split: str):
"""Saves the dataset inputs to cache.
Args:
split: Which dataset split to save.
"""
dataset_inputs = self.get_dataset_inputs(split=split)
dataset_config_hash_filename = self._get_cache_filename(split)
write_to_pkl(dataset_config_hash_filename, dataset_inputs)
def _get_dataset_inputs_from_cache(self, split: str) -> DatasetInputs:
"""Loads the dataset inputs from cache. If the cache does not exist, it will be created.
Args:
split: Which dataset split to load.
"""
dataset_config_hash_filename = self._get_cache_filename(split)
if dataset_config_hash_filename.exists():
logging.info("Loading dataset from cache.")
dataset_inputs = load_from_pkl(dataset_config_hash_filename)
else:
logging.info("Cache file not found. Generating and saving dataset to cache.")
dataset_inputs = self._generate_dataset_inputs(split=split)
self.save_dataset_inputs_to_cache(split)
return dataset_inputs
@@ -0,0 +1,95 @@
# 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.
"""Data parser for blender dataset"""
from __future__ import annotations
from dataclasses import dataclass
from pathlib import Path
import imageio
import numpy as np
import torch
from nerfactory.cameras.cameras import Cameras, CameraType
from nerfactory.configs import base as cfg
from nerfactory.datamanagers.dataparsers.base import DataParser
from nerfactory.datamanagers.structs import DatasetInputs, SceneBounds
from nerfactory.utils.colors import get_color
from nerfactory.utils.io import get_absolute_path, load_from_json
@dataclass
class Blender(DataParser):
"""Blender Dataset
Some of this code comes from https://github.com/yenchenlin/nerf-pytorch/blob/master/load_blender.py#L37.
Args:
data_directory: Location of data
alpha_color: Sets transparent regions to specified color, otherwise black.
scale_factor: How much to scale the camera origins by.
"""
def __init__(self, config: cfg.BlenderDataParserConfig):
super().__init__(config=config)
self.data_directory: Path = config.data_directory
self.scale_factor: float = config.scale_factor
self.alpha_color = config.alpha_color
def _generate_dataset_inputs(self, split="train"):
if self.alpha_color is not None:
alpha_color_tensor = get_color(self.alpha_color)
else:
alpha_color_tensor = None
abs_dir = get_absolute_path(self.data_directory)
meta = load_from_json(abs_dir / f"transforms_{split}.json")
image_filenames = []
poses = []
for frame in meta["frames"]:
fname = abs_dir / Path(frame["file_path"].replace("./", "") + ".png")
image_filenames.append(fname)
poses.append(np.array(frame["transform_matrix"]))
poses = np.array(poses).astype(np.float32)
img_0 = imageio.imread(image_filenames[0])
image_height, image_width = img_0.shape[:2]
camera_angle_x = float(meta["camera_angle_x"])
focal_length = 0.5 * image_width / np.tan(0.5 * camera_angle_x)
cx = image_width / 2.0
cy = image_height / 2.0
camera_to_world = torch.from_numpy(poses[:, :3]) # camera to world transform
# in x,y,z order
camera_to_world[..., 3] *= self.scale_factor
scene_bounds = SceneBounds(aabb=torch.tensor([[-1.5, -1.5, -1.5], [1.5, 1.5, 1.5]], dtype=torch.float32))
cameras = Cameras(
camera_to_worlds=camera_to_world,
fx=focal_length,
fy=focal_length,
cx=cx,
cy=cy,
camera_type=CameraType.PERSPECTIVE,
)
dataset_inputs = DatasetInputs(
image_filenames=image_filenames,
cameras=cameras,
alpha_color=alpha_color_tensor,
scene_bounds=scene_bounds,
)
return dataset_inputs
@@ -0,0 +1,183 @@
# 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.
"""Data parser for friends dataset"""
from __future__ import annotations
from dataclasses import dataclass
from pathlib import Path
import numpy as np
import torch
from nerfactory.cameras.cameras import Cameras, CameraType
from nerfactory.datamanagers.dataparsers.base import DataParser
from nerfactory.datamanagers.structs import (
DatasetInputs,
PointCloud,
SceneBounds,
Semantics,
)
from nerfactory.utils.colmap_utils import (
read_cameras_binary,
read_images_binary,
read_points3d_binary,
)
from nerfactory.utils.io import get_absolute_path, load_from_json
@dataclass
class Friends(DataParser):
"""Friends Dataset
Args:
data_directory: Location of data
include_semantics: whether or not to include the semantics. Defaults to False.
include_point_cloud: whether or not to include the point cloud. Defaults to False.
"""
data_directory: Path
include_semantics: bool = True
include_point_cloud: bool = False
@classmethod
def _get_aabb_and_transform(cls, basedir):
"""Returns the aabb and pointcloud transform from the threejs.json file."""
filename = basedir / "threejs.json"
assert filename.exists()
data = load_from_json(filename)
# point cloud transformation
transposed_point_cloud_transform = np.array(data["object"]["children"][0]["matrix"]).reshape(4, 4).T
assert transposed_point_cloud_transform[3, 3] == 1.0
# bbox transformation
bbox_transform = np.array(data["object"]["children"][1]["matrix"]).reshape(4, 4).T
w, h, d = data["geometries"][1]["width"], data["geometries"][1]["height"], data["geometries"][1]["depth"]
temp = np.array([w, h, d]) / 2.0
bbox = np.array([-temp, temp])
bbox = np.concatenate([bbox, np.ones_like(bbox[:, 0:1])], axis=1)
bbox = (bbox_transform @ bbox.T).T[:, 0:3]
aabb = bbox # rename to aabb because it's an axis-aligned bounding box
return torch.from_numpy(aabb).float(), torch.from_numpy(transposed_point_cloud_transform).float()
def _generate_dataset_inputs(self, split="train"): # pylint: disable=too-many-statements
abs_dir = get_absolute_path(self.data_directory)
images_data = read_images_binary(abs_dir / "colmap" / "images.bin")
# `image_path` is only the end of the filename, including the extension e.g., `.jpg`
image_paths = sorted((abs_dir / "images").iterdir())
image_path_to_image_id = {}
image_id_to_image_path = {}
for v in images_data.values():
image_path_to_image_id[v.name] = v.id
image_id_to_image_path[v.id] = v.name
# TODO: handle the splits differently
image_filenames = [abs_dir / "images" / image_path for image_path in image_paths]
# -- set the bounding box ---
aabb, transposed_point_cloud_transform = self._get_aabb_and_transform(abs_dir)
scene_bounds_original = SceneBounds(aabb=aabb)
# for shifting and rescale accoding to scene bounds
box_center = scene_bounds_original.get_center()
box_scale_factor = 5.0 / scene_bounds_original.get_diagonal_length() # the target diagonal length
scene_bounds = scene_bounds_original.get_centered_and_scaled_scene_bounds(box_scale_factor)
# --- intrinsics ---
cameras_data = read_cameras_binary(abs_dir / "colmap" / "cameras.bin")
focal_lengths = []
for image_path in image_paths:
cam = cameras_data[image_path_to_image_id[image_path]]
assert len(cam.params) == 3
focal_lengths.append(cam.params[0]) # f (fx and fy)
focal_lengths = torch.stack(focal_lengths, dim=0)
cam = cameras_data[image_path_to_image_id[image_paths[0]]]
cx = cam.params[1] # cx
cy = cam.params[2] # cy
# --- camera_to_world (extrinsics) ---
camera_to_world = []
bottom_row = np.array([0, 0, 0, 1.0]).reshape(1, 4)
for image_path in image_paths:
image_data = images_data[image_path_to_image_id[image_path]]
rot = image_data.qvec2rotmat()
trans = image_data.tvec.reshape(3, 1)
c2w = np.concatenate([np.concatenate([rot, trans], 1), bottom_row], 0)
camera_to_world.append(c2w)
camera_to_world = torch.tensor(np.array(camera_to_world)).float()
camera_to_world = torch.inverse(camera_to_world)
camera_to_world[..., 1:3] *= -1
camera_to_world = transposed_point_cloud_transform @ camera_to_world
camera_to_world = camera_to_world[:, :3]
camera_to_world[..., 3] = (camera_to_world[..., 3] - box_center) * box_scale_factor # center and rescale
# --- semantics ---
semantics = None
if self.include_semantics:
thing_filenames = [
Path(str(image_filename).replace("/images/", "/segmentations/thing/").replace(".jpg", ".png"))
for image_filename in image_filenames
]
stuff_filenames = [
Path(str(image_filename).replace("/images/", "/segmentations/stuff/").replace(".jpg", ".png"))
for image_filename in image_filenames
]
panoptic_classes = load_from_json(abs_dir / "panoptic_classes.json")
stuff_classes = panoptic_classes["stuff"]
stuff_colors = torch.tensor(panoptic_classes["stuff_colors"], dtype=torch.float32) / 255.0
thing_classes = panoptic_classes["thing"]
thing_colors = torch.tensor(panoptic_classes["thing_colors"], dtype=torch.float32) / 255.0
semantics = Semantics(
stuff_classes=stuff_classes,
stuff_colors=stuff_colors,
stuff_filenames=stuff_filenames,
thing_classes=thing_classes,
thing_colors=thing_colors,
thing_filenames=thing_filenames,
)
# Possibly include the sparse point cloud from COLMAP in the dataset inputs.
# NOTE(ethan): this will be common across the different splits.
point_cloud = PointCloud()
if self.include_point_cloud:
points_3d = read_points3d_binary(abs_dir / "colmap" / "points3D.bin")
xyz = torch.tensor(np.array([p_value.xyz for p_id, p_value in points_3d.items()])).float()
rgb = torch.tensor(np.array([p_value.rgb for p_id, p_value in points_3d.items()])).float()
xyz_h = torch.cat([xyz, torch.ones_like(xyz[..., :1])], -1)
xyz = (xyz_h @ transposed_point_cloud_transform.T)[..., :3]
xyz = (xyz - box_center) * box_scale_factor # center and rescale
point_cloud.xyz = xyz
point_cloud.rgb = rgb
cameras = Cameras(
fx=focal_lengths,
fy=focal_lengths,
cx=cx,
cy=cy,
camera_to_worlds=camera_to_world,
camera_type=CameraType.PERSPECTIVE,
)
dataset_inputs = DatasetInputs(
image_filenames=image_filenames,
cameras=cameras,
semantics=semantics,
point_cloud=point_cloud,
scene_bounds=scene_bounds,
)
return dataset_inputs
@@ -0,0 +1,106 @@
# 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.
"""Data parser for instant ngp data"""
from __future__ import annotations
import logging
from dataclasses import dataclass
from pathlib import Path
import numpy as np
import torch
from nerfactory.cameras import utils as camera_utils
from nerfactory.cameras.cameras import Cameras, CameraType
from nerfactory.configs import base as cfg
from nerfactory.datamanagers.dataparsers.base import DataParser
from nerfactory.datamanagers.structs import DatasetInputs, SceneBounds
from nerfactory.utils.io import get_absolute_path, load_from_json
@dataclass
class InstantNGP(DataParser):
"""Instant NGP Dataset
Args:
data_directory: Location of data
scale_factor: How much to scale the camera origins by.
scene_scale: How much to scale the scene. Defaults to 0.33
"""
config: cfg.InstantNGPDataParserConfig
def _generate_dataset_inputs(self, split="train"):
abs_dir = get_absolute_path(self.config.data_directory)
meta = load_from_json(abs_dir / "transforms.json")
image_filenames = []
poses = []
num_skipped_image_filenames = 0
for frame in meta["frames"]:
fname = abs_dir / Path(frame["file_path"])
if not fname:
num_skipped_image_filenames += 1
else:
image_filenames.append(fname)
poses.append(np.array(frame["transform_matrix"]))
if num_skipped_image_filenames >= 0:
logging.info("Skipping %s files in dataset split %s.", num_skipped_image_filenames, split)
assert (
len(image_filenames) != 0
), """
No image files found.
You should check the file_paths in the transforms.json file to make sure they are correct.
"""
poses = np.array(poses).astype(np.float32)
poses[:3, 3] *= self.config.scene_scale
camera_to_world = torch.from_numpy(poses[:, :3]) # camera to world transform
distortion_params = camera_utils.get_distortion_params(
k1=float(meta["k1"]), k2=float(meta["k2"]), p1=float(meta["p1"]), p2=float(meta["p2"])
)
# in x,y,z order
# assumes that the scene is centered at the origin
aabb_scale = meta["aabb_scale"]
scene_bounds = SceneBounds(
aabb=torch.tensor(
[[-aabb_scale, -aabb_scale, -aabb_scale], [aabb_scale, aabb_scale, aabb_scale]], dtype=torch.float32
)
)
cameras = Cameras(
fx=float(meta["fl_x"]),
fy=float(meta["fl_y"]),
cx=float(meta["cx"]),
cy=float(meta["cy"]),
distortion_params=distortion_params,
height=int(meta["h"]),
width=int(meta["w"]),
camera_to_worlds=camera_to_world,
camera_type=CameraType.PERSPECTIVE,
)
# TODO(ethan): add alpha background color
dataset_inputs = DatasetInputs(
image_filenames=image_filenames,
cameras=cameras,
scene_bounds=scene_bounds,
)
return dataset_inputs
@@ -0,0 +1,151 @@
# 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.
"""Data parser for mipnerf dataset"""
from __future__ import annotations
from dataclasses import dataclass
import imageio
import numpy as np
import torch
from nerfactory.cameras.cameras import Cameras, CameraType
from nerfactory.configs import base as cfg
from nerfactory.datamanagers.dataparsers.base import DataParser
from nerfactory.datamanagers.structs import DatasetInputs, SceneBounds
from nerfactory.utils.io import get_absolute_path
@dataclass
class Mipnerf360(DataParser):
"""MipNeRF 360 Dataset
Args:
data_directory: Location of data
downscale_factor: How much to downscale images. Defaults to 1.
val_skip: 1/val_skip images to use for validation. Defaults to 8.
auto_scale: Scale based on pose bounds. Defaults to True.
aabb_scale: Scene scale, Defaults to 1.0.
"""
config: cfg.MipNerf360DataParserConfig
@classmethod
def normalize_orientation(cls, poses: np.ndarray):
"""Set the _up_ direction to be in the positive Y direction.
Args:
poses: Numpy array of poses.
"""
poses_orig = poses.copy()
bottom = np.reshape([0, 0, 0, 1.0], [1, 4])
center = poses[:, :3, 3].mean(0)
vec2 = poses[:, :3, 2].sum(0) / np.linalg.norm(poses[:, :3, 2].sum(0))
up = poses[:, :3, 1].sum(0)
vec0 = np.cross(up, vec2) / np.linalg.norm(np.cross(up, vec2))
vec1 = np.cross(vec2, vec0) / np.linalg.norm(np.cross(vec2, vec0))
c2w = np.stack([vec0, vec1, vec2, center], -1) # [3, 4]
c2w = np.concatenate([c2w[:3, :4], bottom], -2) # [4, 4]
bottom = np.tile(np.reshape(bottom, [1, 1, 4]), [poses.shape[0], 1, 1]) # [BS, 1, 4]
poses = np.concatenate([poses[:, :3, :4], bottom], -2) # [BS, 4, 4]
poses = np.linalg.inv(c2w) @ poses
poses_orig[:, :3, :4] = poses[:, :3, :4]
return poses_orig
def _generate_dataset_inputs(self, split="train"):
abs_dir = get_absolute_path(self.config.data_directory)
image_dir = "images"
if self.config.downscale_factor > 1:
image_dir += f"_{self.config.downscale_factor}"
image_dir = abs_dir / image_dir
if not image_dir.exists():
raise ValueError(f"Image directory {image_dir} doesn't exist")
valid_formats = [".jpg", ".png"]
image_filenames = []
for f in image_dir.iterdir():
ext = f.suffix
if ext.lower() not in valid_formats:
continue
image_filenames.append(image_dir / f)
image_filenames = sorted(image_filenames)
num_images = len(image_filenames)
poses_data = np.load(abs_dir / "poses_bounds.npy")
poses = poses_data[:, :-2].reshape([-1, 3, 5]).astype(np.float32)
bounds = poses_data[:, -2:].transpose([1, 0])
if num_images != poses.shape[0]:
raise RuntimeError(f"Different number of images ({num_images}), and poses ({poses.shape[0]})")
idx_test = np.arange(num_images)[:: self.config.val_skip]
idx_train = np.array([i for i in np.arange(num_images) if i not in idx_test])
idx = idx_train if split == "train" else idx_test
image_filenames = np.array(image_filenames)[idx]
poses = poses[idx]
img_0 = imageio.imread(image_filenames[0])
image_height, image_width = img_0.shape[:2]
poses[:, :2, 4] = np.array([image_height, image_width])
poses[:, 2, 4] = poses[:, 2, 4]
# Reorder pose to match our convention
poses = np.concatenate([poses[:, :, 1:2], -poses[:, :, 0:1], poses[:, :, 2:]], axis=-1)
# Center poses and rotate. (Compute up from average of all poses)
poses = self.normalize_orientation(poses)
# Scale factor used in mipnerf
if self.config.auto_scale:
scale_factor = 1 / (np.min(bounds) * 0.75)
poses[:, :3, 3] *= scale_factor
bounds *= scale_factor
# Center poses
poses[:, :3, 3] = poses[:, :3, 3] - np.mean(poses[:, :3, :], axis=0)[:, 3]
focal_length = poses[0, -1, -1]
cx = image_width / 2.0
cy = image_height / 2.0
camera_to_world = torch.from_numpy(poses[:, :3, :4]) # camera to world transform
num_cameras = len(image_filenames)
num_intrinsics_params = 3
intrinsics = torch.ones((num_cameras, num_intrinsics_params), dtype=torch.float32)
intrinsics *= torch.tensor([cx, cy, focal_length])
aabb = torch.tensor([[-4, -4, -4], [4, 4, 4]], dtype=torch.float32) * self.config.aabb_scale
scene_bounds = SceneBounds(aabb=aabb)
cameras = Cameras(
fx=focal_length,
fy=focal_length,
cx=cx,
cy=cy,
camera_to_worlds=camera_to_world,
camera_type=CameraType.PERSPECTIVE,
)
cameras.rescale_output_resolution(scaling_factor=1.0 / self.config.downscale_factor)
dataset_inputs = DatasetInputs(
image_filenames=image_filenames,
cameras=cameras,
scene_bounds=scene_bounds,
)
return dataset_inputs
@@ -0,0 +1,112 @@
# 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.
from __future__ import annotations
import logging
from dataclasses import dataclass
from pathlib import Path
import numpy as np
import torch
from nerfactory.cameras import utils as camera_utils
from nerfactory.cameras.cameras import Cameras, CameraType
from nerfactory.configs import base as cfg
from nerfactory.datamanagers.dataparsers.base import DataParser
from nerfactory.datamanagers.structs import DatasetInputs, SceneBounds
from nerfactory.utils.io import get_absolute_path, load_from_json
@dataclass
class Nerfactory(DataParser):
"""Nerfactory Dataset
Args:
data_directory: Location of data
scale_factor: How much to scale the camera origins by.
downscale_factor: How much to downscale images.
scene_scale: How much to scale the scene.
orientation_method: The method to use for orientation. Either "pca" or "up".
"""
config: cfg.NerfactoryDataParserConfig
def _generate_dataset_inputs(self, split="train"):
abs_dir = get_absolute_path(self.config.data_directory)
meta = load_from_json(abs_dir / "transforms.json")
image_filenames = []
poses = []
num_skipped_image_filenames = 0
for frame in meta["frames"]:
fname = abs_dir / Path(frame["file_path"])
if self.config.downscale_factor > 1:
fname = abs_dir / f"images_{self.config.downscale_factor}" / Path(frame["file_path"]).name
else:
fname = abs_dir / Path(frame["file_path"])
if not fname:
num_skipped_image_filenames += 1
else:
image_filenames.append(fname)
poses.append(np.array(frame["transform_matrix"]))
if num_skipped_image_filenames >= 0:
logging.info("Skipping %s files in dataset split %s.", num_skipped_image_filenames, split)
assert (
len(image_filenames) != 0
), """
No image files found.
You should check the file_paths in the transforms.json file to make sure they are correct.
"""
poses = torch.from_numpy(np.array(poses).astype(np.float32))
poses = camera_utils.auto_orient_poses(poses, method=self.config.orientation_method)
# Scale poses
scale_factor = 1.0 / torch.max(torch.abs(poses[:, :3, 3]))
poses[:, :3, 3] *= scale_factor
distortion_params = camera_utils.get_distortion_params(
k1=float(meta["k1"]), k2=float(meta["k2"]), p1=float(meta["p1"]), p2=float(meta["p2"])
)
# in x,y,z order
# assumes that the scene is centered at the origin
aabb_scale = self.config.scene_scale
scene_bounds = SceneBounds(
aabb=torch.tensor(
[[-aabb_scale, -aabb_scale, -aabb_scale], [aabb_scale, aabb_scale, aabb_scale]], dtype=torch.float32
)
)
cameras = Cameras(
fx=float(meta["fl_x"]),
fy=float(meta["fl_y"]),
cx=float(meta["cx"]),
cy=float(meta["cy"]),
distortion_params=distortion_params,
height=int(meta["h"]),
width=int(meta["w"]),
camera_to_worlds=poses[:, :3, :4],
camera_type=CameraType.PERSPECTIVE,
)
cameras.rescale_output_resolution(scaling_factor=1.0 / self.config.downscale_factor)
dataset_inputs = DatasetInputs(
image_filenames=image_filenames,
cameras=cameras,
scene_bounds=scene_bounds,
)
return dataset_inputs
@@ -0,0 +1,148 @@
# 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.
"""Data parser for record3d dataset"""
from __future__ import annotations
from dataclasses import dataclass
import numpy as np
import torch
from scipy.spatial.transform import Rotation
from nerfactory.cameras.cameras import Cameras, CameraType
from nerfactory.configs import base as cfg
from nerfactory.datamanagers.dataparsers.base import DataParser
from nerfactory.datamanagers.dataparsers.mipnerf_parser import Mipnerf360
from nerfactory.datamanagers.structs import DatasetInputs, SceneBounds
from nerfactory.utils.io import get_absolute_path, load_from_json
@dataclass
class Record3D(DataParser):
"""Record3D Dataset
Args:
data_directory: Location of data
val_skip: 1/val_skip images to use for validation. Defaults to 8.
aabb_scale: Scene scale, Defaults to 4.0.
max_dataset_size: Max number of images to train on. If the dataset has
more, images will be sampled approximately evenly. Defaults to 150.
"""
config: cfg.Record3DDataParserConfig
def _generate_dataset_inputs(self, split: str = "train") -> DatasetInputs:
abs_dir = get_absolute_path(self.config.data_directory)
image_dir = abs_dir / "rgb"
if not image_dir.exists():
raise ValueError(f"Image directory {image_dir} doesn't exist")
image_filenames = []
for f in image_dir.iterdir():
if f.stem.isdigit(): # removes possible duplicate images (for example, 123(3).jpg)
image_filenames.append(image_dir / f)
image_filenames = sorted(image_filenames, key=lambda fn: int(fn.stem))
image_filenames = np.array(image_filenames)
num_images = len(image_filenames)
metadata_path = abs_dir / "metadata.json"
metadata_dict = load_from_json(metadata_path)
poses_data = np.array(metadata_dict["poses"])
# (N, 3, 4)
poses = np.concatenate(
[Rotation.from_quat(poses_data[:, :4]).as_matrix(), poses_data[:, 4:, None]],
axis=-1,
).astype(np.float32)
if num_images > self.config.max_dataset_size:
# Evenly select max_dataset_size images from dataset, including first
# and last indices.
idx = np.round(np.linspace(0, num_images - 1, self.config.max_dataset_size)).astype(int)
poses = poses[idx]
image_filenames = image_filenames[idx]
num_images = len(image_filenames)
# Normalization similar to Mipnerf360
poses = Mipnerf360.normalize_orientation(poses)
bottom = np.reshape([0, 0, 0, 1.0], [1, 4])
bottom = np.tile(np.reshape(bottom, [1, 1, 4]), [poses.shape[0], 1, 1])
poses = np.concatenate([poses[:, :3, :4], bottom], -2).astype(np.float32)
rotation_matrix = np.array(
[
[1.0, 0.0, 0.0, 0.0],
[0.0, 0.0, -1.0, 0.0],
[0.0, 1.0, 0.0, 0.0],
[0.0, 0.0, 0.0, 1.0],
],
dtype=np.float32,
)
poses = rotation_matrix @ poses
idx_test = np.arange(num_images)[:: self.config.val_skip]
idx_train = np.array([i for i in np.arange(num_images) if i not in idx_test])
idx = idx_train if split == "train" else idx_test
if num_images != poses.shape[0]:
raise RuntimeError(f"Different number of images ({num_images}), and poses ({poses.shape[0]})")
image_filenames = image_filenames[idx]
poses = poses[idx]
# Centering poses
poses[:, :3, 3] = poses[:, :3, 3] - np.mean(poses[:, :3, 3], axis=0)
camera_to_world = torch.from_numpy(poses[:, :3, :4]) # camera to world transform
# Camera intrinsics
K = np.array(metadata_dict["K"]).reshape((3, 3)).T
focal_length = K[0, 0]
H = metadata_dict["h"]
W = metadata_dict["w"]
# TODO(akristoffersen): The metadata dict comes with principle points,
# but caused errors in image coord indexing. Should update once that is fixed.
cx, cy = W / 2, H / 2
num_cameras = len(image_filenames)
num_intrinsics_params = 3
intrinsics = torch.ones((num_cameras, num_intrinsics_params), dtype=torch.float32)
intrinsics *= torch.tensor([cx, cy, focal_length])
# scene_bounds = SceneBounds.from_camera_poses(camera_to_world, self.config.aabb_scale)
aabb = torch.tensor([[-1, -1, -1], [1, 1, 1]], dtype=torch.float32) * self.config.aabb_scale
scene_bounds = SceneBounds(aabb=aabb)
cameras = Cameras(
fx=focal_length,
fy=focal_length,
cx=cx,
cy=cy,
camera_to_worlds=camera_to_world,
camera_type=CameraType.PERSPECTIVE,
)
dataset_inputs = DatasetInputs(
image_filenames=image_filenames,
cameras=cameras,
scene_bounds=scene_bounds,
)
return dataset_inputs
+118
View File
@@ -0,0 +1,118 @@
# 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 dataset code.
"""
from __future__ import annotations
from abc import abstractmethod
from typing import Dict, Union
import numpy as np
import numpy.typing as npt
import torch
from PIL import Image
from torch.utils.data import Dataset
from torchtyping import TensorType
from nerfactory.configs import base as cfg
from nerfactory.datamanagers.structs import DatasetInputs
from nerfactory.utils.misc import is_not_none
class InputDataset(Dataset):
"""Dataset that returns images."""
def __init__(self, config: Union[cfg.DataParserConfig, cfg.InstantiateConfig], split: str):
"""_summary_
Args:
image_filenames (List[str]): List of image filenames
alpha_color (TensorType[3], optional): Sets transparent regions to specified color, otherwise black.
"""
super().__init__()
self.inputs: DatasetInputs = config.setup().get_dataset_inputs(split=split)
def __len__(self):
return len(self.inputs.image_filenames)
def get_numpy_image(self, image_idx: int) -> npt.NDArray[np.uint8]:
"""Returns the image.
Args:
image_idx (int): The image index in the dataset.
Returns:
np.uint8: an image of shape (H, W, 3 or 4)
"""
image_filename = self.inputs.image_filenames[image_idx]
pil_image = Image.open(image_filename)
image = np.array(pil_image, dtype="uint8") # shape is (h, w, 3 or 4)
assert len(image.shape) == 3
assert image.dtype == np.uint8
assert image.shape[2] in [3, 4], f"Image shape of {image.shape} is in correct."
return image
def get_image(self, image_idx: int) -> TensorType["image_height", "image_width", "num_channels"]:
"""Returns a 3 channel image."""
image = torch.from_numpy(self.get_numpy_image(image_idx).astype("float32") / 255.0)
if self.inputs.alpha_color is not None and image.shape[-1] == 4:
assert image.shape[-1] == 4
image = image[:, :, :3] * image[:, :, -1:] + self.inputs.alpha_color * (1.0 - image[:, :, -1:])
else:
image = image[:, :, :3]
return image
@abstractmethod
def get_mask(self, image_idx: int) -> Union[TensorType["image_height", "image_width", 1], None]:
"""Returns a mask, which indicates which pixels are valid to use with nerf."""
if self.inputs.semantics:
person_index = self.inputs.semantics.thing_classes.index("person")
thing_image_filename = self.inputs.semantics.thing_filenames[image_idx]
pil_image = Image.open(thing_image_filename)
thing_semantics = torch.from_numpy(np.array(pil_image, dtype="int32"))[..., None]
mask = (thing_semantics != person_index).to(torch.float32) # 1 where valid
return mask
return None
@abstractmethod
def get_semantics(self, image_idx: int) -> Union[TensorType["image_height", "image_width", "num_classes"], None]:
"""Returns an image with semantic class values."""
if self.inputs.semantics:
stuff_image_filename = self.inputs.semantics.stuff_filenames[image_idx]
pil_image = Image.open(stuff_image_filename)
stuff_semantics = torch.from_numpy(np.array(pil_image, dtype="int32"))[..., None]
return stuff_semantics
return None
def get_data(self, image_idx) -> Dict:
"""Returns the ImageDataset data as a dictionary."""
image = self.get_image(image_idx)
mask = self.get_mask(image_idx)
semantics = self.get_semantics(image_idx)
data = {"image_idx": image_idx}
assert is_not_none(image)
data["image"] = image
if mask is not None:
assert mask.shape[:2] == image.shape[:2]
data["mask"] = mask
if semantics is not None:
assert semantics.shape[:2] == image.shape[:2]
data["semantics"] = semantics
return data
def __getitem__(self, image_idx):
data = self.get_data(image_idx)
return data
+84
View File
@@ -0,0 +1,84 @@
# 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 sampling pixels.
"""
import random
import torch
def collate_image_dataset_batch(batch, num_rays_per_batch, keep_full_image: bool = False):
"""
Operates on a batch of images and samples pixels to use for generating rays.
Returns a collated batch which is input to the Graph.
It will sample only within the valid 'mask' if it's specified.
"""
device = batch["image"].device
num_images, image_height, image_width, _ = batch["image"].shape
# only sample within the mask, if the mask is in the batch
if "mask" in batch:
nonzero_indices = torch.nonzero(batch["mask"][..., 0], as_tuple=False)
chosen_indices = random.sample(range(len(nonzero_indices)), k=num_rays_per_batch)
indices = nonzero_indices[chosen_indices]
else:
indices = torch.floor(
torch.rand((num_rays_per_batch, 3), device=device)
* torch.tensor([num_images, image_height, image_width], device=device)
).long()
c, y, x = (i.flatten() for i in torch.split(indices, 1, dim=-1))
image = batch["image"][c, y, x]
mask, semantics = None, None
if "mask" in batch:
mask = batch["mask"][c, y, x]
if "semantics" in batch:
semantics = batch["semantics"][c, y, x]
assert image.shape == (num_rays_per_batch, 3), image.shape
# Needed to correct the random indices to their actual camera idx locations.
local_indices = indices.clone()
indices[:, 0] = batch["image_idx"][c]
collated_batch = {
"local_indices": local_indices, # local to the batch returned
"indices": indices, # with the abs camera indices
"image": image,
}
if mask is not None:
collated_batch["mask"] = mask
if semantics is not None:
collated_batch["semantics"] = semantics
if keep_full_image:
collated_batch["full_image"] = batch["image"]
return collated_batch
class PixelSampler: # pylint: disable=too-few-public-methods
"""Samples 'pixel_batch's from 'image_batch's."""
def __init__(self, num_rays_per_batch, keep_full_image=False) -> None:
self.num_rays_per_batch = num_rays_per_batch
self.keep_full_image = keep_full_image
def sample(self, image_batch):
"""Sample an image batch and return a pixel batch."""
pixel_batch = collate_image_dataset_batch(
image_batch, self.num_rays_per_batch, keep_full_image=self.keep_full_image
)
return pixel_batch
+133
View File
@@ -0,0 +1,133 @@
# 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.
"""
Dataset input structures.
"""
from dataclasses import dataclass
from pathlib import Path
from typing import Dict, List, Optional, Union
import torch
from torchtyping import TensorType
from nerfactory.cameras.cameras import Cameras
@dataclass
class PointCloud:
"""Dataclass for a point cloud."""
xyz: TensorType["num_points", 3] = None
rgb: TensorType["num_points", 3] = None
@dataclass
class Semantics:
"""Dataclass for semantic labels."""
stuff_filenames: List[Path]
stuff_classes: List[str]
thing_filenames: List[Path]
thing_classes: List[str]
stuff_colors: torch.Tensor
thing_colors: torch.Tensor
@dataclass
class SceneBounds:
"""Data to represent the scene bounds.
Attributes:
aabb: axis-aligned bounding box.
aabb[0] is the minimum (x,y,z) point.
aabb[1] is the maximum (x,y,z) point.
"""
aabb: TensorType[2, 3] = None
def get_diagonal_length(self):
"""Returns the longest diagonal length."""
diff = self.aabb[1] - self.aabb[0]
length = torch.sqrt((diff**2).sum() + 1e-20)
return length
def get_center(self):
"""Returns the center of the box."""
diff = self.aabb[1] - self.aabb[0]
return self.aabb[0] + diff / 2.0
def get_centered_and_scaled_scene_bounds(self, scale_factor: Union[float, torch.Tensor] = 1.0):
"""Returns a new box that has been shifted and rescaled to be centered
about the origin."""
return SceneBounds(aabb=(self.aabb - self.get_center()) * scale_factor)
@staticmethod
def get_normalized_positions(positions: TensorType[..., 3], aabb: TensorType[2, 3]):
"""Return normalized positions in range [0, 1] based on the aabb axis-aligned bounding box.
Args:
positions: the xyz positions
aabb: the axis-aligned bounding box
Returns:
positions that are normalized into the range [0, 1].
"""
aabb_lengths = aabb[1] - aabb[0]
normalized_positions = (positions - aabb[0]) / aabb_lengths
return normalized_positions
def to_json(self) -> Dict:
"""Returns a json object from the Python object."""
return {"type": "aabb", "min_point": self.aabb[0].tolist(), "max_point": self.aabb[1].tolist()}
@staticmethod
def from_json(json_: Dict) -> "SceneBounds":
"""Returns the an instance of SceneBounds from a json dictionary."""
assert json_["type"] == "aabb"
aabb = torch.tensor([json_[0], json_[1]])
return SceneBounds(aabb=aabb)
@staticmethod
def from_camera_poses(poses: TensorType[..., 3, 4], scale_factor: float) -> "SceneBounds":
"""Returns the instance of SceneBounds that fully envelopes a set of poses"""
xyzs = poses[..., :3, -1]
aabb = torch.stack([torch.min(xyzs, dim=0)[0], torch.max(xyzs, dim=0)[0]])
return SceneBounds(aabb=aabb * scale_factor)
@dataclass
class DatasetInputs:
"""Dataset inputs for the image dataset and the ray generator.
Args:
image_filenames: Filenames for the images.
intrinsics: Tensor of per-image camera intrisics.
camera_to_world: Tensor of per-image c2w matrices, in [R | t] format.
...
"""
image_filenames: List[Path]
cameras: Cameras
mask_filenames: Optional[List[Path]] = None
depth_filenames: Optional[List[Path]] = None
scene_bounds: SceneBounds = SceneBounds()
semantics: Optional[Semantics] = None
point_cloud: PointCloud = PointCloud()
alpha_color: Optional[TensorType[3]] = None
def as_dict(self) -> dict:
"""Returns the dataclass as a dictionary."""
return vars(self)