Depth Estimation: Understanding 3D Space
A camera flattens the world into pixels and throws away the one dimension a moving aircraft cares about most: distance. Depth estimation restores it, converting a flat image into a per-pixel map of how far away everything sits. That map is the raw material for obstacle avoidance, terrain following, three-dimensional reconstruction, and landings on surfaces the drone has never seen before.
This lesson compares the four practical depth sensing approaches for drones, derives the stereo triangulation equation from first principles, implements disparity computation, and explains how depth errors propagate so you know which sensor to trust at which range.
Why a drone needs depth
Two categories of onboard decisions require distance. Reactive control â don't hit that tree â needs dense depth at high rate so the avoidance controller can slow or divert before contact. Geometric understanding â build a model of this facade, clear this gap â needs accurate, calibrated depth that can be fused across frames into a consistent structure.
Monocular cameras alone cannot provide either directly. Without a second view or an active probe, a single image has no scale: a close toy and a large building can produce identical pixels. Every depth technique therefore introduces scale through a baseline, a projected pattern, a measured light pulse, or motion over time.
| Method | Principle | Range | Accuracy | Outdoor use |
|---|---|---|---|---|
| Stereo vision | Triangulation from two views | 0.5â50 m | 1â3 percent of range | Yes |
| Structured light | Projected pattern deformation | 0.2â5 m | 0.1â1 mm | No â sunlight swamps pattern |
| Time of flight | Light travel time per pixel | 0.1â10 m | 1â5 cm | Partial â ambient light limits |
| LiDAR | Laser range scanning | 0.1â300 m | 1â3 cm | Yes |
The trade space is clear from the table: stereo and LiDAR survive sunlight, structured light does not, and only stereo and LiDAR reach the tens of meters that matter for flight at speed. Consumer drones overwhelmingly choose stereo â it is passive, cheap, and shares components with the mapping camera.
Stereo triangulation from first principles
Two cameras separated by a known baseline see the same point at slightly different horizontal positions. The difference between those positions â disparity â is inversely proportional to depth. Deriving the relation from similar triangles gives the equation every stereo system runs on:
depth Z = (baseline b à focal length f) / disparity d
A larger baseline resolves fine depth at range but demands a wider physical structure and richer calibration; a longer focal length does the same optically at the cost of field of view. Disparity in pixels, focal length in pixels, baseline in meters â keep the units straight and the result arrives in meters directly.
class StereoRig:
"""Depth from disparity for a rectified stereo pair."""
def __init__(self, baseline_m, focal_px, cxy=(320.0, 240.0)):
self.baseline = baseline_m
self.focal = focal_px
self.cxy = cxy
def depth_from_disparity(self, disparity_px):
"""Single-pixel depth; zero or negative disparity means invalid."""
if disparity_px is None or disparity_px <= 0:
return float("inf")
return (self.baseline * self.focal) / disparity_px
def depth_map(self, disparity):
import numpy as np
disparity = np.asarray(disparity, dtype=float)
depth = np.full_like(disparity, np.inf)
valid = disparity > 0
depth[valid] = (self.baseline * self.focal) / disparity[valid]
return depth
def points_from_depth(self, depth, u, v):
"""Back-project one pixel into camera-frame coordinates."""
z = depth
x = (u - self.cxy[0]) * z / self.focal
y = (v - self.cxy[1]) * z / self.focal
return x, y, z
rig = StereoRig(baseline_m=0.12, focal_px=640)
for d in (1, 5, 10, 20, 40, 60):
print(f"disparity {d:2d} px -> depth {rig.depth_from_disparity(d):6.2f} m")
Run the numbers and the design constraints appear: with a 12 cm baseline and 640-pixel focal length, a 60-pixel disparity corresponds to 1.3 meters while a single pixel of disparity corresponds to 77 meters â at which point one pixel of matching error swings the answer wildly. Depth error scales with the square of distance, which is why stereo is confident up close and speculative far away.
Computing disparity by block matching
Disparity is found by matching small patches between the rectified left and right images: for each pixel in the left image, slide a window along the corresponding row in the right image and keep the offset with the smallest matching cost. Sum of absolute differences is the classic cost function, and a left-to-right consistency check rejects ambiguous matches in textureless regions.
import numpy as np
def block_matching_disparity(left, right, block=7, max_disparity=64):
"""Exhaustive row-wise block matching with SAD cost."""
left = left.astype(np.int16)
right = right.astype(np.int16)
height, width = left.shape
half = block // 2
disparity = np.zeros((height, width), dtype=np.float32)
for y in range(half, height - half):
for x in range(half + max_disparity, width - half):
patch = left[y - half:y + half + 1, x - half:x + half + 1]
best_cost, best_d = float("inf"), 0
for d in range(1, max_disparity + 1):
xr = x - d
if xr - half < 0:
break
candidate = right[y - half:y + half + 1, xr - half:xr + half + 1]
cost = np.abs(patch - candidate).sum()
if cost < best_cost:
best_cost, best_d = cost, d
disparity[y, x] = best_d
return disparity
np.random.seed(42)
left = np.random.randint(0, 256, (60, 120), dtype=np.uint8)
right = np.roll(left, 8, axis=1) # constant 8 px disparity
disp = block_matching_disparity(left, right, block=7, max_disparity=16)
valid = disp[10:50, 30:100]
print(f"median disparity {np.median(valid):.1f} px "
f"-> depth {0.12 * 640 / max(np.median(valid), 1):.2f} m")
Production pipelines never run this Python loop â OpenCV's semi-global block matching and modern learning-based matchers do the same job orders of magnitude faster â but the structure is identical, and understanding it lets you diagnose the failure modes: repeated textures locking onto the wrong period, occlusion regions with no counterpart at all, and low-texture walls where every offset costs the same.
Depth map quality and visualization
Raw depth needs filtering before any consumer trusts it. Median filters remove speckle outliers without eroding edges, range gates discard returns beyond the sensor's useful envelope, and confidence maps derived from matching cost tell downstream code which pixels are guesses.
Visualizations exist for humans, not algorithms. Jet rainbow maps are familiar but perceptually non-uniform, so equal color steps do not equal equal depth steps â magma, viridis, and plain grayscale are safer for judging structure. Whatever palette you display, keep the underlying array in meters and label the colorbar accordingly.
Three failure signatures are worth recognizing on sight. Streaking along rows indicates matching cost aliasing in repetitive texture. Holes around object silhouettes indicate occlusion that no right-image patch can explain. Systematic doubling of an object indicates a periodic pattern locking to the wrong disparity period â fences and roof tiles are the usual culprits.
Choosing and fusing depth sensors
Sensor choice follows the flight envelope. Indoor hover at two meters: structured light or short-range ToF delivers millimeter data with no calibration burden. Low-altitude inspection under five meters: a ToF camera or stereo pair both work, with stereo preferred if you also need texture imagery. Open-field flight at twenty meters and above: stereo with a wide baseline, or LiDAR if the budget allows, because ToF loses to sunlight and structured light stops functioning entirely.
Fusion covers what no single sensor does. Ultrasonic provides a trustworthy floor reading directly beneath the aircraft where stereo texture is often poorest. Barometer supplies low-frequency absolute altitude. Stereo supplies dense structure ahead. Combining them with a covariance-aware filter gives an avoidance stack that degrades gracefully â lose the stereo to a sun flare and the ultrasonic floor guard still prevents a ground strike.
Calibration that depth accuracy depends on
Every depth number rests on calibration quality. Intrinsics â focal length, principal point, distortion coefficients â define how pixels map to rays; extrinsics define the baseline and relative orientation between the two cameras. Rectification reprojects both images so corresponding points share a row, and block matching only searches along that row. If rectification is off by even a fraction of a pixel, matching systematically misses and depth acquires a bias that no amount of filtering removes.
Recalibrate after any mechanical event: a hard landing, a mount adjustment, a camera replacement, or even repeated temperature cycling on a light airframe. The standard procedure â capturing dozens of checkerboard images covering the full field of view at varying angles â produces reprojection residuals that quantify whether the model still fits; sub-pixel residuals are the gate, and anything above a tenth of a pixel deserves a fresh capture. Store the calibration with the sensor, not the laptop, and verify it on first use by measuring a known distance: a tape check at three meters will expose a stale calibration faster than any residual report.
Common Mistakes
Assuming stereo depth is uniform across range
Fix: Depth error grows with the square of distance; gate stereo inputs by range and rely on other sensors beyond confident limits.
Feeding unfiltered disparity straight into control
Fix: Apply median filtering, range gating, and confidence masking before the controller sees the data.
Expecting structured light to work in sunlight
Fix: Reserve projected-pattern sensors for indoor or night work; use stereo or ToF outdoors.
Forgetting occlusion holes during mapping
Fix: Mark invalid pixels explicitly and interpolate only for visualization, never for obstacle decisions.
Best Practices
- Calibrate stereo intrinsics and extrinsics after any mechanical disturbance to the camera mount.
- Log raw disparity alongside depth so matching regressions can be replayed offline.
- Tune block or window size to texture scale; coarse texture needs bigger windows, fine detail needs smaller.
- Validate depth against known distances before each campaign â a 5-minute tape check catches most drift.
- Carry depth confidence into the planner so uncertain space is approached conservatively.
Key Takeaways
- Depth restores the dimension a monocular image discards; every method introduces scale through baseline, pattern, pulse timing, or motion.
- Stereo depth equals baseline times focal length divided by disparity, and error grows with the square of distance â strong up close, weak at range.
- Block matching finds disparity by minimizing patch cost along epipolar rows; occlusion, repetition, and texturelessness are its three classic failures.
- Filter and confidence-mask depth before control, and recognize streaking, holes, and ghost doubling as specific diagnosable signatures.
- No single depth sensor covers all regimes â fuse stereo, ultrasonic, and barometric sources so sensing degrades gracefully.