diff --git a/linearize-ricoh-z10-wb-3500.json b/linearize-ricoh-z10-wb-3500.json index 6ff6171b1..112314c91 100644 --- a/linearize-ricoh-z10-wb-3500.json +++ b/linearize-ricoh-z10-wb-3500.json @@ -1 +1 @@ -{"B": [54.09578323364258, 0.2747989296913147, 0.0019784104079008102], "G": [48.520992279052734, 0.05255260691046715, 0.0029351452831178904], "R": [47.87550735473633, 0.19775021076202393, 0.0023990024346858263], "type": "deg2"} \ No newline at end of file +{"b": [2.6464749792362516], "g": [3.2232453214278767], "r": [2.9613987706773113]} \ No newline at end of file diff --git a/nerfstudio/data/dataparsers/nerfstudio_dataparser.py b/nerfstudio/data/dataparsers/nerfstudio_dataparser.py index e6b08b2d2..d040ba2d4 100644 --- a/nerfstudio/data/dataparsers/nerfstudio_dataparser.py +++ b/nerfstudio/data/dataparsers/nerfstudio_dataparser.py @@ -61,7 +61,7 @@ class NerfstudioDataParserConfig(DataParserConfig): """The method to use for orientation.""" center_method: Literal["poses", "focus", "none"] = "poses" """The method to use to center the poses.""" - auto_scale_poses: bool = True + auto_scale_poses: bool = False """Whether to automatically scale the poses to fit in +/- 1 bounding box.""" train_split_fraction: float = 0.9 """The fraction of images to use for training. The remaining images are for eval.""" @@ -294,6 +294,8 @@ class Nerfstudio(DataParser): else: distortion_params = torch.stack(distort, dim=0)[idx_tensor] + exposure_tensor = torch.tensor([exposures], dtype=torch.float32).T + cameras = Cameras( fx=fx, fy=fy, @@ -304,6 +306,9 @@ class Nerfstudio(DataParser): width=width, camera_to_worlds=poses[:, :3, :4], camera_type=camera_type, + metadata={ + 'exposures': exposure_tensor + } ) assert self.downscale_factor is not None diff --git a/nerfstudio/data/pixel_samplers.py b/nerfstudio/data/pixel_samplers.py index 27480dcc6..7bd526510 100644 --- a/nerfstudio/data/pixel_samplers.py +++ b/nerfstudio/data/pixel_samplers.py @@ -59,8 +59,12 @@ class PixelSampler: """ config: PixelSamplerConfig - states_of_mask: int=0 - masks_indices: torch.Tensor + is_well_exposed_computed: bool = False + is_fast_exposed_computed: bool = False + well_exposed_indices: torch.Tensor + fast_exposed_indices: torch.Tensor + fast_image_batch = {} + well_image_batch = {} def __init__(self, config: PixelSamplerConfig, **kwargs) -> None: self.kwargs = kwargs self.config = config @@ -77,6 +81,39 @@ class PixelSampler: num_rays_per_batch: number of rays to sample per batch """ self.num_rays_per_batch = num_rays_per_batch + + + def sample_considering_mask(self, mask, device, batch_size): + num_masks = mask.shape[0] + size_of_disk = 50 + num_disks = ceil(num_masks / size_of_disk) + # slice mask to 100 disk + random_idx_disk = int(torch.randint(0, num_disks, (1,))) + indices = torch.tensor([]).cuda().to(device) + nonzero_indices_whole = torch.tensor([]).to(device) + + for current_disk, start in enumerate(range(0, num_masks, size_of_disk)): + is_last_disk = ((start//size_of_disk) == num_disks-1) + end = start + size_of_disk if not is_last_disk else num_masks + current_masks = mask[start:end,...].to(device) + nonzero_indices = torch.nonzero(current_masks, as_tuple=False) + # Add offset to indices:local indices --> global + nonzero_indices[:,0] += start + + num_samples = batch_size // (num_disks-1) if current_disk != random_idx_disk \ + else batch_size % (num_disks-1) + chosen_indices = torch.randint(0, nonzero_indices.shape[0], (num_samples,), device=device) + + indice_this_disk = nonzero_indices[chosen_indices] + indices = torch.cat((indices, indice_this_disk), dim=0).long() + nonzero_indices_whole = torch.cat((nonzero_indices_whole, nonzero_indices.cpu()), dim=0) + + del current_masks + del nonzero_indices + del indice_this_disk + + return indices, nonzero_indices_whole + @profiler.time_function def sample_method( @@ -87,6 +124,8 @@ class PixelSampler: image_width: int, mask: Optional[Tensor] = None, device: Union[torch.device, str] = "cpu", + is_fast_expo: bool = False, + only_light_sources: bool = False, ) -> Int[Tensor, "batch_size 3"]: """ Naive pixel sampler, uniformly samples across all possible pixels of all possible images. @@ -100,46 +139,29 @@ class PixelSampler: if isinstance(mask, torch.Tensor): # mask size: batch * h * w * 1 # Init state, cache masks indices. - if self.states_of_mask == 0: - with profiler.time_function("mask squeeze: whole"): - mask = mask.squeeze(-1) - num_masks = mask.shape[0] - size_of_disk = 100 - num_disks = ceil(num_masks / size_of_disk) - # slice mask to 100 disk - random_idx_disk = int(torch.randint(0, num_disks, (1,))) - indices = torch.tensor([]).to(device) - nonzero_indices_whole = torch.tensor([]) - - for current_disk, start in enumerate(range(0, num_masks, size_of_disk)): - is_last_disk = ((start//size_of_disk) == num_disks-1) - end = start + size_of_disk if not is_last_disk else num_masks - current_masks = mask[start:end,...].to(device) - nonzero_indices = torch.nonzero(current_masks, as_tuple=False) - # Add offset to indices:local indices --> global - nonzero_indices[:,0] += start - - num_samples = batch_size // (num_disks-1) if current_disk != random_idx_disk \ - else batch_size % (num_disks-1) - chosen_indices = torch.randint(0, nonzero_indices.shape[0], (num_samples,), device=device) - - indice_this_disk = nonzero_indices[chosen_indices] - indices = torch.cat((indices, indice_this_disk), dim=0).long() - nonzero_indices_whole = torch.cat((nonzero_indices_whole, nonzero_indices.cpu()), dim=0).long() - del current_masks - del nonzero_indices - del indice_this_disk - - self.masks_indices = nonzero_indices_whole.cpu() - self.states_of_mask = 1 - return indices - - elif self.states_of_mask == 1: - chosen_indices = torch.randint(0, self.masks_indices.shape[0], (batch_size,)) - return self.masks_indices[chosen_indices].to(device) - - + # if self.states_of_mask != 2: + with profiler.time_function("mask squeeze: whole"): + mask = mask.squeeze(-1) + + if is_fast_expo: + if self.is_fast_exposed_computed: + chosen_indices = torch.randint(0, self.fast_exposed_indices.shape[0], (batch_size,)) + return self.fast_exposed_indices[chosen_indices].to(device) + else: + indices, nonzero_indices_whole = self.sample_considering_mask(mask, device, batch_size) + self.fast_exposed_indices = nonzero_indices_whole.long().cpu() + self.is_fast_exposed_computed = True + return indices + else: + if self.is_well_exposed_computed: + chosen_indices = torch.randint(0, self.well_exposed_indices.shape[0], (batch_size,)) + return self.well_exposed_indices[chosen_indices].to(device) + else: + indices, nonzero_indices_whole = self.sample_considering_mask(mask, device, batch_size) + self.well_exposed_indices = nonzero_indices_whole.long().cpu() + self.is_well_exposed_computed = True + return indices else: indices = torch.floor( torch.rand((batch_size, 3), device=device) @@ -178,7 +200,7 @@ class PixelSampler: return indices - def collate_image_dataset_batch(self, batch: Dict, num_rays_per_batch: int, keep_full_image: bool = False): + def collate_image_dataset_batch(self, batch: Dict, num_rays_per_batch: int, keep_full_image: bool = False, is_fast_expo: bool = False): """ Operates on a batch of images and samples pixels to use for generating rays. Returns a collated batch which is input to the Graph. @@ -200,7 +222,7 @@ class PixelSampler: ) else: indices = self.sample_method( - num_rays_per_batch, num_images, image_height, image_width, mask=batch["mask"], device=device + num_rays_per_batch, num_images, image_height, image_width, mask=batch["mask"], device=device, is_fast_expo=is_fast_expo ) else: if self.config.is_equirectangular: @@ -210,23 +232,21 @@ class PixelSampler: else: indices = self.sample_method(num_rays_per_batch, num_images, image_height, image_width, device=device) - c, y, x = (i.flatten() for i in torch.split(indices, 1, dim=-1)) - c, y, x = c.cpu(), y.cpu(), x.cpu() + chan, y, x = (i.flatten() for i in torch.split(indices, 1, dim=-1)) + chan, y, x = chan.cpu(), y.cpu(), x.cpu() collated_batch = { - key: value[c, y, x] for key, value in batch.items() if key != "image_idx" and key != "exposure" and value is not None + key: value[chan, y, x] for key, value in batch.items() if key != "image_idx" and key != "exposure" and value is not None } - for key, value in batch.items(): - if key == "exposure": - collated_batch["exposure"] = value[c] - - assert collated_batch["image"].shape[0] == num_rays_per_batch # Needed to correct the random indices to their actual camera idx locations. - indices[:, 0] = batch["image_idx"][c] - collated_batch["indices"] = indices # with the abs camera indices + collated_batch["indices"] = indices.clone() # with the abs camera indices + collated_batch["indices"][:, 0] = batch["image_idx"][chan].clone() + if "exposure" in batch: + collated_batch["exposure"] = batch["exposure"][chan] + if keep_full_image: collated_batch["full_image"] = batch["image"] @@ -319,9 +339,26 @@ class PixelSampler: image_batch, self.num_rays_per_batch, keep_full_image=self.config.keep_full_image ) elif isinstance(image_batch["image"], torch.Tensor): - pixel_batch = self.collate_image_dataset_batch( - image_batch, self.num_rays_per_batch, keep_full_image=self.config.keep_full_image - ) + if "exposure" in image_batch: + if not(self.well_image_batch and self.fast_image_batch): + well_ones = (image_batch["exposure"] == 1.0).cpu() + fast_ones = ~well_ones + for key in image_batch.keys(): + self.well_image_batch[key] = image_batch[key][well_ones] + self.fast_image_batch[key] = image_batch[key][fast_ones] + well_pixel_batch = self.collate_image_dataset_batch( + self.well_image_batch, int(1.0 * self.num_rays_per_batch), keep_full_image=self.config.keep_full_image + ) + pixel_batch = well_pixel_batch #.copy() + fast_pixel_batch = self.collate_image_dataset_batch( + self.fast_image_batch, int(0.0 * self.num_rays_per_batch), keep_full_image=self.config.keep_full_image, is_fast_expo=True + ) + for key, value in fast_pixel_batch.items(): + pixel_batch[key] = torch.cat((pixel_batch[key], value), 0) + else: + pixel_batch = self.collate_image_dataset_batch( + image_batch, self.num_rays_per_batch, keep_full_image=self.config.keep_full_image + ) else: raise ValueError("image_batch['image'] must be a list or torch.Tensor") return pixel_batch @@ -369,7 +406,8 @@ class PatchPixelSampler(PixelSampler): if isinstance(mask, Tensor): 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) + # m = erode_mask(mask.permute(0, 3, 1, 2).float(), pixel_radius=half_patch_size) + m = mask.permute(0, 3, 1, 2).float() nonzero_indices = torch.nonzero(m[:, 0], as_tuple=False).to(device) chosen_indices = random.sample(range(len(nonzero_indices)), k=sub_bs) indices = nonzero_indices[chosen_indices] @@ -448,7 +486,8 @@ class PairPixelSampler(PixelSampler): # pylint: disable=too-few-public-methods device: Union[torch.device, str] = "cpu", ) -> Int[Tensor, "batch_size 3"]: if isinstance(mask, Tensor): - 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) + m = mask.permute(0, 3, 1, 2).float() nonzero_indices = torch.nonzero(m[:, 0], as_tuple=False).to(device) chosen_indices = random.sample(range(len(nonzero_indices)), k=self.rays_to_sample) indices = nonzero_indices[chosen_indices] diff --git a/nerfstudio/field_components/field_heads.py b/nerfstudio/field_components/field_heads.py index 44df9f602..e67ebd557 100644 --- a/nerfstudio/field_components/field_heads.py +++ b/nerfstudio/field_components/field_heads.py @@ -41,7 +41,8 @@ class FieldHeadNames(Enum): SDF = "sdf" ALPHA = "alpha" GRADIENT = "gradient" - + VALIDITY = 'validity' + RGB_FAST = 'rgb_fast' class FieldHead(FieldComponent): """Base field output diff --git a/nerfstudio/fields/nerfacto_field.py b/nerfstudio/fields/nerfacto_field.py index 34c6346fc..25ad3a965 100644 --- a/nerfstudio/fields/nerfacto_field.py +++ b/nerfstudio/fields/nerfacto_field.py @@ -27,6 +27,7 @@ from nerfstudio.data.scene_box import SceneBox from nerfstudio.field_components.activations import trunc_exp from nerfstudio.field_components.embedding import Embedding from nerfstudio.field_components.encodings import HashEncoding, NeRFEncoding, SHEncoding +from nerfstudio.field_components.encodings import Encoding, Identity from nerfstudio.field_components.field_heads import ( FieldHeadNames, PredNormalsFieldHead, @@ -96,6 +97,8 @@ class NerfactoField(Field): use_average_appearance_embedding: bool = False, spatial_distortion: Optional[SpatialDistortion] = None, implementation: Literal["tcnn", "torch"] = "tcnn", + use_appearance_embedding: bool = True, + predicts_validity: bool = True, ) -> None: super().__init__() @@ -116,16 +119,18 @@ class NerfactoField(Field): self.use_pred_normals = use_pred_normals self.pass_semantic_gradients = pass_semantic_gradients self.base_res = base_res + self.use_appearance_embedding = use_appearance_embedding + self.predicts_validity = predicts_validity self.direction_encoding = SHEncoding( levels=4, implementation=implementation, ) + # HASH ENCODING self.position_encoding = NeRFEncoding( in_dim=3, num_frequencies=2, min_freq_exp=0, max_freq_exp=2 - 1, implementation=implementation ) - self.mlp_base_grid = HashEncoding( num_levels=num_levels, min_res=base_res, @@ -134,6 +139,7 @@ class NerfactoField(Field): features_per_level=features_per_level, implementation=implementation, ) + self.mlp_base_mlp = MLP( in_dim=self.mlp_base_grid.get_out_dim(), num_layers=num_layers, @@ -144,7 +150,7 @@ class NerfactoField(Field): implementation=implementation, ) self.mlp_base = torch.nn.Sequential(self.mlp_base_grid, self.mlp_base_mlp) - + # transients if self.use_transient_embedding: self.transient_embedding_dim = transient_embedding_dim @@ -190,18 +196,52 @@ class NerfactoField(Field): ) self.field_head_pred_normals = PredNormalsFieldHead(in_dim=self.mlp_pred_normals.get_out_dim()) - self.mlp_head = MLP( - in_dim=self.direction_encoding.get_out_dim() + self.geo_feat_dim + self.appearance_embedding_dim, - num_layers=num_layers_color, - layer_width=hidden_dim_color, - out_dim=3, - activation=nn.ReLU(), - out_activation=nn.Sigmoid(), - implementation=implementation, - ) + if self.predicts_validity: + if self.use_appearance_embedding: + self.mlp_validity = MLP( + in_dim=self.geo_feat_dim +self.direction_encoding.get_out_dim()+ self.appearance_embedding_dim, + num_layers=3, + layer_width=64, + out_dim=2, + activation=nn.ReLU(), + out_activation=None, + implementation=implementation, + ) + else: + self.mlp_validity = MLP( + in_dim=self.geo_feat_dim +self.direction_encoding.get_out_dim(), + num_layers=3, + layer_width=64, + out_dim=2, + activation=nn.ReLU(), + out_activation=nn.Sigmoid(), + implementation=implementation, + ) + + if self.use_appearance_embedding: + self.mlp_head = MLP( + in_dim=self.direction_encoding.get_out_dim() + self.geo_feat_dim + self.appearance_embedding_dim, + num_layers=num_layers_color, + layer_width=hidden_dim_color, + out_dim=3, + activation=nn.ReLU(), + out_activation=nn.Sigmoid(), + implementation=implementation, + ) + else: + self.mlp_head = MLP( + in_dim=self.direction_encoding.get_out_dim() + self.geo_feat_dim, + num_layers=num_layers_color, + layer_width=hidden_dim_color, + out_dim=3, + activation=nn.ReLU(), + out_activation=nn.Sigmoid(), + implementation=implementation, + ) def get_density(self, ray_samples: RaySamples) -> Tuple[Tensor, Tensor]: """Computes and returns the densities.""" + # with torch.no_grad(): if self.spatial_distortion is not None: positions = ray_samples.frustums.get_positions() positions = self.spatial_distortion(positions) @@ -230,6 +270,7 @@ class NerfactoField(Field): self, ray_samples: RaySamples, density_embedding: Optional[Tensor] = None ) -> Dict[FieldHeadNames, Tensor]: assert density_embedding is not None + # with torch.no_grad(): outputs = {} if ray_samples.camera_indices is None: raise AttributeError("Camera indices are not provided.") @@ -241,17 +282,18 @@ class NerfactoField(Field): outputs_shape = ray_samples.frustums.directions.shape[:-1] # appearance - if self.training: - embedded_appearance = self.embedding_appearance(camera_indices) - else: - if self.use_average_appearance_embedding: - embedded_appearance = torch.ones( - (*directions.shape[:-1], self.appearance_embedding_dim), device=directions.device - ) * self.embedding_appearance.mean(dim=0) + if self.use_appearance_embedding: + if self.training: + embedded_appearance = self.embedding_appearance(camera_indices) else: - embedded_appearance = torch.zeros( - (*directions.shape[:-1], self.appearance_embedding_dim), device=directions.device - ) + if self.use_average_appearance_embedding: + embedded_appearance = torch.ones( + (*directions.shape[:-1], self.appearance_embedding_dim), device=directions.device + ) * self.embedding_appearance.mean(dim=0) + else: + embedded_appearance = torch.zeros( + (*directions.shape[:-1], self.appearance_embedding_dim), device=directions.device + ) # transients if self.use_transient_embedding and self.training: @@ -287,15 +329,32 @@ class NerfactoField(Field): x = self.mlp_pred_normals(pred_normals_inp).view(*outputs_shape, -1).to(directions) outputs[FieldHeadNames.PRED_NORMALS] = self.field_head_pred_normals(x) - h = torch.cat( - [ - d, - density_embedding.view(-1, self.geo_feat_dim), - embedded_appearance.view(-1, self.appearance_embedding_dim), - ], - dim=-1, - ) + if self.use_appearance_embedding: + h = torch.cat( + [ + d, + density_embedding.view(-1, self.geo_feat_dim), + embedded_appearance.view(-1, self.appearance_embedding_dim), + ], + dim=-1, + ) + else: + h = torch.cat( + [ + d, + density_embedding.view(-1, self.geo_feat_dim), + ], + dim=-1, + ) rgb = self.mlp_head(h).view(*outputs_shape, -1).to(directions) outputs.update({FieldHeadNames.RGB: rgb}) + rgb_fast = self.mlp_head_fast(h).view(*outputs_shape, -1).to(directions) + outputs.update({FieldHeadNames.RGB_FAST: rgb_fast}) + + if self.predicts_validity: + h_no_grad = h.clone() + validity = self.mlp_validity(h_no_grad).view(*outputs_shape, -1).to(directions) + outputs.update({FieldHeadNames.VALIDITY: validity}) + return outputs diff --git a/nerfstudio/lantern/dataset.py b/nerfstudio/lantern/dataset.py index 07a46063d..bbfa71f1f 100644 --- a/nerfstudio/lantern/dataset.py +++ b/nerfstudio/lantern/dataset.py @@ -71,7 +71,10 @@ class HDRInputDataset(InputDataset): hdr_image = cv2.resize(hdr_image, newsize, interpolation = cv2.INTER_LINEAR) hdr_image = cv2.cvtColor(hdr_image, cv2.COLOR_BGR2RGB) hdr_image = hdr_image.astype("float32") # shape is (h, w) or (h, w, 3 or 4) + if str(image_filename).endswith('.png'): + hdr_image = hdr_image / 255.0 if len(hdr_image.shape) == 2: + raise "SHAPE ISSUE" hdr_image = hdr_image[:, :, None].repeat(3, axis=2) assert len(hdr_image.shape) == 3 assert hdr_image.dtype == np.float32 @@ -86,11 +89,12 @@ class HDRInputDataset(InputDataset): """ # Compress HDR using: pixel = log(pixel + 1.) - image = torch.from_numpy(self.get_numpy_image(image_idx).astype("float32")) + image = torch.from_numpy(self.get_numpy_image(image_idx)) # Compress HDR using u-law: pixel = log(u * pixel + 1.) / log(u + 1.) - u = 5000. - image = torch.log(1. + u * image) / torch.log(torch.tensor(1.+u)) + # u = 10. + # image = torch.log(1. + u * image) / torch.log(torch.tensor(1.+u)) + # image = torch.pow(image, 1/ 2.2) if self._dataparser_outputs.alpha_color is not None and image.shape[-1] == 4: image = image[:, :, :3] * image[:, :, -1:] + self._dataparser_outputs.alpha_color * (1.0 - image[:, :, -1:]) @@ -118,11 +122,15 @@ class HDRInputDataset(InputDataset): data["saturation_mask"].shape[:2] == data["image"].shape[:2] ), f"Saturation mask and image have different shapes. Got {data['saturation_mask'].shape[:2]} and {data['image'].shape[:2]}" + # Let's and the masks + # data["mask"] = torch.logical_and(data["mask"], data["saturation_mask"]) + if self._dataparser_outputs.exposures is not None: exposure_value = self._dataparser_outputs.exposures[image_idx] data["exposure"] = exposure_value metadata = self.get_metadata(data) data.update(metadata) + return data def get_metadata(self, data: Dict) -> Dict: diff --git a/nerfstudio/lantern/field.py b/nerfstudio/lantern/field.py index c8e8ca5d6..20f26bb2f 100644 --- a/nerfstudio/lantern/field.py +++ b/nerfstudio/lantern/field.py @@ -42,7 +42,7 @@ class LanternNerfactoField(NerfactoField): hidden_dim_transient: int = 64, appearance_embedding_dim: int = 32, transient_embedding_dim: int = 16, - use_transient_embedding: bool = False, + use_transient_embedding: bool = True, use_semantics: bool = False, num_semantic_classes: int = 100, pass_semantic_gradients: bool = False, @@ -50,6 +50,8 @@ class LanternNerfactoField(NerfactoField): use_average_appearance_embedding: bool = False, spatial_distortion: Optional[SpatialDistortion] = None, implementation: Literal["tcnn", "torch"] = "tcnn", + use_appearance_embedding: bool = True, + predicts_validity: bool = True, ) -> None: super().__init__(aabb, num_images, num_layers, hidden_dim, geo_feat_dim, num_levels, base_res, @@ -58,14 +60,51 @@ class LanternNerfactoField(NerfactoField): hidden_dim_transient, appearance_embedding_dim, transient_embedding_dim, use_transient_embedding, use_semantics, num_semantic_classes, pass_semantic_gradients, use_pred_normals, use_average_appearance_embedding, - spatial_distortion, implementation) + spatial_distortion, implementation, use_appearance_embedding, predicts_validity) + + if self.use_appearance_embedding: + self.mlp_head = MLP( + in_dim=self.direction_encoding.get_out_dim() + self.geo_feat_dim + self.appearance_embedding_dim, + num_layers=num_layers_color, + layer_width=hidden_dim_color, + out_dim= 3, + activation=nn.ReLU(), + # out_activation=nn.ReLU(), + out_activation=nn.Sigmoid(), + implementation=implementation, + ) + + self.mlp_head_fast = MLP( + in_dim=self.direction_encoding.get_out_dim() + self.geo_feat_dim + self.appearance_embedding_dim, + num_layers=num_layers_color, + layer_width=hidden_dim_color, + out_dim= 3, + activation=nn.ReLU(), + # out_activation=nn.ReLU(), + out_activation=nn.Sigmoid(), + implementation=implementation, + ) + # Define the last part MLP for RGB outputs and Masks - self.mlp_head = MLP( - in_dim=self.direction_encoding.get_out_dim() + self.geo_feat_dim + self.appearance_embedding_dim, - num_layers=num_layers_color, - layer_width=hidden_dim_color, - out_dim= 3 + 2, - activation=nn.ReLU(), - out_activation=nn.ReLU(), - implementation=implementation, - ) \ No newline at end of file + else: + self.mlp_head = MLP( + in_dim=self.direction_encoding.get_out_dim() + self.geo_feat_dim, + num_layers=num_layers_color, + layer_width=hidden_dim_color, + out_dim= 6, + activation=nn.ReLU(), + # out_activation=nn.ReLU(), + out_activation=nn.Sigmoid(), + implementation=implementation, + ) + + self.mlp_head_fast = MLP( + in_dim=self.direction_encoding.get_out_dim() + self.geo_feat_dim, + num_layers=num_layers_color, + layer_width=hidden_dim_color, + out_dim= 3, + activation=nn.ReLU(), + # out_activation=nn.ReLU(), + out_activation=nn.Sigmoid(), + implementation=implementation, + ) \ No newline at end of file diff --git a/nerfstudio/lantern/model.py b/nerfstudio/lantern/model.py index e48eb5958..72486b217 100644 --- a/nerfstudio/lantern/model.py +++ b/nerfstudio/lantern/model.py @@ -33,6 +33,7 @@ from nerfstudio.model_components.renderers import ( AccumulationRenderer, DepthRenderer, NormalsRenderer, + SemanticRenderer, ) from nerfstudio.model_components.scene_colliders import NearFarCollider from nerfstudio.model_components.shaders import NormalsShader @@ -42,8 +43,11 @@ from nerfstudio.models.nerfacto import ( # for subclassing Nerfacto model ) from nerfstudio.utils import colormaps -FAST_EXPOSURE_CUTOFF = 0.26 # good for real data (0.1 for synthetic) -WELL_EXPOSURE_CUTOFF = 0.9 # good for real data (0.9 for synthetic) +FAST_EXPOSURE_CUTOFF = 0.27 # good for real data (0.1 for synthetic) +WELL_EXPOSURE_CUTOFF = 0.95 # good for real data (0.9 for synthetic) + +WELL_EXPOSURE = 1.0 +FAST_EXPOSURE = 0.004 @dataclass class LanternModelConfig(NerfactoModelConfig): @@ -54,6 +58,8 @@ class LanternModelConfig(NerfactoModelConfig): _target: Type = field(default_factory=lambda: LanternModel) + appearance_embed_dim: int = 32 + class LanternModel(NerfactoModel): """Template Model.""" @@ -144,6 +150,7 @@ class LanternModel(NerfactoModel): self.renderer_accumulation = AccumulationRenderer() self.renderer_depth = DepthRenderer() self.renderer_normals = NormalsRenderer() + self.renderer_validity = SemanticRenderer() # shaders self.normals_shader = NormalsShader() @@ -160,6 +167,7 @@ class LanternModel(NerfactoModel): def get_outputs(self, ray_bundle: RayBundle): ray_samples: RaySamples ray_samples, weights_list, ray_samples_list = self.proposal_sampler(ray_bundle, density_fns=self.density_fns) + field_outputs = self.field.forward(ray_samples, compute_normals=self.config.predict_normals) if self.config.use_gradient_scaling: field_outputs = scale_gradients_by_distance_squared(field_outputs, ray_samples) @@ -171,15 +179,18 @@ class LanternModel(NerfactoModel): rgb = self.renderer_rgb(rgb=field_outputs[FieldHeadNames.RGB], weights=weights) depth = self.renderer_depth(weights=weights, ray_samples=ray_samples) accumulation = self.renderer_accumulation(weights=weights) + validity = self.renderer_rgb(rgb=field_outputs[FieldHeadNames.VALIDITY], weights=weights) + rgb_fast = self.renderer_rgb(rgb=field_outputs[FieldHeadNames.RGB_FAST], weights=weights) outputs = { - "rgb": rgb[:, 0:3], + "rgb": rgb, + "rgb_fast": rgb_fast, "accumulation": accumulation, "depth": depth, - "validity_w": rgb[:, 4], - "validity_f": rgb[:, 3], + "validity_w": validity[:, 1], + "validity_f": validity[:, 0], } - + if self.config.predict_normals: normals = self.renderer_normals(normals=field_outputs[FieldHeadNames.NORMALS], weights=weights) pred_normals = self.renderer_normals(field_outputs[FieldHeadNames.PRED_NORMALS], weights=weights) @@ -271,36 +282,28 @@ class LanternModel(NerfactoModel): def cut_weighting_function(self, pixels, exposures): - # TODO make sure the values for cuts are not fixed + weights = torch.zeros(pixels.shape, dtype = pixels.dtype).to(self.device) - well_exposure = torch.max(exposures) - fast_exposure = torch.min(exposures) - - weights = torch.ones(pixels.shape, dtype = pixels.dtype).to(self.device) - - fast_expo_valids = (exposures == fast_exposure).repeat(1,pixels.shape[-1]) - weights[fast_expo_valids] = torch.clip(10.0 * (pixels[fast_expo_valids] - FAST_EXPOSURE_CUTOFF), 0.0, 1.0) - - well_expo_valids = ~fast_expo_valids + well_expo_valids = (exposures == 1.0).repeat(1,pixels.shape[-1]) weights[well_expo_valids] = torch.clip(-20.0 * (pixels[well_expo_valids] - WELL_EXPOSURE_CUTOFF) + 1, 0.0, 1.0) + fast_expo_valids = ~well_expo_valids + weights[fast_expo_valids] = torch.clip(10.0 * (pixels[fast_expo_valids] - FAST_EXPOSURE_CUTOFF), 0.0, 1.0) + return weights - def cut_weighting_for_mask_function(self, pixels, exposures): - well_exposure = torch.max(exposures) - fast_exposure = torch.min(exposures) - - weights1 = torch.zeros(exposures.shape, dtype = exposures.dtype).to(self.device) - weights2 = torch.zeros(exposures.shape, dtype = exposures.dtype).to(self.device) + def cut_weighting_for_mask_function(self, exposures): + weights_f = torch.zeros(exposures.shape, dtype = exposures.dtype).to(self.device) + weights_w = torch.zeros(exposures.shape, dtype = exposures.dtype).to(self.device) - fast_expo_valids = (exposures == fast_exposure).repeat(1, 1) - weights1[fast_expo_valids] = 1.0 + well_expo_valids = (exposures == 1.0).repeat(1, 1) + weights_w[well_expo_valids] = 1.0 + + fast_expo_valids = ~well_expo_valids + weights_f[fast_expo_valids] = 1.0 - well_expo_valids = ~fast_expo_valids - weights2[well_expo_valids] = 1.0 - - return weights1, weights2 + return weights_f, weights_w def get_loss_dict(self, outputs, batch, metrics_dict=None): @@ -310,44 +313,71 @@ class LanternModel(NerfactoModel): image = batch["image"].to(self.device) if "exposure" in batch: - u = 5000. - img_uncompress = torch.exp(image * torch.log(torch.tensor(u+1.))) - 1. - img_uncompress /= u + # u = 10. + # img_uncompress = torch.exp(image * torch.log(torch.tensor(u+1.))) - 1. + # img_uncompress /= u + # img_uncompress = torch.pow(image, 2.2) exposures_resized = batch["exposure"].view(batch["exposure"].shape[0], 1) - img_uncompress_re_exposed = exposures_resized * img_uncompress + # img_uncompress_re_exposed = exposures_resized * img_uncompress - # Debevec Hat weights for Loss - # weights_for_loss = self.hat_weighting_function(torch.clip(img_uncompress_re_exposed, 0, 1), 0.0, 1.0) + # # # Debevec Hat weights for Loss + # # # weights_for_loss = self.hat_weighting_function(torch.clip(img_uncompress_re_exposed, 0, 1), 0.0, 1.0) - # Clear cut weights for Loss - weights_for_RGB_loss = self.cut_weighting_function(torch.clip(img_uncompress_re_exposed, 0, 1), exposures_resized) - mask1_w, mask2_w = self.cut_weighting_for_mask_function(img_uncompress_re_exposed, exposures_resized) - + # # # Clear cut weights for Loss + # # weights_for_RGB_loss = self.cut_weighting_function(torch.clip(img_uncompress_re_exposed, 0, 1), exposures_resized) + mask_f_w, mask_w_w = self.cut_weighting_for_mask_function(exposures_resized) + pred_rgb, gt_rgb = self.renderer_rgb.blend_background_for_loss_computation( pred_image=outputs["rgb"], pred_accumulation=outputs["accumulation"], gt_image=image, ) + pred_rgb_f, gt_rgb_f = self.renderer_rgb.blend_background_for_loss_computation( + pred_image=outputs["rgb_fast"], + pred_accumulation=outputs["accumulation"], + gt_image=image, + ) + + # import pdb; pdb.set_trace() + # MSE loss for mask with weights - mask_in_float = batch['saturation_mask'].type(torch.float).to(self.device) - negative_mask_in_float = torch.ones(mask_in_float.shape).to(self.device) - mask_in_float - loss_mask_fast_expo = (mask1_w * (( negative_mask_in_float - torch.unsqueeze(outputs["validity_f"], 1)) ** 2)).mean() - loss_mask_well_expo = (mask2_w * (( mask_in_float - torch.unsqueeze(outputs["validity_w"], 1)) ** 2)).mean() - loss_dict["validity_loss_well_exposed"] = loss_mask_well_expo - loss_dict["validity_loss_fast_exposure"] = loss_mask_fast_expo + # if "saturation_mask" in batch: + # mask_in_float = batch['saturation_mask'].type(torch.float).to(self.device) + # negative_mask_in_float = torch.ones(mask_in_float.shape).to(self.device) - mask_in_float + # loss_mask_fast_expo = (mask_f_w * (( 10.0 * mask_in_float - torch.unsqueeze(outputs["validity_f"], 1)) ** 2)).mean() + # # loss_mask_fast_expo = (mask_f_w * (( mask_in_float - torch.unsqueeze(outputs["validity_f"], 1)) ** 2)).mean() + # loss_mask_well_expo = (mask_w_w * (( mask_in_float - torch.unsqueeze(outputs["validity_w"], 1)) ** 2)).mean() + # loss_dict["validity_loss_well_exposed"] = loss_mask_well_expo # 0.01 + # loss_dict["validity_loss_fast_exposure"] = loss_mask_fast_expo - if weights_for_RGB_loss is not None: - loss_dict["rgb_loss"] = (weights_for_RGB_loss * ((gt_rgb - pred_rgb) ** 2)).mean() - else: - loss_dict["rgb_loss"] = self.rgb_loss(gt_rgb, pred_rgb) + gt_rgb_w = gt_rgb.clone() + # gt_rgb_w[(exposures_resized != 1.0).repeat(1, 3)] = 1.0# torch.clamp(gt_rgb_w[(exposures_resized != 1.0).repeat(1, 3)] / 0.004, 0, 1) + # import pdb; pdb.set_trace() + gt_rgb_f = gt_rgb.clone() + # gt_rgb_f[(exposures_resized == 1.0).repeat(1, 3)] = gt_rgb_f[(exposures_resized == 1.0).repeat(1, 3)] * 0.004 + # loss_dict["rgb_loss"] = self.rgb_loss(gt_rgb_w, pred_rgb) + # loss_dict["rgb_loss_fast"] = self.rgb_loss(gt_rgb_f, pred_rgb_f) + # loss_dict["rgb_loss"] = self.rgb_loss(gt_rgb_f, pred_rgb_f) + + # loss_dict["rgb_loss"] = (mask_w_w * ((gt_rgb_w - pred_rgb) ** 2)).mean() + # loss_dict["rgb_loss_fast"] = (mask_f_w * ((10.0 * gt_rgb_f - pred_rgb_f) ** 2)).mean() + + # loss_dict["rgb_loss_fast"] = 300.0 * (mask_f_w * ((gt_rgb_f - pred_rgb_f) ** 2)).mean() + # import pdb; pdb.set_trace() + + # if weights_for_RGB_loss is not None: + # loss_dict["rgb_loss"] = (weights_for_RGB_loss * ((gt_rgb - pred_rgb) ** 2)).mean() + # else: + loss_dict["rgb_loss"] = self.rgb_loss(gt_rgb, pred_rgb) + # print("rgb_loss: ", loss_dict["rgb_loss"], ", rgb_fast_expo_loss: ", loss_dict["rgb_fast_expo_loss"]) if self.training: loss_dict["interlevel_loss"] = self.config.interlevel_loss_mult * interlevel_loss( outputs["weights_list"], outputs["ray_samples_list"] ) assert metrics_dict is not None and "distortion" in metrics_dict - # loss_dict["distortion_loss"] = self.config.distortion_loss_mult * metrics_dict["distortion"] + loss_dict["distortion_loss"] = self.config.distortion_loss_mult * metrics_dict["distortion"] if self.config.predict_normals: # orientation loss for computed normals loss_dict["orientation_loss"] = self.config.orientation_loss_mult * torch.mean( diff --git a/nerfstudio/process_data/equirect_utils.py b/nerfstudio/process_data/equirect_utils.py index eb9985711..db9e78406 100644 --- a/nerfstudio/process_data/equirect_utils.py +++ b/nerfstudio/process_data/equirect_utils.py @@ -485,7 +485,7 @@ def generate_planar_projections_from_equirectangular_GT( crop_factor: Tuple[float, float, float, float] = (0.0, 0.0, 0.0, 0.0), clip_output: bool = False, use_mask = False, - use_exposure = False, + prefix = None, ) -> Path: """Given camera pose, generate planar projections from an equirectangular image. And output corresponding camera pose. @@ -592,16 +592,18 @@ def generate_planar_projections_from_equirectangular_GT( im = torch.tensor(im, dtype=torch.float32, device=device) im = torch.permute(im, (2, 0, 1)) / 255.0 count = 0 - current_pano_camera_pose = camera_to_worlds_panos[f"{i[:-4]}"] + current_pano_camera_pose = camera_to_worlds_panos[prefix + f"_{i[:-4]}"] current_pano_camera_rotation = current_pano_camera_pose[:3, :3] for u_deg, v_deg in yaw_pitch_pairs: v_rad = torch.pi * v_deg / 180.0 u_rad = torch.pi * u_deg / 180.0 - pers_image = equi2pers(im, rots={"roll": 0, "pitch": v_rad, "yaw": u_rad}, clip_output=clip_output) + # pers_image = equi2pers(im, rots={"roll": 0, "pitch": v_rad, "yaw": u_rad}, clip_output=clip_output) + pers_image = equi2pers(im, rots={"roll": 0, "pitch": v_rad, "yaw": u_rad}) if mask_dir is not None: pers_mask = equi2pers(mask, rots={"roll": 0, "pitch": v_rad, "yaw": u_rad}) * 255.0 # transform matrix for blender: object.matrix_world perspective_camera_rotation = inv(Rotation.from_euler('XYZ', [v_rad, -u_rad, 0], degrees=False).as_matrix()) + # perspective_camera_rotation = inv(Rotation.from_euler('XYZ', [v_rad, u_rad, 0], degrees=False).as_matrix()) perspective_camera_rotation = current_pano_camera_rotation @ perspective_camera_rotation perspective_camera_pose = current_pano_camera_pose.copy() perspective_camera_pose[:3, :3] = perspective_camera_rotation @@ -611,22 +613,17 @@ def generate_planar_projections_from_equirectangular_GT( if i.lower().endswith((".exr")): # normalize alpha channel pers_image = (pers_image.permute(1, 2, 0)).type(torch.float32).to("cpu").numpy() - cv2.imwrite(f"{output_dir}/{i[:-4]}_{count}.exr", pers_image) + cv2.imwrite(f"{output_dir}/{prefix}_{i[:-4]}_{count}.exr", pers_image) frame = { - "file_path": f"{output_dir}/{i[:-4]}_{count}.exr", + "file_path": f"{output_dir}/{prefix}_{i[:-4]}_{count}.exr", "transform_matrix": perspective_camera_pose.tolist(), } - if use_exposure: - exposure = 1.0 - if i[0:3] == "rhs": - exposure = 0.009 - frame["exposure"] = exposure else: pers_image *= 255.0 pers_image = (pers_image.permute(1, 2, 0)).type(torch.uint8).to("cpu").numpy() - cv2.imwrite(f"{output_dir}/{i[:-4]}_{count}.png", pers_image) + cv2.imwrite(f"{output_dir}/{prefix}_{i[:-4]}_{count}.png", pers_image) frame = { - "file_path": f"{output_dir}/{i[:-4]}_{count}.png", + "file_path": f"{output_dir}/{prefix}_{i[:-4]}_{count}.png", "transform_matrix": perspective_camera_pose.tolist(), } @@ -635,14 +632,16 @@ def generate_planar_projections_from_equirectangular_GT( mask = np.array(cv2.imread(os.path.join(frame_dir, "mask", mask_file_name))).astype("uint8") mask = ~((mask == 0).all(axis=-1)) mask = mask.astype("uint8") * 255 + mask[mask < 250] = 0 + mask[mask >= 250] = 255 # black corresponde to pixel to be ignored mask = torch.tensor(mask[:,:,None], dtype=torch.uint8, device=device) mask = torch.permute(mask, (2, 0, 1)) pers_mask = equi2pers(mask, rots={"roll": 0, "pitch": v_rad, "yaw": u_rad}) pers_mask = pers_mask.permute(1, 2, 0) pers_mask = pers_mask[:, :, 0].to("cpu").numpy() - cv2.imwrite(f"{output_mask_dir}/{i[:-4]}_{count}.png", pers_mask) - frame["mask_path"] = f"{output_mask_dir}/{i[:-4]}_{count}.png" + cv2.imwrite(f"{output_mask_dir}/{prefix}_{i[:-4]}_{count}.png", pers_mask) + frame["mask_path"] = f"{output_mask_dir}/{prefix}_{i[:-4]}_{count}.png" frames.append(frame) count += 1 diff --git a/nerfstudio/scripts/process_data.py b/nerfstudio/scripts/process_data.py index 1d2568703..3ee63f896 100644 --- a/nerfstudio/scripts/process_data.py +++ b/nerfstudio/scripts/process_data.py @@ -45,6 +45,9 @@ from nerfstudio.process_data.lantern_images_to_nerfstudio_dataset import ( from nerfstudio.process_data.aligned_pano2plane import ( ProcessAlignedPano ) +from nerfstudio.process_data.openSFM_to_nerfstudio import ( + OpenSFMToNeRFStudioDataset +) from nerfstudio.process_data.video_to_nerfstudio_dataset import VideoToNerfstudioDataset from nerfstudio.utils.rich_utils import CONSOLE @@ -406,6 +409,7 @@ Commands = Union[ Annotated[ProcessRecord3D, tyro.conf.subcommand(name="record3d")], Annotated[ProcessAlignedPano, tyro.conf.subcommand(name="aligned_pano2plane")], Annotated[LanternImagesToNerfstudioDataset, tyro.conf.subcommand(name="lantern")], + Annotated[OpenSFMToNeRFStudioDataset, tyro.conf.subcommand(name="lantern-openSFM")], ] diff --git a/nerfstudio/scripts/render.py b/nerfstudio/scripts/render.py index bd53890c8..678477444 100644 --- a/nerfstudio/scripts/render.py +++ b/nerfstudio/scripts/render.py @@ -98,7 +98,7 @@ def _render_trajectory_video( CONSOLE.print("[bold green]Creating trajectory " + output_format) cameras.rescale_output_resolution(rendered_resolution_scaling_factor) cameras = cameras.to(pipeline.device) - fps = len(cameras) / seconds + fps = len(cameras) / seconds if seconds != 0 else 1 print(len(cameras)) progress = Progress( TextColumn(":movie_camera: Rendering :movie_camera:"), @@ -171,11 +171,11 @@ def _render_trajectory_video( ) elif is_validity: mask_f = torch.clip(outputs["validity_f"], 0, 1) - mask_f = torch.ones(mask_f.shape).to(mask_f.get_device()) - mask_f + # mask_f = torch.ones(mask_f.shape).to(mask_f.get_device()) - mask_f - final_mask = torch.clip(outputs["validity_w"], 0, 1) + mask_f - final_mask[final_mask > 0.5] = 1 - final_mask[final_mask <= 0.5] = 0 + final_mask = torch.clip(outputs["validity_w"], 0, 1) # + mask_f + # final_mask[final_mask > 0.5] = 1 + # final_mask[final_mask <= 0.5] = 0 output_image = ( colormaps.apply_colormap( @@ -186,9 +186,10 @@ def _render_trajectory_video( .numpy() ) elif image_format == "exr": - u = 5000. - output_image = torch.exp(output_image * torch.log(torch.tensor(u+1.))) - 1. - output_image /= u + # u = 10. + # output_image = torch.exp(output_image * torch.log(torch.tensor(u+1.))) - 1. + # output_image /= u + # output_image = output_image output_image = ( output_image.cpu().numpy() ) diff --git a/nerfstudio/utils/colormaps.py b/nerfstudio/utils/colormaps.py index 89ddba073..c8aca1e51 100644 --- a/nerfstudio/utils/colormaps.py +++ b/nerfstudio/utils/colormaps.py @@ -65,14 +65,9 @@ def apply_colormap( # default for rgb images if image.shape[-1] == 3: - if(colormap_options.exposure_scale != 0 or image.max() > 1): - # Log - # img_gamma_22 = torch.exp(image) - 1. - - # u-law - u = 5000. - img_gamma_22 = torch.exp(image * torch.log(torch.tensor(u+1.))) - 1. - img_gamma_22 /= u + # if(colormap_options.exposure_scale != 0 or image.max() > 1): + if True: + img_gamma_22 = image img_gamma_22 *= 2.**(colormap_options.exposure_scale) img_gamma_22 = torch.pow(img_gamma_22, 1./2.2) return torch.clamp(img_gamma_22, 0., 1.) diff --git a/stick_masks/left_mask.png b/stick_masks/left_mask.png index aca7abefd..03ba7fbdc 100644 Binary files a/stick_masks/left_mask.png and b/stick_masks/left_mask.png differ diff --git a/stick_masks/left_mask_bak.png b/stick_masks/left_mask_bak.png index 5c62b0c7c..a329c5e94 100644 Binary files a/stick_masks/left_mask_bak.png and b/stick_masks/left_mask_bak.png differ