mirror of
https://github.com/nerfstudio-project/nerfstudio.git
synced 2026-11-23 16:15:36 +08:00
visibility field code without modifications to pipeline yet
This commit is contained in:
1 parent
42081b7ad4
commit
159b3707a9
5 files changed
+135
-17
No files matched your search
@@ -851,7 +851,7 @@ class Cameras(TensorDataclass):
|
||||
Returns:
|
||||
Pinhole camera intrinsics matrices
|
||||
"""
|
||||
K = torch.zeros((*self.shape, 3, 3), dtype=torch.float32)
|
||||
K = torch.zeros((*self.shape, 3, 3), dtype=torch.float32, device=self.device)
|
||||
K[..., 0, 0] = self.fx.squeeze(-1)
|
||||
K[..., 1, 1] = self.fy.squeeze(-1)
|
||||
K[..., 0, 2] = self.cx.squeeze(-1)
|
||||
|
||||
@@ -0,0 +1,90 @@
|
||||
# Copyright 2022 the Regents of the University of California, Nerfstudio Team and contributors. 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.
|
||||
|
||||
"""Visibility Field"""
|
||||
|
||||
import torch
|
||||
from torch import nn
|
||||
|
||||
from nerfstudio.cameras.cameras import Cameras
|
||||
from nerfstudio.cameras.rays import RaySamples
|
||||
|
||||
|
||||
class VisibilityField(nn.Module):
|
||||
"""Visibility Field"""
|
||||
|
||||
def __init__(self, cameras: Cameras) -> None:
|
||||
super().__init__()
|
||||
# training camera tranforms
|
||||
# TODO: use optimized cameras
|
||||
self.c2ws = cameras.camera_to_worlds
|
||||
self.c2whs = torch.cat([self.c2ws, torch.zeros_like(self.c2ws[:, :1, :])], dim=1)
|
||||
self.c2whs[:, 3, 3] = 1.0
|
||||
self.w2chs = torch.inverse(self.c2whs)
|
||||
self.K = cameras.get_intrinsics_matrices()
|
||||
self.image_height = cameras.height
|
||||
self.image_width = cameras.width
|
||||
|
||||
@torch.no_grad()
|
||||
def forward(self, ray_samples: RaySamples, camera_chunk_size=50, ray_chunk_size=4096):
|
||||
"""
|
||||
Args:
|
||||
ray_samples: Ray samples.
|
||||
camera_chunk_size: Number of cameras to process at once to avoid memory issues.
|
||||
ray_chunk_size: Number of rays to process at once to avoid memory issues.
|
||||
Returns:
|
||||
"""
|
||||
# get positions
|
||||
positions = ray_samples.frustums.get_positions() # [N, S, 3]
|
||||
# project positions into each camera
|
||||
# move to homogeneous coordinates
|
||||
positions = torch.cat([positions, torch.ones_like(positions[..., :1])], dim=-1)
|
||||
N, S, _ = positions.shape
|
||||
B = self.w2chs.shape[0] # num cameras
|
||||
p = positions.view(N * S, 4).transpose(0, 1).unsqueeze(0) # [1, 4, N*S]
|
||||
p = p.expand(B, *p.shape[1:]) # [B, 4, N*S]
|
||||
|
||||
num_views = torch.zeros([N, S, 1], device=positions.device)
|
||||
for i in range(0, B, camera_chunk_size):
|
||||
ccs = min(camera_chunk_size, B - i)
|
||||
for j in range(0, N, ray_chunk_size):
|
||||
rcs = min(ray_chunk_size, N - j)
|
||||
|
||||
ptemp = p.reshape(B, 4, N, S)[i : i + ccs, :, j : j + rcs, :].reshape(ccs, 4, rcs * S)
|
||||
cam_coords = torch.bmm(self.w2chs[i : i + ccs, :], ptemp)
|
||||
|
||||
# flip y and z axes
|
||||
cam_coords[:, 1, :] *= -1
|
||||
cam_coords[:, 2, :] *= -1
|
||||
|
||||
z = cam_coords[:, 2:3, :].transpose(1, 2).view(ccs, rcs, S, 1) # [CS, RCS, S, 1]
|
||||
mask_z = z[..., 0] > 0
|
||||
|
||||
# divide by z
|
||||
cam_coords = cam_coords[:, :3, :] / cam_coords[:, 2:3, :]
|
||||
|
||||
cam_points = torch.bmm(self.K[i : i + ccs], cam_coords)
|
||||
|
||||
pixel_coords = cam_points[:, :2, :].transpose(1, 2).view(ccs, rcs, S, 2) # [CS, RCS, S, 2]
|
||||
x = pixel_coords[..., 0]
|
||||
y = pixel_coords[..., 1]
|
||||
mask_x = (x >= 0) & (x < self.image_width.view(B, 1, 1)[i : i + ccs])
|
||||
mask_y = (y >= 0) & (y < self.image_height.view(B, 1, 1)[i : i + ccs])
|
||||
mask = mask_x & mask_y & mask_z
|
||||
# sum over the batch dimension
|
||||
nv = mask.sum(dim=0).unsqueeze(-1)
|
||||
# nv is [N, S, 1] # this is the number of camera frustums that the point belongs to
|
||||
# for this particular chunk of cameras
|
||||
num_views[j : j + rcs] += nv
|
||||
return num_views
|
||||
@@ -578,6 +578,7 @@ class ProposalNetworkSampler(Sampler):
|
||||
assert ray_bundle is not None
|
||||
assert density_fns is not None
|
||||
|
||||
densities_list = []
|
||||
weights_list = []
|
||||
ray_samples_list = []
|
||||
|
||||
@@ -604,6 +605,7 @@ class ProposalNetworkSampler(Sampler):
|
||||
else:
|
||||
with torch.no_grad():
|
||||
density = density_fns[i_level](ray_samples.frustums.get_positions())
|
||||
densities_list.append(density)
|
||||
weights = ray_samples.get_weights(density)
|
||||
weights_list.append(weights) # (num_rays, num_samples)
|
||||
ray_samples_list.append(ray_samples)
|
||||
@@ -611,7 +613,7 @@ class ProposalNetworkSampler(Sampler):
|
||||
self._steps_since_update = 0
|
||||
|
||||
assert ray_samples is not None
|
||||
return ray_samples, weights_list, ray_samples_list
|
||||
return ray_samples, densities_list, weights_list, ray_samples_list
|
||||
|
||||
|
||||
class NeuSSampler(Sampler):
|
||||
|
||||
@@ -250,7 +250,8 @@ class DepthRenderer(nn.Module):
|
||||
ray_samples: RaySamples,
|
||||
ray_indices: Optional[Int[Tensor, "num_samples"]] = None,
|
||||
num_rays: Optional[int] = None,
|
||||
) -> Float[Tensor, "*batch 1"]:
|
||||
quantity: Optional[Float[Tensor, "*batch num_samples 1"]] = None,
|
||||
) -> Float[Tensor, "*bs 1"]:
|
||||
"""Composite samples along ray and calculate depths.
|
||||
|
||||
Args:
|
||||
@@ -258,39 +259,37 @@ class DepthRenderer(nn.Module):
|
||||
ray_samples: Set of ray samples.
|
||||
ray_indices: Ray index for each sample, used when samples are packed.
|
||||
num_rays: Number of rays, used when samples are packed.
|
||||
quantity: If specified, then take the median of this quantity instead of the depth.
|
||||
|
||||
Returns:
|
||||
Outputs of depth values.
|
||||
"""
|
||||
|
||||
if self.method == "median":
|
||||
steps = (ray_samples.frustums.starts + ray_samples.frustums.ends) / 2
|
||||
if quantity is None:
|
||||
# set the quantity to steps
|
||||
quantity = (ray_samples.frustums.starts + ray_samples.frustums.ends) / 2
|
||||
|
||||
if self.method == "median":
|
||||
if ray_indices is not None and num_rays is not None:
|
||||
raise NotImplementedError("Median depth calculation is not implemented for packed samples.")
|
||||
cumulative_weights = torch.cumsum(weights[..., 0], dim=-1) # [..., num_samples]
|
||||
split = torch.ones((*weights.shape[:-2], 1), device=weights.device) * 0.5 # [..., 1]
|
||||
median_index = torch.searchsorted(cumulative_weights, split, side="left") # [..., 1]
|
||||
median_index = torch.clamp(median_index, 0, steps.shape[-2] - 1) # [..., 1]
|
||||
median_depth = torch.gather(steps[..., 0], dim=-1, index=median_index) # [..., 1]
|
||||
median_index = torch.clamp(median_index, 0, quantity.shape[-2] - 1) # [..., 1]
|
||||
median_depth = torch.gather(quantity[..., 0], dim=-1, index=median_index) # [..., 1]
|
||||
return median_depth
|
||||
if self.method == "expected":
|
||||
eps = 1e-10
|
||||
steps = (ray_samples.frustums.starts + ray_samples.frustums.ends) / 2
|
||||
|
||||
if ray_indices is not None and num_rays is not None:
|
||||
# Necessary for packed samples from volumetric ray sampler
|
||||
depth = nerfacc.accumulate_along_rays(
|
||||
weights[..., 0], values=steps, ray_indices=ray_indices, n_rays=num_rays
|
||||
)
|
||||
accumulation = nerfacc.accumulate_along_rays(
|
||||
weights[..., 0], values=None, ray_indices=ray_indices, n_rays=num_rays
|
||||
)
|
||||
depth = nerfacc.accumulate_along_rays(weights, ray_indices, quantity, num_rays)
|
||||
accumulation = nerfacc.accumulate_along_rays(weights, ray_indices, None, num_rays)
|
||||
depth = depth / (accumulation + eps)
|
||||
else:
|
||||
depth = torch.sum(weights * steps, dim=-2) / (torch.sum(weights, -2) + eps)
|
||||
depth = torch.sum(weights * quantity, dim=-2) / (torch.sum(weights, -2) + eps)
|
||||
|
||||
depth = torch.clip(depth, steps.min(), steps.max())
|
||||
depth = torch.clip(depth, quantity.min(), quantity.max())
|
||||
|
||||
return depth
|
||||
|
||||
|
||||
@@ -38,6 +38,7 @@ from nerfstudio.field_components.field_heads import FieldHeadNames
|
||||
from nerfstudio.field_components.spatial_distortions import SceneContraction
|
||||
from nerfstudio.fields.density_fields import HashMLPDensityField
|
||||
from nerfstudio.fields.nerfacto_field import NerfactoField
|
||||
from nerfstudio.fields.visibility_field import VisibilityField
|
||||
from nerfstudio.model_components.losses import (
|
||||
MSELoss,
|
||||
distortion_loss,
|
||||
@@ -168,6 +169,10 @@ class NerfactoModel(Model):
|
||||
implementation=self.config.implementation,
|
||||
)
|
||||
|
||||
# this can be set by the pipeline
|
||||
# is set, then we create a visibility outputs
|
||||
self.visibility_field: Optional[VisibilityField] = None
|
||||
|
||||
self.density_fns = []
|
||||
num_prop_nets = self.config.num_proposal_iterations
|
||||
# Build the proposal network(s)
|
||||
@@ -224,6 +229,8 @@ class NerfactoModel(Model):
|
||||
self.renderer_rgb = RGBRenderer(background_color=self.config.background_color)
|
||||
self.renderer_accumulation = AccumulationRenderer()
|
||||
self.renderer_depth = DepthRenderer()
|
||||
self.renderer_depth_expected = DepthRenderer(method="expected")
|
||||
self.renderer_depth_median = DepthRenderer(method="median")
|
||||
self.renderer_normals = NormalsRenderer()
|
||||
|
||||
# shaders
|
||||
@@ -279,11 +286,14 @@ class NerfactoModel(Model):
|
||||
|
||||
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)
|
||||
ray_samples, densities_list, 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)
|
||||
|
||||
densities_list.append(field_outputs[FieldHeadNames.DENSITY])
|
||||
weights = ray_samples.get_weights(field_outputs[FieldHeadNames.DENSITY])
|
||||
weights_list.append(weights)
|
||||
ray_samples_list.append(ray_samples)
|
||||
@@ -298,6 +308,22 @@ class NerfactoModel(Model):
|
||||
"depth": depth,
|
||||
}
|
||||
|
||||
if self.visibility_field is not None:
|
||||
assert isinstance(self.visibility_field, VisibilityField), "self.visibility_field must be a VisibilityField"
|
||||
visibility_samples = self.visibility_field.forward(ray_samples_list[-1])
|
||||
visibility = self.renderer_depth_expected(
|
||||
weights=weights, ray_samples=ray_samples, quantity=visibility_samples
|
||||
)
|
||||
outputs["visibility_count"] = visibility.long()
|
||||
visibility = visibility.float() / len(self.visibility_field.c2ws) # [0, 1] 1 is seen by all cameras
|
||||
outputs["visibility"] = visibility
|
||||
visibility_median = self.renderer_depth_median(
|
||||
weights=weights, ray_samples=ray_samples, quantity=visibility_samples
|
||||
)
|
||||
outputs["visibility_median_count"] = visibility_median.long()
|
||||
visibility_median = visibility_median.float() / len(self.visibility_field.c2ws) # [0, 1]
|
||||
outputs["visibility_median"] = visibility_median
|
||||
|
||||
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)
|
||||
@@ -305,6 +331,7 @@ class NerfactoModel(Model):
|
||||
outputs["pred_normals"] = self.normals_shader(pred_normals)
|
||||
# These use a lot of GPU memory, so we avoid storing them for eval.
|
||||
if self.training:
|
||||
outputs["densities_list"] = densities_list
|
||||
outputs["weights_list"] = weights_list
|
||||
outputs["ray_samples_list"] = ray_samples_list
|
||||
|
||||
|
||||
Reference in new issue
Block a user