🎉 75% of content is free forever — Unlock Premium from $10/mo →
CW
NEWSLIVESearch All Content
đŸ’ŧ Servicesâ„šī¸ Aboutâœ‰ī¸ ContactView Pricing Plansfrom $10

Neural Radiance Fields: Volume Rendering and 3DGS

Computer VisionNeRF and Neural Implicit Representations for 3DđŸŸĸ Free Lesson

Neural Radiance Fields: Volume Rendering and 3DGS

Module: Computer Vision | Difficulty: Premium

Prerequisites

  • !Camera intrinsics and extrinsics
  • !How MLPs and ReLU activations behave
  • !Differentiable programming in PyTorch

What You'll Learn

  • 1Explain why a radiance field is a continuous function rather than a mesh
  • 2Implement the quadrature used by volume rendering
  • 3Diagnose positional encoding failures from artifacts
  • 4Train a small radiance field on posed captures
  • 5Decide between implicit fields and Gaussian splatting for a project

A scene stored as a function

Traditional reconstruction ends with a mesh: vertices, faces, and a texture atlas. A radiance field stores something different, a continuous mapping from a three-dimensional point and a viewing direction to a density and a colour. Points that lie in empty space return zero density; points on a surface return high density and a view-dependent colour, since glossy materials genuinely change hue with the camera.

The immediate payoff is resolution independence. Because the scene is a function sampled on demand, there is no polygon budget and no texel density to manage. Zooming in produces new detail as the network is queried at finer steps. The cost is that nothing is explicitly stored, so extracting a mesh, measuring a dimension, or editing an object requires an additional step such as marching cubes over a density grid or fitting a surface to the extracted point cloud.

View dependence is usually handled by feeding the viewing direction into a later part of the network, after the geometry has already been decided by the position-only trunk. That separation is deliberate: it prevents the model from hiding geometric errors behind view-dependent colour, and it makes the density field consistent across cameras.

Discretizing the rendering equation

Rendering a pixel means marching a ray from the camera through the scene and accumulating the colour of everything the ray hits, weighted by how opaque the material in front of it was. Formally this is an integral of transmittance times density times colour along the ray; in code it becomes a weighted sum over samples.

Two implementation choices matter. Stratified sampling across the ray during early training gives coverage; hierarchical sampling with a second network trained on the first pass concentrates samples where density is high, which is what keeps quality up at reasonable cost. And delta, the distance between consecutive samples, must be the true spacing between near and far planes, otherwise densities are mis-scaled and the network compensates by learning wrong geometry.

Positional encoding is not optional

A multilayer perceptron applied to raw coordinates behaves like a low-pass filter: it reproduces smooth functions easily and fine detail poorly. Mapping each coordinate through a family of sine and cosine frequencies before the network restores high-frequency capacity, and it is the single change that turned volume rendering from a smooth blur into a photoreal result.

The failure mode is recognizable in the renders. Too few frequencies produces waxy surfaces with no texture. Too many, combined with a learning rate that is too high, produces floaters, tiny density blobs hanging in mid-air that the optimizer placed to satisfy a few rays. Annealing the number of active frequencies from low to high over the first epochs suppresses floaters while still recovering detail, and it is the default in most maintained implementations.

Training a field from posed images

Posed images are the input, meaning every training frame comes with its camera matrix. COLMAP structure-from-motion provides those poses automatically; a calibrated turntable or a robot arm provides them exactly. The loop samples rays, predicts colour and density, and compares against the ground-truth pixel colour with mean squared error plus a distortion regularizer that discourages scattered density along a ray.

python
import torch
import torch.nn as nn
import torch.nn.functional as F


