Skip to main content
Open In Colab In Images and Geometry a small network fθ(x,y)f_\theta(x, y) stored an image: you asked it for a coordinate and it returned an intensity. A neural radiance field (NeRF) applies the same idea to a whole scene. The network takes a 3D point and a viewing direction and returns a color and a density. A renderer turns these into pixels. You fit the network until its renderings match a set of photos taken from known camera poses. This section follows Chapter 45, Radiance Fields, of Foundations of Computer Vision by Torralba, Isola and Freeman, and the original paper by Mildenhall et al. (Mildenhall2020-bc). You build every part in PyTorch:
  1. the volume rendering sum that turns densities and colors along a ray into a pixel color,
  2. the positional encoding that lets a small network represent fine detail,
  3. hierarchical sampling, which spends network evaluations where the ray actually stops,
  4. a fitted field for the Mip-NeRF 360 garden scene, with camera poses from Structure from Motion.
The same scene, image size and test views appear in Gaussian Splatting, so you can compare the two methods number for number.

From the plenoptic function to a radiance field

The plenoptic function records the light that travels through every point of space in every direction. Chapter 1 of the book sets it aside because it is too large to measure. A radiance field is a version of it that you can fit. It assigns to each point x=(X,Y,Z)\mathbf{x} = (X, Y, Z) and viewing direction d\mathbf{d} two quantities: Fθ(x,d)=(c,σ).F_\theta(\mathbf{x}, \mathbf{d}) = (\mathbf{c}, \sigma). The color c=(r,g,b)\mathbf{c} = (r, g, b) is the light that the point sends toward direction d\mathbf{d}. It depends on the direction, so a shiny surface can look different from different sides. The density σ≥0\sigma \ge 0 measures how much matter sits at x\mathbf{x}. It depends only on the point, because a surface is either there or not, whichever way you look at it. A NeRF stores FθF_\theta as a multilayer perceptron. Like the SIREN image, the network has no grid. You can query it at any point, and the network weights θ\theta are the scene.

Volume rendering

A camera pixel looks along a ray r(t)=o+t d\mathbf{r}(t) = \mathbf{o} + t\,\mathbf{d} that leaves the camera center o\mathbf{o}. Think of the density as the rate at which the ray hits a particle: over a short step dtdt the chance of a hit is σ(r(t)) dt\sigma(\mathbf{r}(t))\,dt. Let T(t)T(t) be the probability that the ray travels from the near bound tnt_n to tt without a hit. It falls at a rate set by the density, dTdt=−σ(r(t)) T(t),T(t)=exp⁡ ⁣(−∫tntσ(r(s)) ds).\frac{dT}{dt} = -\sigma(\mathbf{r}(t))\,T(t), \qquad T(t) = \exp\!\Big(-\int_{t_n}^{t} \sigma(\mathbf{r}(s))\,ds\Big). TT is called the transmittance. The ray stops in [t,t+dt][t, t + dt] with probability T(t) σ(r(t)) dtT(t)\,\sigma(\mathbf{r}(t))\,dt: it must survive up to tt and then hit something. The pixel color is the color at the stopping point, averaged over that distribution: C(r)=∫tntfT(t) σ(r(t)) c(r(t),d) dt.C(\mathbf{r}) = \int_{t_n}^{t_f} T(t)\,\sigma(\mathbf{r}(t))\,\mathbf{c}(\mathbf{r}(t), \mathbf{d})\,dt. To compute the integral, split the ray at sample points t1<⋯<tNt_1 < \dots < t_N with gaps δi=ti+1−ti\delta_i = t_{i+1} - t_i, and assume σ\sigma and c\mathbf{c} are constant on each gap. The integral of TσT\sigma over gap ii is then exact, and the color becomes a weighted sum: αi=1−e−σiδi,Ti=∏j<i(1−αj),wi=Ti αi,C^(r)=∑i=1Nwi ci.\begin{aligned} \alpha_i &= 1 - e^{-\sigma_i \delta_i}, \\ T_i &= \textstyle\prod_{j<i} (1 - \alpha_j), \\ w_i &= T_i\,\alpha_i, \\ \hat C(\mathbf{r}) &= \textstyle\sum_{i=1}^{N} w_i\,\mathbf{c}_i . \end{aligned} αi\alpha_i is the probability that the ray stops inside gap ii given that it reached it, and wiw_i is the probability that it stops there at all. The weights sum to 1−TN+1≤11 - T_{N+1} \le 1. They are a probability distribution over where the ray stops, plus the leftover chance that it passes through everything. The same weights give an expected depth, ∑iwiti\sum_i w_i t_i. The cell below draws one ray through a density with two bumps: a faint haze near t=2t = 2 and a solid surface near t=4t = 4.
Output from cell 3 The haze lowers the transmittance from 1 to about 0.6, so about 40% of the rays stop there and take the haze’s color. The rest reach the surface and stop within about a tenth of a unit, because its density is large. The stopping density has one small, wide bump and one tall, narrow spike. A pixel on this ray mixes the two colors in that proportion.

