From c397588300751148c5eccccca3a8060562949dca Mon Sep 17 00:00:00 2001 From: Ethan Weber Date: Mon, 29 Jan 2024 11:47:49 -0800 Subject: [PATCH] Mask flexibility for methods than need to sample in the masked region (#2647) * minor changes to make masking more flexible * formatting * updating ignore mask --------- Co-authored-by: Justin Kerr --- nerfstudio/data/datamanagers/base_datamanager.py | 4 ++-- nerfstudio/data/dataparsers/nerfstudio_dataparser.py | 5 ++++- nerfstudio/data/datasets/base_dataset.py | 5 +++++ nerfstudio/data/pixel_samplers.py | 12 +++++++----- nerfstudio/engine/callbacks.py | 3 +++ nerfstudio/engine/trainer.py | 4 +--- 6 files changed, 22 insertions(+), 11 deletions(-) diff --git a/nerfstudio/data/datamanagers/base_datamanager.py b/nerfstudio/data/datamanagers/base_datamanager.py index 570c94ad4..cff03607b 100644 --- a/nerfstudio/data/datamanagers/base_datamanager.py +++ b/nerfstudio/data/datamanagers/base_datamanager.py @@ -406,9 +406,9 @@ class VanillaDataManager(DataManager, Generic[TDataset]): self.train_dataset = self.create_train_dataset() self.eval_dataset = self.create_eval_dataset() self.exclude_batch_keys_from_device = self.train_dataset.exclude_batch_keys_from_device - if self.config.masks_on_gpu is True: + if self.config.masks_on_gpu is True and "mask" in self.exclude_batch_keys_from_device: self.exclude_batch_keys_from_device.remove("mask") - if self.config.images_on_gpu is True: + if self.config.images_on_gpu is True and "image" in self.exclude_batch_keys_from_device: self.exclude_batch_keys_from_device.remove("image") if self.train_dataparser_outputs is not None: diff --git a/nerfstudio/data/dataparsers/nerfstudio_dataparser.py b/nerfstudio/data/dataparsers/nerfstudio_dataparser.py index aa06c53d3..910e0bc15 100644 --- a/nerfstudio/data/dataparsers/nerfstudio_dataparser.py +++ b/nerfstudio/data/dataparsers/nerfstudio_dataparser.py @@ -17,7 +17,7 @@ from __future__ import annotations from dataclasses import dataclass, field from pathlib import Path -from typing import Literal, Optional, Type +from typing import Literal, Optional, Tuple, Type import numpy as np import torch @@ -73,6 +73,8 @@ class NerfstudioDataParserConfig(DataParserConfig): """The interval between frames to use for eval. Only used when eval_mode is eval-interval.""" depth_unit_scale_factor: float = 1e-3 """Scales the depth values to meters. Default value is 0.001 for a millimeter to meter conversion.""" + mask_color: Optional[Tuple[float, float, float]] = None + """Replace the unknown pixels with this color. Relevant if you have a mask but still sample everywhere.""" load_3D_points: bool = False """Whether to load the 3D points from the colmap reconstruction.""" @@ -411,6 +413,7 @@ class Nerfstudio(DataParser): metadata={ "depth_filenames": depth_filenames if len(depth_filenames) > 0 else None, "depth_unit_scale_factor": self.config.depth_unit_scale_factor, + "mask_color": self.config.mask_color, **metadata, }, ) diff --git a/nerfstudio/data/datasets/base_dataset.py b/nerfstudio/data/datasets/base_dataset.py index 0e40f312d..5d44470fe 100644 --- a/nerfstudio/data/datasets/base_dataset.py +++ b/nerfstudio/data/datasets/base_dataset.py @@ -53,6 +53,7 @@ class InputDataset(Dataset): self.metadata = deepcopy(dataparser_outputs.metadata) self.cameras = deepcopy(dataparser_outputs.cameras) self.cameras.rescale_output_resolution(scaling_factor=scale_factor) + self.mask_color = dataparser_outputs.metadata.get("mask_color", None) def __len__(self): return len(self._dataparser_outputs.image_filenames) @@ -129,6 +130,10 @@ class InputDataset(Dataset): assert ( data["mask"].shape[:2] == data["image"].shape[:2] ), f"Mask and image have different shapes. Got {data['mask'].shape[:2]} and {data['image'].shape[:2]}" + if self.mask_color: + data["image"] = torch.where( + data["mask"] == 1.0, data["image"], torch.ones_like(data["image"]) * torch.tensor(self.mask_color) + ) metadata = self.get_metadata(data) data.update(metadata) return data diff --git a/nerfstudio/data/pixel_samplers.py b/nerfstudio/data/pixel_samplers.py index 144e405a5..ef6238aaf 100644 --- a/nerfstudio/data/pixel_samplers.py +++ b/nerfstudio/data/pixel_samplers.py @@ -41,6 +41,8 @@ class PixelSamplerConfig(InstantiateConfig): """Whether or not to include a reference to the full image in returned batch.""" is_equirectangular: bool = False """List of whether or not camera i is equirectangular.""" + ignore_mask: bool = False + """Whether to ignore the masks when sampling.""" fisheye_crop_radius: Optional[float] = None """Set to the radius (in pixels) for fisheye cameras.""" rejection_sample_mask: bool = True @@ -98,7 +100,7 @@ class PixelSampler: * torch.tensor([num_images, image_height, image_width], device=device) ).long() - if isinstance(mask, torch.Tensor): + if isinstance(mask, torch.Tensor) and not self.config.ignore_mask: if self.config.rejection_sample_mask: num_valid = 0 for _ in range(self.config.max_num_iterations): @@ -143,7 +145,7 @@ class PixelSampler: mask: Optional[Tensor] = None, device: Union[torch.device, str] = "cpu", ) -> Int[Tensor, "batch_size 3"]: - if isinstance(mask, torch.Tensor): + if isinstance(mask, torch.Tensor) and not self.config.ignore_mask: # Note: if there is a mask, sampling reduces back to uniform sampling, which gives more # sampling weight to the poles of the image than the equators. # TODO(kevinddchen): implement the correct mask-sampling method. @@ -173,7 +175,7 @@ class PixelSampler: mask: Optional[Tensor] = None, device: Union[torch.device, str] = "cpu", ) -> Int[Tensor, "batch_size 3"]: - if isinstance(mask, torch.Tensor): + if isinstance(mask, torch.Tensor) and not self.config.ignore_mask: indices = self.sample_method(batch_size, num_images, image_height, image_width, mask=mask, device=device) else: rand_samples = torch.rand((batch_size, 3), device=device) @@ -383,7 +385,7 @@ class PatchPixelSampler(PixelSampler): mask: Optional[Tensor] = None, device: Union[torch.device, str] = "cpu", ) -> Int[Tensor, "batch_size 3"]: - if isinstance(mask, Tensor): + if isinstance(mask, Tensor) and not self.config.ignore_mask: sub_bs = batch_size // (self.config.patch_size**2) half_patch_size = int(self.config.patch_size / 2) m = erode_mask(mask.permute(0, 3, 1, 2).float(), pixel_radius=half_patch_size) @@ -471,7 +473,7 @@ class PairPixelSampler(PixelSampler): # pylint: disable=too-few-public-methods ), f"PairPixelSampler can only return batch sizes in multiples of two (got {batch_size})" rays_to_sample = batch_size // 2 - if isinstance(mask, Tensor): + if isinstance(mask, Tensor) and not self.config.ignore_mask: m = erode_mask(mask.permute(0, 3, 1, 2).float(), pixel_radius=self.radius) nonzero_indices = torch.nonzero(m[:, 0], as_tuple=False).to(device) chosen_indices = random.sample(range(len(nonzero_indices)), k=rays_to_sample) diff --git a/nerfstudio/engine/callbacks.py b/nerfstudio/engine/callbacks.py index 45aa1d24b..f37cc7501 100644 --- a/nerfstudio/engine/callbacks.py +++ b/nerfstudio/engine/callbacks.py @@ -27,6 +27,7 @@ from torch.cuda.amp.grad_scaler import GradScaler from nerfstudio.engine.optimizers import Optimizers if TYPE_CHECKING: + from nerfstudio.engine.trainer import Trainer from nerfstudio.pipelines.base_pipeline import Pipeline @@ -43,6 +44,8 @@ class TrainingCallbackAttributes: """gradient scalers""" pipeline: Optional["Pipeline"] # Prevent circular import. """reference to training pipeline""" + trainer: Optional["Trainer"] # Prevent circular import. + """reference to trainer""" class TrainingCallbackLocation(Enum): diff --git a/nerfstudio/engine/trainer.py b/nerfstudio/engine/trainer.py index c4b867f9f..68b026c13 100644 --- a/nerfstudio/engine/trainer.py +++ b/nerfstudio/engine/trainer.py @@ -191,9 +191,7 @@ class Trainer: self.callbacks = self.pipeline.get_training_callbacks( TrainingCallbackAttributes( - optimizers=self.optimizers, - grad_scaler=self.grad_scaler, - pipeline=self.pipeline, + optimizers=self.optimizers, grad_scaler=self.grad_scaler, pipeline=self.pipeline, trainer=self ) )