update docstrings and random cleanups (#387)

* fixing docstrings and small nits; up to fileds

* finished adding and fixing docstrings
This commit is contained in:
evonneng authored and GitHub committed 2022-09-10 23:09:44 -07:00
1 parent bd5967461d
commit d50c71ac43
52 files changed
+846 -646

No files matched your search

+5 -1
View File
@@ -201,7 +201,11 @@ class VanillaDataManager(DataManager): # pylint: disable=abstract-method
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."""
next_train and next_eval functions.
Args:
config: the DataManagerConfig used to instantiate class
"""
config: cfg.VanillaDataManagerConfig
+18 -17
View File
@@ -35,10 +35,10 @@ class CacheImageDataloader(DataLoader):
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".
dataset: Dataset to sample from.
num_samples_to_collate: How many images to sample rays for each batch. Defaults to all images.
num_times_to_repeat_images: How often to collate new images. Defaults to every iteration.
device: Device to perform computation. Defaults to "cpu".
"""
def __init__(
@@ -104,7 +104,6 @@ class EvalDataloader(DataLoader):
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
"""
@@ -153,8 +152,12 @@ class EvalDataloader(DataLoader):
)
return camera
def get_data_from_image_idx(self, image_idx) -> Tuple[RayBundle, Dict]:
"""Returns the data for a specific image index."""
def get_data_from_image_idx(self, image_idx: int) -> Tuple[RayBundle, Dict]:
"""Returns the data for a specific image index.
Args:
image_idx: Camera 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()
@@ -164,7 +167,14 @@ class EvalDataloader(DataLoader):
class FixedIndicesEvalDataloader(EvalDataloader):
"""Dataloader that returns a fixed set of indices."""
"""Dataloader that returns a fixed set of indices.
Args:
input_dataset: InputDataset to load data from
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
"""
def __init__(
self,
@@ -174,14 +184,6 @@ class FixedIndicesEvalDataloader(EvalDataloader):
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)))
@@ -209,7 +211,6 @@ class RandIndicesEvalDataloader(EvalDataloader):
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
"""
+10 -6
View File
@@ -25,7 +25,11 @@ from nerfactory.datamanagers.structs import DatasetInputs
@dataclass
class DataParser:
"""A dataset."""
"""A dataset.
Args:
config: datasetparser config containing all information needed to instantiate dataset
"""
def __init__(self, config: cfg.DataParserConfig):
super().__init__()
@@ -33,23 +37,23 @@ class DataParser:
@abstractmethod
def _generate_dataset_inputs(self, split: str = "train") -> DatasetInputs:
"""Returns the dataset inputs for the given split.
"""Abstract method that returns the dataset inputs for the given split.
Args:
split: Which dataset split to generate.
split: Which dataset split to generate (train/test).
Returns:
DatasetInputs
DatasetInputs containing data for the specified dataset and split
"""
def get_dataset_inputs(self, split: str = "train") -> DatasetInputs:
"""Returns the dataset inputs for the given split.
Args:
split: Which dataset split to generate.
split: Which dataset split to generate (train/test).
Returns:
DatasetInputs
DatasetInputs containing data for the specified dataset and split
"""
dataset_inputs = self._generate_dataset_inputs(split)
return dataset_inputs
@@ -34,11 +34,6 @@ from nerfactory.utils.io import get_absolute_path, load_from_json
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):
@@ -33,7 +33,12 @@ CONSOLE = Console()
def get_semantics_and_masks(image_idx: int, semantics: Semantics):
"""function to process additional semantics and mask information"""
"""function to process additional semantics and mask information
Args:
image_idx: specific image index to work with
semantics: semantics data
"""
# handle mask
person_index = semantics.thing_classes.index("person")
thing_image_filename = semantics.thing_filenames[image_idx]
@@ -55,7 +60,11 @@ class Friends(DataParser):
@classmethod
def _get_aabb_and_transform(cls, basedir):
"""Returns the aabb and pointcloud transform from the threejs.json file."""
"""Returns the aabb and pointcloud transform from the threejs.json file.
Args:
basedir: base directory to load from
"""
filename = basedir / "threejs.json"
assert filename.exists()
data = load_from_json(filename)
@@ -33,13 +33,7 @@ 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
"""
"""Instant NGP Dataset"""
config: cfg.InstantNGPDataParserConfig
@@ -30,15 +30,7 @@ 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.
"""
"""MipNeRF 360 Dataset"""
config: cfg.MipNerf360DataParserConfig
@@ -31,15 +31,7 @@ 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".
"""
"""Nerfactory Dataset"""
config: cfg.NerfactoryDataParserConfig
@@ -31,15 +31,7 @@ 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.
"""
"""Record3D Dataset"""
config: cfg.Record3DDataParserConfig
+17 -14
View File
@@ -32,15 +32,13 @@ from nerfactory.utils.misc import is_not_none
class InputDataset(Dataset):
"""Dataset that returns images."""
"""Dataset that returns images.
Args:
config: the DataParserConfig used to instantiate class, which in turn is used to load dataset inputs
"""
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.dataset_inputs: DatasetInputs = config.setup().get_dataset_inputs(split=split)
@@ -48,13 +46,10 @@ class InputDataset(Dataset):
return len(self.dataset_inputs.image_filenames)
def get_numpy_image(self, image_idx: int) -> npt.NDArray[np.uint8]:
"""Returns the image.
"""Returns the image of shape (H, W, 3 or 4).
Args:
image_idx (int): The image index in the dataset.
Returns:
np.uint8: an image of shape (H, W, 3 or 4)
image_idx: The image index in the dataset.
"""
image_filename = self.dataset_inputs.image_filenames[image_idx]
pil_image = Image.open(image_filename)
@@ -65,7 +60,11 @@ class InputDataset(Dataset):
return image
def get_image(self, image_idx: int) -> TensorType["image_height", "image_width", "num_channels"]:
"""Returns a 3 channel image."""
"""Returns a 3 channel image.
Args:
image_idx: The image index in the dataset.
"""
image = torch.from_numpy(self.get_numpy_image(image_idx).astype("float32") / 255.0)
if self.dataset_inputs.alpha_color is not None and image.shape[-1] == 4:
assert image.shape[-1] == 4
@@ -75,7 +74,11 @@ class InputDataset(Dataset):
return image
def get_data(self, image_idx) -> Dict:
"""Returns the ImageDataset data as a dictionary."""
"""Returns the ImageDataset data as a dictionary.
Args:
image_idx: The image index in the dataset.
"""
image = self.get_image(image_idx)
data = {"image_idx": image_idx}
assert is_not_none(image)
+20 -5
View File
@@ -17,15 +17,21 @@ Code for sampling pixels.
"""
import random
from typing import Dict
import torch
def collate_image_dataset_batch(batch, num_rays_per_batch, keep_full_image: bool = False):
def collate_image_dataset_batch(batch: Dict, num_rays_per_batch: int, 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.
Args:
batch: batch of images to sample from
num_rays_per_batch: number of rays to sample per batch
keep_full_image: whether or not to include a reference to the full image in returned batch
"""
device = batch["image"].device
num_images, image_height, image_width, _ = batch["image"].shape
@@ -70,14 +76,23 @@ def collate_image_dataset_batch(batch, num_rays_per_batch, keep_full_image: bool
class PixelSampler: # pylint: disable=too-few-public-methods
"""Samples 'pixel_batch's from 'image_batch's."""
"""Samples 'pixel_batch's from 'image_batch's.
def __init__(self, num_rays_per_batch, keep_full_image=False) -> None:
Args:
num_rays_per_batch: number of rays to sample per batch
keep_full_image: whether or not to include a reference to the full image in returned batch
"""
def __init__(self, num_rays_per_batch: int, keep_full_image: bool = 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."""
def sample(self, image_batch: Dict):
"""Sample an image batch and return a pixel batch.
Args:
image_batch: batch of images to sample from
"""
pixel_batch = collate_image_dataset_batch(
image_batch, self.num_rays_per_batch, keep_full_image=self.keep_full_image
)
+41 -24
View File
@@ -32,7 +32,9 @@ class PointCloud:
"""Dataclass for a point cloud."""
xyz: TensorType["num_points", 3] = None
"""the 3D points in point cloud"""
rgb: TensorType["num_points", 3] = None
"""the color of each point in point cloud"""
@dataclass
@@ -40,24 +42,27 @@ class Semantics:
"""Dataclass for semantic labels."""
stuff_filenames: List[Path]
"""filenames to load "stuff"/background data"""
stuff_classes: List[str]
thing_filenames: List[Path]
thing_classes: List[str]
"""class labels for "stuff" data"""
stuff_colors: torch.Tensor
"""color mapping for "stuff" classes"""
thing_filenames: List[Path]
"""filenames to load "thing"/foreground data"""
thing_classes: List[str]
"""class labels for "thing" data"""
thing_colors: torch.Tensor
"""color mapping for "thing" classes"""
@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.
"""
"""Data to represent the scene bounds."""
aabb: TensorType[2, 3] = None
"""aabb: axis-aligned bounding box.
aabb[0] is the minimum (x,y,z) point.
aabb[1] is the maximum (x,y,z) point."""
def get_diagonal_length(self):
"""Returns the longest diagonal length."""
@@ -72,7 +77,11 @@ class SceneBounds:
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."""
about the origin.
Args:
scale_factor: How much to scale the camera origins by.
"""
return SceneBounds(aabb=(self.aabb - self.get_center()) * scale_factor)
@staticmethod
@@ -82,9 +91,6 @@ class SceneBounds:
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
@@ -96,14 +102,23 @@ class SceneBounds:
@staticmethod
def from_json(json_: Dict) -> "SceneBounds":
"""Returns the an instance of SceneBounds from a json dictionary."""
"""Returns the an instance of SceneBounds from a json dictionary.
Args:
json_: the json dictionary containing scene bound information
"""
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"""
"""Returns the instance of SceneBounds that fully envelopes a set of poses
Args:
poses: tensor of camera pose matrices
scale_factor: How much to scale the camera origins by.
"""
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)
@@ -111,22 +126,24 @@ class SceneBounds:
@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.
...
"""
"""Dataset inputs for the image dataset and the ray generator."""
image_filenames: List[Path]
"""Filenames for the images."""
cameras: Cameras
"""Camera object storing collection of camera information in dataset"""
alpha_color: Optional[TensorType[3]] = None
"""color of dataset background"""
scene_bounds: SceneBounds = SceneBounds()
point_cloud: PointCloud = PointCloud()
"""scene bounds of dataset"""
# we support additional input information/formats including mask/depth/semantics.
additional_inputs: Dict[str, Any] = to_immutable_dict({})
"""Dictionary of additional dataset information (e.g. semantics/point clouds/masks).
{input_name:
... {"func": function to process additional dataset inputs,
... "kwargs": dictionary of data to pass into "func"}
}
"""
def as_dict(self) -> dict:
"""Returns the dataclass as a dictionary."""