Skip to content
ImagineWorld

Understanding Differentiable Volumetric Rendering

node_idnode-book_3d-deep-learning-with-python_chapter-05-understanding-differentiable-volumetric-rendering
node_typechapter-node
schema_profileworld.chapter_node.v1
statusactive
entropyhigh
manifoldworld
domainimagineworld.net
authorityinforms
layercorpus
chapter_num5
chapter_titleUnderstanding Differentiable Volumetric Rendering
governed_byCORPUS
constitutional_citationCONSTITUTION
local graph

In this chapter, we are going to discuss a new way of differentiable rendering. We are going to use a voxel 3D data representation, unlike the mesh 3D data representation we used in the last chapter. Voxel 3D data representation has certain advantages compared to mesh models. For example, it is more flexible and highly structured. To understand volumetric rendering, we need to understand several important concepts, such as ray sampling, volumes, volume sampling, and ray marching. All these concepts have corresponding PyTorch3D implementations. We will discuss each of these concepts using explanations and coding exercises. After we understand the preceding basic concepts of volumetric rendering, we can then see easily that all the operations mentioned already are already differentiable. Volumetric rendering is naturally differentiable. Thus, by then, we will be ready to use differentiable volumetric rendering for some real applications. We are going to go over a coding example of reconstructing 3D voxel models from multiple images by using differentiable volumetric rendering. We will first understand volumetric rendering on a high level. We will then dive into the basic concepts, such as ray sampling, volumes, volume sampling, and ray marching. We will then present a coding example of reconstructing 3D object shapes from a collection of images taken from different views of the object. In this chapter, we’re going to cover the following main topics:

  • A high-level description of volumetric rendering
  • Understanding ray sampling
  • Using volume sampling
  • Understanding ray marching
  • Reconstructing 3D objects and colors from multi-view images

Volumetric rendering is a collection of techniques used to generate a 2D view of discrete 3D data. This 3D discrete data could be a collection of images, voxel representation, or any other discrete representation of data. The main goal of volumetric rendering is to render a 2D projection of 3D data since that is what our eyes can perceive on a flat screen. This method generated such projections without any explicit conversion to a geometric representation (such as meshes). Volumetric rendering is typically used when generating surfaces is difficult or can lead to errors. It can also be used when the content (and not just the geometry and surface) of the volume is important. It is typically used for data visualization. For example, in brain scans, a visualization of the content of the interior of the brain is typically very important. In this section, we will explore the volumetric rendering of a volume. We will get a high-level overview of volumetric rendering as shown in Figure 5*.1*:

  1. First, we represent the 3D space and objects in it by using a volume, which is a 3D grid of regularly spaced nodes. Each node has two properties: density and color features. The density typically ranges from 0 to 1. Density can also be understood as the probability of occupancy. That is, how sure we think that the node is occupied by a certain object. In some cases, the probability can also be opacity.
  2. We need to define one or multiple cameras. The rendering is the process that determines what the cameras can observe from their views.
  3. To determine the RGB values at each pixel of the preceding cameras, a ray is generated from the projection center going through each image pixel of the cameras. We need to check the probability of occupancy or opacity and colors along this ray to determine RGB values for the pixel. Note there are infinitely many points on each such ray. Thus, we need to have a sampling scheme to select a certain number of points along this ray. This sampling operation is called ray sampling.
  4. Note that we have densities and colors defined on the nodes of the volume but not on the points on the rays. Thus, we need to have a way to convert densities and colors of volumes to points on rays. This operation is called volume sampling.
  5. Finally, from the densities and colors of the rays, we need to determine the RGB values of each pixel. In this process, we need to compute how many incident lights can arrive at each point along the ray and how many lights are reflected to the image pixel. We call this process ray marching.

Figure 5.1: Volumetric rendering

Having understood the basic process of volumetric rendering, let us dive deeper into the first concept: ray sampling.

Ray sampling is the process of emitting rays from the camera that goes through the image pixels and sampling points along these rays. The ray sampling scheme depends on the use case. For example, sometimes we might want to randomly sample rays that go through some random subset of image pixels. Typically, we need to use such a sampler during training since we only need a representative sample from the full data. In such cases, we can use MonteCarloRaysampler in Pytorch3D. In other cases, we want to get the pixel values for each pixel on the image and maintain a spatial order. This is useful for rendering and visualization. For such use cases, PyTorch3D provides NDCMultiNomialRaysampler. In the following, we will demonstrate how to use one of the PyTorch3D ray samplers, NDCGridRaysampler. This is like NDCMultiNomialRaysampler, where pixels are sampled along a grid. The codes can be found in the GitHub repository named understand_ray_sampling.py:

  1. First, we need to import all the Python modules, including the definition of NDCGridRaysampler:
