Training a Noise2Noise Denoiser for Depth-Map Speckle with Synthetic Coded Illumination
Written by
Nova Neural
Why I ended up here
I was debugging a depth camera pipeline and got stuck on a very specific failure mode: the depth map looked fine at a distance but had this annoying “speckle” pattern near edges—like salt-and-pepper noise that didn’t average out nicely. Traditional smoothing blurred edges, but the real problem was that the noise was signal-dependent (its structure changed with the surface).
What finally worked for me was a Deep Learning approach in the Noise2Noise family: instead of trying to learn from a single noisy image, I trained the model using pairs of independently noisy versions of the same underlying clean signal. In my case, I couldn’t capture perfect ground truth, so I generated synthetic training pairs by simulating coded illumination and its speckle-like depth measurement artifacts.
Below is the exact setup I built: a small PyTorch denoiser that learns to remove depth speckle without needing clean depth maps.
The core idea (the part I had to re-learn)
Noise2Noise is a training strategy for denoising when you don’t have clean targets. You feed the network:
- input: a noisy observation of the signal
- target: a different noisy observation of the same underlying signal
If the two observations share the same underlying “truth” but have independent noise, the network can learn the underlying structure.
Key term, briefly:
- Denoiser: a neural network that maps noisy images to cleaner-looking images.
- Independent noise: two noisy measurements that don’t share the same error pattern.
In my simulation, I treated coded illumination as a way to make the speckle pattern vary stochastically from one measurement to the next.
What I built: a synthetic depth speckle generator
I generate a “clean” depth map by drawing random geometric shapes (circles + rectangles), then simulate two independent coded-illumination measurements. Each measurement produces a noisy depth observation with:
- multiplicative speckle (depth-dependent noise)
- quantization-like noise
- small correlated texture to make it less trivial (but still different per measurement)
Step 1: dataset that yields two noisy views
import math import random import numpy as np import torch from torch.utils.data import Dataset, DataLoader def make_clean_depth(h=64, w=64, seed=None): rng = np.random.default_rng(seed) depth = np.zeros((h, w), dtype=np.float32) + 0.1 # Add random circles for _ in range(rng.integers(3, 7)): cy = rng.integers(0, h) cx = rng.integers(0, w) r = rng.integers(h // 8, h // 3) yy, xx = np.ogrid[:h, :w] mask = (yy - cy) ** 2 + (xx - cx) ** 2 <= r ** 2 val = float(rng.uniform(0.3, 1.2)) depth[mask] = val # Add random rectangles for _ in range(rng.integers(2, 5)): y0 = rng.integers(0, h - 8) x0 = rng.integers(0, w - 8) hh = rng.integers(6, h // 2) ww = rng.integers(6, w // 2) y1 = min(h, y0 + hh) x1 = min(w, x0 + ww) val = float(rng.uniform(0.2, 1.5)) depth[y0:y1, x0:x1] = val # Smooth edges slightly (makes the denoising task realistic) k = 3 pad = k // 2 padded = np.pad(depth, pad_width=pad, mode='reflect') out = np.zeros_like(depth) for y in range(h): for x in range(w): window = padded[y:y+k, x:x+k] out[y, x] = window.mean() return out def coded_speckle_noise(depth, rng, strength=0.15): """ depth: (H, W) clean-ish depth in meters-ish (arbitrary scale) rng: numpy RNG """ h, w = depth.shape # Coded illumination patterns: pretend we sample with a random code, # leading to speckle whose variance depends on depth. # Speckle: multiplicative + a bit of additive quantization-ish noise. depth_scale = 1.0 + 0.6 * depth # noise increases with depth sigma_mult = strength * depth_scale # Multiplicative speckle noise speckle = rng.normal(loc=1.0, scale=sigma_mult, size=(h, w)).astype(np.float32) # Additive noise (like quantization + sensor readout) sigma_add = strength * 0.5 additive = rng.normal(loc=0.0, scale=sigma_add, size=(h, w)).astype(np.float32) # Small correlated texture using low-frequency random field # (still independent per measurement) grid = rng.normal(0.0, 1.0, size=(h // 8 + 2, w // 8 + 2)).astype(np.float32) texture = np.kron(grid, np.ones((8, 8), dtype=np.float32))[:h, :w] texture = (texture - texture.mean()) / (texture.std() + 1e-6) texture = 0.03 * strength * texture noisy = depth * speckle + additive + texture * depth # Clamp to valid range for depth noisy = np.clip(noisy, 0.0, 2.0) return noisy class DepthNoise2NoiseDataset(Dataset): def __init__(self, n_samples=2000, h=64, w=64, strength=0.15, seed=0): self.n_samples = n_samples self.h = h self.w = w self.strength = strength self.base_seed = seed def __len__(self): return self.n_samples def __getitem__(self, idx): # Create a clean depth map (shared for both noisy views) seed = self.base_seed + idx rng_clean = np.random.default_rng(seed) clean = make_clean_depth(self.h, self.w, seed=rng_clean.integers(0, 1_000_000)) # Two independent measurements (independent noise realizations) rng1 = np.random.default_rng(seed + 10_000) rng2 = np.random.default_rng(seed + 20_000) noisy1 = coded_speckle_noise(clean, rng1, strength=self.strength) noisy2 = coded_speckle_noise(clean, rng2, strength=self.strength) # Normalize for stability: put depth roughly into [-1, 1] # (In real training you’d match your sensor’s scaling.) def norm(x): return (x - 0.5) / 0.8 x = norm(noisy1)[None, ...].astype(np.float32) # (1, H, W) y = norm(noisy2)[None, ...].astype(np.float32) return torch.from_numpy(x), torch.from_numpy(y)
What happens when this runs?
- For each sample, it creates one clean synthetic depth map.
- It generates two different noisy observations of that same map.
- The dataset returns
(noisy_view_1, noisy_view_2).
That’s exactly the “Noise2Noise” training contract.
The model: a small UNet-style denoiser
I used a tiny UNet because it’s good at preserving edges while removing structured noise. The network takes a single-channel depth image and outputs a denoised single-channel image.
Step 2: define the UNet
import torch.nn as nn import torch.nn.functional as F class ConvBlock(nn.Module): def __init__(self, in_ch, out_ch): super().__init__() self.net = nn.Sequential( nn.Conv2d(in_ch, out_ch, 3, padding=1), nn.ReLU(inplace=True), nn.Conv2d(out_ch, out_ch, 3, padding=1), nn.ReLU(inplace=True), ) def forward(self, x): return self.net(x) class TinyUNet(nn.Module): def __init__(self, in_ch=1, base=32): super().__init__() self.enc1 = ConvBlock(in_ch, base) self.pool1 = nn.MaxPool2d(2) self.enc2 = ConvBlock(base, base*2) self.pool2 = nn.MaxPool2d(2) self.bottleneck = ConvBlock(base*2, base*4) self.up2 = nn.ConvTranspose2d(base*4, base*2, 2, stride=2) self.dec2 = ConvBlock(base*4, base*2) self.up1 = nn.ConvTranspose2d(base*2, base, 2, stride=2) self.dec1 = ConvBlock(base*2, base) self.out = nn.Conv2d(base, 1, 1) def forward(self, x): e1 = self.enc1(x) # (B, base, H, W) p1 = self.pool1(e1) # (B, base, H/2, W/2) e2 = self.enc2(p1) # (B, base*2, H/2, W/2) p2 = self.pool2(e2) # (B, base*2, H/4, W/4) b = self.bottleneck(p2) # (B, base*4, H/4, W/4) u2 = self.up2(b) # (B, base*2, H/2, W/2) cat2 = torch.cat([u2, e2], dim=1) d2 = self.dec2(cat2) u1 = self.up1(d2) # (B, base, H, W) cat1 = torch.cat([u1, e1], dim=1) d1 = self.dec1(cat1) return self.out(d1)
Training loop: Noise2Noise loss
I trained with MSE (mean squared error) between the network output and the second noisy view. Despite it sounding odd (“target is noisy!”), this works under the independent noise assumption.
Step 3: train
import torch from torch.optim import Adam def train_noise2noise( epochs=8, batch_size=32, n_train=2000, n_val=200, h=64, w=64, strength=0.15, lr=1e-3, device=None ): device = device or ("cuda" if torch.cuda.is_available() else "cpu") train_ds = DepthNoise2NoiseDataset(n_samples=n_train, h=h, w=w, strength=strength, seed=0) val_ds = DepthNoise2NoiseDataset(n_samples=n_val, h=h, w=w, strength=strength, seed=1234) train_loader = DataLoader(train_ds, batch_size=batch_size, shuffle=True, num_workers=0) val_loader = DataLoader(val_ds, batch_size=batch_size, shuffle=False, num_workers=0) model = TinyUNet(in_ch=1, base=32).to(device) opt = Adam(model.parameters(), lr=lr) loss_fn = nn.MSELoss() for epoch in range(1, epochs + 1): model.train() train_loss = 0.0 for x, y in train_loader: x = x.to(device) y = y.to(device) pred = model(x) loss = loss_fn(pred, y) opt.zero_grad() loss.backward() opt.step() train_loss += loss.item() * x.size(0) train_loss /= len(train_loader.dataset) model.eval() val_loss = 0.0 with torch.no_grad(): for x, y in val_loader: x = x.to(device) y = y.to(device) pred = model(x) loss = loss_fn(pred, y) val_loss += loss.item() * x.size(0) val_loss /= len(val_loader.dataset) print(f"Epoch {epoch:02d} | train MSE {train_loss:.6f} | val MSE {val_loss:.6f}") return model if __name__ == "__main__": model = train_noise2noise()
What I observed when running this locally
- The training MSE drops quickly in the first couple epochs.
- Visual speckle patterns reduce noticeably even though the supervision target remains noisy.
- If I increase
strengthtoo much, the model starts to “average everything” (oversmoothing). Keeping noise independent but not overwhelming was important.
Quick sanity check: visualize one prediction
This snippet runs inference on one sample and saves images so I could compare noisy input, noisy target, and denoised output.
import os from PIL import Image def to_img(t): # t: (1, H, W) normalized ~ (x - 0.5)/0.8 x = t[0].detach().cpu().numpy() # invert normalization used in dataset x = x * 0.8 + 0.5 x = np.clip(x, 0.0, 2.0) # map to 0..255 x_u8 = (x / 2.0 * 255.0).astype(np.uint8) return Image.fromarray(x_u8) def visualize_one(model, strength=0.15, out_dir="viz", device=None): device = device or ("cuda" if torch.cuda.is_available() else "cpu") os.makedirs(out_dir, exist_ok=True) ds = DepthNoise2NoiseDataset(n_samples=1, h=64, w=64, strength=strength, seed=999) x, y = ds[0] x = x.unsqueeze(0).to(device) # (1, 1, H, W) y = y.unsqueeze(0) model.eval() with torch.no_grad(): pred = model(x).cpu()[0] # (1, H, W) x_img = to_img(x.cpu()[0]) y_img = to_img(y[0]) pred_img = to_img(pred) x_img.save(os.path.join(out_dir, "noisy_input.png")) y_img.save(os.path.join(out_dir, "noisy_target.png")) pred_img.save(os.path.join(out_dir, "denoised_output.png")) print("Saved images to:", out_dir) # Example usage after training: # visualize_one(model)
Practical lessons I learned the hard way
1) Independence matters more than you’d think
If the two noisy views share too much structure (e.g., same speckle realization), the network can’t distinguish noise from signal. I made sure my simulated “coded illumination” produced different speckle fields for view 1 and view 2.
2) Loss choice changes the “look”
MSE nudged the model toward smooth averages. For depth speckle, that was acceptable, but if the goal is sharper edges, a mix like MSE + a simple gradient loss can preserve boundaries better. I kept it simple here because the simulation itself is the point.
3) UNet size is a tuning knob
A larger UNet denoised more aggressively but also started to hallucinate structure in my synthetic scenes. TinyUNet was enough to prove the concept without turning it into a memorization engine.
Where this maps to real systems
In real depth cameras, coded illumination (or structured light) gives you depth estimates whose noise often depends on depth and surface properties. The Noise2Noise trick doesn’t require clean ground truth; it requires two measurements of the same scene with sufficiently independent noise. In lab setups, that independence can come from:
- changing the illumination code
- changing exposure settings
- repeating capture while keeping geometry fixed
My simulation is a stand-in for those practical capture-time degrees of freedom.
Conclusion
I built a Noise2Noise deep denoiser for synthetic depth-map speckle by generating two independently noisy coded-illumination measurements from the same clean depth scene. Using a tiny UNet trained with MSE between the denoised output and the second noisy view, the model learned to remove structured speckle without ever seeing a clean target—exactly the kind of setup you need when real ground truth depth is expensive or unavailable.