# Pipeline (identique a 3D-01) : gamma, MLP, rayons, echantillonnage, compositing.
def gamma(p, L):
freqs = 2.0 ** torch.arange(L, device=p.device) * math.pi
angles = p[..., None] * freqs
return torch.cat([p, torch.sin(angles).flatten(-2), torch.cos(angles).flatten(-2)], dim=-1)
L_X, L_D = 10, 4
class NeRF(nn.Module):
def __init__(self, hidden=256, L_x=L_X, L_d=L_D):
super().__init__()
self.in_x, self.in_d = 3 + 2 * 3 * L_x, 3 + 2 * 3 * L_d
self.entree_x = nn.Linear(self.in_x, hidden)
self.tronc1 = nn.ModuleList([nn.Linear(hidden, hidden) for _ in range(4)])
self.saut = nn.Linear(hidden + self.in_x, hidden)
self.tronc2 = nn.ModuleList([nn.Linear(hidden, hidden) for _ in range(3)])
self.sigma = nn.Linear(hidden, 1)
self.tete_feat = nn.Linear(hidden + self.in_d, hidden // 2)
self.rgb = nn.Linear(hidden // 2, 3)
# Biais sigma positif a l'init : evite le ReLU mort du tronc profond
# (sigma = 0 partout, rendu noir, cf 3D-01). Regimes par donnees : scene
# jouet = largeur 256 (celle du papier), 2048 rayons/pas ; Lego = regime
# canonique tiny_nerf (largeur 128, 4096 rayons/pas, lr quasi plat),
# mesure stable pour L in {0, 4, 10} (cf 3D-01 section 6).
nn.init.constant_(self.sigma.bias, 0.1)
def forward(self, gx, gd):
h = torch.relu(self.entree_x(gx))
for lin in self.tronc1:
h = torch.relu(lin(h))
h = torch.relu(self.saut(torch.cat([h, gx], dim=-1)))
for lin in self.tronc2:
h = torch.relu(lin(h))
sigma = torch.relu(self.sigma(h))
h = torch.relu(self.tete_feat(torch.cat([h, gd], dim=-1)))
rgb = torch.sigmoid(self.rgb(h))
return rgb, sigma
def get_rays(H, W, focal, c2w):
i, j = torch.meshgrid(torch.arange(W, dtype=torch.float32, device=c2w.device),
torch.arange(H, dtype=torch.float32, device=c2w.device),
indexing="xy")
dirs_cam = torch.stack([(i - W / 2) / focal,
-(j - H / 2) / focal,
-torch.ones_like(i)], dim=-1)
rays_d = torch.sum(dirs_cam[..., None, :] * c2w[:3, :3], dim=-1)
rays_o = c2w[:3, -1].expand(rays_d.shape)
return rays_o.reshape(-1, 3), rays_d.reshape(-1, 3)
def sample_stratifie(rays_o, rays_d, n_samples, near, far, jitter=True):
t = torch.linspace(near, far, n_samples, device=rays_o.device)
t = t.expand(rays_o.shape[0], n_samples)
if jitter:
ecart = (far - near) / n_samples
t = t + torch.rand_like(t) * ecart
pts = rays_o[:, None, :] + rays_d[:, None, :] * t[..., None]
return pts, t
def rendu_volumique(rgb, sigma, t):
delta = t[:, 1:] - t[:, :-1]
delta = torch.cat([delta, torch.full_like(delta[:, :1], 1e9)], dim=-1)
alpha = 1.0 - torch.exp(-torch.relu(sigma[..., 0]) * delta)
poids = alpha * torch.cumprod(
torch.cat([torch.ones_like(alpha[:, :1]), 1.0 - alpha + 1e-10], dim=-1),
dim=-1)[:, :-1]
couleur = torch.sum(poids[..., None] * rgb, dim=-2)
profondeur = torch.sum(poids * t, dim=-1)
return couleur, poids, profondeur
def rendu_nerf(modele, rays_o, rays_d, n_samples, near, far, chunk=4096):
couleurs, profondeurs = [], []
for o, d in zip(rays_o.split(chunk), rays_d.split(chunk)):
pts, t = sample_stratifie(o, d, n_samples, near, far)
d_norm = torch.nn.functional.normalize(d, dim=-1)
gx = gamma(pts, modele.L_x if hasattr(modele, "L_x") else L_X)
gd = gamma(d_norm[:, None, :].expand_as(pts), L_D)
rgb, sigma = modele(gx, gd)
c, _, prof = rendu_volumique(rgb, sigma, t)
couleurs.append(c)
profondeurs.append(prof)
return torch.cat(couleurs), torch.cat(profondeurs)
def generer_image_verite(c2w, H, W, focal, n_samples=128, scene_fn=scene_jouet):
rays_o, rays_d = get_rays(H, W, focal, c2w.to(DEVICE))
pts, t = sample_stratifie(rays_o, rays_d, n_samples, NEAR, FAR)
with torch.no_grad():
sigma, rgb = scene_fn(pts[..., 0], pts[..., 1], pts[..., 2])
c, _, prof = rendu_volumique(rgb, sigma[..., None], t)
return c.reshape(H, W, 3), prof.reshape(H, W)
with torch.no_grad():
images = torch.stack([generer_image_verite(p, RES, RES, FOCAL)[0] for p in poses])
image_test, _ = generer_image_verite(pose_test, RES, RES, FOCAL)
print("dataset jouet pret :", tuple(images.shape))