import torch
import math
import numpy as np
from pytorch3d.renderer import (
FoVPerspectiveCameras,
PointLights,
look_at_view_transform,
NDCGridRaysampler,
)
  1. Set up the devices for use in the following steps. If we have GPUs, then we are going to use the first GPU. Otherwise, we are going to use the CPU:
if torch.cuda.is_available():
device = torch.device("cuda:0")
torch.cuda.set_device(device)
else:
device = torch.device("cpu")
  1. We define a batch of 10 cameras. Here, num_views is the number of views, which is 10 in this case. The elev variable denotes the elevation angle, and azim denotes the azimuth angle. The rotation, R, and translation, T, can thus be determined using the PyTorch3D look_at_view_transform function. The 10 cameras then can be defined by using rotations and translations. The 10 cameras all point at an object located at the center of the world coordinates:num_views: int = 10 azimuth_range: float = 180
elev = torch.linspace(0, 0, num_views)
azim = torch.linspace(-azimuth_range, azimuth_range, num_views) + 180.0
lights = PointLights(device=device, location=[[0.0, 0.0, -3.0]])
R, T = look_at_view_transform(dist=2.7, elev=elev, azim=azim)
cameras = FoVPerspectiveCameras(device=device, R=R, T=T)
  1. Finally, we can define the ray sampler, which is the raysampler variable. We need to specify the image size of the camera. We also need to specify the minimum and maximum depths that the ray ranges from. The n_pts_per_ray input is the number of points along the ray:
image_size = 64
volume_extent_world = 3.0
raysampler = NDCGridRaysampler(
image_width=image_size,
image_height=image_size,
n_pts_per_ray=50,
min_depth=0.1,
max_depth=volume_extent_world,
)
  1. In the preceding step, we have already defined a ray sampler. To make the ray sampler samples rays and points for use, we need to let the ray sampler know where our cameras are and in what directions they are pointing. This can be easily achieved by passing the cameras defined in step 3 to raysampler. What we obtain is then a ray_bundle variable:
ray_bundle = raysampler(cameras)
  1. The ray_bundle variable contains a collection of different PyTorch tensors that specify the sampled rays and points. We can print these member variables to check their shapes and verify their contents:
print('ray_bundle origins tensor shape = ', ray_bundle.origins.shape)
print('ray_bundle directions shape = ', ray_bundle.directions.shape)
print('ray_bundle lengths = ', ray_bundle.lengths.shape)
print('ray_bundle xys shape = ', ray_bundle.xys.shape)
  1. The codes should run and print the following information:
    • We can see that ray_bundle.origins is a tensor about the origins of the rays, and the batch size is 10. Because the image size is 64 by 64, the size of the second and third dimensions are both 64. For each origin, we need three numbers to specify its 3D location.
      • ray_bundle.directions is a tensor about the directions of the ray. Again, the batch size is 10 and the image size is 64 by 64. These explain the size of the first three dimensions of the tensor. We need three numbers to specify a direction in 3D spaces.
      • ray_bundle.lengths is a tensor about the depths of each point on the rays. There are 10x64x64 rays and there are 50 points on each ray.
      • ray_bundle.xys is a tensor about the x and y locations on the image plane corresponding to each ray. There are 10x64x64 rays. We need one number to represent the x location and one number to represent the y location:ray_bundle origins tensor shape = torch.Size([10, 64, 64, 3]) ray_bundle directions shape = torch.Size([10, 64, 64, 3]) ray_bundle lengths = torch.Size([10, 64, 64, 50]) ray_bundle xys shape = torch.Size([10, 64, 64, 2])
  2. Finally, we save ray_bundle to a ray_sampling.pt file. These rays are useful for our coding exercises in the following sections:
torch.save({
'ray_bundle': ray_bundle
}, 'ray_sampling.pt')

By now, we understand what ray samplers do. Ray samplers give us a batch of rays and discrete points on the rays. However, we still do not have densities and colors defined on these points and rays. Next, we are going to learn how to get these densities and colors from the volumes.