class RadianceField(nn.Module):
    def __init__(self, pos_freqs=10, dir_freqs=4, width=256):
        super().__init__()
        pos_dim = 3 + 3 * 2 * pos_freqs
        dir_dim = 3 + 3 * 2 * dir_freqs
        self.geo = nn.Sequential(
            nn.Linear(pos_dim, width), nn.ReLU(inplace=True),
            nn.Linear(width, width), nn.ReLU(inplace=True),
            nn.Linear(width, width), nn.ReLU(inplace=True),
            nn.Linear(width, width), nn.ReLU(inplace=True),
        )
        self.density = nn.Linear(width, 1)
        self.skip = nn.Linear(pos_dim + width, width)
        self.feature = nn.Linear(width, width)
        self.color = nn.Sequential(
            nn.Linear(width + dir_dim, width // 2), nn.ReLU(inplace=True),
            nn.Linear(width // 2, 3), nn.Sigmoid(),
        )

    def encode(self, xyz, freqs):
        enc = [xyz]
        for i in range(freqs):
            enc.append(torch.sin(2 ** i * torch.pi * xyz))
            enc.append(torch.cos(2 ** i * torch.pi * xyz))
        return torch.cat(enc, dim=-1)

    def forward(self, xyz, dirs):
        h = self.geo(self.encode(xyz, 10))
        h = self.skip(torch.cat([self.encode(xyz, 10), h], dim=-1))
        sigma = F.relu(self.density(h))
        feats = self.feature(h)
        rgb = self.color(torch.cat(
            [feats, self.encode(dirs, 4)], dim=-1))
        return rgb, sigma


def stratified_sample(t_near, t_far, n_samples):
    edges = torch.linspace(t_near, t_far, n_samples + 1)
    lower, upper = edges[:-1], edges[1:]
    u = torch.rand(*t_near.shape, n_samples)
    return lower + (upper - lower) * u


def volume_render(rgb, sigma, z, delta):
    alpha = 1.0 - torch.exp(-sigma[:, :-1] * delta)
    trans = torch.cumprod(
        torch.cat([torch.ones_like(alpha[:, :1]),
                   1.0 - alpha + 1e-10], dim=1), dim=1)
    weights = trans[:, :-1] * alpha
    color = (weights.unsqueeze(-1) * rgb[:, :-1]).sum(1)
    depth = (weights * z[:, :-1]).sum(1)
    return color, depth, weights.sum(-1)


model = RadianceField()
opt = torch.optim.Adam(model.parameters(), lr=5e-4)

for step in range(30000):
    origins, directions, target = sample_rays(batch_size=4096)
    z = stratified_sample(2.0, 6.0, 64).expand(len(origins), -1)
    pts = origins[:, None, :] + directions[:, None, :] * z[..., None]
    rgb, sigma = model(pts.reshape(-1, 3),
                       directions[:, None, :].expand_as(pts).reshape(-1, 3))
    rgb = rgb.reshape(len(origins), -1, 3)
    sigma = sigma.reshape(len(origins), -1)
    delta = z[:, 1:] - z[:, :-1]
    pred, _, _ = volume_render(rgb, sigma, z, delta)
    loss = F.mse_loss(pred, target)
    opt.zero_grad()
    loss.backward()
    opt.step()

Twenty to thirty thousand iterations on a few hundred views is the realistic range for a research-quality result on a single consumer GPU, measured in tens of minutes to a few hours.

Why Gaussian splatting won the speed race

Implicit fields render slowly because every pixel requires dozens of network evaluations. The alternative is to represent the scene explicitly as a cloud of anisotropic 3D Gaussians, each carrying position, covariance, opacity, and spherical-harmonic colour coefficients, then rasterize them with a differentiable tile-based renderer.

RepresentationTrain timeRender timeMemoryBest used for
Original NeRFHours to a daySeconds per frameSmallOffline, high quality
Instant-NGP with hash gridsMinutesAbout 10 msMediumInteractive editors
3D Gaussian SplattingMinutesNear real timeLargeVideo, VR, live capture
Nerfacto combined modelMinutesAbout 10 msMediumGeneral purpose tools

Adaptive density control is what makes splatting converge quickly. Gaussians that consistently under-reconstruct split into smaller ones, Gaussians in flat regions clone along their principal direction, and those with opacity near zero are pruned. The result adapts capacity to geometric complexity automatically, which is the same goal the hash grid serves for implicit methods. The trade is memory: a million Gaussians with third-order spherical harmonics is hundreds of megabytes, and streaming or compression becomes necessary for delivery on the web.

python
import torch


@torch.no_grad()
def adaptive_density_control(means, scales, opacity, grads,
                             opa_thresh=0.005, scale_thresh=0.01):
    """Prune dead Gaussians, then clone or split the under-reconstructed ones."""
    alive = opacity.squeeze(-1) > opa_thresh
    means, scales, opacity, grads = (
        means[alive], scales[alive], opacity[alive], grads[alive])

    grad_norm = grads.norm(dim=-1, keepdim=True)
    grad_mean = grad_norm.mean().clamp_min(1e-8)
    split_mask = (scales.max(dim=-1).values > scale_thresh) & \
                 (grad_norm > grad_mean)
    clone_mask = ~split_mask & (grad_norm >= grad_mean)

    new_means = means.clone()
    new_scales = scales.clone()

    if clone_mask.any():
        offsets = torch.randn_like(means[clone_mask]) * scales[clone_mask]
        new_means = torch.cat([new_means, means[clone_mask] + offsets])
        new_scales = torch.cat([new_scales, scales[clone_mask]])

    if split_mask.any():
        big = means[split_mask]
        big_scales = scales[split_mask]
        eps = torch.randn_like(big) * big_scales
        new_means = torch.cat([new_means, big + eps, big - eps])
        shrunk = big_scales / 1.6
        new_scales = torch.cat([new_scales, shrunk, shrunk])

    new_opacity = opacity.repeat(1, 1).view(-1, 1) \
        if new_means.shape[0] != opacity.shape[0] else opacity
    return new_means, new_scales, new_opacity

Running this control step every few hundred iterations keeps the cloud sized to the actual scene complexity; running it every iteration tends to thrash the optimizer and produce a cloud that never settles.

Capture discipline decides the outcome

No method recovers information the capture never contained. Overlap between neighbouring views should exceed sixty percent, which usually means walking a slow orbit at roughly ten-degree steps rather than a few wide snaps. Lock white balance and exposure, because per-frame auto exposure shows up as view-dependent colour that the model faithfully learns as floaters. Avoid rolling shutter on fast motion, and prefer raw or high-quality video over heavily compressed streams, since compression artifacts are reconstructed as geometry.

Depth range discipline matters just as much as colour. Tighten the near and far planes around the object rather than using a generous default, because samples spent on empty space are samples not spent on the surface, and loose bounds are a common cause of hazy density around the subject. If your capture includes a moving element, such as a person walking through the frame, mask those views out during training; otherwise the model averages two incompatible geometries into a translucent smear.

Validation during capture is cheap and worth doing on site. Reconstruct a quick preview and render a held-out camera path; if the preview already shows blur in a corner, that corner was under-observed and more footage there is cheaper now than a reshoot later. Finally, decide your background early. Fields trained on white backgrounds render a halo when composited over anything else, and fields with an unobserved region behind the object will hallucinate density there.

Common Mistakes

Training on images with automatic exposure and per-frame color correction

Fix: Lock exposure, white balance and focus for the entire capture so colour variation is real, not an artifact

Leaving positional encoding frequencies at maximum from the first iteration

Fix: Anneal active frequencies from low to high over the opening epochs to suppress floaters

Judging quality on training views only

Fix: Hold out several cameras and render the novel view path, since that is the only honest test of reconstruction

Choosing implicit fields for a real-time web deliverable by default

Fix: Measure the budget; splatting or hash-grid methods are usually the only ones that fit real-time constraints

Best Practices

  • Capture with a turntable or a steady orbit and verify overlap before leaving the site
  • Use hierarchical sampling after the coarse pass so sample budget follows density
  • Report held-out PSNR and SSIM together with training-view numbers
  • Profile memory for splatting scenes early, since million-Gaussian clouds need compression for shipping
  • Keep the near and far plane bounds tight to the object to reduce wasted samples and floaters

Interview Questions

Q1: Why does volume rendering use transmittance rather than simple averaging of sampled colours?

Because samples in front occlude samples behind. Transmittance accumulates how much light survived to each sample, so opaque regions correctly dominate the pixel and empty space contributes nothing.

Q2: What problem does positional encoding solve, and what artifact indicates too many frequencies?

MLPs are biased toward smooth functions, and encoding coordinates into sine and cosine bands restores high-frequency detail. Too many active frequencies early in training produces floating density blobs that the optimizer uses to explain individual rays.

Q3: How does 3D Gaussian Splatting achieve real-time rendering?

It replaces per-pixel network queries with an explicit cloud of anisotropic Gaussians that can be sorted and rasterized with a tile-based differentiable renderer, trading memory for a several-thousand-fold speedup in per-frame cost.

Q4: What capture mistakes most often ruin a reconstruction?

Auto exposure and white balance, low overlap between views, motion blur, and heavy compression. Each of these becomes a learned artifact that no amount of training iterations can remove.

Key Takeaways

  • A radiance field is a continuous function from point and direction to density and colour, not a mesh
  • Volume rendering accumulates colour with transmittance weights along each ray
  • Positional encoding is required for detail, and frequency annealing is required to avoid floaters
  • Posed images come from structure-from-motion or a calibrated rig; pose quality caps reconstruction quality
  • Hash grids and Gaussian splatting cut training and rendering time by orders of magnitude
  • Splatting trades memory for speed, so compression matters for delivery
  • Capture discipline, especially locked exposure and dense overlap, decides the final result more than architecture does
CW

ChatWhole Learn Editorial Team

Written by experienced data scientists, software engineers, and educators. All content is reviewed by industry professionals to ensure accuracy and relevance.

Last reviewed: 2026-10-13

—
☆☆☆☆☆
0 ratings

Rate & Feedback

Continue Learning

Suggested next tutorials based on this topic

Need Expert Computer Vision Help?

Get personalized tutoring, project support, or professional consulting.

Advertisement