Chapter 3: Epipolar Geometry & Stereo Vision
Master the geometry that relates two views of the same scene. Learn how epipolar constraints reduce stereo matching from a 2D search to a 1D scan, how the fundamental and essential matrices encode this geometry, and how to build a complete stereo depth pipeline from rectification through disparity estimation to 3D reconstruction.
- Topics
- 7
- Demos
- 2
- Videos
- 3
- Min read
- 40
Chapter Overview
Epipolar geometry is the intrinsic projective geometry between two views of the same scene. It describes the geometric constraints that arise when two cameras observe common 3D points, regardless of the scene's content. These constraints are among the most powerful tools in computer vision: they tell us where a point visible in one image must lie in the other image, dramatically simplifying correspondence search and enabling depth estimation.
What is this chapter about? We develop the mathematical framework for two-view geometry from first principles. Starting with the epipolar constraint, we derive the fundamental matrix (uncalibrated cameras) and essential matrix (calibrated cameras), learn stereo rectification to simplify matching, explore stereo matching algorithms, and build a complete pipeline from image pairs to depth maps.
Why does this matter? Stereo vision is one of the oldest and most reliable methods for recovering 3D structure from images. It is used in autonomous driving (stereo depth cameras), robotics (obstacle avoidance), AR/VR (depth sensing), and medical imaging (endoscopic 3D reconstruction). Understanding epipolar geometry is also a prerequisite for multi-view reconstruction and SLAM.
How the topics connect: We start with the epipolar constraint to establish the geometric relationship between views. The fundamental matrix algebraically encodes this relationship for arbitrary cameras. The essential matrix specializes it for calibrated cameras and enables pose recovery. Stereo rectification transforms images to exploit epipolar geometry for efficient matching. Stereo matching algorithms compute dense correspondences, producing disparity maps that convert to depth. Finally, we assemble everything into end-to-end stereo pipelines.
Chapter Roadmap
Click any topic to jump in
Epipolar Constraint
The coplanarity condition — how two views of one point constrain each other to epipolar lines.
The fundamental and essential matrices
Fundamental Matrix
The 3x3 rank-2 matrix F that encodes epipolar geometry for uncalibrated cameras.
Essential Matrix
F for calibrated cameras — E = K'^T F K directly gives rotation and translation.
Rectification and correspondence search
Stereo Rectification
Warping images so epipolar lines become horizontal — enabling efficient 1D matching.
Stereo Matching
Block matching, SGM, and cost volumes — finding correspondences along epipolar lines.
Depth estimation and complete pipelines
Disparity & Depth
Disparity d = f*B/Z — converting pixel shifts to metric depth measurements.
End-to-End Stereo
Classical OpenCV pipelines, deep learning stereo, and practical failure modes.
Topics
7 topics in this chapter
Chapter 2 ended with a calibrated stereo rig, but it left the central question of two-view vision open. A pixel in the left image could be the image of any point along its viewing ray, so where can its partner appear in the right image? Searching every pixel of a 640 by 480 image for each of its 307,200 pixels is hopeless, and most candidates would be false matches anyway. The geometry of two cameras rescues us. The two camera centres and any scene point span a plane, and that plane cuts each image in a line, so the partner of a pixel must lie on one known line in the other image. This topic builds that idea step by step: the epipolar plane and the epipolar lines it creates, the epipoles where every epipolar line meets, and the compact algebraic form that packs the whole constraint into one 3 by 3 matrix. The rest of the chapter estimates that matrix, specialises it to calibrated cameras, warps images so the lines become rows, and finally turns matched rows into depth.
Definition
Epipolar geometry is the projective geometry relating two views of one scene. The camera centres and a scene point span the epipolar plane, which cuts each image in an epipolar line. Corresponding pixels , satisfy , so each point's match lies on the line , and all such lines pass through the epipole.
In this topic
- 1The Epipolar Plane and Epipolar Lines
- 2Epipoles
- 3The Epipolar Constraint Equation
The Epipolar Plane and Epipolar Lines
Given a 3D point X and two camera centers C1 and C2, the epipolar plane is the plane defined by these three points. This plane intersects each image to form an epipolar line. A point x1 in the first image projects to a 3D ray from C1. The projection of this ray into the second image is the epipolar line l2---the set of all possible locations where the 3D point could appear in the second image. Every pair of corresponding points must satisfy this constraint: x2 lies on l2, and x1 lies on l1.
Given cameras at and observing a 3D point , the epipolar plane is . This plane intersects image 1 along the epipolar line and image 2 along . The critical consequence: if is a point in image 1, its corresponding point must lie on . This reduces the matching search from the entire image to a single line, a factor-of- speedup. All epipolar lines in one image pass through its epipole, forming a pencil of lines.
Two cameras are 1 meter apart with parallel optical axes. A 3D point at (0.5, 0, 5) is visible to both cameras. Camera 1 is at the origin and Camera 2 is at (1, 0, 0). Both have f=500 and principal point (320, 240). Where are the epipolar lines?
Epipoles
The epipole is the projection of camera 's center onto camera 1's image plane, and vice versa for . All epipolar lines in one image pass through its epipole. When cameras are parallel, the epipoles are at infinity (epipolar lines are parallel horizontal lines). When one camera can see the other camera, the epipole is at a finite image location. The epipoles encode the direction of the baseline between cameras as seen from each camera's perspective.
The epipole in image 1 is the projection of : . Since and , the epipoles are the left and right null vectors of . When cameras have parallel optical axes (common in stereo), the epipoles are at infinity and all epipolar lines are horizontal. The baseline direction in each image is encoded by the epipole: if , then the other camera is in the direction relative to the optical axis.
Camera 1 is at (0,0,0) looking along Z. Camera 2 is at (1,0,0) looking along Z. Both have K = [[500,0,320],[0,500,240],[0,0,1]]. Find the epipoles.
The Epipolar Constraint Equation
The epipolar constraint states that for any pair of corresponding points and (in homogeneous pixel coordinates), the product , where is the fundamental matrix. This equation encodes the coplanarity condition: lies on the epipolar line , and lies on . The fundamental matrix has rank 2 () and 7 degrees of freedom (a matrix up to scale, minus the rank constraint). It can be estimated from as few as 7 point correspondences.
The fundamental matrix encodes the epipolar geometry between two views. For corresponding points and in homogeneous pixel coordinates, the constraint means lies on the epipolar line in the second image. is a matrix with rank 2 () and 7 degrees of freedom (9 entries minus 1 for scale minus 1 for the rank constraint). It can be estimated from as few as 7 point correspondences, though the 8-point algorithm is more commonly used for its simplicity.
Given and a point in image 1, the epipolar line in image 2 is . What is the equation of this line in image 2?
The previous topic showed that every pixel in one view confines its partner to a line in the other, and that a single matrix produces all of those lines. In practice nobody hands us . We have two photographs and, from a feature matcher, a few hundred candidate correspondences, some of them wrong. The task is to recover from those matches alone, without knowing either camera's focal length or pose. That is possible because each correspondence gives one linear equation in the nine entries of , so eight good matches pin it down up to scale. The naive version of this idea fails badly on raw pixel coordinates, and the fix, a simple normalization published by Hartley in 1997, is one of the most quoted lessons in computer vision. This topic covers the 8-point algorithm with that normalization, the rank-2 correction that makes all epipolar lines meet at a single epipole, and the properties of that follow from its structure: seven degrees of freedom, epipoles as null vectors, and transposition when the two views swap roles.
Definition
The fundamental matrix is the 3 by 3, rank-2 matrix that satisfies for every pair of corresponding pixels in two uncalibrated views. It is defined up to scale, has seven degrees of freedom, maps a point to its epipolar line , and has the epipoles as its right and left null vectors.
In this topic
- 1The 8-Point Algorithm
- 2Enforcing the Rank-2 Constraint
- 3Properties of the Fundamental Matrix
The 8-Point Algorithm
The 8-point algorithm estimates from 8 or more point correspondences. Each correspondence gives one linear equation in the 9 entries of : expands to a single row of a matrix equation . With 8+ correspondences, the system is over-determined, and is found as the null space of (the right singular vector of the smallest singular value of ). A critical preprocessing step is Hartley normalization: translate and scale the points so their centroid is at the origin and their average distance from the origin is . Without normalization, the algorithm is numerically unstable.
The linear system mixes entries of very different size: products of pixel coordinates near , single coordinates near , and a constant 1. Small noise in the large entries then swamps the information in the small ones, and the null vector found by SVD is badly perturbed. Hartley normalization moves the centroid to the origin and scales the mean distance to , so every entry is of order 1. In a simulation with 20 matches, the ratio of the largest to the eighth singular value fell from about to about 27, and with 0.5 pixel noise the median epipolar error fell tenfold, from 3.5 to 0.35 pixels. The normalizing transforms are undone at the end with .
Why is normalization critical? If pixel coordinates are around (300, 200), what is the condition number issue in the 8-point algorithm?
Enforcing the Rank-2 Constraint
The fundamental matrix must have rank 2 () to correctly define epipolar lines that converge at the epipole. The SVD solution from the 8-point algorithm typically gives a rank-3 matrix due to noise. The fix is to compute the SVD and set the smallest singular value to zero: . This rank-2 enforcement is the closest rank-2 matrix to in the Frobenius norm and ensures the epipolar geometry is geometrically consistent.
The raw from the 8-point algorithm is generally rank 3. To enforce rank 2, compute the SVD and set the smallest singular value to zero: . This is the closest rank-2 matrix to in the Frobenius norm. Without this correction, the epipolar lines from do not converge to a single epipole (they form a general pencil instead of passing through a common point), which breaks stereo rectification and triangulation algorithms.
The SVD of an estimated gives singular values . What is the corrected ?
Properties of the Fundamental Matrix
The fundamental matrix has 7 degrees of freedom: 9 entries minus 1 for scale ( is defined up to a multiplicative constant) minus 1 for the rank-2 constraint. Key properties: (1) and (epipoles are null spaces), (2) and (epipolar line computation), (3) is invariant to 3D scene structure (it depends only on camera configuration), (4) changes under camera relabeling: if relates cam1 to cam2, then relates cam2 to cam1.
Key properties: (1) has 7 degrees of freedom and rank 2; (2) and , so the epipoles are its null vectors; (3) gives the epipolar line in image 2 and the line in image 1; (4) is defined up to scale. For two cameras with identical intrinsics related by a pure translation, is skew-symmetric, ; with different intrinsics it is not. Seven degrees of freedom means seven matches suffice: the 7-point algorithm solves a cubic in one unknown and returns one or three real solutions.
Given the fundamental matrix F, how do you find the epipoles e1 and e2?
The fundamental matrix of the previous topic works on raw pixels and needs nothing but matches, but that generality has a price: it mixes the camera intrinsics with the motion, so alone cannot tell you how far the second camera rotated or in which direction it moved. Most real systems, from phone AR to robot visual odometry, already know their intrinsics from the calibration of Chapter 2. Removing from both sides leaves the essential matrix , which depends only on the relative rotation and the direction of translation. That is exactly the quantity visual odometry and structure from motion need to start. This topic first relates to and shows the special structure that makes a matrix essential, two equal singular values and a zero. It then decomposes into four candidate poses and picks the physical one by checking which places the scene in front of both cameras. Finally it covers Nister's 5-point algorithm, the minimal solver that runs inside RANSAC in nearly every calibrated two-view pipeline today.
Definition
The essential matrix relates normalized image coordinates of two calibrated views by , with . It has five degrees of freedom, three for rotation and two for the translation direction, and its singular values are . It relates to the fundamental matrix by .
In this topic
- 1Relationship Between E and F
- 2Decomposing E into R and t
- 3The 5-Point Algorithm
Relationship Between E and F
The essential matrix relates to the fundamental matrix through the intrinsic matrices: . Equivalently, . While operates on pixel coordinates (), operates on normalized coordinates (, where ). The essential matrix is a specialized fundamental matrix for calibrated cameras and has exactly 5 degrees of freedom (3 rotation + 2 translation direction, since the baseline length cannot be recovered from images alone).
The essential matrix and fundamental matrix are related by , where are the camera intrinsics. While operates on pixel coordinates, operates on normalized image coordinates : . has only 5 DOF (3 rotation + 2 translation direction, since translation scale is unrecoverable from images alone). The singular values of satisfy and , a stronger constraint than 's mere rank deficiency.
Two cameras share K = [[500,0,320],[0,500,240],[0,0,1]]. The second camera is rotated 5 degrees about the y-axis and translated by t = (1, 0, 0). Build E = [t]x R, check its singular values, and compare them with those of F = K^-T E K^-1.
Decomposing E into R and t
Given , the relative rotation and translation direction (up to sign) can be recovered via SVD. The decomposition gives and yields 4 possible combinations: , , , , where is a 90-degree rotation matrix and is the third column of . Only one of these four solutions places the triangulated 3D points in front of both cameras (positive depth test). The translation is recovered only up to scale---the absolute baseline cannot be determined from images alone.
Given , the rotation and translation are recovered as and (third column of ), where . This yields 4 candidate solutions . The correct one is selected by the cheirality constraint: triangulated points must have positive depth in both cameras ( and ). Exactly one of the four solutions satisfies this for all visible points.
After SVD of E, the 4 solutions give these counts of points with positive depth in both cameras: Solution 1: 0, Solution 2: 48, Solution 3: 2, Solution 4: 0. Which is correct?
The 5-Point Algorithm
The 5-point algorithm is the minimal solver for the essential matrix: it uses exactly 5 point correspondences (in normalized coordinates) to estimate E. It produces up to 10 solutions (from a degree-10 polynomial) and is the standard minimal solver used inside RANSAC for calibrated cameras. The algorithm is more complex than the 8-point but uses fewer points, making RANSAC more efficient (each sample has higher probability of being outlier-free). Nister's 5-point algorithm (2004) is the most widely used implementation.
The 5-point algorithm exploits the additional constraints of (the essential matrix constraint ) to solve from the minimum number of correspondences. The algorithm uses Grobner bases to solve a system of 10 polynomial equations in 3 unknowns, yielding up to 10 solutions. Combined with RANSAC, it is the standard method for relative pose estimation from calibrated cameras: sample 5 points, compute candidates, select by most inliers. The 5-point algorithm is more robust than the 8-point because it uses fewer points (reducing the chance of including outliers in a RANSAC sample).
You have 200 feature matches with 25% outliers. Compare the probability of drawing an all-inlier sample with the 5-point vs 8-point algorithm.
Related Problems on PixelBank
The essential matrix of the previous topic tells us how the two cameras are related, so every pixel now has a known epipolar line in the other view. A dense matcher, however, must search that line for every pixel of the image, and in a real rig the lines are tilted, converge toward an epipole, and differ from pixel to pixel. Walking a different slanted line for each of 300,000 pixels defeats the memory-friendly row-by-row processing that makes stereo fast. Rectification removes the problem by warping both images, before any matching, so that every pair of epipolar lines becomes the same horizontal row. After that, a pixel's partner lies in the same row of the other image, a fixed number of columns to the left, and that offset is the disparity used in the next topics. This topic explains why rectification is worth doing, how Bouguet's method in OpenCV's stereoRectify picks the two rotations, and how to check the result: residual vertical disparity between matched points, and how much of each image survives the warp.
Definition
Stereo rectification applies a homography to each image of a stereo pair so that the epipoles move to infinity along the x-axis. Afterwards all epipolar lines are horizontal and corresponding points share the same row, , so correspondence search becomes a 1D scan along each row, where the column offset is the disparity.
In this topic
- 1Why Rectification is Necessary
- 2Bouguet's Rectification Algorithm
- 3Rectification Quality Metrics
Why Rectification is Necessary
For general camera configurations, epipolar lines can be slanted, curved (after distortion), or even non-parallel. Searching along arbitrary epipolar lines for correspondences is computationally expensive and complicates the matching algorithm. Rectification warps both images with homographies so that corresponding epipolar lines become the same horizontal row in both images. This means the matching algorithm only needs to search along a single row---a 1D problem instead of a 2D one---enabling efficient block matching and dynamic programming approaches.
Without rectification, the epipolar line for a point at pixel in image 1 is an arbitrary line in image 2 with slope . Searching along an arbitrary line is algorithmically complex and prevents the use of efficient scanline-based matching. Rectification applies homographies so that and epipolar lines become horizontal rows. After rectification, matching point in image 1 only requires scanning row in image 2 from to .
Before rectification, corresponding points in two images differ by up to 30 pixels vertically. After rectification, the maximum vertical disparity should be approximately zero. What is the search reduction?
Bouguet's Rectification Algorithm
Bouguet's method (used by OpenCV's stereoRectify) splits the rotation between the two cameras equally and applies a rotation to each image so both cameras become parallel. Specifically: compute the rotation between cameras, apply to camera 1 and to camera 2. Then rotate both so the baseline is horizontal (epipolar lines are horizontal rows). The algorithm also computes new projection matrices that share the same focal length and vertical principal point, ensuring perfect row alignment.
Bouguet's method writes the relative rotation as a rotation vector and gives each camera half of it: camera 1 is turned by and camera 2 by , which makes the two optical axes parallel while warping each image as little as possible. A second rotation , shared by both cameras, then turns the rotated baseline onto the image -axis, so epipoles go to infinity and rows align. The final rectifying rotations are composed with the half rotations. How evenly the warp is shared depends on the baseline as well as the rotation: when the baseline is not perpendicular to the mean viewing direction, adds extra rotation, and one camera may turn much more than the other.
Two cameras 12 cm apart are toed in symmetrically, each turned 5 degrees toward the other, so their relative rotation is 10 degrees about the vertical axis. How far does stereoRectify rotate each camera? What changes if instead camera 1 looks straight ahead along its own baseline and only camera 2 is turned 10 degrees?
Rectification Quality Metrics
The quality of rectification is measured by the vertical disparity (y-difference) between corresponding points after rectification. Ideally this is exactly zero, meaning all correspondences lie on the same row. In practice, residual vertical disparities of 0.1-0.5 pixels are common due to lens distortion modeling errors and calibration imprecision. Another metric is the valid image area: rectification warps the image boundaries, and the overlapping valid region determines how much of the original image is usable for stereo matching.
Rectification quality is measured by the -disparity: the vertical difference between matched points after rectification. Perfect rectification gives -disparity everywhere. In practice, mean -disparity pixels is excellent, is acceptable, and indicates a calibration or rectification error. The -disparity can also reveal systematic problems: a non-zero slope across the image suggests residual rotation error, while a quadratic pattern suggests uncorrected lens distortion.
After rectification, the mean vertical disparity is 0.3 pixels and the max is 1.2 pixels. The stereo matcher uses a 7x7 block. Is the rectification acceptable?
Related Problems on PixelBank
Rectification, the previous topic, turned correspondence into a one-dimensional problem: for each pixel in the left image, find the column in the same row of the right image that shows the same surface point. That sounds simple, but a single pixel's brightness is matched by dozens of candidates along the row, so every method compares neighbourhoods instead of pixels, and every method faces the same dilemma. Small windows keep depth edges sharp but are fooled by noise and blank surfaces; large windows are stable but blur boundaries. Classical stereo answers in two ways. Local methods such as block matching compare a window at each candidate disparity and keep the best, which is very fast. Semi-global matching adds a smoothness penalty for disparity changes between neighbouring pixels and optimises it along several straight paths through the image, which fixes most local errors at a few times the cost. Both are built on a cost volume that stores a matching cost for every pixel and every disparity, and both finish with a winner-take-all choice refined to sub-pixel precision.
Definition
Stereo matching assigns each pixel of a rectified left image a disparity , the column offset of its correspondence in the right image, by minimizing a matching cost over candidates . Local methods minimize a window cost per pixel; semi-global methods also penalize disparity changes between neighbours along several image paths.
In this topic
- 1Block Matching (BM)
- 2Semi-Global Matching (SGM)
- 3Cost Volumes and Winner-Take-All
Block Matching (BM)
Block matching compares a square patch around each pixel in the left image with patches at all disparity candidates in the right image. The best match (lowest cost) determines the disparity. Common cost functions are Sum of Absolute Differences (SAD), Sum of Squared Differences (SSD), and Normalized Cross-Correlation (NCC). Larger blocks are more robust to noise but blur depth edges. Typical block sizes are 5x5 to 21x21 pixels. BM is very fast (real-time on CPU) but produces noisy disparity maps with poor performance in textureless regions.
Block matching compares a window in the left image with windows at each disparity along the same row of the right image, using SAD, SSD or NCC, and keeps . Done directly, that costs , but per-disparity window sums can be built with a running box filter, cutting the cost to , independent of . OpenCV's StereoBM ran 128 disparities on a 640 by 480 pair in about 14 ms on one CPU thread for window sizes from 5 to 21. The window size therefore trades noise robustness against edge sharpness, not speed.
A 640x480 rectified stereo pair is processed with block matching using block size 9 and max disparity 128. How many SAD computations are performed?
Semi-Global Matching (SGM)
SGM aggregates matching costs along multiple (typically 8 or 16) directions through the image, applying a smoothness penalty for disparity changes between adjacent pixels. For each path direction, it computes the minimum cost of assigning a disparity d to pixel p by considering the costs of neighboring pixels along the path plus a penalty for disparity jumps. The final cost at each pixel is the sum across all paths. This approximates 2D global optimization (which is NP-hard) with a tractable 1D dynamic programming approach along each path. SGM produces much smoother and more accurate disparity maps than BM.
Along each path direction , SGM computes , where the last term only keeps values bounded. The small penalty allows slanted surfaces and the large allows true depth jumps. Summing over paths approximates a 2D smoothness prior that is NP-hard to optimise exactly. The cost per path is . On the same 640 by 480 pair, OpenCV's StereoSGBM took 53 ms in its default 5-path mode, 3.6 times StereoBM, and 127 ms in full 8-path mode.
SGM uses penalty (small disparity change) and (large disparity change). A pixel path has costs: : cost=100, : cost=95, : cost=90. What are the aggregated costs?
Cost Volumes and Winner-Take-All
A cost volume is a 3D array storing the matching cost of every pixel at every candidate disparity . For a 640 by 480 image with 128 disparities it holds about 39 million entries. Block matching fills it with window costs, and semi-global matching aggregates them along paths. The disparity at each pixel is then chosen by winner-take-all, . A parabola fitted through the costs at , and refines it to sub-pixel precision, which matters most for distant points with small disparities.
A cost volume has entries. At 1280 by 720 with 192 disparities and 4 bytes each, that is 708 MB (675 MiB), which is why GPU stereo networks build their cost volumes at reduced resolution. The parabola through three costs has its minimum at . The fit is biased toward whole pixels, an effect called pixel locking: with SAD costs on a smooth 1D signal, a true offset of 0.3 pixels was estimated as 0.19, and 0.1 as 0.05. Only offsets of 0 and 0.5 came out exact.
A cost volume has values at disparities d=45: cost=120, d=46: cost=85, d=47: cost=105. Compute the sub-pixel disparity using parabola fitting.
Stereo matching, the previous topic, produces a disparity map: for each left-image pixel, how many columns its partner sits to the left in the right image. Robots, cars and AR headsets need metres, not columns, so the last step converts disparity into depth, and that conversion explains most of what stereo can and cannot do. In a rectified rig, similar triangles give : depth is inversely proportional to disparity. Nearby objects shift a lot between the views and are measured precisely. A distant object shifts by a pixel or two, so a quarter-pixel matching error can move it by metres. This topic derives the formula and its error law, which grows with the square of distance. It then shows how baseline and focal length set a rig's useful range, why a wide baseline that helps far away also creates a near-field blind zone and larger occlusions, and finally how raw disparity maps are cleaned with left-right checks, speckle removal and edge-aware filtering before anyone trusts the depth.
Definition
Disparity is the horizontal offset between corresponding pixels in a rectified stereo pair. With focal length in pixels and baseline in metres, depth is , and a disparity error gives a depth error of about , which grows with the square of distance.
In this topic
- 1The Disparity-to-Depth Formula
- 2Baseline Effects on Depth Range
- 3Depth Map Post-Processing
The Disparity-to-Depth Formula
For a rectified stereo pair with focal length (in pixels) and baseline (in meters), the depth of a point with disparity is: . This formula comes directly from similar triangles in the stereo geometry. Key implications: (1) depth precision degrades quadratically with distance (), (2) zero disparity means infinite depth, (3) negative disparity means the point is behind the camera, and (4) sub-pixel disparity accuracy is critical for distant objects.
For a rectified stereo pair with baseline and focal length , depth is where is the disparity (horizontal pixel offset between left and right projections). This inverse relationship means depth precision degrades quadratically with distance: . For px, m, and px: at m, m; at m, m; at m, m. This is why stereo depth is most useful at short to medium ranges.
A stereo camera with pixels and m (12cm baseline). Compute depth for disparities pixels. What is the depth precision at 5m?
Baseline Effects on Depth Range
The baseline sets the trade-off between far and near. Depth error is , so doubling the baseline halves the error at every range. But the nearest measurable depth is , set by the largest disparity the matcher searches, so a wider rig also has a larger blind zone close in. It also suffers more occlusion, since each camera sees around foreground edges differently. Rather than a fixed ratio of range to baseline, size the rig from an error budget: choose the farthest depth and the acceptable relative error, then solve for .
The minimum and maximum measurable depths are determined by the baseline and disparity range. With max disparity : . With min detectable disparity px: . For , , : m, m. Increasing the baseline increases linearly but also increases . This is the fundamental baseline-range trade-off: a wider baseline resolves distant objects but creates a larger near-field blind zone.
Design a stereo system for (a) indoor robotics (0.3-5m range) and (b) autonomous driving (2-80m range). What baselines are appropriate?
Depth Map Post-Processing
Raw disparity maps from stereo matching contain noise, holes (occluded or textureless regions), and outliers. Common post-processing steps include: (1) left-right consistency check (compute disparity from both directions and reject pixels where they disagree), (2) speckle filtering (remove small disconnected regions), (3) median filtering (reduce salt-and-pepper noise), (4) weighted median or bilateral filtering (smooth disparity while preserving edges), and (5) hole filling using interpolation or inpainting. These steps can improve the usable pixel percentage from 70% to 95%.
The left-right consistency check computes disparity maps from both images and keeps a left pixel only if . Occluded pixels, which are visible in only one view, fail it, and so do most outright mismatches. It can also reject correct pixels on thin structures, where the two maps disagree slightly. Speckle filtering then removes small connected blobs whose disparity differs from their surroundings, OpenCV's filterSpeckles. A median filter (3 by 3 or 5 by 5) removes isolated spikes. Edge-aware filters, such as weighted median or the weighted-least-squares filter, fill and smooth while keeping depth edges aligned with image edges.
A stereo system produces a disparity map where 85% of pixels pass the left-right consistency check. After speckle filtering, 82% remain. After median filtering and hole filling, 97% have valid depth. What is the effective coverage?
Related Problems on PixelBank
The previous topics built every piece of a stereo system in isolation: epipolar geometry, rectification, matching, and the conversion of disparity into depth. A deployed system has to chain them under a time budget, and choose between two very different families of method. The classical OpenCV pipeline calibrates once, precomputes rectification maps, and then runs block matching or semi-global matching on a CPU in tens of milliseconds per frame. It is transparent and cheap, but it fails on blank walls, reflections and repeated patterns. Learned stereo networks, from PSMNet through LEAStereo and RAFT-Stereo, replace hand-crafted matching costs with features trained on large synthetic and real datasets. They cut the error rate on the KITTI driving benchmark by roughly five times, but they need a GPU and inherit the biases of their training data. This topic walks through the classical pipeline step by step, compares it with deep stereo on measured benchmark numbers, and ends with a catalogue of failure modes, so you can predict where any stereo system will break before you deploy it.
Definition
An end-to-end stereo pipeline turns synchronized image pairs into metric depth: offline stereo calibration and rectification maps, then per frame remapping, disparity estimation by a classical matcher or a learned network, filtering, and reprojection to 3D with , or OpenCV's matrix. It is judged by accuracy, density, and latency.
In this topic
- 1Classical OpenCV Stereo Pipeline
- 2Deep Learning Stereo (RAFT-Stereo, LEAStereo)
- 3Practical Considerations and Failure Modes
Classical OpenCV Stereo Pipeline
The classical pipeline chains five steps: (1) stereo calibration, done once per rig; (2) rectification, with remap tables precomputed by stereoRectify and initUndistortRectifyMap; (3) matching each frame with StereoBM or StereoSGBM; (4) post-processing such as speckle removal and the weighted-least-squares filter from the ximgproc contrib module; and (5) reprojection to 3D through the matrix. StereoBM is the fast local matcher. StereoSGBM runs semi-global matching, by default along 5 paths in a single pass. On a desktop CPU at 640 by 480 with 128 disparities, BM takes milliseconds and SGBM tens of milliseconds.
The standard OpenCV stereo pipeline: (1) calibrate each camera (K, distortion), (2) stereo calibrate (R, t between cameras), (3) compute rectification maps (stereoRectify), (4) remap images (remap), (5) compute disparity (StereoBM or StereoSGBM), (6) reproject to 3D (reprojectImageTo3D using the matrix). The matrix maps to : , then divide by . This is a complete, well-tested pipeline that works reliably for baselines up to meter.
You need stereo depth at 30 FPS on a 640x480 resolution using CPU only. Compare BM and SGBM timing.
Deep Learning Stereo (RAFT-Stereo, LEAStereo)
Neural stereo methods learn the matching cost and the regularisation from data. PSMNet (2018) builds a 4D feature cost volume and regularises it with 3D convolutions. LEAStereo (2020) uses neural architecture search to find a compact version of that design. RAFT-Stereo (3DV 2021) borrows the RAFT optical-flow design: it builds a correlation pyramid once, then refines a disparity field iteratively with multi-level recurrent units. Learned features recover textureless and reflective regions where classical matchers fail. The costs are a GPU, sensitivity to the training domain, and runtimes of roughly 0.1 to 0.4 seconds per KITTI frame for the accurate models, though a slimmed RAFT-Stereo runs at 26 FPS.
Learned stereo still uses the classical structure: features, a cost volume or correlation, aggregation and a disparity readout. The learned parts make the costs and the smoothing context-aware. RAFT-Stereo correlates features at all disparities once and then runs recurrent updates that look up only a local window around the current estimate, so the cost per iteration is small and more iterations trade time for accuracy. On KITTI 2015 it reports D1-all 1.96 percent, against 10.86 for OpenCV SGBM. On Middlebury it beat the next-best method's 1-pixel error by 29 percent at publication. A real-time configuration reached 26 FPS at 1248 by 384, with a zero-shot (synthetic-trained) D1 of 5.91 percent.
On the KITTI 2015 stereo benchmark, a pixel is an outlier when its disparity error exceeds both 3 px and 5 percent of the true disparity (the D1 metric). OpenCV's SGBM baseline scores D1-all 10.86 percent; RAFT-Stereo scores 1.96 percent. KITTI's rig has f of about 721 px and b = 0.54 m. What do these numbers mean for a car at 50 m?
Practical Considerations and Failure Modes
Stereo vision fails in predictable ways: (1) textureless regions have no matching features, (2) reflective/transparent surfaces violate the Lambertian assumption, (3) repetitive patterns cause ambiguous matches, (4) occlusions near depth boundaries have no valid correspondence, (5) very close objects exceed the maximum disparity range, (6) very far objects have sub-pixel disparity that is lost in noise. Understanding these failure modes helps in designing robust systems that combine stereo with other depth sensors (structured light, ToF, LiDAR) for complementary coverage.
Every stereo matcher assumes that a surface patch looks the same from both cameras and that it has enough texture to be found. Textureless regions give a nearly flat cost curve with no clear minimum. Repetitive texture gives several equal minima, one per period of the pattern. Specular and transparent surfaces break the same-appearance assumption, because the reflection moves with the viewpoint. Occlusions have no partner at all. Range limits add two more failures: objects closer than fall outside the search range, and far objects have disparities so small that a fraction of a pixel of error becomes metres. Active illumination, ToF or LiDAR fusion, and learned priors each address a different subset.
A stereo camera on a robot encounters: a white wall (textureless), a glass door (transparent), a tiled floor (repetitive). Which will produce valid depth?