Fixing nerfw and adding to GH Actions (#167)

* added beta_min to nerfw, which I think is needed

* added camera interpolation path and restructured run_eval code

* adding to gitignore

* addressing github comments. mostly documentation

* fixing nerfw dataset for test cases
This commit is contained in:
Ethan Weber authored and GitHub committed 2022-07-19 16:21:54 -07:00
1 parent f77d1fc110
commit 05b92e228b
13 files changed
+197 -67

No files matched your search

+14 -8
View File
@@ -45,20 +45,24 @@ def get_interpolated_camera_path(camera_a: Camera, camera_b: Camera, steps: int)
Returns:
CameraPath: A camera path.
"""
Ka = camera_a.get_intrinsics_matrix()
pose_a = camera_a.get_camera_to_world_h()
Kb = camera_b.get_intrinsics_matrix()
pose_b = camera_b.get_camera_to_world_h()
device = camera_a.device
Ka = camera_a.get_intrinsics_matrix().cpu().numpy()
pose_a = camera_a.get_camera_to_world_h().cpu().numpy()
Kb = camera_b.get_intrinsics_matrix().cpu().numpy()
pose_b = camera_b.get_camera_to_world_h().cpu().numpy()
poses = [pose_a, pose_b]
Ks = [Ka, Kb]
poses, Ks = get_interpolated_poses_many(poses, Ks, steps_per_transition=steps)
# create a list of cameras
cameras = []
for pose, K in zip(poses, Ks):
intrinsics = get_intrinsics_from_intrinsics_matrix(K)
camera_to_world = torch.from_numpy(pose[:3])
camera = get_camera(intrinsics, camera_to_world, None)
intrinsics = get_intrinsics_from_intrinsics_matrix(K).to(device).float()
# TODO: this makes cx and cy an integer, but this code should be fixed
# it was added to avoid floating point errors when rescaling and the image resolution
# being different per rendered image in a camera path
intrinsics[:2] = torch.round(intrinsics[:2])
camera_to_world = torch.from_numpy(pose[:3]).to(device).float()
camera = get_camera(intrinsics, camera_to_world, camera_index=camera_a.camera_index)
cameras.append(camera)
return CameraPath(cameras=cameras)
@@ -94,7 +98,9 @@ def get_spiral_path(
else:
raise ValueError("Only one of radius or radiuses must be specified.")
# TODO: don't hardcode this. pass this in
up = camera.camera_to_world[:3, 2] # scene is z up
# up = camera.camera_to_world[:3, 1] # this will rotate 90 degrees
focal = min(camera.fx, camera.fy)
target = torch.tensor([0, 0, -focal], device=camera.device) # camera looking in -z direction
+22
View File
@@ -91,6 +91,18 @@ class Camera:
"""
return
@abstractmethod
def rescale_output_resolution(self, scaling_factor: float) -> None:
"""Rescales the camera intrinsics for output resolution.
Args:
scaling_factor (float): Scaling factor
Returns:
None
"""
return
def get_image_coords(self, pixel_offset: float = 0.5) -> TensorType["image_height", "image_width", 2]:
"""
Args:
@@ -207,6 +219,12 @@ class PinholeCamera(Camera):
"""
return 3
def rescale_output_resolution(self, scaling_factor: float) -> None:
self.cx *= scaling_factor
self.cy *= scaling_factor
self.fx *= scaling_factor
self.fy *= scaling_factor
@classmethod
def generate_rays(
cls,
@@ -289,6 +307,10 @@ class EquirectangularCamera(Camera):
def get_intrinsics(self) -> torch.Tensor:
return torch.tensor([self.height, self.width])
def rescale_output_resolution(self, scaling_factor: float) -> None:
self.height *= scaling_factor
self.width *= scaling_factor
@classmethod
def generate_rays(
cls,
+6
View File
@@ -57,6 +57,12 @@ def load_instant_ngp_data(
poses.append(np.array(frame["transform_matrix"]))
if num_skipped_image_filenames >= 0:
logging.info("Skipping %s files in dataset split %s.", num_skipped_image_filenames, split)
assert (
len(image_filenames) != 0
), """
No image files found.
You should check the file_paths in the transforms.json file to make sure they are correct.
"""
poses = np.array(poses).astype(np.float32)
poses[:3, 3] *= camera_translation_scalar
+14 -4
View File
@@ -108,20 +108,30 @@ class VanillaNerfWField(Field):
def get_density(self, ray_samples: RaySamples):
"""Computes and returns the densities."""
encoded_xyz = self.position_encoding(ray_samples.frustums.positions())
encoded_xyz = self.position_encoding(ray_samples.frustums.get_positions())
encoded_xyz = self.position_encoding(ray_samples.frustums.get_positions())
base_mlp_out = self.mlp_base(encoded_xyz)
density = self.field_head_density(base_mlp_out)
return density, base_mlp_out
def get_outputs(
self, ray_samples: RaySamples, density_embedding: Optional[TensorType] = None
self, ray_samples: RaySamples, density_embedding: Optional[TensorType[..., "embedding_size"]] = None
) -> Dict[FieldHeadNames, TensorType]:
"""Returns the outputs of the NeRF-W field.
Args:
ray_samples (RaySamples): Ray samples.
density_embedding (TensorType[..., "embedding_size"], optional): Density embedding. Defaults to None.
Returns:
Dict[FieldHeadNames, TensorType]: Outputs of the NeRF-W field.
"""
outputs = {}
encoded_dir = self.direction_encoding(ray_samples.frustums.directions)
embedded_appearance = self.embedding_appearance(ray_samples.camera_indices)
embedded_appearance = self.embedding_appearance(ray_samples.camera_indices.squeeze())
mlp_head_out = self.mlp_head(torch.cat([density_embedding, encoded_dir, embedded_appearance], dim=-1))
outputs[self.field_head_rgb.field_head_name] = self.field_head_rgb(mlp_head_out) # static rgb
embedded_transient = self.embedding_transient(ray_samples.camera_indices)
embedded_transient = self.embedding_transient(ray_samples.camera_indices.squeeze())
transient_mlp_out = self.mlp_transient(torch.cat([density_embedding, embedded_transient], dim=-1))
outputs[self.field_head_transient_uncertainty.field_head_name] = self.field_head_transient_uncertainty(
transient_mlp_out
+6
View File
@@ -59,6 +59,11 @@ class AbstractGraph(nn.Module):
"""Returns the device that the torch parameters are on."""
return self.device_indicator_param.device
@property
def device(self):
"""Returns the device that the graph is on."""
return self.device_indicator_param.device
@abstractmethod
def forward(self, ray_indices: TensorType["num_rays", 3], batch: Union[str, Dict[str, torch.tensor]] = None):
"""Process starting with ray indices. Turns them into rays, then performs volume rendering."""
@@ -104,6 +109,7 @@ class Graph(AbstractGraph):
self.callbacks = None
# variable for visualizer to fetch TODO(figure out if there is cleaner way to do this)
self.vis_outputs = None
self.default_output_name = None
def register_callbacks(self): # pylint:disable=no-self-use
"""Option to register callback for training functions"""
+16 -3
View File
@@ -44,13 +44,24 @@ class NerfWGraph(Graph):
near_plane=2.0,
far_plane=6.0,
num_coarse_samples=64,
num_importance_samples=128,
num_importance_samples=64,
uncertainty_min=0.03,
**kwargs,
) -> None:
"""A NeRF-W graph.
Args:
...
uncertainty_min (float, optional): This is added to the end of the uncertainty
rendering operation. It's called 'beta_min' in other repos.
This avoids calling torch.log() on a zero value, which would be undefined.
Defaults to 0.03.
"""
self.near_plane = near_plane
self.far_plane = far_plane
self.num_coarse_samples = num_coarse_samples
self.num_importance_samples = num_importance_samples
self.uncertainty_min = uncertainty_min
self.field_coarse = None
self.field_fine = None
self.num_images = len(intrinsics)
@@ -151,6 +162,7 @@ class NerfWGraph(Graph):
# uncertainty
uncertainty = self.renderer_uncertainty(field_outputs_fine[FieldHeadNames.UNCERTAINTY], weights_fine_transient)
uncertainty += self.uncertainty_min
outputs = {
"rgb_coarse": rgb_coarse, # (num_rays, 3)
@@ -206,5 +218,6 @@ class NerfWGraph(Graph):
writer.put_image(name=f"img/image_idx_{image_idx}-nerfw", image=combined_image, step=step)
mask = batch["mask"].repeat(1, 1, 3)
writer.put_image(name=f"mask/image_idx_{image_idx}", image=mask, step=step)
if "mask" in batch:
mask = batch["mask"].repeat(1, 1, 3)
writer.put_image(name=f"mask/image_idx_{image_idx}", image=mask, step=step)