Positional encoding

A plain MLP fed with raw coordinates learns smooth functions first and fine detail very slowly. NeRF passes each coordinate pp through a fixed map before the network, γ(p)=(sin⁡(20πp),cos⁡(20πp),…,sin⁡(2L−1πp),cos⁡(2L−1πp)),\gamma(p) = \big(\sin(2^0 \pi p), \cos(2^0 \pi p), \dots, \sin(2^{L-1} \pi p), \cos(2^{L-1} \pi p)\big), with L=10L = 10 for positions and L=4L = 4 for directions. The book links this to the positional encodings of transformers. The purpose here is different: the high-frequency sines let the network build sharp changes from a few combinations of its inputs. Tancik et al. analyze this effect (Tancik2020-hy). The experiment fits the same network to a 1D signal made of a slow sine, a square wave with 12 periods and a fast sine with 30 periods. It fits once on the raw coordinate and once on γ(p)\gamma(p) with L=8L = 8.
Output from cell 5 The network on raw coordinates finds the slow sine but rounds off the steps and misses the fast sine. With the encoding, the same network, optimizer and number of steps reproduce both. A NeRF with raw coordinates renders the garden as a blur for the same reason.

Hierarchical sampling

The weights show that a ray only needs samples near where it stops. Evenly spaced samples waste most network evaluations on empty air or on space hidden behind the first surface. NeRF therefore samples each ray twice:
  1. A coarse network is evaluated at NcN_c points spread evenly with a random jitter (stratified sampling). Its weights wiw_i give a rough picture of where the ray stops.
  2. The normalized weights w^i=wi/∑jwj\hat w_i = w_i / \sum_j w_j define a piecewise-constant probability density along the ray. NfN_f more points are drawn from it by inverse transform sampling: draw u∼U[0,1]u \sim \mathcal{U}[0, 1], find the bin where the cumulative distribution crosses uu, and interpolate linearly inside that bin.
  3. A fine network is evaluated at all Nc+NfN_c + N_f points, sorted, and the volume rendering sum gives the final color.
Both networks are trained, each against the pixel colors, so that the coarse weights stay a good guide. The paper uses Nc=64N_c = 64 and Nf=128N_f = 128. The paper also points out a difference from textbook importance sampling. The fine points are not reweighted by 1/w^i1/\hat w_i. They only form a denser, uneven set of sample points for the same rendering sum. The figure runs both stages on the toy ray with 16 coarse points and 64 fine points.
Output from cell 7 The coarse pass sees the surface in one bin and the haze in a few. The fine samples pile up in those bins, mostly at the surface, and almost none land in the empty space before the haze or behind the surface. With 80 points in total, most of them sit where the weights are large.

The garden scene

The real scene is garden from the Mip-NeRF 360 dataset: 185 photos of a table in a garden, taken while walking around it. The dataset ships with the output of COLMAP, the structure-from-motion program that Structure from Motion explains. COLMAP writes three binary files, described in Structure from Motion at Scale. cameras.bin holds the intrinsics. images.bin holds one pose per photo. points3D.bin holds the sparse point cloud. You use the copy of the photos reduced 8 times and then halve them again, to 324×210324 \times 210 pixels, so that a NeRF trains in minutes. Every 8th photo (sorted by name) is held out for testing. Gaussian Splatting uses exactly the same images and split.
COLMAP stores each pose as world-to-camera: a point X\mathbf{X} in world coordinates lands at RX+tR\mathbf{X} + \mathbf{t} in camera coordinates, with xx to the right, yy down and zz forward. The camera center in the world is therefore o=−R⊤t\mathbf{o} = -R^\top \mathbf{t}. A pixel (u,v)(u, v), measured to the pixel center, looks along d∝R⊤((u+12−cx)/fx(v+12−cy)/fy1),\mathbf{d} \propto R^\top \begin{pmatrix} (u + \tfrac12 - c_x)/f_x \\ (v + \tfrac12 - c_y)/f_y \\ 1 \end{pmatrix}, which inverts the pinhole projection of Stereo Vision. Downscaling an image by a factor ss scales fx,fy,cx,cyf_x, f_y, c_x, c_y by ss. The scene has no fixed scale, so you choose one. Here the world is shifted so that the mean camera center is the origin and scaled so that the farthest camera sits at distance 1. The table and everything near it then lie inside the unit ball.
Output from cell 11

An unbounded scene

