Neural 3D representations: depth, NeRF and Gaussian splatting
Compare classical 3D representations and monocular depth, derive differentiable NeRF volume rendering and Fourier features, and study Gaussian splatting and feedforward reconstruction.
After this lesson you can
- Compare voxels, meshes, SDFs, point clouds and implicit fields by memory, precision and differentiability.
- Derive discrete volume rendering and its relationship to alpha compositing.
- Implement a small NeRF with Fourier features and hierarchical sampling and train it on a local GPU.
- Explain 3D Gaussian projection and composition and their rendering speed.
- Use a pretrained depth or point-map estimator and evaluate scale errors.
Before you start
What geometry does a robot need?
A “cup” label does not indicate where its surface is or whether a grasp will collide with it. 3D representations retain different information: a point cloud is easy to obtain but leaves gaps; a mesh connects vertices and facilitates intersections, though its topology can be hard to update. A regular voxel grid allows local queries, but dense memory grows with the cube of resolution. A signed distance function (SDF) describes a surface as a zero level set and assigns a sign to each side; that convention requires defining inside and outside. An implicit field evaluates a continuous function at coordinates, but recovering or rendering a surface requires additional queries.
No representation automatically turns incomplete observations into safe geometry. Occlusion and reflective surfaces produce uncertainty; manipulation requires calibration, scale, dynamics, and collisions, not just the appearance of one view. In a digital twin, a visual reconstruction can serve as texture or scenery, but does not by itself provide masses, friction, or physical guarantees.
A cloud stores observed samples without specifying whether the space between them is occupied. A closed mesh can represent that boundary, but reconstructing connections between noisy points can create spurious surfaces. An SDF specifies distances to the surface and its gradient can give a normal where differentiable; far from observations that distance may be poorly estimated. A sparse or hierarchical grid saves memory if only a fraction of space is occupied, while a dense grid of cells per axis allocates values even for empty regions. Neural field query cost depends on the network and number of queries, not just parameter count.
One image does not fix scale
Learned monocular depth exploits visual regularities, but one image admits scenes of different sizes and distances with the same projection. A scale-invariant loss compares relative shapes without requiring metric scale: that property also prevents interpreting output directly as distance for a grasp. Some models produce relative or inverse depth with affine ambiguity; others are trained for metric depth under specific assumptions. Check the particular model and validate its domain.
The lab uses Depth Anything V2 Small, which produces relative output. We fit an affine transformation to true inverse depth in one simulated view and evaluate two others. Fitting uses simulator truth: it demonstrates supervised calibration, not autonomous conversion to meters.
From the integral to compositing
Volume rendering accumulates radiance along a ray. With constant density in an interval of length , the fraction surviving the interval is . Interaction probability there is and transmittance to its start is .
Each is an RGB color and has units inverse to the distance of . Weights sum to ; the background supplies the remaining energy. Without background, the transmitted contribution is black. An opaque interval near the camera reduces the weight of everything behind it. Discretization introduces error when density or color vary inside an interval; more samples improve the approximation at computational cost.
To see why the formula works, first consider two intervals. The first contributes ; the second receives only fraction and contributes . The remaining fraction multiplies the background. The same rule repeats for any number of intervals. Transmittance is calculated with a cumulative sum of optical thicknesses, avoiding long products; for small densities expm1 calculates more accurately than subtracting two nearly equal numbers.
NeRF and frequencies
A NeRF uses a network to query density and color at 3D positions, usually conditioning color on viewing direction. With known cameras, it compares rendered pixels to images and updates parameters by gradient. Original NeRF combines coarse and fine networks: the first estimates ray weights and a distribution based on them selects additional samples. Add a small mass to the distribution to avoid division by zero in empty rays. Discrete sample selection is not differentiated in our example; each update does differentiate compositing for chosen samples.
Fourier features apply sines and cosines of different frequencies to coordinates before the MLP. They can make high-frequency edges easier to learn than for a simple network. They can also amplify noise or make interpolation between samples difficult: frequency, scale, sampling, and capacity matter. Multiresolution hash grids are another way to encode position and accelerate queries, with collisions and memory tradeoffs; they are not part of the minimal NeRF below.
In three dimensions sample position is , where and depend on the camera. If is not unit length, a parameter increment travels physical distance : this matters because density is expressed per unit distance. Poses and calibration are fixed in the lab. If incorrect, the same structures can project to incompatible pixels across views and optimization may learn a blurry or duplicated field. Jointly adjusting poses and geometry is another problem with its own ambiguities.
Projected Gaussians and feedforward reconstruction
In Gaussian splatting each primitive has a center, 3D covariance, opacity, and direction-dependent color, often encoded with spherical harmonics. For a point in front of the camera, a local approximation projects covariance as , where transforms to the camera frame and is the projection Jacobian. Rasterization groups footprints into tiles and composites contributions ordered by depth. Ordering and visibility can change discontinuously; differentiability is local to visibility decisions.
Splitting or cloning primitives and pruning less useful Gaussians adapts the representation, but can increase memory. Primitives allow explicit editing and often fast rendering; speed and quality depend on resolution, Gaussian count, hardware, and coverage. Poorly observed views can show gaps or incorrect geometry with both NeRF and splats. A visually convincing render does not prove geometric accuracy.
The comparison uses eight training views and two held out, with random Gaussian initialization without true depth. In one run NeRF trained for 7.49 s and gsplat for 7.58 s on the same RTX 3060; PSNR calculated from combined held-out-view MSE was 23.39 and 23.20 dB respectively. Degree zero of the same Gaussians gave MSE 0.029314: this is not a network trained exclusively with degree zero, but a test omitting degree-one coefficients after training. This is a small one-scene comparison with different architectures and programs and similar times, not a general ranking. Concurrent machine load affects timings.
Feedforward reconstruction predicts geometry from images without optimizing a scene from scratch on each query. DUSt3R predicts point maps from pairs and allows alignment; MASt3R adds correspondences and VGGT jointly predicts geometric attributes from multiple views. “Feedforward” does not remove inference cost, scale ambiguity, or the need to check calibration and domain. Subsequent optimization can improve consistency; a robot must validate geometry with suitable measurements and margins.
Lab: a 2D NeRF from scratch
Scene and cameras are synthetic: five views train and one is held out. The code composites rays, checks analytic derivatives with central differences, trains an MLP in NumPy with Fourier features, and resamples according to weights. The network learns density and color constant with respect to direction; it is an educational version, not a full implementation of the paper. In Pyodide maximum density and color gradient error was below ; the held-out view reached 39.82 dB. That PSNR applies only to this simple planar scene.
import numpy as np
def composite(sigmas,colors,deltas,background=np.ones(3)):
optical=sigmas*deltas;alpha=-np.expm1(-optical)
T=np.exp(-np.cumsum(np.c_[np.zeros(len(sigmas)),optical[:,:-1]],axis=1))
weights=T*alpha;end=np.exp(-np.sum(optical,axis=1))
return np.sum(weights[:,:,None]*colors,axis=1)+end[:,None]*background,weights,T,end
def composite_grad(sigmas,colors,deltas,target,background=np.ones(3)):
rgb,w,T,end=composite(sigmas,colors,deltas,background);g=2*(rgb-target)/(3*len(rgb))
weighted=w[:,:,None]*colors
after=np.cumsum(weighted[:,::-1],axis=1)[:,::-1]-weighted+end[:,None,None]*background
Tnext=T*np.exp(-sigmas*deltas)
gs=deltas*np.sum(g[:,None,:]*(Tnext[:,:,None]*colors-after),axis=2)
gc=w[:,:,None]*g[:,None,:]
return rgb,gs,gc
def check_gradient():
rng=np.random.default_rng(1);s=rng.uniform(.1,2,(2,5));c=rng.uniform(0,1,(2,5,3));d=rng.uniform(.1,.4,(2,5));y=rng.uniform(0,1,(2,3))
_,gs,gc=composite_grad(s,c,d,y);h=1e-6;errors=[]
for arr,analytic in [(s,gs),(c,gc)]:
num=np.zeros_like(arr)
for ix in np.ndindex(arr.shape):
arr[ix]+=h;plus=np.mean((composite(s,c,d)[0]-y)**2);arr[ix]-=2*h;minus=np.mean((composite(s,c,d)[0]-y)**2);arr[ix]+=h
num[ix]=(plus-minus)/(2*h)
errors.append(float(np.max(np.abs(num-analytic))))
return errors
def scene(points):
a=points-np.array([-.22,.1]);b=points-np.array([.25,-.2])
sa=8*np.exp(-np.sum(a*a,axis=-1)/.08);sb=6*np.exp(-np.sum(b*b,axis=-1)/.06);sigma=sa+sb
ca=np.array([.9,.2,.1]);cb=np.array([.1,.3,.9]);color=(sa[...,None]*ca+sb[...,None]*cb)/(sigma[...,None]+1e-10)
return sigma,color
def rays(camera_x,pixels=24):
screen=np.linspace(-.8,.8,pixels);origin=np.tile([camera_x,-2.],(pixels,1));dirs=np.c_[screen-camera_x,np.full(pixels,2.)]
dirs/=np.linalg.norm(dirs,axis=1)[:,None];return origin,dirs
def intervals(t,far=4.):return np.diff(np.c_[t,np.full(len(t),far)],axis=1)
def encoded(x,L=4):
parts=[x]
for k in range(L):parts.extend([np.sin(2**k*np.pi*x),np.cos(2**k*np.pi*x)])
return np.concatenate(parts,axis=-1)
def evaluate(params,points):
W1,b1,W2,b2=params;feat=encoded(points);h=np.tanh(feat@W1+b1);raw=h@W2+b2
sigma=np.logaddexp(0,raw[...,0]);color=1/(1+np.exp(-np.clip(raw[...,1:],-30,30)))
return sigma,color,(feat,h,raw)
def sample_hierarchical(params,o,d,rng,coarse=20,fine=12):
edges=np.linspace(.5,4.,coarse+1);t=np.tile((edges[:-1]+edges[1:])/2,(len(o),1));deltas=intervals(t)
sigma,color,_=evaluate(params,o[:,None,:]+d[:,None,:]*t[:,:,None]);_,weights,_,_=composite(sigma,color,deltas)
pdf=(weights+1e-3);pdf/=pdf.sum(axis=1,keepdims=True);cdf=np.c_[np.zeros(len(o)),np.cumsum(pdf,axis=1)];cdf[:,-1]=1
samples=[]
for row in cdf:
u=rng.random(fine);idx=np.clip(np.searchsorted(row,u,side='right')-1,0,coarse-1)
frac=(u-row[idx])/(row[idx+1]-row[idx]);samples.append(edges[idx]+frac*(edges[idx+1]-edges[idx]))
return np.sort(np.c_[t,np.array(samples)],axis=1)
def train(seed=12,steps=450):
rng=np.random.default_rng(seed);train_o=[];train_d=[];train_y=[];test_o,test_d=rays(.15)
for pos in [-.6,-.3,0.,.3,.6]:
o,d=rays(pos);t=np.tile(np.linspace(.5,3.99,128),(len(o),1));delta=intervals(t)
sig,col=scene(o[:,None,:]+d[:,None,:]*t[:,:,None]);y=composite(sig,col,delta)[0]
train_o.extend(o);train_d.extend(d);train_y.extend(y)
o=np.array(train_o);d=np.array(train_d);y=np.array(train_y);t=np.tile(np.linspace(.5,3.99,128),(len(test_o),1));sig,col=scene(test_o[:,None,:]+test_d[:,None,:]*t[:,:,None]);test_y=composite(sig,col,intervals(t))[0]
D=encoded(np.zeros((1,2))).shape[1];params=[rng.normal(0,.2,(D,32)),np.zeros(32),rng.normal(0,.1,(32,4)),np.zeros(4)]
m=[np.zeros_like(p) for p in params];v=[np.zeros_like(p) for p in params];losses=[]
for step in range(steps):
ids=rng.choice(len(o),24,replace=False);ob=o[ids];db=d[ids];target=y[ids]
ts=sample_hierarchical(params,ob,db,rng);delta=intervals(ts);points=ob[:,None,:]+db[:,None,:]*ts[:,:,None]
sigma,color,(feat,h,raw)=evaluate(params,points);pred,gs,gc=composite_grad(sigma,color,delta,target)
ds=gs/(1+np.exp(-np.clip(raw[...,0],-30,30)));dc=gc*color*(1-color);gout=np.concatenate([ds[...,None],dc],axis=-1)
dh=gout@params[2].T*(1-h*h);grads=[np.einsum('bni,bnj->ij',feat,dh),dh.sum((0,1)),np.einsum('bni,bnj->ij',h,gout),gout.sum((0,1))]
for k,g in enumerate(grads):
m[k]=.9*m[k]+.1*g;v[k]=.999*v[k]+.001*g*g
params[k]-=.01*(m[k]/(1-.9**(step+1)))/(np.sqrt(v[k]/(1-.999**(step+1)))+1e-8)
losses.append(float(np.mean((pred-target)**2)))
tt=np.tile(np.linspace(.5,3.99,128),(len(test_o),1));sigma,color,_=evaluate(params,test_o[:,None,:]+test_d[:,None,:]*tt[:,:,None]);pred=composite(sigma,color,intervals(tt))[0]
mse=float(np.mean((pred-test_y)**2));print('gradientes sigma/color:',check_gradient())
print('pérdida lote inicial/final:',round(losses[0],5),round(losses[-1],5),'vista retenida MSE/PSNR:',round(mse,6),round(-10*np.log10(mse),2))
return params,losses,test_y,pred
train()Local lab: MuJoCo cameras and networks
We generate ten RGB images and depths with known-pose cameras. Eight views train and two are held out. NeRF uses 48 samples per ray, an MLP and 800 updates; with an RTX 3060 one run produced held-out PSNR 23.39 dB on 64×64 images and 7.49 s training. Peak PyTorch allocated memory was 53.6 MiB, excluding all process or CUDA memory. The result depends on seed, version, and hardware; it does not measure physical camera geometry.
Install NumPy, mujoco==4.0.1, PyTorch compatible with your GPU, Pillow and transformers. Rendering requires an OpenGL context. Local cells share variables when run in order; the first defines the scene for the following cells.
import numpy as np
import mujoco
def render_scene(size=64):
tiles=[]
for y in range(8):
for x in range(10):
c='.75 .75 .75 1' if (x+y)%2 else '.18 .20 .24 1'
tiles.append(f'<geom type="box" pos="{(x-4.5)*.35} {(y-3.5)*.35} -5" size=".175 .175 .005" rgba="{c}"/>')
xml=f'''<mujoco><visual><global offwidth="{size}" offheight="{size}"/></visual>
<worldbody><light pos="0 1 0" dir="0 0 -1" diffuse=".8 .8 .8" ambient=".4 .4 .4"/>
<body name="rig"><freejoint/><geom type="sphere" size=".01" mass="1" rgba="0 0 0 0"/><camera name="cam" fovy="50"/></body>
<geom type="sphere" pos="0 0 -3" size=".5" rgba=".8 .12 .08 1"/>
<geom type="box" pos="-.7 -.25 -3.8" size=".38 .38 .38" rgba=".08 .65 .25 1"/>
<geom type="box" pos=".65 .2 -4" size=".32 .45 .32" rgba=".08 .2 .75 1"/>{''.join(tiles)}</worldbody></mujoco>'''
model=mujoco.MjModel.from_xml_string(xml);data=mujoco.MjData(model);renderer=mujoco.Renderer(model,size,size)
positions=np.array([[-.45,0.,0.],[-.35,.08,0.],[-.25,-.08,0.],[-.15,.08,0.],[-.05,-.08,0.],
[.05,.08,0.],[.15,-.08,0.],[.25,.08,0.],[.35,-.08,0.],[.45,0.,0.]])
rgb=[];depth=[]
for pos in positions:
data.qpos[:3]=pos;data.qpos[3:7]=[1,0,0,0];mujoco.mj_forward(model,data)
renderer.disable_depth_rendering();renderer.update_scene(data,camera='cam');rgb.append(renderer.render().copy()/255.)
renderer.enable_depth_rendering();renderer.update_scene(data,camera='cam');depth.append(renderer.render().copy())
renderer.close();f=size/(2*np.tan(np.deg2rad(50)/2))
return np.asarray(rgb,dtype=np.float32),np.asarray(depth,dtype=np.float32),positions,f
images,depth,poses,f=render_scene()
print("RGB/profundidad:",images.shape,depth.shape,"focal:",f)npm run lab and open the connection link.import time
import numpy as np
import torch
torch.manual_seed(24);np.random.seed(24)
images,depths,positions,f=render_scene();device=torch.device('cuda' if torch.cuda.is_available() else 'cpu')
H,W=images.shape[1:3];train_ids=[0,1,2,4,5,7,8,9];test_ids=[3,6]
yy,xx=np.meshgrid(np.arange(H)+.5,np.arange(W)+.5,indexing='ij')
direction=np.stack(((xx-W/2)/f,-(yy-H/2)/f,-np.ones_like(xx)),axis=-1)
origins=np.broadcast_to(positions[:,None,None,:],(len(positions),H,W,3)).copy()
directions=np.broadcast_to(direction,(len(positions),H,W,3)).copy()
O=torch.tensor(origins,dtype=torch.float32,device=device);D=torch.tensor(directions,dtype=torch.float32,device=device);Y=torch.tensor(images,device=device)
class TinyNeRF(torch.nn.Module):
def __init__(self):
super().__init__();self.net=torch.nn.Sequential(torch.nn.Linear(3*13,64),torch.nn.ReLU(),torch.nn.Linear(64,64),torch.nn.ReLU(),torch.nn.Linear(64,64),torch.nn.ReLU(),torch.nn.Linear(64,4))
def forward(self,x):
x=x/5.;features=[x]
for k in range(6):features.extend((torch.sin((2**k)*torch.pi*x),torch.cos((2**k)*torch.pi*x)))
v=self.net(torch.cat(features,dim=-1));return torch.nn.functional.softplus(v[...,0]),torch.sigmoid(v[...,1:])
model=TinyNeRF().to(device);opt=torch.optim.Adam(model.parameters(),lr=.002)
ts=torch.linspace(1.,6.,48,device=device);step=ts[1]-ts[0]
def render(o,d):
points=o[:,None,:]+d[:,None,:]*ts[None,:,None];sigma,color=model(points)
delta=step*torch.linalg.norm(d,dim=-1,keepdim=True);optical=sigma*delta
alpha=1-torch.exp(-optical);T=torch.exp(-torch.cat([torch.zeros_like(optical[:,:1]),torch.cumsum(optical[:,:-1],dim=1)],dim=1))
return torch.sum((T*alpha)[...,None]*color,dim=1)
ot=O[train_ids].reshape(-1,3);dt=D[train_ids].reshape(-1,3);yt=Y[train_ids].reshape(-1,3)
if device.type=='cuda':torch.cuda.reset_peak_memory_stats();torch.cuda.synchronize()
start=time.perf_counter();losses=[]
for k in range(800):
ix=torch.randint(len(ot),(512,),device=device);pred=render(ot[ix],dt[ix]);loss=torch.mean((pred-yt[ix])**2)
opt.zero_grad();loss.backward();opt.step()
if k in (0,199,399,799):losses.append(float(loss.detach()))
if device.type=='cuda':torch.cuda.synchronize()
elapsed=time.perf_counter()-start
def mse(ids):
oo=O[ids].reshape(-1,3);dd=D[ids].reshape(-1,3);gt=Y[ids].reshape(-1,3);pred=[]
with torch.no_grad():
for i in range(0,len(oo),512):pred.append(render(oo[i:i+512],dd[i:i+512]))
out=torch.cat(pred);return float(torch.mean((out-gt)**2)),out.reshape(len(ids),H,W,3).cpu().numpy()
train_mse,_=mse(train_ids);test_mse,pred=mse(test_ids)
print('dispositivo:',device,'pasos:',800,'tiempo entrenamiento (s):',round(elapsed,2))
print('pérdidas de lote:',np.round(losses,6),'MSE train/test:',round(train_mse,6),round(test_mse,6),'PSNR test:',round(-10*np.log10(test_mse),2))
if device.type=='cuda':print('memoria máxima torch (MiB):',round(torch.cuda.max_memory_allocated()/1024**2,1))npm run lab and open the connection link.Local comparison with gsplat
The following test uses the open gsplat 1.5.3 CUDA rasterizer, without Gaussian splitting or pruning. On Windows it was checked in an isolated environment with Python 3.10, PyTorch 2.4.1+cu124, NumPy 1.26.4 and MuJoCo 3.17.0. The precompiled gsplat wheel matches those Python, PyTorch and CUDA versions exactly. Install PyTorch from https://download.pytorch.org/whl/cu124, NumPy below 2 and MuJoCo 3.17.0; install the official Windows wheel. A compatible CUDA GPU and OpenGL backend are required. Other systems need compatible wheels and environments; see the official index.
This cell is self-contained for copying to the Python 3.10 environment; the others were tested with Python 3.12 and MuJoCo 4.0.1. RGB images generated by both versions matched exactly on this machine. The timer measures training and synchronizes CUDA every ten steps; initial calls and shared load can change how many steps fit. Degree-one SH is used during training without claiming this configuration is optimal.
import numpy as np
import mujoco
def render_scene(size=64):
tiles=[]
for y in range(8):
for x in range(10):
c='.75 .75 .75 1' if (x+y)%2 else '.18 .20 .24 1'
tiles.append(f'<geom type="box" pos="{(x-4.5)*.35} {(y-3.5)*.35} -5" size=".175 .175 .005" rgba="{c}"/>')
xml=f'''<mujoco><visual><global offwidth="{size}" offheight="{size}"/></visual>
<worldbody><light pos="0 1 0" dir="0 0 -1" diffuse=".8 .8 .8" ambient=".4 .4 .4"/>
<body name="rig"><freejoint/><geom type="sphere" size=".01" mass="1" rgba="0 0 0 0"/><camera name="cam" fovy="50"/></body>
<geom type="sphere" pos="0 0 -3" size=".5" rgba=".8 .12 .08 1"/>
<geom type="box" pos="-.7 -.25 -3.8" size=".38 .38 .38" rgba=".08 .65 .25 1"/>
<geom type="box" pos=".65 .2 -4" size=".32 .45 .32" rgba=".08 .2 .75 1"/>{''.join(tiles)}</worldbody></mujoco>'''
model=mujoco.MjModel.from_xml_string(xml);data=mujoco.MjData(model);renderer=mujoco.Renderer(model,size,size)
positions=np.array([[-.45,0.,0.],[-.35,.08,0.],[-.25,-.08,0.],[-.15,.08,0.],[-.05,-.08,0.],
[.05,.08,0.],[.15,-.08,0.],[.25,.08,0.],[.35,-.08,0.],[.45,0.,0.]])
rgb=[];depth=[]
for pos in positions:
data.qpos[:3]=pos;data.qpos[3:7]=[1,0,0,0];mujoco.mj_forward(model,data)
renderer.disable_depth_rendering();renderer.update_scene(data,camera='cam');rgb.append(renderer.render().copy()/255.)
renderer.enable_depth_rendering();renderer.update_scene(data,camera='cam');depth.append(renderer.render().copy())
renderer.close();f=size/(2*np.tan(np.deg2rad(50)/2))
return np.asarray(rgb,dtype=np.float32),np.asarray(depth,dtype=np.float32),positions,f
import time
import numpy as np
import torch
from gsplat import rasterization
torch.manual_seed(24); np.random.seed(24)
images,depths,positions,f=render_scene();H,W=images.shape[1:3]
device=torch.device('cuda');N=1500
# Inicialización aleatoria en volumen; no se usa profundidad verdadera.
rng=np.random.default_rng(24)
initial=np.column_stack((rng.uniform(-1.8,1.8,N),rng.uniform(-1.5,1.5,N),rng.uniform(-5.1,-2,N)))
means=torch.nn.Parameter(torch.tensor(initial,dtype=torch.float32,device=device))
quats=torch.nn.Parameter(torch.tensor(np.tile([1.,0,0,0],(N,1)),dtype=torch.float32,device=device))
logs=torch.nn.Parameter(torch.full((N,3),-2.7,device=device))
opacity=torch.nn.Parameter(torch.full((N,),-1.,device=device))
sh=torch.nn.Parameter(torch.zeros((N,4,3),device=device))
views=[]
for p in positions:
V=np.eye(4);V[:3,:3]=np.diag([1,-1,-1]);V[:3,3]=-V[:3,:3]@p;views.append(V)
V=torch.tensor(np.array(views),dtype=torch.float32,device=device)
K=torch.tensor([[[f,0,W/2],[0,f,H/2],[0,0,1]]],dtype=torch.float32,device=device)
Y=torch.tensor(images,dtype=torch.float32,device=device)
train=[0,1,2,4,5,7,8,9];test=[3,6]
optimizer=torch.optim.Adam([{'params':means,'lr':.006},{'params':quats,'lr':.002},{'params':logs,'lr':.006},{'params':opacity,'lr':.01},{'params':sh,'lr':.01}])
def render(ids,degree=1):
return rasterization(means,quats,torch.exp(logs),torch.sigmoid(opacity),sh,V[ids],K.expand(len(ids),-1,-1),W,H,sh_degree=degree,packed=False)[0]
torch.cuda.synchronize();start=time.perf_counter();losses=[];step=0
while True:
idx=train[step%len(train)];pred=render([idx]);loss=((pred-Y[idx:idx+1])**2).mean()
optimizer.zero_grad();loss.backward();optimizer.step();step+=1
if step in (1,100,300):losses.append(float(loss.detach()))
if step%10==0:
torch.cuda.synchronize()
if time.perf_counter()-start>=7.49:break
torch.cuda.synchronize();elapsed=time.perf_counter()-start
with torch.no_grad():
pred0=render(test,0);pred1=render(test,1);mse0=float(((pred0-Y[test])**2).mean());mse1=float(((pred1-Y[test])**2).mean())
print('pasos:',step,'tiempo:',round(elapsed,2),'losses:',losses,'test MSE grado 0/1:',round(mse0,6),round(mse1,6),'PSNR grado 1:',round(-10*np.log10(mse1),2))npm run lab and open the connection link.The following cell downloads published weights pinned to revision 5426e4f0f36572d16453bbda7a8389317b1bef99. It fits a line between relative output and inverse metric depth in view 0; background beyond 6 m is discarded. In one CUDA run with 1824 valid pixels per view, inverse-depth RMSE was 0.02508 and 0.02896 m⁻¹ in views 3 and 6. After inverting calibrated predictions, metric RMSE was 0.3878 and 0.46742 m. Clipping inverse depth to 0.05 avoids extreme divisions; that processing and use of truth for calibration are part of the result. Training and depth cells are long and were run separately.
import numpy as np
from PIL import Image
import torch
from transformers import AutoImageProcessor, AutoModelForDepthEstimation
model_name='depth-anything/Depth-Anything-V2-Small-hf';revision='5426e4f0f36572d16453bbda7a8389317b1bef99'
images,depth,poses,f=render_scene();device=torch.device('cuda' if torch.cuda.is_available() else 'cpu')
processor=AutoImageProcessor.from_pretrained(model_name,revision=revision)
model=AutoModelForDepthEstimation.from_pretrained(model_name,revision=revision).to(device).eval()
predictions=[]
for idx in (0,3,6):
picture=Image.fromarray(np.round(images[idx]*255).astype('uint8'))
inputs=processor(images=picture,return_tensors='pt').to(device)
with torch.no_grad():out=model(**inputs).predicted_depth
pred=torch.nn.functional.interpolate(out[:,None],size=depth.shape[1:],mode='bicubic',align_corners=False)[0,0]
predictions.append(pred.cpu().numpy())
valid=(depth[0]>0)&(depth[0]<6);A=np.column_stack((predictions[0][valid],np.ones(valid.sum())))
coeff=np.linalg.lstsq(A,1/depth[0][valid],rcond=None)[0]
print('modelo:',model_name,'revisión:',revision,'dispositivo:',device)
print('calibración afín en inversa vista 0:',np.round(coeff,6),'píxeles:',int(valid.sum()))
for i,p in zip((3,6),predictions[1:]):
valid=(depth[i]>0)&(depth[i]<6);inv=coeff[0]*p[valid]+coeff[1];z=depth[i][valid]
inv_rmse=float(np.sqrt(np.mean((inv-1/z)**2)));aligned=1/np.clip(inv,.05,None)
metric_rmse=float(np.sqrt(np.mean((aligned-z)**2)))
print('vista',i,'píxeles',int(valid.sum()),'RMSE inversa (1/m)',round(inv_rmse,5),'RMSE profundidad alineada (m)',round(metric_rmse,5))npm run lab and open the connection link.Exercises
Step 1 of 3. What fraction of light passes through interval i?
import numpy as np
def composite(sigmas, colors, deltas):
passSources: NeRF, Fourier features, 3D Gaussian Splatting, Depth Anything V2, DUSt3R, MASt3R and VGGT.


