Skip to main content

Overview

Stereo vision uses two cameras to compute depth information by triangulation. OpenCV provides functions for:
  • Calibrating stereo camera systems
  • Computing rectification transformations
  • Stereo correspondence algorithms (StereoBM, StereoSGBM)
  • 3D reconstruction from disparity maps

Stereo Calibration

stereoCalibrate

Calibrates a stereo camera setup by finding intrinsic parameters for each camera and extrinsic parameters between them.
objectPoints
InputArrayOfArrays
required
Vector of vectors of calibration pattern points. Both cameras need to see the same object points. Structure same as calibrateCamera.
imagePoints1
InputArrayOfArrays
required
Vector of vectors of projections of calibration pattern points observed by the first camera.
imagePoints2
InputArrayOfArrays
required
Vector of vectors of projections of calibration pattern points observed by the second camera.
cameraMatrix1
InputOutputArray
required
Input/output camera intrinsic matrix for the first camera.
distCoeffs1
InputOutputArray
required
Input/output vector of distortion coefficients for the first camera.
cameraMatrix2
InputOutputArray
required
Input/output camera intrinsic matrix for the second camera.
distCoeffs2
InputOutputArray
required
Input/output vector of distortion coefficients for the second camera.
imageSize
Size
required
Size of the image used only to initialize camera intrinsic matrices.
R
OutputArray
required
Output rotation matrix between the first and second camera coordinate systems. This matrix brings points from the first camera’s coordinate system to the second camera’s coordinate system.
T
OutputArray
required
Output translation vector between the coordinate systems of the cameras. Equivalent to the position of the first camera with respect to the second camera.
E
OutputArray
required
Output essential matrix.
F
OutputArray
required
Output fundamental matrix.
flags
int
default:"CALIB_FIX_INTRINSIC"
Different flags for stereo calibration (see Stereo Calibration Flags below).
criteria
TermCriteria
default:"TermCriteria(COUNT+EPS, 30, 1e-6)"
Termination criteria for the iterative optimization algorithm.
Returns: The overall RMS re-projection error. The function estimates the transformation between two cameras:
Optionally computes the essential matrix E:
where [T]_x is the skew-symmetric matrix of T. And the fundamental matrix F:
Due to high dimensionality and noise, the function can diverge. If intrinsic parameters can be estimated with high accuracy for each camera individually (using calibrateCamera), it’s recommended to pass CALIB_FIX_INTRINSIC flag with the computed intrinsic parameters.

Extended Version

rvecs
OutputArrayOfArrays
Output vector of rotation vectors (Rodrigues) estimated for each pattern view in the coordinate system of the first camera.
tvecs
OutputArrayOfArrays
Output vector of translation vectors estimated for each pattern view.
perViewErrors
OutputArray
Output vector of the RMS re-projection error estimated for each pattern view.

Stereo Calibration Flags

Flags control the calibration behavior (in addition to single camera flags):
It’s usually reasonable to restrict some parameters, e.g., pass CALIB_SAME_FOCAL_LENGTH and CALIB_ZERO_TANGENT_DIST flags.

Stereo Rectification

stereoRectify

Computes rectification transforms for each head of a calibrated stereo camera.
cameraMatrix1
InputArray
required
First camera intrinsic matrix.
distCoeffs1
InputArray
required
First camera distortion parameters.
cameraMatrix2
InputArray
required
Second camera intrinsic matrix.
distCoeffs2
InputArray
required
Second camera distortion parameters.
imageSize
Size
required
Size of the image used for stereo calibration.
R
InputArray
required
Rotation matrix from the coordinate system of the first camera to the second camera (from stereoCalibrate).
T
InputArray
required
Translation vector from the coordinate system of the first camera to the second camera (from stereoCalibrate).
R1
OutputArray
required
Output 3x3 rectification transform (rotation matrix) for the first camera. Performs change of basis from unrectified to rectified first camera’s coordinate system.
R2
OutputArray
required
Output 3x3 rectification transform (rotation matrix) for the second camera.
P1
OutputArray
required
Output 3x4 projection matrix in the new (rectified) coordinate systems for the first camera. Projects points given in the rectified first camera coordinate system into the rectified first camera’s image.
P2
OutputArray
required
Output 3x4 projection matrix in the new (rectified) coordinate systems for the second camera.
Q
OutputArray
required
Output 4x4 disparity-to-depth mapping matrix (see reprojectImageTo3D).
flags
int
default:"CALIB_ZERO_DISPARITY"
Operation flags:
  • CALIB_ZERO_DISPARITY (0x00400): Makes principal points of each camera have the same pixel coordinates in rectified views
alpha
double
default:"-1"
Free scaling parameter between 0 and 1:
  • alpha=0: Rectified images are zoomed and shifted so only valid pixels are visible (no black areas)
  • alpha=1: Rectified images are decimated and shifted so all pixels from original images are retained
  • -1: Default scaling
newImageSize
Size
default:"Size()"
New image resolution after rectification. When (0,0), it’s set to the original imageSize. Setting to larger value helps preserve details.
validPixROI1
Rect*
Optional output rectangle inside the rectified first image where all pixels are valid.
validPixROI2
Rect*
Optional output rectangle inside the rectified second image where all pixels are valid.
The function computes rotation matrices for each camera that make both camera image planes the same plane. This makes all epipolar lines parallel, simplifying dense stereo correspondence. Horizontal Stereo: For cameras shifted mainly along x-axis, the projection matrices are:
where Tx is horizontal shift between cameras and cx1=cx2 if CALIB_ZERO_DISPARITY is set. Vertical Stereo: For cameras shifted mainly along y-axis:
The first three columns of P1 and P2 are the new “rectified” camera matrices. Pass these with R1 and R2 to initUndistortRectifyMap to initialize rectification maps.