The photos also show trees and a house far behind the table. Their distance has no useful upper limit, so evenly spaced samples along [tn,tf][t_n, t_f] cannot cover both the table and the background. Mip-NeRF 360 (Barron2021-nb) solves this with a contraction that maps all of space into a ball of radius 2: contract⁡(x)={x,∥x∥≤1,(2−1∥x∥)x∥x∥,∥x∥>1.\operatorname{contract}(\mathbf{x}) = \begin{cases} \mathbf{x}, & \lVert\mathbf{x}\rVert \le 1,\\[2pt] \Big(2 - \dfrac{1}{\lVert\mathbf{x}\rVert}\Big)\dfrac{\mathbf{x}}{\lVert\mathbf{x}\rVert}, & \lVert\mathbf{x}\rVert > 1 . \end{cases} Inside the unit ball nothing changes. Outside, a point at distance rr moves to distance 2−1/r2 - 1/r, so the whole region from the unit sphere to infinity fits in the shell between radius 1 and 2. The network sees only contracted points. Along each ray you place half the coarse samples evenly in distance up to the unit sphere, and the other half evenly in disparity 1/t1/t from the sphere out to t=1000t = 1000. Samples evenly spaced in disparity land roughly evenly spaced in the contracted shell, so the network spends about as much effort on the background as on the table. In code, the samples live in a coordinate s∈[0,1]s \in [0, 1]. The first half of ss maps linearly to distance and the second half maps linearly to disparity. Hierarchical sampling also works in ss.

Fitting the field

The field network follows the paper’s layout at a smaller size for the coarse pass. Positions are contracted, divided by 2 so they lie in [−1,1][-1, 1], and encoded with L=10L = 10. The position MLP has a skip connection that feeds the encoding in again halfway. Its last layer gives the density and a feature vector. The color head takes the feature vector and the encoded direction (L=4L = 4), so only the color can depend on the direction. A softplus keeps the density non-negative, and a sigmoid keeps the color in [0,1][0, 1]. The loss is the paper’s squared error on both renderings for a batch R\mathcal{R} of random rays drawn from all training photos: L=∑r∈R∥C^c(r)−C(r)∥2+∥C^f(r)−C(r)∥2.\mathcal{L} = \sum_{\mathbf{r} \in \mathcal{R}} \big\lVert \hat C_c(\mathbf{r}) - C(\mathbf{r}) \big\rVert^2 + \big\lVert \hat C_f(\mathbf{r}) - C(\mathbf{r}) \big\rVert^2 . Each step uses 4096 rays, Nc=64N_c = 64 and Nf=128N_f = 128, and Adam with a learning rate that decays from 5×10−45 \times 10^{-4} to 5×10−55 \times 10^{-5}, as in the paper. Quality is measured by the peak signal-to-noise ratio, PSNR=−10log⁡10MSE\mathrm{PSNR} = -10 \log_{10} \mathrm{MSE} for colors in [0,1][0, 1]. Higher is better, and each 1 dB is about a 21% smaller squared error.
Output from cell 15

Rendering the test views

To render a full image you cast one ray per pixel, with no jitter: the coarse points sit at bin centers and the fine points at evenly spaced values of uu. The expected distance ∑iwiti\sum_i w_i t_i from the fine weights gives a depth map at no extra cost. The figure shows it as disparity, 1/depth1/\text{depth}, so that near objects are bright and the far background is dark.
Output from cell 17 Output from cell 18 The network never saw the held-out photos. It renders them from a field fitted to the other 161, which means it has recovered geometry that agrees across views, not 161 separate pictures. The disparity map separates the table top, its legs, the vase and the ground, although no depth was ever given to the network. The mean test score is the number printed above, about 24 dB. The weakest views look past the table toward the house and the trees. There the distant background fills much of the frame, and the contraction squeezes it into a thin shell, so the field resolves it only coarsely. Fine texture such as the joints between the paving stones and the leaves is softer than in the photos, because this run stops at 12,000 steps while the paper trains for 100,000 to 300,000.

What a radiance field cannot do

A NeRF is fitted to one scene. It holds no knowledge that carries over to a new set of photos, and every new scene starts from random weights. It also depends on the camera poses: if structure from motion gets a pose wrong, the field blurs the content of that photo across space. Rendering is slow. Each pixel costs 192 network evaluations here, which is why one small test image takes the render time printed with the test score. Faster versions replace most of the network with lookup tables, such as the hash grid of Instant-NGP (Müller et al., 2022). The field also has no notion of light sources. Volume rendering lets light leave a point and reach the camera in a straight line, with no bounces. The book makes this point with the rendering equation: shadows, reflections and highlights become part of the fitted color, so you cannot move a light or change a material without fitting again. Gaussian Splatting keeps the rendering weights wi=Tiαiw_i = T_i \alpha_i from this section but replaces the network with millions of explicit 3D Gaussians that start at the sparse COLMAP points (Kerbl et al., 2023). Rendering then needs no network evaluations at all, and it runs in real time.

References

  • Kerbl, B., Kopanas, G., Leimkühler, T., Drettakis, G. (2023). 3D Gaussian splatting for real-time radiance Field rendering. arXiv [cs.GR]. Link
  • Müller, T., Evans, A., Schied, C., Keller, A. (2022). Instant neural graphics primitives with a multiresolution hash encoding. arXiv [cs.CV]. DOI

Found an error on this page? Report an issue.