Camera distance measurement solution

Copyright © Quectel Wireless Solutions Co., Ltd. 2026. All rights reserved.


This application is a stereo ranging project based on the Quectel Pi H1 smart single-board computer: it captures video feeds using a stereo camera, allowing you to measure the physical distance (target depth) from the camera to an object by clicking the target area in the preview interface.

The project synchronously captures frames from the left and right lenses, calculates target distances using stereo disparity, and provides utilities such as camera calibration and image parameter tuning. It serves as a reference implementation for stereo ranging, stereo vision, and robotic visual navigation applications.

../../../_images/image_J7bHbJb1toHhB7xvsGYcN0QSnNW.webp

Development resources

Development accessory list

Accessory name

Quantity

Specifications

Quectel Pi H1 smart single-board computer

1

Quectel Pi H1 smart single-board computer

USB stereo camera

1

Recommended resolution: 2560 × 720 (1280 × 720 per eye); Output format: YUYV/MJPG

USB-C power adapter

1

USB type-C power supply

Micro HDMI cable

1

HDMI 2.0; Length: 1 m; HDMI-A (male) to HDMI-D (male)

CPU cooling fan (optional)

1

Active cooler (B) for Raspberry Pi 5 with thermal pad

Display

1

HDMI monitor

Chessboard calibration board

1

9×6 inner corners (can be displayed on a phone screen; make sure to update the physical square size in the calibration script)

Ethernet cable

1

Length: 1 m; Data Rate: Gigabit

Accessory reference images

Quectel kit

../../../_images/image_YrnNboXuMocBbpxyvqac6d3TnBf.webp

Quick start

Development preparation

The Quectel Pi H1 comes pre-installed with Debian 13, so reflashing the OS image is typically not required. Follow the steps below to get started:

Hardware connections

Display connection

Connect the Micro HDMI end of the cable to the Micro HDMI port on the board, and connect the other end to the HDMI port on your monitor.

../../../_images/image_PmFIbEk2roCmE8xS8r6cb4ppnJc.webp

Input device connection (optional)

Connect a USB keyboard and mouse to the two USB-A ports on the board. If USB ports are limited, using wireless input devices or a touchscreen is recommended.

../../../_images/image_UsSBbGywKoJq7nxXOcpclsm4nIe.webp

Stereo camera connection

Connect the USB stereo camera to a USB-A port of the board.

../../../_images/image_C16HbZFMFohbP9xLb7LcMIKNnne.webp

Network connection

Connect one end of the Ethernet cable to the Gigabit Ethernet port of the board and the other end to a LAN port of the router (make sure the router is connected to the Internet).

../../../_images/image_UKSBbK3sVopMujxn4h6cXGxOn8g.webp

Power connection

Connect the USB Type-C connector of the power adapter to the power port (labeled POWER IN) on the board, and plug the other end into a power outlet.

../../../_images/image_Q5gCbTG79oyThmx4BJ2cZS3nnpf.webp

Project implementation

Prerequisites

After verifying that your network connection is working, open a terminal and run the following command:

sudo apt update && sudo apt install -y v4l-utils python3-pip python3-venv

This command updates the package lists and installs system prerequisites and utilities, including:

  • v4l-utils: Provides camera utilities such as v4l2-ctl to inspect and configure camera parameters.

  • python3-pip: Python package manager, used to install project dependencies.

  • python3-venv: Python virtual environment support.

Get the code

Click Download code, then extract the code onto the board.

Install Python dependencies

cd <project_dir>
# Create a Python virtual environment named venv
python3 -m venv venv
# Activate the virtual environment
source venv/bin/activate
# Install dependencies in the virtual environment
pip install -r requirements.txt

Description of the dependency packages:

  • PySide6: Python bindings for Qt6, used to build the graphical user interface;

  • opencv-python: The OpenCV image processing library, used for camera capture, image processing, and stereo vision computation;

  • numpy: The numerical computing library, used for matrix operations and calibration parameter processing.

Capture calibration images

Run the calibration image capture tool:

python3 tools/capture_calib_images.py

The program automatically detects the stereo camera and shows a preview. Follow the prompts:

  1. Place the chessboard calibration board at different positions and angles in front of the camera.

  2. Press S to save the current image pair (15~20 pairs recommended).

  3. Press Q to exit the capture program.

Generate calibration parameters

Once capture is complete, run the calibration parameter generation tool. The default square size is 9 mm; you can modify the SQUARE_SIZE parameter in the script under the tools/ directory:

