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 ( +
+ + + +
+

Load Camera Path

+ {camera_paths_arr.length > 0 && ( + <> +

+ Either upload a local file or select a saved camera path +

+ + Existing Path + + + +
+

+

OR
+

+ + )} + {camera_paths_arr.length === 0 && ( +

No existing saved paths found

+ )} +
+ +
+
+
+
+
+
+ ); +} diff --git a/nerfstudio/viewer/app/src/modules/LoadPathModal/index.jsx b/nerfstudio/viewer/app/src/modules/LoadPathModal/index.jsx new file mode 100644 index 000000000..c7f0dc4a1 --- /dev/null +++ b/nerfstudio/viewer/app/src/modules/LoadPathModal/index.jsx @@ -0,0 +1,3 @@ +import LoadPathModal from './LoadPathModal'; + +export default LoadPathModal; diff --git a/nerfstudio/viewer/app/src/modules/RenderModal/RenderModal.jsx b/nerfstudio/viewer/app/src/modules/RenderModal/RenderModal.jsx index c9cea8f1b..8b0a18321 100644 --- a/nerfstudio/viewer/app/src/modules/RenderModal/RenderModal.jsx +++ b/nerfstudio/viewer/app/src/modules/RenderModal/RenderModal.jsx @@ -19,9 +19,7 @@ export default function RenderModal(props: RenderModalProps) { (state) => state.renderingState.config_base_dir, ); - const export_path = useSelector( - (state) => state.renderingState.export_path, - ); + const export_path = useSelector((state) => state.renderingState.export_path); const data_base_dir = useSelector( (state) => state.renderingState.data_base_dir, @@ -34,12 +32,14 @@ export default function RenderModal(props: RenderModalProps) { // Copy the text inside the text field const config_filename = `${config_base_dir}/config.yml`; const camera_path_filename = `${export_path}.json`; - const cmd = `ns-render --load-config ${config_filename} --traj filename --camera-path-filename ${data_base_dir}/camera_paths/${camera_path_filename} --output-path renders/${data_base_dir}/${export_path}.mp4`; + const data_base_dir_leaf = data_base_dir.split('/').pop(); + const cmd = `ns-render --load-config ${config_filename} --traj filename --camera-path-filename ${data_base_dir}/camera_paths/${camera_path_filename} --output-path renders/${data_base_dir_leaf}/${export_path}.mp4`; const text_intro = `To render a full resolution video, run the following command in a terminal.`; const handleCopy = () => { navigator.clipboard.writeText(cmd); + handleClose(); }; return ( @@ -63,11 +63,11 @@ export default function RenderModal(props: RenderModalProps) {
The video will be saved to{' '} - ./renders/{data_base_dir}/{export_path}.mp4 + ./renders/{data_base_dir_leaf}/{export_path}.mp4 .

- +
{cmd}
@@ -1160,6 +1234,7 @@ export default function CameraPanel(props) { variant="outlined" startIcon={} onClick={export_camera_path} + disabled={cameras.length === 0} > Export Path @@ -1172,6 +1247,7 @@ export default function CameraPanel(props) { size="small" startIcon={} onClick={open_render_modal} + disabled={cameras.length === 0} > Render diff --git a/nerfstudio/viewer/app/src/modules/ViewerWindow/ViewerWindow.jsx b/nerfstudio/viewer/app/src/modules/ViewerWindow/ViewerWindow.jsx index d48edfff3..5218b82b8 100644 --- a/nerfstudio/viewer/app/src/modules/ViewerWindow/ViewerWindow.jsx +++ b/nerfstudio/viewer/app/src/modules/ViewerWindow/ViewerWindow.jsx @@ -18,13 +18,9 @@ const msgpack = require('msgpack-lite'); function CameraToggle() { const dispatch = useDispatch(); - const websocket = useContext(WebSocketContext).socket; const camera_choice = useSelector( (state) => state.renderingState.camera_choice, ); - const crop_enabled = useSelector( - (state) => state.renderingState.crop_enabled, - ); const set_camera_choice = (event: SelectChangeEvent, value: string[]) => { if (value != null) { dispatch({ @@ -32,21 +28,6 @@ function CameraToggle() { path: 'renderingState/camera_choice', data: value, }); - if (websocket.readyState === WebSocket.OPEN) { - const path = 'renderingState/crop_enabled'; - const data = { - type: 'write', - path, - data: false, - }; - if (value === 'Render Camera') { - data.data = false; - } else { - data.data = crop_enabled; - } - const message = msgpack.encode(data); - websocket.send(message); - } } }; diff --git a/nerfstudio/viewer/app/src/reducer.js b/nerfstudio/viewer/app/src/reducer.js index 7d59491cc..6de1ea7c2 100644 --- a/nerfstudio/viewer/app/src/reducer.js +++ b/nerfstudio/viewer/app/src/reducer.js @@ -12,6 +12,7 @@ const initialState = { }, // for sending actual commands to the client camera_path_payload: null, + populate_paths_payload: false, // the rendering state renderingState: { // cameras @@ -25,7 +26,10 @@ const initialState = { camera_type: 'perspective', data_base_dir: 'data_base_dir', // the base directory of the images for saving camera path with the data - export_path: 'export_path', + export_path: 'export_path', // export name for render and camera_path + + all_camera_paths: null, // object containing camera paths and names + isTraining: true, output_options: ['rgb'], // populated by the possible Graph outputs @@ -47,6 +51,7 @@ const initialState = { // Crop Box Options crop_enabled: false, + crop_bg_color: {r: 38, g:42, b:55}, crop_scale: [2.0, 2.0, 2.0], crop_center: [0.0, 0.0, 0.0], }, diff --git a/nerfstudio/viewer/app/src/themes/theme.ts b/nerfstudio/viewer/app/src/themes/theme.ts index 4a973209e..b789c3899 100644 --- a/nerfstudio/viewer/app/src/themes/theme.ts +++ b/nerfstudio/viewer/app/src/themes/theme.ts @@ -169,5 +169,12 @@ export const appTheme = createTheme({ }, }, }, + MuiSelect: { + styleOverrides: { + icon: { + color: '#eeeeee', + }, + }, + }, }, }); diff --git a/nerfstudio/viewer/server/viewer_utils.py b/nerfstudio/viewer/server/viewer_utils.py index c6d8d38b2..f62cf9d8f 100644 --- a/nerfstudio/viewer/server/viewer_utils.py +++ b/nerfstudio/viewer/server/viewer_utils.py @@ -147,7 +147,14 @@ class RenderThread(threading.Thread): try: with SetTrace(self.state.check_interrupt): if self.state.prev_crop_enabled: - with renderers.background_mode_override_context("black"), torch.no_grad(): + color = self.state.prev_crop_bg_color + if color is None: + background_color = torch.tensor([0.0, 0.0, 0.0], device=self.graph.device) + else: + background_color = torch.tensor( + [color["r"] / 255.0, color["g"] / 255.0, color["b"] / 255.0], device=self.graph.device + ) + with renderers.background_color_override_context(background_color), torch.no_grad(): outputs = self.graph.get_outputs_for_camera_ray_bundle(self.camera_ray_bundle) else: with torch.no_grad(): @@ -286,6 +293,7 @@ class ViewerState: self.camera_moving = False self.prev_camera_timestamp = 0 self.prev_crop_enabled = False + self.prev_crop_bg_color = None self.prev_crop_scale = None self.prev_crop_center = None @@ -380,6 +388,21 @@ class ViewerState: write_to_json(Path(os.path.join(camera_paths_directory, camera_path_filename)), camera_path) self.vis["camera_path_payload"].delete() + def _check_populate_paths_payload(self, trainer, step: int): + populate_paths_payload = self.vis["populate_paths_payload"].read() + if populate_paths_payload: + # save a model checkpoint + trainer.save_checkpoint(step) + # get all camera paths + camera_path_dir = os.path.join(self.datapath, "camera_paths") + camera_path_files = os.listdir(camera_path_dir) + all_path_dict = {} + for i in camera_path_files: + if i[-4:] == "json": + all_path_dict[i[:-5]] = load_from_json(Path(os.path.join(camera_path_dir, i))) + self.vis["renderingState/all_camera_paths"].write(all_path_dict) + self.vis["populate_paths_payload"].delete() + def _check_webrtc_offer(self): """Check if there is a webrtc offer to respond to.""" data = self.vis["webrtc/offer"].read() @@ -412,12 +435,18 @@ class ViewerState: if crop_enabled != self.prev_crop_enabled: self.camera_moving = True self.prev_crop_enabled = crop_enabled + self.prev_crop_bg_color = None self.prev_crop_scale = None self.prev_crop_center = None if crop_enabled: crop_scale = self.vis["renderingState/crop_scale"].read() crop_center = self.vis["renderingState/crop_center"].read() + crop_bg_color = self.vis["renderingState/crop_bg_color"].read() + + if crop_bg_color != self.prev_crop_bg_color: + self.camera_moving = True + self.prev_crop_bg_color = crop_bg_color if crop_scale != self.prev_crop_scale or crop_center != self.prev_crop_center: self.camera_moving = True @@ -449,7 +478,6 @@ class ViewerState: step: iteration step of training graph: the current checkpoint of the model """ - has_temporal_distortion = getattr(graph, "temporal_distortion", None) is not None self.vis["model/has_temporal_distortion"].write(str(has_temporal_distortion).lower()) @@ -457,6 +485,7 @@ class ViewerState: self.step = step self._check_camera_path_payload(trainer, step) + self._check_populate_paths_payload(trainer, step) self._check_webrtc_offer() camera_object = self._get_camera_object() @@ -501,6 +530,7 @@ class ViewerState: self._render_image_in_viewer(camera_object, graph, is_training) camera_object = self._get_camera_object() is_training = self.vis["renderingState/isTraining"].read() + self._check_populate_paths_payload(trainer, step) self._check_camera_path_payload(trainer, step) self._check_webrtc_offer() run_loop = not is_training @@ -542,6 +572,11 @@ class ViewerState: if self.prev_colormap_type != colormap_type: self.camera_moving = True + crop_bg_color = self.vis["renderingState/crop_bg_color"].read() + if self.prev_crop_enabled: + if self.prev_crop_bg_color != crop_bg_color: + self.camera_moving = True + crop_scale = self.vis["renderingState/crop_scale"].read() if self.prev_crop_enabled: if self.prev_crop_scale != crop_scale: diff --git a/pyproject.toml b/pyproject.toml index 68bb8d8be..42fd7b146 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -4,7 +4,7 @@ build-backend = "setuptools.build_meta" [project] name = "nerfstudio" -version = "0.1.15" +version = "0.1.16" description = "All-in-one repository for state-of-the-art NeRFs" readme = "README.md" license = { text="Apache 2.0"} @@ -34,6 +34,7 @@ dependencies = [ "nerfacc==0.3.3", "open3d>=0.16.0", "opencv-python==4.6.0.66", + "Pillow>=9.3.0", "plotly>=5.7.0", "protobuf<=3.20.3.*,!=3.20.0", "pymeshlab>=2022.2.post2", diff --git a/scripts/blender/nerfstudio_blender.py b/scripts/blender/nerfstudio_blender.py index 78e7cb945..dee0b4ab3 100644 --- a/scripts/blender/nerfstudio_blender.py +++ b/scripts/blender/nerfstudio_blender.py @@ -76,6 +76,10 @@ class CreateJSONCameraPath(bpy.types.Operator): curr_frame += bpy.context.scene.frame_step nerf_mesh_mat_list += [self.nerf_bg_mesh.matrix_world.copy()] + # case when step size is 0 there is only one frame + if bpy.context.scene.frame_step == 0: + break + # transform the camera world matrix based on the NeRF mesh transformation for i, org_cam_path_mat_val in enumerate(org_camera_path_mat): self.transformed_camera_path_mat += [nerf_mesh_mat_list[i].inverted() @ org_cam_path_mat_val] @@ -110,9 +114,15 @@ class CreateJSONCameraPath(bpy.types.Operator): bpy.context.scene.render.resolution_x * (bpy.context.scene.render.resolution_percentage * 0.01) ) render_fps = bpy.context.scene.render.fps - render_seconds = ( - (bpy.context.scene.frame_end - bpy.context.scene.frame_start + 1) // (bpy.context.scene.frame_step) - ) / render_fps + + # case when step size is 0 there is only one frame + if bpy.context.scene.frame_step == 0: + render_seconds = 1 / render_fps + else: + render_seconds = ( + ((bpy.context.scene.frame_end - bpy.context.scene.frame_start) // (bpy.context.scene.frame_step) + 1) + ) / render_fps + smoothness_value = 0 is_cycle = False diff --git a/scripts/process_data.py b/scripts/process_data.py index a8551dff3..4727e2b2c 100755 --- a/scripts/process_data.py +++ b/scripts/process_data.py @@ -526,7 +526,8 @@ class ProcessPolycam: """Minimum blur score to use an image. If the blur score is below this value, the image will be skipped.""" crop_border_pixels: int = 15 """Number of pixels to crop from each border of the image. Useful as borders may be black due to undistortion.""" - + use_depth: bool = False + """If True, processes the generated depth maps from Polycam""" verbose: bool = False """If True, print extra logging.""" @@ -551,47 +552,47 @@ class ProcessPolycam: else: polycam_image_dir = self.data / "keyframes" / "images" polycam_cameras_dir = self.data / "keyframes" / "cameras" - self.crop_border_pixels = 0 if not self.use_uncorrected_images: CONSOLE.print("[bold yellow]Corrected images not found, using raw images.") if not polycam_image_dir.exists(): raise ValueError(f"Image directory {polycam_image_dir} doesn't exist") - # Copy images to output directory - polycam_image_filenames, num_orig_images = process_data_utils.get_image_filenames( - polycam_image_dir, self.max_dataset_size - ) + if not (self.data / "keyframes" / "depth").exists(): + depth_dir = self.data / "keyframes" / "depth" + raise ValueError(f"Depth map directory {depth_dir} doesn't exist") - copied_image_paths = process_data_utils.copy_images_list( - polycam_image_filenames, - image_dir=image_dir, + (image_processing_log, polycam_image_filenames) = polycam_utils.process_images( + polycam_image_dir, + image_dir, crop_border_pixels=self.crop_border_pixels, + max_dataset_size=self.max_dataset_size, + num_downscales=self.num_downscales, verbose=self.verbose, ) - num_frames = len(copied_image_paths) - copied_image_paths = [Path("images/" + copied_image_path.name) for copied_image_path in copied_image_paths] + summary_log.extend(image_processing_log) - if self.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 [yellow]--max_dataset_size[/yellow] to " - f"larger than the current value ({self.max_dataset_size}), or -1 to use all images." + polycam_depth_filenames = [] + if self.use_depth: + polycam_depth_image_dir = self.data / "keyframes" / "depth" + depth_dir = self.output_dir / "depth" + depth_dir.mkdir(parents=True, exist_ok=True) + (depth_processing_log, polycam_depth_filenames) = polycam_utils.process_depth_maps( + polycam_depth_image_dir, + depth_dir, + num_processed_images=len(polycam_image_filenames), + crop_border_pixels=self.crop_border_pixels, + max_dataset_size=self.max_dataset_size, + num_downscales=self.num_downscales, + verbose=self.verbose, ) - else: - summary_log.append(f"Started with {num_frames} images") + summary_log.extend(depth_processing_log) - # Downscale images - summary_log.append(process_data_utils.downscale_images(image_dir, self.num_downscales, verbose=self.verbose)) - - # Save json - if num_frames == 0: - CONSOLE.print("[bold red]No images found, exiting") - sys.exit(1) summary_log.extend( polycam_utils.polycam_to_json( image_filenames=polycam_image_filenames, + depth_filenames=polycam_depth_filenames, cameras_dir=polycam_cameras_dir, output_dir=self.output_dir, min_blur_score=self.min_blur_score, diff --git a/scripts/render.py b/scripts/render.py index 357b902ed..4466c5385 100644 --- a/scripts/render.py +++ b/scripts/render.py @@ -11,7 +11,7 @@ import sys from contextlib import ExitStack from dataclasses import dataclass, field from pathlib import Path -from typing import List, Optional +from typing import Any, Dict, List, Optional import mediapy as media import numpy as np @@ -25,10 +25,13 @@ from rich.progress import ( TextColumn, TimeRemainingColumn, ) +from torchtyping import TensorType from typing_extensions import Literal, assert_never from nerfstudio.cameras.camera_paths import get_path_from_json, get_spiral_path from nerfstudio.cameras.cameras import Cameras, CameraType +from nerfstudio.data.scene_box import SceneBox +from nerfstudio.model_components import renderers from nerfstudio.pipelines.base_pipeline import Pipeline from nerfstudio.utils import install_checks from nerfstudio.utils.eval_utils import eval_setup @@ -42,6 +45,7 @@ def _render_trajectory_video( cameras: Cameras, output_filename: Path, rendered_output_names: List[str], + crop_data: Optional[CropData] = None, rendered_resolution_scaling_factor: float = 1.0, seconds: float = 5.0, output_format: Literal["images", "video"] = "video", @@ -54,6 +58,7 @@ def _render_trajectory_video( cameras: Cameras to render. output_filename: Name of the output file. rendered_output_names: List of outputs to visualise. + crop_data: Crop data to apply to the rendered images. rendered_resolution_scaling_factor: Scaling factor to apply to the camera image resolution. seconds: Length of output video. output_format: How to save output data. @@ -89,9 +94,23 @@ def _render_trajectory_video( with progress: for camera_idx in progress.track(range(cameras.size), description=""): - camera_ray_bundle = cameras.generate_rays(camera_indices=camera_idx) - with torch.no_grad(): - outputs = pipeline.model.get_outputs_for_camera_ray_bundle(camera_ray_bundle) + + aabb_box = None + if crop_data is not None: + bounding_box_min = crop_data.center - crop_data.scale / 2.0 + bounding_box_max = crop_data.center + crop_data.scale / 2.0 + aabb_box = SceneBox(torch.stack([bounding_box_min, bounding_box_max]).to(pipeline.device)) + camera_ray_bundle = cameras.generate_rays(camera_indices=camera_idx, aabb_box=aabb_box) + + if crop_data is not None: + with renderers.background_color_override_context( + crop_data.background_color.to(pipeline.device) + ), torch.no_grad(): + outputs = pipeline.model.get_outputs_for_camera_ray_bundle(camera_ray_bundle) + else: + with torch.no_grad(): + outputs = pipeline.model.get_outputs_for_camera_ray_bundle(camera_ray_bundle) + render_image = [] for rendered_output_name in rendered_output_names: if rendered_output_name not in outputs: @@ -110,8 +129,8 @@ def _render_trajectory_video( media.write_image(output_image_dir / f"{camera_idx:05d}.png", render_image) if output_format == "video": if writer is None: - render_width = int(render_image.shape[1] * rendered_resolution_scaling_factor) - render_height = int(render_image.shape[0] * rendered_resolution_scaling_factor) + render_width = int(render_image.shape[1]) + render_height = int(render_image.shape[0]) writer = stack.enter_context( media.VideoWriter( path=output_filename, @@ -196,28 +215,60 @@ xmlns:GSpherical='http://ns.google.com/videos/1.0/spherical/'> mp4file.close() +@dataclass +class CropData: + """Data for cropping an image.""" + + background_color: TensorType[3] = torch.Tensor([0.0, 0.0, 0.0]) + """background color""" + center: TensorType[3] = torch.Tensor([0.0, 0.0, 0.0]) + """center of the crop""" + scale: TensorType[3] = torch.Tensor([2.0, 2.0, 2.0]) + """scale of the crop""" + + +def get_crop_from_json(camera_json: Dict[str, Any]) -> Optional[CropData]: + """Load crop data from a camera path JSON + + args: + camera_json: camera path data + returns: + Crop data + """ + if "crop" not in camera_json or camera_json["crop"] is None: + return None + + bg_color = camera_json["crop"]["crop_bg_color"] + + return CropData( + background_color=torch.Tensor([bg_color["r"] / 255.0, bg_color["g"] / 255.0, bg_color["b"] / 255.0]), + center=torch.Tensor(camera_json["crop"]["crop_center"]), + scale=torch.Tensor(camera_json["crop"]["crop_scale"]), + ) + + @dataclass class RenderTrajectory: """Load a checkpoint, render a trajectory, and save to a video file.""" - # Path to config YAML file. load_config: Path - # Name of the renderer outputs to use. rgb, depth, etc. concatenates them along y axis + """Path to config YAML file.""" rendered_output_names: List[str] = field(default_factory=lambda: ["rgb"]) - # Trajectory to render. + """Name of the renderer outputs to use. rgb, depth, etc. concatenates them along y axis""" traj: Literal["spiral", "filename"] = "spiral" - # Scaling factor to apply to the camera image resolution. + """Trajectory to render.""" downscale_factor: int = 1 - # Filename of the camera path to render. + """Scaling factor to apply to the camera image resolution.""" camera_path_filename: Path = Path("camera_path.json") - # Name of the output file. + """Filename of the camera path to render.""" output_path: Path = Path("renders/output.mp4") - # How long the video should be. + """Name of the output file.""" seconds: float = 5.0 - # How to save output data. + """How long the video should be.""" output_format: Literal["images", "video"] = "video" - # Specifies number of rays per chunk during eval. + """How to save output data.""" eval_num_rays_per_chunk: Optional[int] = None + """Specifies number of rays per chunk during eval.""" def main(self) -> None: """Main function.""" @@ -230,6 +281,7 @@ class RenderTrajectory: install_checks.check_ffmpeg_installed() seconds = self.seconds + crop_data = None # TODO(ethan): use camera information from parsing args if self.traj == "spiral": @@ -249,6 +301,7 @@ class RenderTrajectory: camera_type = CameraType.EQUIRECTANGULAR else: camera_type = CameraType.PERSPECTIVE + crop_data = get_crop_from_json(camera_path) camera_path = get_path_from_json(camera_path) else: assert_never(self.traj) @@ -259,6 +312,7 @@ class RenderTrajectory: output_filename=self.output_path, rendered_output_names=self.rendered_output_names, rendered_resolution_scaling_factor=1.0 / self.downscale_factor, + crop_data=crop_data, seconds=seconds, output_format=self.output_format, camera_type=camera_type,