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 <justin.g.kerr@gmail.com>
This commit is contained in:
Ethan WeberandJustin Kerr authored and GitHub committed 2024-01-29 11:47:49 -08:00
1 parent d8b517d6a5
commit c397588300
6 files changed
+22 -11

No files matched your search

@@ -406,9 +406,9 @@ class VanillaDataManager(DataManager, Generic[TDataset]):
self.train_dataset = self.create_train_dataset() self.train_dataset = self.create_train_dataset()
self.eval_dataset = self.create_eval_dataset() self.eval_dataset = self.create_eval_dataset()
self.exclude_batch_keys_from_device = self.train_dataset.exclude_batch_keys_from_device 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") 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") self.exclude_batch_keys_from_device.remove("image")
if self.train_dataparser_outputs is not None: if self.train_dataparser_outputs is not None:
@@ -17,7 +17,7 @@ from __future__ import annotations
from dataclasses import dataclass, field from dataclasses import dataclass, field
from pathlib import Path from pathlib import Path
from typing import Literal, Optional, Type from typing import Literal, Optional, Tuple, Type
import numpy as np import numpy as np
import torch 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.""" """The interval between frames to use for eval. Only used when eval_mode is eval-interval."""
depth_unit_scale_factor: float = 1e-3 depth_unit_scale_factor: float = 1e-3
"""Scales the depth values to meters. Default value is 0.001 for a millimeter to meter conversion.""" """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 load_3D_points: bool = False
"""Whether to load the 3D points from the colmap reconstruction.""" """Whether to load the 3D points from the colmap reconstruction."""
@@ -411,6 +413,7 @@ class Nerfstudio(DataParser):
metadata={ metadata={
"depth_filenames": depth_filenames if len(depth_filenames) > 0 else None, "depth_filenames": depth_filenames if len(depth_filenames) > 0 else None,
"depth_unit_scale_factor": self.config.depth_unit_scale_factor, "depth_unit_scale_factor": self.config.depth_unit_scale_factor,
"mask_color": self.config.mask_color,
**metadata, **metadata,
}, },
) )
+5
View File
@@ -53,6 +53,7 @@ class InputDataset(Dataset):
self.metadata = deepcopy(dataparser_outputs.metadata) self.metadata = deepcopy(dataparser_outputs.metadata)
self.cameras = deepcopy(dataparser_outputs.cameras) self.cameras = deepcopy(dataparser_outputs.cameras)
self.cameras.rescale_output_resolution(scaling_factor=scale_factor) self.cameras.rescale_output_resolution(scaling_factor=scale_factor)
self.mask_color = dataparser_outputs.metadata.get("mask_color", None)
def __len__(self): def __len__(self):
return len(self._dataparser_outputs.image_filenames) return len(self._dataparser_outputs.image_filenames)
@@ -129,6 +130,10 @@ class InputDataset(Dataset):
assert ( assert (
data["mask"].shape[:2] == data["image"].shape[:2] 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]}" ), 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) metadata = self.get_metadata(data)
data.update(metadata) data.update(metadata)
return data return data
+7 -5
View File
@@ -41,6 +41,8 @@ class PixelSamplerConfig(InstantiateConfig):
"""Whether or not to include a reference to the full image in returned batch.""" """Whether or not to include a reference to the full image in returned batch."""
is_equirectangular: bool = False is_equirectangular: bool = False
"""List of whether or not camera i is equirectangular.""" """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 fisheye_crop_radius: Optional[float] = None
"""Set to the radius (in pixels) for fisheye cameras.""" """Set to the radius (in pixels) for fisheye cameras."""
rejection_sample_mask: bool = True rejection_sample_mask: bool = True
@@ -98,7 +100,7 @@ class PixelSampler:
* torch.tensor([num_images, image_height, image_width], device=device) * torch.tensor([num_images, image_height, image_width], device=device)
).long() ).long()
if isinstance(mask, torch.Tensor): if isinstance(mask, torch.Tensor) and not self.config.ignore_mask:
if self.config.rejection_sample_mask: if self.config.rejection_sample_mask:
num_valid = 0 num_valid = 0
for _ in range(self.config.max_num_iterations): for _ in range(self.config.max_num_iterations):
@@ -143,7 +145,7 @@ class PixelSampler:
mask: Optional[Tensor] = None, mask: Optional[Tensor] = None,
device: Union[torch.device, str] = "cpu", device: Union[torch.device, str] = "cpu",
) -> Int[Tensor, "batch_size 3"]: ) -> 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 # 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. # sampling weight to the poles of the image than the equators.
# TODO(kevinddchen): implement the correct mask-sampling method. # TODO(kevinddchen): implement the correct mask-sampling method.
@@ -173,7 +175,7 @@ class PixelSampler:
mask: Optional[Tensor] = None, mask: Optional[Tensor] = None,
device: Union[torch.device, str] = "cpu", device: Union[torch.device, str] = "cpu",
) -> Int[Tensor, "batch_size 3"]: ) -> 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) indices = self.sample_method(batch_size, num_images, image_height, image_width, mask=mask, device=device)
else: else:
rand_samples = torch.rand((batch_size, 3), device=device) rand_samples = torch.rand((batch_size, 3), device=device)
@@ -383,7 +385,7 @@ class PatchPixelSampler(PixelSampler):
mask: Optional[Tensor] = None, mask: Optional[Tensor] = None,
device: Union[torch.device, str] = "cpu", device: Union[torch.device, str] = "cpu",
) -> Int[Tensor, "batch_size 3"]: ) -> 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) sub_bs = batch_size // (self.config.patch_size**2)
half_patch_size = int(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) 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})" ), f"PairPixelSampler can only return batch sizes in multiples of two (got {batch_size})"
rays_to_sample = batch_size // 2 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) 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) nonzero_indices = torch.nonzero(m[:, 0], as_tuple=False).to(device)
chosen_indices = random.sample(range(len(nonzero_indices)), k=rays_to_sample) chosen_indices = random.sample(range(len(nonzero_indices)), k=rays_to_sample)
+3
View File
@@ -27,6 +27,7 @@ from torch.cuda.amp.grad_scaler import GradScaler
from nerfstudio.engine.optimizers import Optimizers from nerfstudio.engine.optimizers import Optimizers
if TYPE_CHECKING: if TYPE_CHECKING:
from nerfstudio.engine.trainer import Trainer
from nerfstudio.pipelines.base_pipeline import Pipeline from nerfstudio.pipelines.base_pipeline import Pipeline
@@ -43,6 +44,8 @@ class TrainingCallbackAttributes:
"""gradient scalers""" """gradient scalers"""
pipeline: Optional["Pipeline"] # Prevent circular import. pipeline: Optional["Pipeline"] # Prevent circular import.
"""reference to training pipeline""" """reference to training pipeline"""
trainer: Optional["Trainer"] # Prevent circular import.
"""reference to trainer"""
class TrainingCallbackLocation(Enum): class TrainingCallbackLocation(Enum):
+1 -3
View File
@@ -191,9 +191,7 @@ class Trainer:
self.callbacks = self.pipeline.get_training_callbacks( self.callbacks = self.pipeline.get_training_callbacks(
TrainingCallbackAttributes( TrainingCallbackAttributes(
optimizers=self.optimizers, optimizers=self.optimizers, grad_scaler=self.grad_scaler, pipeline=self.pipeline, trainer=self
grad_scaler=self.grad_scaler,
pipeline=self.pipeline,
) )
) )