python3 tools/generate_calib_params.py

The program reads the calibration images, calculates the stereo calibration parameters, and generates the tools/stereo_calib_params.npz file.

Run the ranging application

After calibration, run the main program:

cd src
python3 main.py

After the program starts, a graphical interface with the following functions is displayed:

../../../_images/image_W9pGbuNnFoJJOUxCJtzc0jQ1nBd.webp

Button descriptions

Button

Description

Left Camera Preview

Previews the video feed from the left camera only.

Right Camera Preview

Previews the video feed from the right camera only.

Take Left/Right Picture

Captures stereo snapshots to compare left and right camera feeds.

Start Ranging Mode

Enters ranging mode; click anywhere on the preview feed to measure target distance.

Save Parameters

Saves parameters (settings may vary by camera model and require manual adjustment).

Reset Parameters

Resets parameters (settings may vary by camera model and require manual adjustment).

Stop Camera

Stops capture and closes the cameras.

Log display area

The area in the upper right outputs log information while the application is running.

../../../_images/image_C1uDbF5txoYMJ9xUErmcIyK1nWD.webp

Camera parameter tuning

The control panel on the right side of the application allows you to tune Tuthe following camera parameters (available ranges depend on the camera's hardware specifications):

Parameter

Description

Range

Brightness

Image brightness

-64–64

Contrast

Contrast

0–95

Saturation

Saturation

0–100

Hue

Hue

-2000–2000

Gamma

Gamma value

100–300

Sharpness

Sharpness

1–7

Backlight Comp

Backlight compensation

0 / 1

Exposure Time

Exposure time

3–2047

WB Temp

White balance color temperature

2800–6500

Auto

Automated controls (e.g., auto exposure, auto white balance)

-

Ranging

  1. Click Start Ranging Mode to enter ranging mode.

  2. Click the target position in the preview image.

  3. Wait for the distance result to be displayed in the prompt bar at the top.

  4. If invalid is displayed, check the log pane on the right for details—this is typically caused by insufficient texture in the selected region.

Application demo

distance_video

Considerations & FAQs

Calibration image capture guidelines

Image quality

Requirements:

  • Clarity: Ensure the chessboard is fully visible in both the left and right camera feeds, and avoid motion blur.

  • Lighting conditions: Avoid direct glare and harsh shadows; maintain uniform illumination.

  • Screen reflections: If displaying the chessboard on a phone screen, avoid reflections that can cause corner detection to fail.

Capture strategy:

  • Varied distances: Vary the target distance within a range of 0.3–2 m from the cameras.

  • Varied angles: Tilt ±30° horizontally, ±20° vertically, and rotate ±15°.

  • Varied coverage: Position the chessboard across different regions of the frame, including top-left, top-right, bottom-left, bottom-right, and center.

  • Recommended sample count: Capture at least 15 valid image pairs; 20+ pairs are recommended to improve calibration accuracy.

Important notes:

  • Inner Corner Count: CHESSBOARD_SIZE represents the number of inner corners, not the total number of squares. For example, 9 × 6 inner corners correspond to a 10 × 7 chessboard.

  • Physical dimension accuracy: SQUARE_SIZE must strictly match the actual physical square size, as it directly affects baseline distance estimation and ranging accuracy.

  • Setup & printing recommendations:

    • When printing a paper chessboard, ensure it is mounted completely flat and wrinkle-free.

    • When displaying the pattern on a phone screen, verify that the measured dimensions are accurate.

    • Recommended square size: 20–30 mm.

Improving accuracy:

  • Increase the number of calibration images (20+ pairs recommended).

  • Ensure the images cover a wider variety of angles and positions.

  • Improve image sharpness and eliminate blur.

  • Verify that the physical dimensions of the chessboard are configured correctly.

Key validation checks:

  • Baseline distance: The calibrated baseline should closely match the actual physical separation between the stereo cameras.

  • Reprojection Error (RMS): The stereo calibration RMS reprojection error should be ≤ 0.5 pixels (< 0.3 pixels indicates high-quality calibration). If the error is significantly larger, the calibration has diverged and the results are unusable, requiring recalibration.

  • Focal length consistency: The focal lengths of the left and right cameras should be closely aligned; a large discrepancy indicates a calibration issue.

  • Distortion Coefficients: The values of dist_l and dist_r should remain within a reasonable range (typically with an absolute value < 1).

Precautions for stereo ranging

Ranging principle and formula

# Ranging formula: Z = (f × B) / d
# Where:
# - f: focal length (pixels)
# - B: baseline distance (meters)
# - d: disparity (pixels)
distance = (f * self._baseline) / disparity

Key factors affecting ranging accuracy:

  • Disparity calculation accuracy: Affected by the stereo matching algorithm and the image quality.

  • Calibration parameter accuracy: The accuracy of the baseline distance and focal length parameters.

  • Target point features: The richness of the texture affects the disparity calculation.

SGBM stereo matching parameter tuning

stereo = cv2.StereoSGBM_create(
    minDisparity=0,               # Minimum disparity
    numDisparities=16*12,         # Disparity search range (must be a multiple of 16)
    blockSize=11,                 # Matching block size (odd number, 3-21)
    P1=8*3*11*11,                 # Disparity smoothing penalty term 1
    P2=32*3*11*11,                # Disparity smoothing penalty term 2
    disp12MaxDiff=1,              # Left-right consistency check maximum difference
    uniquenessRatio=10,           # Uniqueness ratio
    speckleWindowSize=100,        # Speckle filtering window size
    speckleRange=32,              # Speckle filtering range
    mode=cv2.STEREO_SGBM_MODE_HH  # High precision mode
    )

Tuning recommendations:

Parameter

Tuning principle

Impact

numDisparities

Tune according to the minimum ranging distance; Larger values slow down the computation

Affects the minimum ranging distance

blockSize

Increase it for sparse textures and decrease it for rich textures

Affects the matching accuracy and speed

P1/P2

P2 should be greater than P1; Usually P2=4×P1

Affects the smoothness of the disparity map

uniquenessRatio

Larger values make the matching stricter

Reduces mismatches

speckleWindowSize

Removes noise from the disparity map

Larger values give stronger denoising

speckleRange

Used in conjunction with speckleWindowSize to set the speckle evaluation threshold.

Larger speckleWindowSize and smaller speckleRange yield stronger speckle filtering.

Factors affecting ranging accuracy

Effective ranging range

# The effective range is determined by the near blind zone (Z_min) and maximum effective distance (Z_max)
# Disparity is computed on the downsampled image and scaled back to native resolution (RANGE_DOWNSAMPLE=2);
# therefore, the maximum disparity at the native scale = numDisparities * RANGE_DOWNSAMPLE
max_disparity = NUM_DISPARITIES * RANGE_DOWNSAMPLE   # 128 × 2 = 256
min_distance = (f * baseline) / max_disparity        # Minimum ranging distance (Z_min)
max_distance = (f * baseline) / MIN_RESOLVABLE_DISP  # Maximum effective distance (Z_max)

Example calculation:

  • Focal length f = 695 pixels.

  • Baseline B = 0.0735 m.

  • Maximum disparity at native scale = 256.

  • Minimum ranging distance Z_min = (695 × 0.060)/ 256 ≈ 0.16 m.

  • Maximum effective distance = (f × B)/ d_min, where d_min is the minimum resolvable disparity. Setting d_min ≈ 1 pixel yields Z_max ≈ 41.7 m (theoretical upper limit); in practice, due to subpixel noise, the practical operating range is approximately 5–8 m.

Disparity validity filtering

kernel = 9   # 9x9 neighborhood
for dy in range(-kernel//2, kernel//2 + 1):
    for dx in range(-kernel//2, kernel//2 + 1):
        x = raw_point[0] + dx
        y = raw_point[1] + dy
        # Bounds check to prevent out-of-bounds access
        if 0 <= x < disparity_map.shape[1] and 0 <= y < disparity_map.shape[0]:
            d = disparity_map[y, x]
            if d > 0.5:      # Filter out low-disparity noise
                disparity += d
                valid_count += 1

Notes:

  • A disparity below 0.5 usually indicates an invalid match.

  • A 5×5 neighborhood average is used to reduce the effect of noise.

  • If there are too few valid points, the user is prompted to click again.

Distance sanity check

# Perform a sanity check on the calculated results
# Valid range: near end is bounded by maximum disparity (Z_min ≈ 0.18 m); far end approaches subpixel levels where errors escalate sharply
MIN_VALID_Z = 0.2   # meters
MAX_VALID_Z = 5.0   # meters

z_3d = point_3d[2]
if MIN_VALID_Z < z_3d < MAX_VALID_Z:
    distance = z_3d
else:
    # An abnormal z_3d implies invalid disparity; treat ranging as failed to align with the UI's Invalid state
    distance = 0.0   # UI displays: Measured distance: Invalid

Sources of ranging error:

  • Calibration error: Inaccurate baseline distance and focal length parameters.

  • Disparity error: Precision limits of the stereo matching algorithm.

  • Image quality: Lighting, blur, and insufficient texture.

  • Distance: The farther the target, the smaller the disparity and the larger the relative error.

Troubleshooting

Calibration issues

High corner detection failure rate

Symptom:

Warning: Skip 5th pair - chessboard not detected in left image
Valid image pairs for calibration: 8 (need ≥15)

Solutions:

  • Improve lighting conditions to avoid harsh shadows and glare.

  • Make sure the chessboard is completely contained within the frame.

  • Increase image contrast.

  • Decrease capture distance to position the calibration target so it occupies at least 1/3–1/2 of the frame.

  • Use a sharper, higher-quality chessboard image source.

Abnormal baseline distance

Symptom:

Baseline Length: 0.1234 meters

Solutions:

  • Re-measure the actual size of the squares.

  • Check the SQUARE_SIZE parameter.

  • Make sure the chessboard is flat.

  • Calibrate again.

Ranging issues

Distance output displays 0 or invalid

Symptom:

# Displayed in the log pane
Error: Ranging failed - No valid disparity points

Possible causes:

  • The clicked area has insufficient or repetitive texture.

  • The clicked area is too far away or too close.

  • The image quality is poor (blur, insufficient lighting).

  • The calibration parameters are not loaded.

Solutions:

# Check whether calibration parameters are loaded
if not self._is_calibrated:
    LogManager.append_log("Warning: No calibration loaded!")
  • Verify that the calibration parameters have been successfully imported.

  • Click areas with distinct textures or well-defined object edges, and avoid large textureless surfaces (such as blank white walls).

  • Eliminate glare, harsh shadows, and motion blur.

  • Increase blockSize(expands the matching window size) or moderately decrease uniquenessRatio(relaxes matching strictness).

  • Ensure the target object is within the effective ranging range—placing an object too close or too far makes disparity estimation impossible.

Low ranging accuracy or large error

Symptom:
The actual distance is 1 m, but the measured result is 0.8 m or 1.2 m.

Solutions:

  • Check calibration quality: The stereo calibration RMS reprojection error should be ≤ 0.5 pixels (< 0.3 pixels indicates high-quality calibration); an elevated error indicates calibration divergence, requiring recalibration.

  • Tune SGBM parameters: Tune numDisparities and blockSize based on the target ranging distance.

  • Improve the image quality:

# Enhance contrast (must be applied identically to both left and right frames)
clahe = cv2.createCLAHE(clipLimit=4.0, tileGridSize=(8, 8))
gray_left = clahe.apply(gray_left)
gray_right = clahe.apply(gray_right)

Poor disparity map quality

Symptom:
The disparity map is full of noise and object contours cannot be identified.

Solutions:

  • Tune preprocessing parameters:

# Enhance contrast
clahe = cv2.createCLAHE(clipLimit=6.0, tileGridSize=(8, 8))

# Enhanced denoising (applied synchronously to both views; lightweight 3x3 filtering to avoid over-smoothing edges)
gray_left = cv2.GaussianBlur(gray_left, (3, 3), 0)
gray_right = cv2.GaussianBlur(gray_right, (3, 3), 0)
gray_left = cv2.medianBlur(gray_left, 3)
gray_right = cv2.medianBlur(gray_right, 3)
  • Tune SGBM parameters:

stereo = cv2.StereoSGBM_create(
    minDisparity=0,                 # Minimum disparity
    numDisparities=128,             # Disparity search range (must be a multiple of 16)
    blockSize=11,                   # Matched block size (odd number, 3–21)
    P1=8*3*11*11,                   # Disparity smoothness penalty P1
    P2=32*3*11*11,                  # Disparity smoothness penalty P2
    disp12MaxDiff=2,                # Maximum allowed difference in left-right consistency check
    uniquenessRatio=5,              # Uniqueness ratio
    speckleWindowSize=100,          # Speckle filter window size
    speckleRange=32,                # Speckle filter range
    mode=cv2.STEREO_SGBM_MODE_SGBM  # Prioritize execution speed
)
  • Check calibration parameters: Recalibrate for better rectification.

Technical support and contributions

If you encounter any issues during use, please submit technical inquiries on the Quectel official forum. Our technical support team will respond promptly.

Project repository: https://github.com/Quectel-Pi/demo-camera-distance-measurement

Issues and pull requests are welcome.