stereoRectifyUncalibrated

Computes a rectification transform for an uncalibrated stereo camera.
points1
InputArray
required
Array of feature points in the first image.
points2
InputArray
required
Corresponding points in the second image.
F
InputArray
required
Input fundamental matrix. Can be computed from the same point pairs using findFundamentalMat.
imgSize
Size
required
Size of the image.
H1
OutputArray
required
Output rectification homography matrix for the first image.
H2
OutputArray
required
Output rectification homography matrix for the second image.
threshold
double
default:"5"
Optional threshold to filter outliers. If >0, point pairs not complying with epipolar geometry are rejected. Otherwise all points are considered inliers.
Computes rectification transformations without knowing intrinsic parameters. Implements the algorithm from Hartley99.
Algorithm heavily depends on epipolar geometry. If camera lenses have significant distortion, correct it before computing fundamental matrix and calling this function.

Utility Functions

getOptimalNewCameraMatrix

Returns the new camera intrinsic matrix based on the free scaling parameter.
cameraMatrix
InputArray
required
Input camera intrinsic matrix.
distCoeffs
InputArray
required
Input vector of distortion coefficients. If NULL/empty, zero distortion is assumed.
imageSize
Size
required
Original image size.
alpha
double
required
Free scaling parameter between 0 (only valid pixels) and 1 (retain all source pixels). See stereoRectify for details.
newImgSize
Size
default:"Size()"
Image size after rectification. By default, set to imageSize.
validPixROI
Rect*
Optional output rectangle outlining all-good-pixels region in undistorted image.
centerPrincipalPoint
bool
default:"false"
Optional flag indicating whether the principal point should be at image center or chosen to best fit source image (determined by alpha).
Returns: New camera intrinsic matrix. By varying alpha parameter, you can retrieve only sensible pixels (alpha=0), keep all original pixels (alpha=1), or get something in between. When alpha>0, undistorted result likely has black pixels corresponding to “virtual” pixels outside captured distorted image.

rectify3Collinear

Computes rectification transforms for 3-head camera where all heads are on the same line.
Computes rectification transformations for tri-focal stereo camera systems with collinear arrangement.

Stereo Matching Classes

StereoBM

Class for computing stereo correspondence using the block matching algorithm.
Key Parameters:
numDisparities
int
default:"0"
Maximum disparity minus minimum disparity. Must be divisible by 16. Typical value: 16, 32, 48, 64, etc.
blockSize
int
default:"21"
Matched block size. Must be odd number ≥1. Typical values: 5-21. Larger blocks produce smoother but less detailed disparity maps.
preFilterType
int
Type of the prefilter:
  • PREFILTER_NORMALIZED_RESPONSE: Normalized response
  • PREFILTER_XSOBEL: Sobel prefilter
preFilterSize
int
Prefilter window size (5-255, must be odd).
preFilterCap
int
Truncation value for prefiltered image pixels (1-63).
textureThreshold
int
Minimum texture for disparity computation. Areas with low texture are filtered out.
uniquenessRatio
int
Margin in percentage by which best computed cost function value should “win” second best value. Typically 5-15.
Example:

StereoSGBM

Class for computing stereo correspondence using Semi-Global Block Matching algorithm.
Key Parameters:
minDisparity
int
default:"0"
Minimum possible disparity value. Typically 0, but can be adjusted.
numDisparities
int
default:"16"
Maximum disparity minus minimum disparity. Must be divisible by 16. Values: 16, 32, 48, 64, 96, 128, etc.
blockSize
int
default:"3"
Matched block size. Must be odd number ≥1. Values: 3, 5, 7, etc. SGBM works well with smaller blocks than BM.
P1
int
default:"0"
First parameter controlling disparity smoothness. Penalty for disparity change by ±1. If 0, default is 8 * channels * blockSize^2.
P2
int
default:"0"
Second parameter controlling disparity smoothness. Penalty for disparity change by more than 1. If 0, default is 32 * channels * blockSize^2. P2 > P1.
disp12MaxDiff
int
default:"0"
Maximum allowed difference in left-right disparity check. Set to negative value to disable check.
preFilterCap
int
default:"0"
Truncation value for prefiltered image pixels. Default: 63.
uniquenessRatio
int
default:"0"
Margin by which best cost function value should “win” second best. Typically 5-15.
speckleWindowSize
int
default:"0"
Maximum size of smooth disparity regions to consider noise speckles and invalidate. Set to 0 to disable. Typical: 50-200.
speckleRange
int
default:"0"
Maximum disparity variation within connected component. Typical: 1-2.
mode
int
default:"MODE_SGBM"
Algorithm mode:
  • MODE_SGBM: Standard Semi-Global Block Matching
  • MODE_HH: Hirschmuller algorithm
  • MODE_SGBM_3WAY: Modified SGBM
  • MODE_HH4: Full-scale two-pass algorithm
SGBM produces smoother and more accurate disparity maps than BM but is computationally more expensive. Example:
SGBM is more suitable for real-time applications and produces better results than BM, especially in textured regions. Consider using MODE_SGBM_3WAY or MODE_HH4 for best quality.

See Also

  • Camera Calibration - calibrateCamera for obtaining camera intrinsics
  • Pose Estimation - solvePnP for 3D-2D correspondences
  • OpenCV samples: stereo_calib.cpp, stereo_match.cpp