diff --git a/nerfstudio/cameras/cameras.py b/nerfstudio/cameras/cameras.py index f2020916f..fee7495a8 100644 --- a/nerfstudio/cameras/cameras.py +++ b/nerfstudio/cameras/cameras.py @@ -314,7 +314,7 @@ class Cameras(TensorDataclass): distortion_params_delta: Optional[TensorType["num_rays":..., 6]] = None, keep_shape: Optional[bool] = None, disable_distortion: bool = False, - aabb_box: SceneBox = None, + aabb_box: Optional[SceneBox] = None, ) -> RayBundle: """Generates rays for the given camera indices. diff --git a/nerfstudio/cameras/rays.py b/nerfstudio/cameras/rays.py index e81e52642..8718712fb 100644 --- a/nerfstudio/cameras/rays.py +++ b/nerfstudio/cameras/rays.py @@ -134,6 +134,7 @@ class RaySamples(TensorDataclass): transmittance = torch.exp(-transmittance) # [..., "num_samples"] weights = alphas * transmittance # [..., "num_samples"] + weights = torch.nan_to_num(weights) return weights diff --git a/nerfstudio/data/datamanagers/base_datamanager.py b/nerfstudio/data/datamanagers/base_datamanager.py index 4fc1822dd..d032c4d48 100644 --- a/nerfstudio/data/datamanagers/base_datamanager.py +++ b/nerfstudio/data/datamanagers/base_datamanager.py @@ -38,6 +38,7 @@ from nerfstudio.configs.base_config import InstantiateConfig from nerfstudio.data.dataparsers.base_dataparser import DataparserOutputs from nerfstudio.data.dataparsers.blender_dataparser import BlenderDataParserConfig from nerfstudio.data.dataparsers.dnerf_dataparser import DNeRFDataParserConfig +from nerfstudio.data.dataparsers.dycheck_dataparser import DycheckDataParserConfig from nerfstudio.data.dataparsers.friends_dataparser import FriendsDataParserConfig from nerfstudio.data.dataparsers.instant_ngp_dataparser import ( InstantNGPDataParserConfig, @@ -73,6 +74,7 @@ AnnotatedDataParserUnion = tyro.conf.OmitSubcommandPrefixes[ # Omit prefixes of "nuscenes-data": NuScenesDataParserConfig(), "dnerf-data": DNeRFDataParserConfig(), "phototourism-data": PhototourismDataParserConfig(), + "dycheck-data": DycheckDataParserConfig(), }, prefix_names=False, # Omit prefixes in subcommands themselves. ) diff --git a/nerfstudio/data/dataparsers/dycheck_dataparser.py b/nerfstudio/data/dataparsers/dycheck_dataparser.py new file mode 100644 index 000000000..92cca35ff --- /dev/null +++ b/nerfstudio/data/dataparsers/dycheck_dataparser.py @@ -0,0 +1,342 @@ +# Copyright 2022 The Nerfstudio 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 DyCheck (https://arxiv.org/abs/2210.13445) dataset of `iphone` subset""" +from __future__ import annotations + +import math +from dataclasses import dataclass, field +from pathlib import Path +from typing import Dict, List, Tuple, Type + +import cv2 +import numpy as np +import torch +from rich.progress import Console + +from nerfstudio.cameras.cameras import Cameras, CameraType +from nerfstudio.data.dataparsers.base_dataparser import ( + DataParser, + DataParserConfig, + DataparserOutputs, +) +from nerfstudio.data.scene_box import SceneBox +from nerfstudio.utils.colors import get_color +from nerfstudio.utils.io import load_from_json + +CONSOLE = Console(width=120) + + +def downscale(img, scale: int) -> np.ndarray: + """Function from DyCheck's repo. Downscale an image. + + Args: + img: Input image + scale: Factor of the scale + + Returns: + New image + """ + if scale == 1: + return img + height, width = img.shape[:2] + if height % scale > 0 or width % scale > 0: + raise ValueError(f"Image shape ({height},{width}) must be divisible by the" f" scale ({scale}).") + out_height, out_width = height // scale, width // scale + resized = cv2.resize(img, (out_width, out_height), cv2.INTER_AREA) + return resized + + +def upscale(img, scale: int) -> np.ndarray: + """Function from DyCheck's repo. Upscale an image. + + Args: + img: Input image + scale: Factor of the scale + + Returns: + New image + """ + if scale == 1: + return img + height, width = img.shape[:2] + out_height, out_width = height * scale, width * scale + resized = cv2.resize(img, (out_width, out_height), cv2.INTER_AREA) + return resized + + +def rescale(img, scale_factor: float, interpolation=cv2.INTER_AREA) -> np.ndarray: + """Function from DyCheck's repo. Rescale an image. + + Args: + img: Input image + scale: Factor of the scale + interpolation: Interpolation method in opencv + + Returns: + New image + """ + scale_factor = float(scale_factor) + if scale_factor <= 0.0: + raise ValueError("scale_factor must be a non-negative number.") + if scale_factor == 1.0: + return img + + height, width = img.shape[:2] + if scale_factor.is_integer(): + return upscale(img, int(scale_factor)) + + inv_scale = 1.0 / scale_factor + if inv_scale.is_integer() and (scale_factor * height).is_integer() and (scale_factor * width).is_integer(): + return downscale(img, int(inv_scale)) + + print(f"Resizing image by non-integer factor {scale_factor}, this may lead to artifacts.") + height, width = img.shape[:2] + out_height = math.ceil(height * scale_factor) + out_height -= out_height % 2 + out_width = math.ceil(width * scale_factor) + out_width -= out_width % 2 + + return cv2.resize(img, (out_width, out_height), interpolation) + + +def _load_scene_info(data_dir: Path) -> Tuple[np.ndarray, float, float, float]: + """Function from DyCheck's repo. Load scene info from json. + + Args: + data_dir: data path + + Returns: + A tuple of scene info: center, scale, near, far + """ + scene_dict = load_from_json(data_dir / "scene.json") + center = np.array(scene_dict["center"], dtype=np.float32) + scale = scene_dict["scale"] + near = scene_dict["near"] + far = scene_dict["far"] + return center, scale, near, far + + +def _load_metadata_info(data_dir: Path) -> Tuple[np.ndarray, np.ndarray, np.ndarray]: + """Function from DyCheck's repo. Load scene metadata from json. + + Args: + data_dir: data path + + Returns: + A tuple of scene info: frame_names_map, time_ids, camera_ids + """ + dataset_dict = load_from_json(data_dir / "dataset.json") + _frame_names = np.array(dataset_dict["ids"]) + + metadata_dict = load_from_json(data_dir / "metadata.json") + time_ids = np.array([metadata_dict[k]["warp_id"] for k in _frame_names], dtype=np.uint32) + camera_ids = np.array([metadata_dict[k]["camera_id"] for k in _frame_names], dtype=np.uint32) + + frame_names_map = np.zeros((time_ids.max() + 1, camera_ids.max() + 1), _frame_names.dtype) + for i, (t, c) in enumerate(zip(time_ids, camera_ids)): + frame_names_map[t, c] = _frame_names[i] + + return frame_names_map, time_ids, camera_ids + + +def _rescale_depth(depth_raw: np.ndarray, cam: Dict) -> np.ndarray: + """Depth rescale function from DyCheck. + + Args: + depth: A numpy ndarray of the raw depth + cam: Dict of the camera + + Returns: + A numpy ndarray of the processed depth + """ + xx, yy = np.meshgrid(np.arange(cam["width"], dtype=np.float32), np.arange(cam["height"], dtype=np.float32)) + pixels = np.stack([xx, yy], axis=-1) + batch_shape = pixels.shape[:-1] + pixels = np.reshape(pixels, (-1, 2)) + y = (pixels[..., 1] - cam["cy"]) / cam["fy"] + x = (pixels[..., 0] - cam["cx"]) / cam["fx"] + # x = (pixels[..., 0] - self.principal_point_x - y * self.skew) / self.scale_factor_x + # assume skew = 0 + viewdirs = np.stack([x, y, np.ones_like(x)], axis=-1) + local_viewdirs = viewdirs / np.linalg.norm(viewdirs, axis=-1, keepdims=True) + viewdirs = (cam["camera_to_worlds"][:3, :3] @ local_viewdirs[..., None])[..., 0] + viewdirs /= np.linalg.norm(viewdirs, axis=-1, keepdims=True) + viewdirs = viewdirs.reshape((*batch_shape, 3)) + cosa = viewdirs @ (cam["camera_to_worlds"][:, 2]) + depth = depth_raw / cosa[..., None] + return depth + + +@dataclass +class DycheckDataParserConfig(DataParserConfig): + """Dycheck (https://arxiv.org/abs/2210.13445) dataset parser config""" + + _target: Type = field(default_factory=lambda: Dycheck) + """target class to instantiate""" + data: Path = Path("data/iphone/mochi-high-five") + """Directory specifying location of data.""" + scale_factor: float = 5.0 + """How much to scale the camera origins by.""" + alpha_color: str = "white" + """alpha color of background""" + downscale_factor: int = 1 + """How much to downscale images.""" + scene_box_bound: float = 1.5 + """Boundary of scene box.""" + + +@dataclass +class Dycheck(DataParser): + """Dycheck (https://arxiv.org/abs/2210.13445) Dataset `iphone` subset""" + + config: DycheckDataParserConfig + + def __init__(self, config: DycheckDataParserConfig): + super().__init__(config=config) + self.data: Path = config.data + self.scale_factor: float = config.scale_factor + self.alpha_color = config.alpha_color + # load extra info from "extra.json" + extra_path = self.data / "extra.json" + extra_dict = load_from_json(extra_path) + self._factor = extra_dict["factor"] + self._fps = extra_dict["fps"] + self._bbox = np.array(extra_dict["bbox"], dtype=np.float32) + self._lookat = np.array(extra_dict["lookat"], dtype=np.float32) + self._up = np.array(extra_dict["up"], dtype=np.float32) + self._center, self._scale, self._near, self._far = _load_scene_info(self.data) + self._frame_names_map, self._time_ids, self._camera_ids = _load_metadata_info(self.data) + + def _generate_dataparser_outputs(self, split="train"): + if self.alpha_color is not None: + alpha_color_tensor = get_color(self.alpha_color) + else: + alpha_color_tensor = None + splits_dir = self.data / "splits" + + # scale the scene to fill the aabb bbox + sf = self.config.scene_box_bound / 4 / (self._scale * self._far) + # CONSOLE.print(f"scale factor changed from {self.config.scale_factor} to {sf}") + self.config.scale_factor = sf + + if not (splits_dir / f"{split}.json").exists(): + CONSOLE.print(f"split {split} not found, using split train") + split = "train" + split_dict = load_from_json(splits_dir / f"{split}.json") + frame_names = np.array(split_dict["frame_names"]) + time_ids = np.array(split_dict["time_ids"]) + if split != "train": + CONSOLE.print(f"split {split} is empty, using the 1st training image") + split_dict = load_from_json(splits_dir / "train.json") + frame_names = np.array(split_dict["frame_names"])[[0]] + time_ids = np.array(split_dict["time_ids"])[[0]] + + image_filenames, depth_filenames, cams = self.process_frames(frame_names, time_ids) + + scene_box = SceneBox( + aabb=torch.tensor( + [[-self.config.scene_box_bound] * 3, [self.config.scene_box_bound] * 3], dtype=torch.float32 + ) + ) + cam_dict = {} + for k in cams[0].keys(): + cam_dict[k] = torch.stack([torch.as_tensor(c[k]) for c in cams], dim=0) + cameras = Cameras(camera_type=CameraType.PERSPECTIVE, **cam_dict) + + scale = self._scale * self.config.scale_factor + dataparser_outputs = DataparserOutputs( + image_filenames=image_filenames, + cameras=cameras, + alpha_color=alpha_color_tensor, + scene_box=scene_box, + metadata={ + "depth_filenames": depth_filenames, + "depth_unit_scale_factor": scale, + "scale": scale, + "near": self._near * scale, + "far": self._far * scale, + }, + ) + + return dataparser_outputs + + def process_frames(self, frame_names: List[str], time_ids: np.ndarray) -> Tuple[List, List, List]: + """Read cameras and filenames from the name list. + + Args: + frame_names: list of file names. + time_ids: time id of each frame. + + Returns: + A list of camera, each entry is a dict of the camera. + """ + image_filenames, depth_filenames = [], [] + cams = [] + for idx, frame in enumerate(frame_names): + image_filenames.append(self.data / f"rgb/{self.config.downscale_factor}x/{frame}.png") + depth_filenames.append(self.data / f"processed_depth/{self.config.downscale_factor}x/{frame}.npy") + cam_json = load_from_json(self.data / f"camera/{frame}.json") + c2w = torch.as_tensor(cam_json["orientation"]).T + position = torch.as_tensor(cam_json["position"]) + position -= self._center # some scenes look weird (wheel) + position *= self._scale * self.config.scale_factor + pose = torch.zeros([3, 4]) + pose[:3, :3] = c2w + pose[:3, 3] = position + # from opencv coord to opengl coord (used by nerfstudio) + pose[0:3, 1:3] *= -1 # switch cam coord x,y + pose = pose[[1, 0, 2], :] # switch world x,y + pose[2, :] *= -1 # invert world z + # for aabb bbox usage + pose = pose[[1, 2, 0], :] # switch world xyz to zxy + cams.append( + { + "camera_to_worlds": pose, + "fx": cam_json["focal_length"] / self.config.downscale_factor, + "fy": cam_json["focal_length"] * cam_json["pixel_aspect_ratio"] / self.config.downscale_factor, + "cx": cam_json["principal_point"][0] / self.config.downscale_factor, + "cy": cam_json["principal_point"][1] / self.config.downscale_factor, + "height": cam_json["image_size"][1] // self.config.downscale_factor, + "width": cam_json["image_size"][0] // self.config.downscale_factor, + "times": torch.as_tensor(time_ids[idx] / self._time_ids.max()).float(), + } + ) + + d = self.config.downscale_factor + if not image_filenames[0].exists(): + CONSOLE.print(f"downscale factor {d}x not exist, converting") + ori_h, ori_w = cv2.imread(str(self.data / f"rgb/1x/{frame_names[0]}.png")).shape[:2] + (self.data / f"rgb/{d}x").mkdir(exist_ok=True) + h, w = ori_h // d, ori_w // d + for frame in frame_names: + cv2.imwrite( + str(self.data / f"rgb/{d}x/{frame}.png"), + cv2.resize(cv2.imread(str(self.data / f"rgb/1x/{frame}.png")), [h, w]), + ) + CONSOLE.print("finished") + + if not depth_filenames[0].exists(): + CONSOLE.print(f"processed depth downscale factor {d}x not exist, converting") + (self.data / f"processed_depth/{d}x").mkdir(exist_ok=True, parents=True) + for idx, frame in enumerate(frame_names): + depth = np.load(self.data / f"depth/1x/{frame}.npy") + mask = rescale((depth != 0).astype(np.uint8) * 255, 1 / d, cv2.INTER_AREA) + depth = rescale(depth, 1 / d, cv2.INTER_AREA) + depth[mask != 255] = 0 + depth = _rescale_depth(depth, cams[idx]) + np.save(str(self.data / f"processed_depth/{d}x/{frame}.npy"), depth) + CONSOLE.print("finished") + + return image_filenames, depth_filenames, cams diff --git a/nerfstudio/data/utils/data_utils.py b/nerfstudio/data/utils/data_utils.py index c4b21febd..f04fb368c 100644 --- a/nerfstudio/data/utils/data_utils.py +++ b/nerfstudio/data/utils/data_utils.py @@ -64,8 +64,8 @@ def get_depth_image_from_path( interpolation: int = cv2.INTER_NEAREST, ) -> torch.Tensor: """Loads, rescales and resizes depth images. + Filepath points to a 16-bit or 32-bit depth image, or a numpy array `*.npy`. - Assumes filepath points to a 16-bit or 32-bit depth image. Args: filepath: Path to depth image. height: Target depth image height. @@ -76,7 +76,11 @@ def get_depth_image_from_path( Returns: Depth image torch tensor with shape [width, height, 1]. """ - image = cv2.imread(str(filepath.absolute()), cv2.IMREAD_ANYDEPTH) - image = image.astype(np.float64) * scale_factor - image = cv2.resize(image, (width, height), interpolation=interpolation) + if filepath.suffix == ".npy": + image = np.load(filepath) * scale_factor + image = cv2.resize(image, (width, height), interpolation=interpolation) + else: + image = cv2.imread(str(filepath.absolute()), cv2.IMREAD_ANYDEPTH) + image = image.astype(np.float64) * scale_factor + image = cv2.resize(image, (width, height), interpolation=interpolation) return torch.from_numpy(image[:, :, np.newaxis]) diff --git a/nerfstudio/engine/trainer.py b/nerfstudio/engine/trainer.py index b8632839c..a91da10d0 100644 --- a/nerfstudio/engine/trainer.py +++ b/nerfstudio/engine/trainer.py @@ -228,14 +228,18 @@ class Trainer: self.save_checkpoint(step) writer.write_out_storage() - # save checkpoint at the end of training - self.save_checkpoint(step) - CONSOLE.rule() - CONSOLE.print("[bold green]:tada: :tada: :tada: Training Finished :tada: :tada: :tada:", justify="center") - if not self.config.viewer.quit_on_train_completion: - CONSOLE.print("Use ctrl+c to quit", justify="center") - self._always_render(step) + # save checkpoint at the end of training + self.save_checkpoint(step) + + # write out any remaining events (e.g., total train time) + writer.write_out_storage() + + CONSOLE.rule() + CONSOLE.print("[bold green]:tada: :tada: :tada: Training Finished :tada: :tada: :tada:", justify="center") + if not self.config.viewer.quit_on_train_completion: + CONSOLE.print("Use ctrl+c to quit", justify="center") + self._always_render(step) @check_main_thread def _always_render(self, step): diff --git a/nerfstudio/model_components/renderers.py b/nerfstudio/model_components/renderers.py index 9b48c22c8..24ce46085 100644 --- a/nerfstudio/model_components/renderers.py +++ b/nerfstudio/model_components/renderers.py @@ -39,19 +39,19 @@ from typing_extensions import Literal from nerfstudio.cameras.rays import RaySamples from nerfstudio.utils.math import components_from_spherical_harmonics -BACKGROUND_MODE_OVERRIDE: Optional[Literal["last_sample", "black", "random"]] = None +BACKGROUND_COLOR_OVERRIDE: Optional[TensorType[3]] = None @contextlib.contextmanager -def background_mode_override_context(mode: Literal["last_sample", "black"]) -> Generator[None, None, None]: +def background_color_override_context(mode: TensorType[3]) -> Generator[None, None, None]: """Context manager for setting background mode.""" - global BACKGROUND_MODE_OVERRIDE # pylint: disable=global-statement - old_background_mode = BACKGROUND_MODE_OVERRIDE + global BACKGROUND_COLOR_OVERRIDE # pylint: disable=global-statement + old_background_color = BACKGROUND_COLOR_OVERRIDE try: - BACKGROUND_MODE_OVERRIDE = mode + BACKGROUND_COLOR_OVERRIDE = mode yield finally: - BACKGROUND_MODE_OVERRIDE = old_background_mode + BACKGROUND_COLOR_OVERRIDE = old_background_color class RGBRenderer(nn.Module): @@ -96,8 +96,8 @@ class RGBRenderer(nn.Module): comp_rgb = torch.sum(weights * rgb, dim=-2) accumulated_weight = torch.sum(weights, dim=-2) - if BACKGROUND_MODE_OVERRIDE is not None: - background_color = BACKGROUND_MODE_OVERRIDE + if BACKGROUND_COLOR_OVERRIDE is not None: + background_color = BACKGROUND_COLOR_OVERRIDE if background_color == "last_sample": background_color = rgb[..., -1, :] if background_color == "random": @@ -129,6 +129,8 @@ class RGBRenderer(nn.Module): Outputs of rgb values. """ + if not self.training: + rgb = torch.nan_to_num(rgb) rgb = self.combine_rgb( rgb, weights, background_color=self.background_color, ray_indices=ray_indices, num_rays=num_rays ) @@ -182,7 +184,11 @@ class SHRenderer(nn.Module): if self.activation is not None: self.activation(rgb) + if not self.training: + rgb = torch.nan_to_num(rgb) rgb = RGBRenderer.combine_rgb(rgb, weights, background_color=self.background_color) + if not self.training: + torch.clamp_(rgb, min=0.0, max=1.0) return rgb diff --git a/nerfstudio/models/nerfacto.py b/nerfstudio/models/nerfacto.py index 42ea0f50a..c996e20b3 100644 --- a/nerfstudio/models/nerfacto.py +++ b/nerfstudio/models/nerfacto.py @@ -89,7 +89,7 @@ class NerfactoModelConfig(ModelConfig): """Use the same proposal network. Otherwise use different ones.""" proposal_net_args_list: List[Dict] = field( default_factory=lambda: [ - {"hidden_dim": 16, "log2_hashmap_size": 17, "num_levels": 5, "max_res": 64}, + {"hidden_dim": 16, "log2_hashmap_size": 17, "num_levels": 5, "max_res": 128}, {"hidden_dim": 16, "log2_hashmap_size": 17, "num_levels": 5, "max_res": 256}, ] ) diff --git a/nerfstudio/process_data/insta360_utils.py b/nerfstudio/process_data/insta360_utils.py index febdc7308..56e554e01 100644 --- a/nerfstudio/process_data/insta360_utils.py +++ b/nerfstudio/process_data/insta360_utils.py @@ -165,7 +165,7 @@ def convert_insta360_single_file_to_images( vf_cmds_front = vf_cmds.copy() vf_cmds_back.append( - f"crop=ih*{crop_percentage}:ih*{crop_percentage}:ih*({crop_percentage}/4):ih*({crop_percentage}/4)" + f"crop=ih*{crop_percentage}:ih*{crop_percentage}:ih*{crop_percentage}/4:ih*{crop_percentage}/4" ) vf_cmds_front.append( f"crop=ih*{crop_percentage}:ih*{crop_percentage}:iw/2+ih*{crop_percentage/4}:ih*{crop_percentage/4}" diff --git a/nerfstudio/process_data/polycam_utils.py b/nerfstudio/process_data/polycam_utils.py index a7aa1cb48..d1887833b 100644 --- a/nerfstudio/process_data/polycam_utils.py +++ b/nerfstudio/process_data/polycam_utils.py @@ -17,10 +17,11 @@ import json import sys from pathlib import Path -from typing import List +from typing import List, Tuple from rich.console import Console +from nerfstudio.process_data import process_data_utils from nerfstudio.process_data.process_data_utils import CAMERA_MODELS from nerfstudio.utils import io @@ -29,6 +30,7 @@ CONSOLE = Console(width=120) def polycam_to_json( image_filenames: List[Path], + depth_filenames: List[Path], cameras_dir: Path, output_dir: Path, min_blur_score: float = 0.0, @@ -38,6 +40,7 @@ def polycam_to_json( Args: image_filenames: List of paths to the original images. + depth_filenames: List of paths to the original depth maps. cameras_dir: Path to the polycam cameras directory. output_dir: Path to the output directory. min_blur_score: Minimum blur score to use an image. Images below this value will be skipped. @@ -46,6 +49,7 @@ def polycam_to_json( Returns: Summary of the conversion. """ + use_depth = len(image_filenames) == len(depth_filenames) data = {} data["camera_model"] = CAMERA_MODELS["perspective"].value # Needs to be a string for camera_utils.auto_orient_and_center_poses @@ -67,6 +71,8 @@ def polycam_to_json( frame["w"] = frame_json["width"] - crop_border_pixels * 2 frame["h"] = frame_json["height"] - crop_border_pixels * 2 frame["file_path"] = f"./images/frame_{i+1:05d}{image_filename.suffix}" + if use_depth: + frame["depth_map_path"] = f"./depth/frame_{i+1:05d}{depth_filenames[i].suffix}" # Transform matrix to nerfstudio format. Please refer to the documentation for coordinate system conventions. frame["transform_matrix"] = [ [frame_json["t_20"], frame_json["t_21"], frame_json["t_22"], frame_json["t_23"]], @@ -90,3 +96,127 @@ def polycam_to_json( sys.exit(1) return summary + + +def process_images( + polycam_image_dir: Path, + image_dir: Path, + crop_border_pixels: int = 15, + max_dataset_size: int = 600, + num_downscales: int = 3, + verbose: bool = True, +) -> Tuple[List[str], List[Path]]: + """ + Process RGB images only + + Args: + polycam_image_dir: Path to the directory containing RGB Images + image_dir: Output directory for processed images + crop_border_pixels: Number of pixels to crop from each border of the image. Useful as borders may be + black due to undistortion. + max_dataset_size: Max number of images to train on. If the dataset has more, images will be sampled + approximately evenly. If -1, use all images. + num_downscales: Number of times to downscale the images. Downscales by 2 each time. For example a value of 3 + will downscale the images by 2x, 4x, and 8x. + verbose: If True, print extra logging. + Returns: + summary_log: Summary of the processing. + polycam_image_filenames: List of processed images paths + """ + summary_log = [] + polycam_image_filenames, num_orig_images = process_data_utils.get_image_filenames( + polycam_image_dir, max_dataset_size + ) + + # Copy images to output directory + copied_image_paths = process_data_utils.copy_images_list( + polycam_image_filenames, + image_dir=image_dir, + crop_border_pixels=crop_border_pixels, + verbose=verbose, + ) + num_frames = len(copied_image_paths) + + copied_image_paths = [Path("images/" + copied_image_path.name) for copied_image_path in copied_image_paths] + + if max_dataset_size > 0 and num_frames != num_orig_images: + summary_log.append(f"Started with {num_frames} images out of {num_orig_images} total") + summary_log.append( + "To change the size of the dataset add the argument --max_dataset_size to larger than the " + f"current value ({max_dataset_size}), or -1 to use all images." + ) + else: + summary_log.append(f"Started with {num_frames} images") + + # Downscale images + summary_log.append(process_data_utils.downscale_images(image_dir, num_downscales, verbose=verbose)) + + # Save json + if num_frames == 0: + CONSOLE.print("[bold red]No images found, exiting") + sys.exit(1) + + return summary_log, polycam_image_filenames + + +def process_depth_maps( + polycam_depth_dir: Path, + depth_dir: Path, + num_processed_images: int, + crop_border_pixels: int = 15, + max_dataset_size: int = 600, + num_downscales: int = 3, + verbose: bool = True, +) -> Tuple[List[str], List[Path]]: + """ + Process Depth maps from polycam only + + Args: + polycam_depth_dir: Path to the directory containing depth maps + depth_dir: Output directory for processed depth maps + num_processed_images: Number of RGB processed that must match the number of depth maps + crop_border_pixels: Number of pixels to crop from each border of the image. Useful as borders may be + black due to undistortion. + max_dataset_size: Max number of images to train on. If the dataset has more, images will be sampled + approximately evenly. If -1, use all images. + num_downscales: Number of times to downscale the images. Downscales by 2 each time. For example a value of 3 + will downscale the images by 2x, 4x, and 8x. + verbose: If True, print extra logging. + Returns: + summary_log: Summary of the processing. + polycam_depth_maps_filenames: List of processed depth maps paths + """ + summary_log = [] + polycam_depth_maps_filenames, num_orig_depth_maps = process_data_utils.get_image_filenames( + polycam_depth_dir, max_dataset_size + ) + + # Copy depth images to output directory + copied_depth_maps_paths = process_data_utils.copy_and_upscale_polycam_depth_maps_list( + polycam_depth_maps_filenames, depth_dir=depth_dir, crop_border_pixels=crop_border_pixels, verbose=verbose + ) + + num_processed_depth_maps = len(copied_depth_maps_paths) + + # assert same number of images as depth maps + if num_processed_images != num_processed_depth_maps: + raise ValueError( + f"Expected same amount of depth maps as images. " + f"Instead got {num_processed_images} images and {num_processed_depth_maps} depth maps" + ) + + if crop_border_pixels > 0 and num_processed_depth_maps != num_orig_depth_maps: + summary_log.append(f"Started with {num_processed_depth_maps} images out of {num_orig_depth_maps} total") + summary_log.append( + "To change the size of the dataset add the argument --max_dataset_size to larger than the " + f"current value ({crop_border_pixels}), or -1 to use all images." + ) + else: + summary_log.append(f"Started with {num_processed_depth_maps} images") + + # Downscale depth maps + summary_log.append( + process_data_utils.downscale_images(depth_dir, num_downscales, folder_name="depth", verbose=verbose) + ) + + return summary_log, polycam_depth_maps_filenames diff --git a/nerfstudio/process_data/process_data_utils.py b/nerfstudio/process_data/process_data_utils.py index e6e58f184..d8d9206e9 100644 --- a/nerfstudio/process_data/process_data_utils.py +++ b/nerfstudio/process_data/process_data_utils.py @@ -30,6 +30,7 @@ from nerfstudio.utils.rich_utils import status from nerfstudio.utils.scripts import run_command CONSOLE = Console(width=120) +POLYCAM_UPSCALING_TIMES = 2 class CameraModel(Enum): @@ -180,6 +181,54 @@ def copy_images_list( return copied_image_paths +def copy_and_upscale_polycam_depth_maps_list( + polycam_depth_image_filenames: List[Path], + depth_dir: Path, + crop_border_pixels: Optional[int] = None, + verbose: bool = False, +) -> List[Path]: + """ + Copy depth maps to working location and upscale them to match the RGB images dimensions and finally crop them + equally as RGB Images. + Args: + polycam_depth_image_filenames: List of Paths of images to copy to a new directory. + depth_dir: Path to the output directory. + crop_border_pixels: If not None, crops each edge by the specified number of pixels. + verbose: If True, print extra logging. + Returns: + A list of the copied depth maps paths. + """ + depth_dir.mkdir(parents=True, exist_ok=True) + + # copy and upscale them to new directory + with status(msg="[bold yellow] Upscaling depth maps...", spinner="growVertical", verbose=verbose): + upscale_factor = 2**POLYCAM_UPSCALING_TIMES + assert upscale_factor > 1 + assert isinstance(upscale_factor, int) + + copied_depth_map_paths = [] + for idx, depth_map in enumerate(polycam_depth_image_filenames): + destination = depth_dir / f"frame_{idx + 1:05d}{depth_map.suffix}" + ffmpeg_cmd = [ + f"ffmpeg -y -i {depth_map} ", + f"-q:v 2 -vf scale=iw*{upscale_factor}:ih*{upscale_factor}:flags=neighbor ", + f"{destination}", + ] + ffmpeg_cmd = " ".join(ffmpeg_cmd) + run_command(ffmpeg_cmd, verbose=verbose) + copied_depth_map_paths.append(destination) + + if crop_border_pixels is not None: + file_type = depth_dir.glob("frame_*").__next__().suffix + filename = f"frame_%05d{file_type}" + crop = f"crop=iw-{crop_border_pixels * 2}:ih-{crop_border_pixels * 2}" + ffmpeg_cmd = f"ffmpeg -y -i {depth_dir / filename} -q:v 2 -vf {crop} {depth_dir / filename}" + run_command(ffmpeg_cmd, verbose=verbose) + + CONSOLE.log("[bold green]:tada: Done upscaling depth maps.") + return copied_depth_map_paths + + def copy_images(data: Path, image_dir: Path, verbose) -> int: """Copy images from a directory to a new directory. @@ -203,7 +252,7 @@ def copy_images(data: Path, image_dir: Path, verbose) -> int: return num_frames -def downscale_images(image_dir: Path, num_downscales: int, verbose: bool = False) -> str: +def downscale_images(image_dir: Path, num_downscales: int, folder_name: str = "images", verbose: bool = False) -> str: """Downscales the images in the directory. Uses FFMPEG. Assumes images are named frame_00001.png, frame_00002.png, etc. @@ -211,6 +260,7 @@ def downscale_images(image_dir: Path, num_downscales: int, verbose: bool = False Args: image_dir: Path to the directory containing the images. num_downscales: Number of times to downscale the images. Downscales by 2 each time. + folder_name: Name of the output folder verbose: If True, logs the output of the command. Returns: @@ -225,7 +275,7 @@ def downscale_images(image_dir: Path, num_downscales: int, verbose: bool = False for downscale_factor in downscale_factors: assert downscale_factor > 1 assert isinstance(downscale_factor, int) - downscale_dir = image_dir.parent / f"images_{downscale_factor}" + downscale_dir = image_dir.parent / f"{folder_name}_{downscale_factor}" downscale_dir.mkdir(parents=True, exist_ok=True) # Using %05d ffmpeg commands appears to be unreliable (skips images), so use scandir. files = os.scandir(image_dir) diff --git a/nerfstudio/process_data/realitycapture_utils.py b/nerfstudio/process_data/realitycapture_utils.py index eaba5aeb0..7bc73e132 100644 --- a/nerfstudio/process_data/realitycapture_utils.py +++ b/nerfstudio/process_data/realitycapture_utils.py @@ -32,6 +32,7 @@ def realitycapture_to_json( image_filename_map: List[Path], csv_filename: Path, output_dir: Path, + verbose: bool = False, ) -> List[str]: """Convert RealityCapture data into a nerfstudio dataset. @@ -58,15 +59,28 @@ def realitycapture_to_json( for column, value in row.items(): cameras.setdefault(column, []).append(value) - img = np.array(Image.open(output_dir / image_filename_map[cameras["#name"][0].split(".")[0]])) + for name in cameras["#name"]: + camera_label = name.split(".")[0] + if camera_label in image_filename_map: + img = np.array(Image.open(output_dir / image_filename_map[camera_label])) + break + height, width, _ = img.shape data["h"] = int(height) data["w"] = int(width) + missing_image_data = 0 + for i, name in enumerate(cameras["#name"]): + basename = name.split(".")[0] + if basename not in image_filename_map: + if verbose: + CONSOLE.print(f"Missing image for camera data {basename}, Skipping") + missing_image_data += 1 + continue frame = {} - frame["file_path"] = image_filename_map[name.split(".")[0]].as_posix() + frame["file_path"] = image_filename_map[basename].as_posix() frame["fl_x"] = float(cameras["f"][i]) * max(width, height) / 36 frame["fl_y"] = float(cameras["f"][i]) * max(width, height) / 36 # TODO: Unclear how to get the principal point from RealityCapture, here a guess... @@ -95,6 +109,8 @@ def realitycapture_to_json( json.dump(data, f, indent=4) summary = [] + if missing_image_data > 0: + summary.append(f"Missing image data for {missing_image_data} cameras.") if len(frames) < len(image_filename_map): summary.append(f"Missing camera data for {len(image_filename_map) - len(frames)} frames.") summary.append(f"Final dataset is {len(frames)} frames.") diff --git a/nerfstudio/viewer/app/package.json b/nerfstudio/viewer/app/package.json index 848e1dddc..37f2b7bbb 100644 --- a/nerfstudio/viewer/app/package.json +++ b/nerfstudio/viewer/app/package.json @@ -1,7 +1,7 @@ { "name": "viewer", "homepage": ".", - "version": "23-01-20-0", + "version": "23-01-25-0", "private": true, "dependencies": { "@emotion/react": "^11.10.4", diff --git a/nerfstudio/viewer/app/src/index.scss b/nerfstudio/viewer/app/src/index.scss index fab8b8a68..3a331e37a 100644 --- a/nerfstudio/viewer/app/src/index.scss +++ b/nerfstudio/viewer/app/src/index.scss @@ -242,6 +242,25 @@ $sidebar-width: 100% !default; margin-top: 20px; } +// ------------------------------------ +// Load Path Modal styling + +.LoadPathModal-box { + position: absolute; + top: 50%; + left: 50%; + transform: translate(-50%, -50%); + width: 500px; // 400 + background-color: $base-color2; + border: 2px solid #000; + padding: 32px; + margin-top: 20px; +} + +.LoadPathModal-upload_button { + text-align: center; +} + // ------------------------------------ // Camera Pane diff --git a/nerfstudio/viewer/app/src/modules/ConfigPanel/ConfigPanel.jsx b/nerfstudio/viewer/app/src/modules/ConfigPanel/ConfigPanel.jsx index e710b6733..a1c331fad 100644 --- a/nerfstudio/viewer/app/src/modules/ConfigPanel/ConfigPanel.jsx +++ b/nerfstudio/viewer/app/src/modules/ConfigPanel/ConfigPanel.jsx @@ -48,7 +48,9 @@ export function RenderControls() { (state) => state.renderingState.crop_enabled, ); - const box_size = useSelector((state) => state.renderingState.box_size); + const crop_bg_color = useSelector( + (state) => state.renderingState.crop_bg_color, + ); const crop_scale = useSelector((state) => state.renderingState.crop_scale); @@ -154,7 +156,7 @@ export function RenderControls() { '2048px': () => setControls({ max_resolution: 2048 }), }), // Enable Crop - crop_options: { + crop_enabled: { label: 'Crop Viewport', value: crop_enabled, hint: 'Crop the viewport to the selected box', @@ -167,13 +169,26 @@ export function RenderControls() { ); }, }, + crop_bg_color: { + label: '| Background Color', + value: crop_bg_color, + render: (get) => get('crop_enabled'), + onChange: (v) => { + dispatch_and_send( + websocket, + dispatch, + 'renderingState/crop_bg_color', + v, + ); + }, + }, crop_scale: { label: '| Scale', value: crop_scale, min: 0, max: 10, step: 0.05, - render: (get) => get('crop_options'), + render: (get) => get('crop_enabled'), onChange: (v) => { dispatch_and_send( websocket, @@ -189,7 +204,7 @@ export function RenderControls() { min: -10, max: 10, step: 0.05, - render: (get) => get('crop_options'), + render: (get) => get('crop_enabled'), onChange: (v) => { dispatch_and_send( websocket, @@ -227,7 +242,6 @@ export function RenderControls() { colormapChoice, max_resolution, crop_enabled, - box_size, target_train_util, render_time, display_render_time, @@ -239,6 +253,10 @@ export function RenderControls() { setControls({ max_resolution }); setControls({ output_options: outputChoice }); setControls({ colormap_options: colormapChoice }); + setControls({ crop_enabled }); + setControls({ crop_bg_color }); + setControls({ crop_scale }); + setControls({ crop_center }); }, [ setControls, outputOptions, @@ -248,6 +266,10 @@ export function RenderControls() { max_resolution, target_train_util, render_time, + crop_enabled, + crop_bg_color, + crop_scale, + crop_center, display_render_time, ]); diff --git a/nerfstudio/viewer/app/src/modules/LoadPathModal/LoadPathModal.jsx b/nerfstudio/viewer/app/src/modules/LoadPathModal/LoadPathModal.jsx new file mode 100644 index 000000000..5f79d1e00 --- /dev/null +++ b/nerfstudio/viewer/app/src/modules/LoadPathModal/LoadPathModal.jsx @@ -0,0 +1,149 @@ +/* eslint-disable react/jsx-props-no-spreading */ +import * as React from 'react'; + +import { Box, Button, FormControl, Modal, Typography } from '@mui/material'; +import InputLabel from '@mui/material/InputLabel'; +import { useSelector } from 'react-redux'; +import { FileUpload } from '@mui/icons-material'; +import MenuItem from '@mui/material/MenuItem'; +import Select from '@mui/material/Select'; + +interface LoadPathModalProps { + open: object; + setOpen: object; + pathUploadFunction: any; + loadCameraPathFunction: any; +} + +export default function LoadPathModal(props: LoadPathModalProps) { + const open = props.open; + const setOpen = props.setOpen; + const uploadCameraPath = props.pathUploadFunction; + const loadCameraPath = props.loadCameraPathFunction; + + const [existingPathSelect, setExistingPathSelect] = React.useState(''); + + // redux store state + const all_camera_paths = useSelector( + (state) => state.renderingState.all_camera_paths, + ); + + let camera_paths_arr = []; + if (typeof all_camera_paths === 'object' && all_camera_paths !== null) { + camera_paths_arr = Object.keys(all_camera_paths).map((key) => { + return { + name: key, + val: all_camera_paths[key], + }; + }); + } + + const hiddenFileInput = React.useRef(null); + const handleFileUploadClick = () => { + hiddenFileInput.current.click(); + }; + + // react state + + const handleClose = () => setOpen(false); + const handlePathSelect = (event) => { + setExistingPathSelect(event.target.value); + }; + + const handleExistingLoadClick = () => { + loadCameraPath(existingPathSelect); + handleClose(); + }; + + const handleFileInput = (event) => { + uploadCameraPath(event); + handleClose(); + }; + + return ( +
+ Either upload a local file or select a saved camera path +
++
No existing saved paths found
+ )} +
- ./renders/{data_base_dir}/{export_path}.mp4
+ ./renders/{data_base_dir_leaf}/{export_path}.mp4
.
-
+