restructure codebase pre release (#602)

* moving a lot

* building
This commit is contained in:
Ethan Weber authored and GitHub committed 2022-10-01 16:36:25 -07:00
1 parent 62f492f1bc
commit e13d401b16
97 files changed
+235712 -235721

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.
@@ -0,0 +1,120 @@
# 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
from abc import abstractmethod
from dataclasses import dataclass, field
from pathlib import Path
from typing import Any, Dict, List, Optional, Type
import torch
from torchtyping import TensorType
import nerfstudio.configs.base_config as cfg
from nerfstudio.cameras.cameras import Cameras
from nerfstudio.configs.config_utils import to_immutable_dict
from nerfstudio.data.scene_box import SceneBounds
@dataclass
class Semantics:
"""Dataclass for semantic labels."""
stuff_filenames: List[Path]
"""filenames to load "stuff"/background data"""
stuff_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 DataparserOutputs:
"""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()
"""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."""
return vars(self)
@dataclass
class DataParserConfig(cfg.InstantiateConfig):
"""Basic dataset config"""
_target: Type = field(default_factory=lambda: DataParser)
"""_target: target class to instantiate"""
@dataclass
class DataParser:
"""A dataset.
Args:
config: datasetparser config containing all information needed to instantiate dataset
"""
config: DataParserConfig
def __init__(self, config: DataParserConfig):
super().__init__()
self.config = config
@abstractmethod
def _generate_dataset_inputs(self, split: str = "train") -> DataparserOutputs:
"""Abstract method that returns the dataset inputs for the given split.
Args:
split: Which dataset split to generate (train/test).
Returns:
DatasetInputs containing data for the specified dataset and split
"""
def get_dataset_inputs(self, split: str = "train") -> DataparserOutputs:
"""Returns the dataset inputs for the given split.
Args:
split: Which dataset split to generate (train/test).
Returns:
DatasetInputs containing data for the specified dataset and split
"""
dataset_inputs = self._generate_dataset_inputs(split)
return dataset_inputs
@@ -0,0 +1,109 @@
# 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, field
from pathlib import Path
from typing import Type
import imageio
import numpy as np
import torch
from nerfstudio.cameras.cameras import Cameras, CameraType
from nerfstudio.data.dataparsers.base_dataparser import (
DataParser,
DataParserConfig,
DataparserOutputs,
)
from nerfstudio.data.scene_box import SceneBounds
from nerfstudio.utils.colors import get_color
from nerfstudio.utils.io import load_from_json
@dataclass
class BlenderDataParserConfig(DataParserConfig):
"""Blender dataset parser config"""
_target: Type = field(default_factory=lambda: Blender)
"""target class to instantiate"""
data_directory: Path = Path("data/blender/lego")
"""directory specifying location of data"""
scale_factor: float = 1.0
"""How much to scale the camera origins by."""
alpha_color: str = "white"
"""alpha color of background"""
@dataclass
class Blender(DataParser):
"""Blender Dataset
Some of this code comes from https://github.com/yenchenlin/nerf-pytorch/blob/master/load_blender.py#L37.
"""
config: BlenderDataParserConfig
def __init__(self, config: 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
meta = load_from_json(self.data_directory / f"transforms_{split}.json")
image_filenames = []
poses = []
for frame in meta["frames"]:
fname = self.data_directory / 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 = DataparserOutputs(
image_filenames=image_filenames,
cameras=cameras,
alpha_color=alpha_color_tensor,
scene_bounds=scene_bounds,
)
return dataset_inputs
@@ -0,0 +1,191 @@
# 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, field
from pathlib import Path
from typing import Type
import numpy as np
import torch
from PIL import Image
from rich.console import Console
from nerfstudio.cameras.cameras import Cameras, CameraType
from nerfstudio.data.dataparsers.base_dataparser import (
DataParser,
DataParserConfig,
DataparserOutputs,
Semantics,
)
from nerfstudio.data.scene_box import SceneBounds
from nerfstudio.utils.io import load_from_json
CONSOLE = Console()
def get_semantics_and_masks(image_idx: int, semantics: Semantics):
"""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]
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
# handle semantics
stuff_image_filename = 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 {"mask": mask, "semantics": stuff_semantics}
@dataclass
class FriendsDataParserConfig(DataParserConfig):
"""Friends dataset parser config"""
_target: Type = field(default_factory=lambda: Friends)
"""target class to instantiate"""
data_directory: Path = Path("data/friends/TBBT-big_living_room")
"""directory specifying location of data"""
include_semantics: bool = True
"""whether or not to include loading of semantics data"""
downscale_factor: int = 8
scene_scale: float = 4.0
"""
Sets the bounding cube to have edge length of this size.
The longest dimension of the Friends axis-aligned bbox will be scaled to this value.
"""
@dataclass
class Friends(DataParser):
"""Friends Dataset"""
config: FriendsDataParserConfig
def _generate_dataset_inputs(self, split="train"): # pylint: disable=unused-argument,too-many-statements
cameras_json = load_from_json(self.config.data_directory / "cameras.json")
frames = cameras_json["frames"]
bbox = torch.tensor(cameras_json["bbox"])
downscale_suffix = f"_{self.config.downscale_factor}" if self.config.downscale_factor != 1 else ""
images_folder = f"images{downscale_suffix}"
segmentations_folder = f"segmentations{downscale_suffix}"
image_filenames = []
fx = []
fy = []
cx = []
cy = []
camera_to_worlds = []
for frame in frames:
# unpack data
image_filename = self.config.data_directory / images_folder / frame["image_name"]
intrinsics = torch.tensor(frame["intrinsics"])
camtoworld = torch.tensor(frame["camtoworld"])[:3]
# append data
image_filenames.append(image_filename)
fx.append(intrinsics[0, 0])
fy.append(intrinsics[1, 1])
cx.append(intrinsics[0, 2])
cy.append(intrinsics[1, 2])
camera_to_worlds.append(camtoworld)
fx = torch.stack(fx)
fy = torch.stack(fy)
cx = torch.stack(cx)
cy = torch.stack(cy)
camera_to_worlds = torch.stack(camera_to_worlds)
# rotate the cameras and box 90 degrees about the x axis to put the z axis up
rotation = torch.tensor([[1, 0, 0], [0, 0, -1], [0, 1, 0]], dtype=torch.float32)
camera_to_worlds[:, :3] = rotation @ camera_to_worlds[:, :3]
bbox = (rotation @ bbox.T).T
scene_scale = self.config.scene_scale
# -- set the scene bounds ---
scene_bounds = SceneBounds(aabb=bbox)
# center the box and adjust the cameras too
center = scene_bounds.get_center()
scene_bounds.aabb -= center
camera_to_worlds[..., 3] -= center
# scale the longest dimension to match the cube size
lengths = scene_bounds.aabb[1] - scene_bounds.aabb[0]
longest_dim = torch.argmax(lengths)
longest_length = lengths[longest_dim]
scale = scene_scale / longest_length
scene_bounds.aabb = scene_bounds.aabb * scale # box
camera_to_worlds[..., 3] *= scale # cameras
# --- semantics ---
semantics = None
if self.config.include_semantics:
thing_filenames = [
Path(
str(image_filename)
.replace(f"/{images_folder}/", f"/{segmentations_folder}/thing/")
.replace(".jpg", ".png")
)
for image_filename in image_filenames
]
stuff_filenames = [
Path(
str(image_filename)
.replace(f"/{images_folder}/", f"/{segmentations_folder}/stuff/")
.replace(".jpg", ".png")
)
for image_filename in image_filenames
]
panoptic_classes = load_from_json(self.config.data_directory / "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,
)
assert torch.all(cx[0] == cx), "Not all cameras have the same cx. Our Cameras class does not support this."
assert torch.all(cy[0] == cy), "Not all cameras have the same cy. Our Cameras class does not support this."
cameras = Cameras(
fx=fx,
fy=fy,
cx=float(cx[0]),
cy=float(cy[0]),
camera_to_worlds=camera_to_worlds,
camera_type=CameraType.PERSPECTIVE,
)
cameras.rescale_output_resolution(scaling_factor=1.0 / self.config.downscale_factor)
dataset_inputs = DataparserOutputs(
image_filenames=image_filenames,
cameras=cameras,
scene_bounds=scene_bounds,
additional_inputs={"semantics": {"func": get_semantics_and_masks, "kwargs": {"semantics": semantics}}},
)
return dataset_inputs
@@ -0,0 +1,116 @@
# 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, field
from pathlib import Path
from typing import Type
import numpy as np
import torch
from nerfstudio.cameras import camera_utils
from nerfstudio.cameras.cameras import Cameras, CameraType
from nerfstudio.data.dataparsers.base_dataparser import (
DataParser,
DataParserConfig,
DataparserOutputs,
)
from nerfstudio.data.scene_box import SceneBounds
from nerfstudio.utils.io import load_from_json
@dataclass
class InstantNGPDataParserConfig(DataParserConfig):
"""Instant-NGP dataset parser config"""
_target: Type = field(default_factory=lambda: InstantNGP)
"""target class to instantiate"""
data_directory: Path = Path("data/ours/posterv2")
"""directory specifying location of data"""
scale_factor: float = 1.0
"""How much to scale the camera origins by."""
scene_scale: float = 0.33
"""How much to scale the scene."""
@dataclass
class InstantNGP(DataParser):
"""Instant NGP Dataset"""
config: InstantNGPDataParserConfig
def _generate_dataset_inputs(self, split="train"):
meta = load_from_json(self.config.data_directory / "transforms.json")
image_filenames = []
poses = []
num_skipped_image_filenames = 0
for frame in meta["frames"]:
fname = self.config.data_directory / 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 = DataparserOutputs(
image_filenames=image_filenames,
cameras=cameras,
scene_bounds=scene_bounds,
)
return dataset_inputs
@@ -0,0 +1,164 @@
# 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, field
from pathlib import Path
from typing import Type
import imageio
import numpy as np
import torch
from nerfstudio.cameras.cameras import Cameras, CameraType
from nerfstudio.data.dataparsers.base_dataparser import (
DataParser,
DataParserConfig,
DataparserOutputs,
)
from nerfstudio.data.scene_box import SceneBounds
@dataclass
class MipNerf360DataParserConfig(DataParserConfig):
"""Mipnerf 360 dataset parser config"""
_target: Type = field(default_factory=lambda: Mipnerf360)
"""target class to instantiate"""
data_directory: Path = Path("data/mipnerf_360/garden")
"""directory specifying location of data"""
downscale_factor: int = 1
"""How much to downscale images."""
val_skip: int = 8
"""1/val_skip images to use for validation."""
auto_scale: bool = True
"""Scale based on pose bounds."""
aabb_scale: float = 4
"""Scene scale."""
@dataclass
class Mipnerf360(DataParser):
"""MipNeRF 360 Dataset"""
config: 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"):
image_dir = "images"
if self.config.downscale_factor > 1:
image_dir += f"_{self.config.downscale_factor}"
image_dir = self.config.data_directory / 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(self.config.data_directory / "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 = DataparserOutputs(
image_filenames=image_filenames,
cameras=cameras,
scene_bounds=scene_bounds,
)
return dataset_inputs
@@ -0,0 +1,165 @@
# 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 nerfstudio datasets. """
from __future__ import annotations
import logging
import math
from dataclasses import dataclass, field
from pathlib import Path, PureWindowsPath
from typing import Literal, Type
import numpy as np
import torch
from nerfstudio.cameras import camera_utils
from nerfstudio.cameras.cameras import CAMERA_MODEL_TO_TYPE, Cameras, CameraType
from nerfstudio.data.dataparsers.base_dataparser import (
DataParser,
DataParserConfig,
DataparserOutputs,
)
from nerfstudio.data.scene_box import SceneBounds
from nerfstudio.utils.io import load_from_json
@dataclass
class NerfstudioDataParserConfig(DataParserConfig):
"""Nerfstudio dataset config"""
_target: Type = field(default_factory=lambda: Nerfstudio)
"""target class to instantiate"""
data_directory: Path = Path("data/nerfstudio/poster")
"""directory specifying location of data"""
scale_factor: float = 1.0
"""How much to scale the camera origins by."""
downscale_factor: int = 1
"""How much to downscale images."""
scene_scale: float = 1.0
"""How much to scale the region of interest by."""
orientation_method: Literal["pca", "up"] = "up"
"""The method to use for orientation."""
train_split_percentage: float = 0.9
"""The percent of images to use for training. The remaining images are for eval.
"""
@dataclass
class Nerfstudio(DataParser):
"""Nerfstudio Dataset"""
config: NerfstudioDataParserConfig
def _generate_dataset_inputs(self, split="train"):
# pylint: disable=too-many-statements
meta = load_from_json(self.config.data_directory / "transforms.json")
image_filenames = []
poses = []
num_skipped_image_filenames = 0
for frame in meta["frames"]:
if "\\" in frame["file_path"]:
filepath = PureWindowsPath(frame["file_path"])
else:
filepath = Path(frame["file_path"])
if self.config.downscale_factor > 1:
fname = self.config.data_directory / f"images_{self.config.downscale_factor}" / filepath.name
else:
fname = self.config.data_directory / filepath
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.
"""
# filter image_filenames and poses based on train/eval split percentage
num_images = len(image_filenames)
num_train_images = math.ceil(num_images * self.config.train_split_percentage)
num_eval_images = num_images - num_train_images
i_all = np.arange(num_images)
i_train = np.linspace(
0, num_images - 1, num_train_images, dtype=int
) # equally spaced training images starting and ending at 0 and num_images-1
i_eval = np.setdiff1d(i_all, i_train) # eval images are the remaining images
assert len(i_eval) == num_eval_images
if split == "train":
indices = i_train
elif split in ["val", "test"]:
indices = i_eval
else:
raise ValueError(f"Unknown dataparser split {split}")
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 * self.config.scale_factor
# Choose image_filenames and poses based on split, but after auto orient and scaling the poses.
image_filenames = [image_filenames[i] for i in indices]
poses = poses[indices]
# 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
)
)
if "camera_model" in meta:
camera_type = CAMERA_MODEL_TO_TYPE[meta["camera_model"]]
else:
camera_type = CameraType.PERSPECTIVE
distortion_params = camera_utils.get_distortion_params(
k1=float(meta["k1"]) if "k1" in meta else 0.0,
k2=float(meta["k2"]) if "k2" in meta else 0.0,
k3=float(meta["k3"]) if "k3" in meta else 0.0,
k4=float(meta["k4"]) if "k4" in meta else 0.0,
p1=float(meta["p1"]) if "p1" in meta else 0.0,
p2=float(meta["p2"]) if "p2" in meta else 0.0,
)
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=camera_type,
)
cameras.rescale_output_resolution(scaling_factor=1.0 / self.config.downscale_factor)
dataset_inputs = DataparserOutputs(
image_filenames=image_filenames,
cameras=cameras,
scene_bounds=scene_bounds,
)
return dataset_inputs
@@ -0,0 +1,154 @@
# 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, field
from pathlib import Path
from typing import Literal, Type
import numpy as np
import torch
from scipy.spatial.transform import Rotation
from nerfstudio.cameras import camera_utils
from nerfstudio.cameras.cameras import Cameras, CameraType
from nerfstudio.data.dataparsers.base_dataparser import (
DataParser,
DataParserConfig,
DataparserOutputs,
)
from nerfstudio.data.scene_box import SceneBounds
from nerfstudio.utils import poses as pose_utils
from nerfstudio.utils.io import load_from_json
@dataclass
class Record3DDataParserConfig(DataParserConfig):
"""Record3D dataset config"""
_target: Type = field(default_factory=lambda: Record3D)
"""target class to instantiate"""
data_directory: Path = Path("data/record3d/garden")
"""Location of data"""
val_skip: int = 8
"""1/val_skip images to use for validation."""
aabb_scale: float = 4.0
"""Scene scale."""
orientation_method: Literal["pca", "up"] = "up"
"""The method to use for orientation"""
max_dataset_size: int = 150
"""Max number of images to train on. If the dataset has
more, images will be sampled approximately evenly."""
@dataclass
class Record3D(DataParser):
"""Record3D Dataset"""
config: Record3DDataParserConfig
def _generate_dataset_inputs(self, split: str = "train") -> DataparserOutputs:
image_dir = self.config.data_directory / "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 = self.config.data_directory / "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)
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]
# convert to Tensors
poses = torch.from_numpy(poses[:, :3, :4])
# convert OpenGL to OpenCV coordinate system
poses = poses @ torch.diag(torch.tensor([1.0, -1.0, -1.0, 1.0]))
poses = camera_utils.auto_orient_poses(pose_utils.to4x4(poses), method=self.config.orientation_method)[
:, :3, :4
]
# Centering poses
poses[:, :3, 3] = poses[:, :3, 3] - torch.mean(poses[:, :3, 3], dim=0)
poses = pose_utils.normalize(poses)
# 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=poses,
camera_type=CameraType.PERSPECTIVE,
)
dataset_inputs = DataparserOutputs(
image_filenames=image_filenames,
cameras=cameras,
scene_bounds=scene_bounds,
)
return dataset_inputs