Volume sampling is the process of getting color and occupancy information along the points provided by the ray samples. The volume representation we are working with is discrete. Therefore, the points defined in the ray sampling step might not fall exactly on a point. The nodes of the volume grids and points on rays typically have different spatial locations. We need to use an interpolation scheme to interpolate the densities and colors at points of rays from the densities and colors at volumes. We can do that by using VolumeSampler implemented in PyTorch3D. The following code can be found in the GitHub repository in the understand_volume_sampler.py file:

  1. Import the Python modules that we need:
import torch
from pytorch3d.structures import Volumes
from pytorch3d.renderer.implicit.renderer import VolumeSampler
  1. Set up the devices:
if torch.cuda.is_available():
device = torch.device("cuda:0")
torch.cuda.set_device(device)
else:
device = torch.device("cpu")
  1. Load ray_bundle, which was computed in the last section:
checkpoint = torch.load('ray_sampling.pt')
ray_bundle = checkpoint.get('ray_bundle')
  1. We then define a volume. The densities tensor has a shape of [10, 1, 64, 64, 50], where we have a batch of 10 volumes, and each volume is a grid of 64x64x50 nodes. Each node has one number to represent the density at the node. On the other hand, the colors tensor has a shape of [10, 3, 64, 64, 50], because each color needs three numbers to represent the RGB values:
batch_size = 10
densities = torch.zeros([batch_size, 1, 64, 64, 64]).to(device)
colors = torch.zeros(batch_size, 3, 64, 64, 64).to(device)
voxel_size = 0.1
volumes = Volumes(
densities=densities,
features=colors,
voxel_size=voxel_size
)
  1. We need to define volume_sampler based on the volumes. Here, we use bilinear interpolation for the volume sampling. The densities and colors of points on the rays can then be easily obtained by passing ray_bundle to volume_sampler:
volume_sampler = VolumeSampler(volumes = volumes, sample_mode = "bilinear")
rays_densities, rays_features = volume_sampler(ray_bundle)
  1. We can print out the shape of the densities and colors:
print('rays_densities shape = ', rays_densities.shape)
print('rays_features shape = ', rays_features.shape)
  1. The output is as follows. Note that we have a batch size of 10 cameras, which explains the size of the first dimension of the tensors. We have one ray for each image pixel and our camera image resolution is 64 by 64. The number of points on each ray is 50, which explains the size of the fourth dimension of the tensors. Each density can be represented by one number and each color needs three numbers to represent the RGB values:rays_densities shape = torch.Size([10, 64, 64, 50, 1]) rays_features shape = torch.Size([10, 64, 64, 50, 3])
  2. Finally, let us save the densities and colors because we need to use them in the next section:
torch.save({
'rays_densities': rays_densities,
'rays_features': rays_features
}, 'volume_sampling.pt')

We now have an overview of volume sampling. We know what it is and why it is useful. In the next section, we will learn about how to use these densities and colors to generate the RGB image values on the batch of cameras.

Now that we have the color and density values for all the points sampled with the ray sampler, we need to figure out how to use it to finally render the pixel value on the projected image. In this section, we are going to discuss the process of converting the densities and colors on points of rays to RGB values on images. This process models the physical process of image formation. In this section, we discuss a very simple model, where the RGB value of each image pixel is a weighted sum of the colors on the points of the corresponding ray. If we consider the densities as probabilities of occupancy or opacity, then the incident light intensity at each point of the ray is a = product of (1-p_i), where p_i are the densities. Given the probability that this point is occupied by a certain object is p_i, the expected light intensity reflected from this point is w_i = a p_i. We just use w_i as the weights for the weighted sum of colors. Usually, we normalize the weights by applying a softmax operation, such that the weights all sum up to one. PyTorch3D contains multiple implementations of ray marchers. The following codes can be found in understand_ray_marcher.py in the GitHub repository:

  1. In this first step, we will import all the required packages:
import torch
from pytorch3d.renderer.implicit.raymarching import EmissionAbsorptionRaymarcher
  1. Next, we load the densities and colors on rays from the last section:
checkpoint = torch.load('volume_sampling.pt')
rays_densities = checkpoint.get('rays_densities')
rays_features = checkpoint.get('rays_features')
  1. We define ray_marcher and pass the densities and colors on rays to ray_marcher. This gives us image_features, which are exactly rendered RGB values:
ray_marcher = EmissionAbsorptionRaymarcher()
image_features = ray_marcher(rays_densities = rays_densities, rays_features = rays_features)
  1. We can print the image feature shape:
print('image_features shape = ', image_features.shape)
  1. As we have expected, the shape is [10, 64, 64, 4], where 10 is the batch size, and 64 is the image width and height. The outputs have four channels, the first three are RGBs. The last channel is the alpha channel, which represents whether the pixel is in the foreground or the background:image_features shape = torch.Size([10, 64, 64, 4]) We have now gone through some of the main components of volumetric rendering. Note that the computation process from the volume densities and colors to image pixel RGB values is already differentiable. So, volumetric rendering is naturally differentiable. Given that all the variables in the preceding examples are PyTorch tensors, we can compute gradients on these variables. In the next section, we will learn about differentiable volume rendering and see an example of using volumetric rendering for reconstructing 3D models from multi-view images.

While standard volumetric rendering is used to render 2D projections of 3D data, differentiable volume rendering is used to do the opposite: construct 3D data from 2D images. This is how it works: we represent the shape and texture of the object as a parametric function. This function can be used to generate 2D projections. But, given 2D projections (this is typically multiple views of the 3D scene), we can optimize the parameters of these implicit shape and texture functions so that its projections are the multi-view 2D images. This optimization is possible since the rendering process is completely differentiable, and the implicit functions used are also differentiable.

Reconstructing 3D models from multi-view images

Section titled “Reconstructing 3D models from multi-view images”

In this section, we are going to show an example of using differentiable volumetric rendering for reconstructing 3D models from multi-view images. Reconstructing 3D models is a frequently sought problem. Usually, the direct ways of measuring the 3D world are difficult and costly, for example, LiDAR and Radar are typically expensive. On the other hand, 2D cameras have much lower costs, which makes reconstructing the 3D world from 2D images incredibly attractive. Of course, to reconstruct the 3D world, we need multiple images from multiple views. The following volume_renderer.py code can be found in the GitHub repository and it is modified from a tutorial of PyTorch3D. We will use this coding example to show how the real-world application of volumetric rendering can be:

  1. First, we need to import all the Python modules:
import os
import sys
import time
import json
import glob
import torch
import math
import matplotlib.pyplot as plt
import numpy as np
from PIL import Image
from pytorch3d.structures import Volumes
from pytorch3d.renderer import (
FoVPerspectiveCameras,
VolumeRenderer,
NDCGridRaysampler,
EmissionAbsorptionRaymarcher
)
from pytorch3d.transforms import so3_exp_map
from plot_image_grid import image_grid
from generate_cow_renders import generate_cow_renders
  1. Next, we need to set up the device:
if torch.cuda.is_available():
device = torch.device("cuda:0")
torch.cuda.set_device(device)
else:
device = torch.device("cpu")
  1. Using the provided function from the PyTorch3D tutorial, we generate 40 cameras, images, and silhouette images with different angles. We will consider these images as the given ground-truth images, and we will fit a 3D volumetric model to these observed ground-truth images:
target_cameras, target_images, target_silhouettes = generate_cow_renders(num_views=40)
  1. Next, we define a ray sampler. As we have discussed in the previous sections, the ray sampler is for sample rays, and points per rays for us:
render_size = 128
volume_extent_world = 3.0
raysampler = NDCGridRaysampler(
image_width=render_size,
image_height=render_size,
n_pts_per_ray=150,
min_depth=0.1,
max_depth=volume_extent_world,
)
  1. Next, we create the ray marcher as before. Note, this time, we define a variable renderer of the VolumeRenderer type. VolumeRenderer is just a nice interface, where ray samplers and ray marchers do all the heavy-lifting work under the hood:
raymarcher = EmissionAbsorptionRaymarcher()
renderer = VolumeRenderer(
raysampler=raysampler, raymarcher=raymarcher,
)
  1. Next, we define a VolumeModel class. This class is just for encapsulating a volume so that the gradients can be computed in the forward function and the volume densities and colors can be updated by the optimizer:
class VolumeModel(torch.nn.Module):
def __init__(self, renderer, volume_size=[64] * 3, voxel_size=0.1):
super().__init__()
self.log_densities = torch.nn.Parameter(-4.0 * torch.ones(1, *volume_size))
self.log_colors = torch.nn.Parameter(torch.zeros(3, *volume_size))
self._voxel_size = voxel_size
self._renderer = renderer
def forward(self, cameras):
batch_size = cameras.R.shape[0]
densities = torch.sigmoid(self.log_densities)
colors = torch.sigmoid(self.log_colors)
volumes = Volumes(
densities=densities[None].expand(
batch_size, *self.log_densities.shape),
features=colors[None].expand(
batch_size, *self.log_colors.shape),
voxel_size=self._voxel_size,
)
return self._renderer(cameras=cameras, volumes=volumes)[0]
  1. Define a Huber loss function. The Huber loss function is a robust loss function to prevent a small number of outliers from dragging the optimization away from the true optimal solutions. Minimizing this loss function will move x closer to y:
def huber(x, y, scaling=0.1):
diff_sq = (x - y) ** 2
loss = ((1 + diff_sq / (scaling ** 2)).clamp(1e-4).sqrt() - 1) * float(scaling)
return loss
  1. Move everything to the right device:
target_cameras = target_cameras.to(device)
target_images = target_images.to(device)
target_silhouettes = target_silhouettes.to(device)
  1. Define an instance of VolumeModel:
volume_size = 128
volume_model = VolumeModel(
renderer,
volume_size=[volume_size] * 3,
voxel_size=volume_extent_world / volume_size,
).to(device)
  1. Now let’s set up the optimizer. The learning rate, lr, is set to 0.1. We use an Adam optimizer, and the number of optimization iterations will be 300:
lr = 0.1
optimizer = torch.optim.Adam(volume_model.parameters(), lr=lr)
batch_size = 10
n_iter = 300
  1. Next, we have the main optimization loop. The densities and colors of the volume are rendered, and the resulting colors and silhouettes are compared with the observed multi-view images. The Huber loss between the rendered images and observed ground-truth images is minimized:
for iteration in range(n_iter):
if iteration == round(n_iter * 0.75):
print('Decreasing LR 10-fold ...')
optimizer = torch.optim.Adam(
volume_model.parameters(), lr=lr * 0.1
)
optimizer.zero_grad()
batch_idx = torch.randperm(len(target_cameras))[:batch_size]
# Sample the minibatch of cameras.
batch_cameras = FoVPerspectiveCameras(
R=target_cameras.R[batch_idx],
T=target_cameras.T[batch_idx],
znear=target_cameras.znear[batch_idx],
zfar=target_cameras.zfar[batch_idx],
aspect_ratio=target_cameras.aspect_ratio[batch_idx],
fov=target_cameras.fov[batch_idx],
device=device,
)
rendered_images, rendered_silhouettes = volume_model(
batch_cameras
).split([3, 1], dim=-1)
sil_err = huber(
rendered_silhouettes[..., 0], target_silhouettes[batch_idx],
).abs().mean()
color_err = huber(
rendered_images, target_images[batch_idx],
).abs().mean()
loss = color_err + sil_err
loss.backward()
optimizer.step()
  1. After the optimization is finished, we take the final resulting volumetric model and render images from new angles:
with torch.no_grad():
rotating_volume_frames = ge erate_rotating_volume(volume_model, n_frames=7 * 4)
image_grid(rotating_volume_frames.clamp(0., 1. .cpu().numpy(), rows=4, cols=7, rgb=True, fill=True)
plt.savefig('rotating_volume.png')
plt.show()
  1. Finally, the rendered new images are shown in Figure 5.2:

Figure 5.2: Rendered images from the fitted 3D model

By now, we have an overview of some of the main concepts in differentiable volumetric rendering. We have also learned a concrete example of using differentiable volumetric rendering for reconstructing 3D models from multiview images. You should be able to master the skills already and be able to use the technique for your own problems.

In this chapter, we started with a high-level description of differentiable volumetric rendering. We then dived deep into several important concepts of differentiable volumetric rendering, including ray sampling, volume sampling, and the ray marcher, but only by explanations and coding examples. We walked through a coding example of using differentiable volumetric rendering for reconstructing 3D models from multi-view images. Using volumes for 3D deep learning has become an interesting direction in recent years. As many innovative ideas come out following this direction, many breakthroughs are emerging. One of the breakthroughs, called Neural Radiance Fields (NeRF), will be the topic of our next chapter.