Hi SadiaC
The example you are referencing is related to getting the approximate position when using a calibration board. This should not be used for depth sensing, as it is very inaccurate. The distances are relative to the camera, yes.
For that you would need to use cv2 functions for stereo matching.
GPT guide:
Stereo Calibration and Rectification
Before calculating depth, perform stereo rectification to align the images from both cameras. This uses the intrinsic and extrinsic parameters of the cameras.
Load Calibration Data: Load intrinsic parameters (cameraMatrix1
, cameraMatrix2
) and distortion coefficients (distCoeffs1
, distCoeffs2
) for both cameras, along with extrinsic parameters (rotation R
and translation T
matrices).
Stereo Rectification: Use cv2.stereoRectify()
to compute rectification transforms for each camera. This outputs rectification transforms (R1
, R2
), projection matrices (P1
, P2
), and the disparity-to-depth mapping matrix (Q
).
Image Preprocessing
Capture Images: Capture synchronized images from both cameras.
Undistort and Rectify Images: Use cv2.undistortPoints()
and cv2.initUndistortRectifyMap()
along with cv2.remap()
to undistort and rectify the images.
Disparity Map Calculation
Configure Stereo Matcher: Create a stereo matcher using cv2.StereoBM_create()
or cv2.StereoSGBM_create()
. Tune parameters as needed.
Compute Disparity Map: Use the stereo matcher to compute the disparity map from rectified images.
Depth Calculation
- Calculate Depth: Use the disparity map and
Q
matrix to calculate depth. Depth can be calculated as depth = focal_length * baseline / disparity
, with focal_length
and baseline
derived from P1
, P2
, and Q
.
Example Code Skeleton
import numpy as np
import cv2
# Load camera parameters
cameraMatrix1, cameraMatrix2, distCoeffs1, distCoeffs2, R, T = load_calibration_data()
# Stereo rectification
R1, R2, P1, P2, Q, _, _ = cv2.stereoRectify(cameraMatrix1, distCoeffs1, cameraMatrix2, distCoeffs2, imageSize, R, T)
# Capture images
imgL, imgR = capture_stereo_images()
# Undistort and rectify images
map1x, map1y = cv2.initUndistortRectifyMap(cameraMatrix1, distCoeffs1, R1, P1, imageSize, cv2.CV_32FC1)
map2x, map2y = cv2.initUndistortRectifyMap(cameraMatrix2, distCoeffs2, R2, P2, imageSize, cv2.CV_32FC1)
rectifiedL = cv2.remap(imgL, map1x, map1y, cv2.INTER_LINEAR)
rectifiedR = cv2.remap(imgR, map2x, map2y, cv2.INTER_LINEAR)
# Stereo Matcher and disparity
stereo = cv2.StereoBM_create(numDisparities=16, blockSize=15)
disparity = stereo.compute(rectifiedL, rectifiedR)
# Calculate depth
depth = cv2.reprojectImageTo3D(disparity, Q)
Notes
- Parameter Tuning: Quality of depth estimation depends on correct calibration and parameter tuning.
- Handling Disparities and Depths: The disparity map may contain invalid values. Handle these in the depth map.
- Optimization: Real-time depth calculation can be intensive. Optimizations may be necessary.
Thanks,
Jaka