Skip to content

Instantly share code, notes, and snippets.

What would you like to do?
Calculate the stereo disparity with OpenCV and show a normalized depth map.
# ------------------------------------------------------------
# Adapted from:
# and:
# StereoSGBM Parameter explanations:
# Matched block size. It must be an odd number >=1 . Normally, it should be somewhere in the 3..11 range.
block_size = 11
min_disp = -128
max_disp = 128
# Maximum disparity minus minimum disparity. The value is always greater than zero.
# In the current implementation, this parameter must be divisible by 16.
num_disp = max_disp - min_disp
# Margin in percentage by which the best (minimum) computed cost function value should "win" the second best value to consider the found match correct.
# Normally, a value within the 5-15 range is good enough
uniquenessRatio = 5
# Maximum size of smooth disparity regions to consider their noise speckles and invalidate.
# Set it to 0 to disable speckle filtering. Otherwise, set it somewhere in the 50-200 range.
speckleWindowSize = 200
# Maximum disparity variation within each connected component.
# If you do speckle filtering, set the parameter to a positive value, it will be implicitly multiplied by 16.
# Normally, 1 or 2 is good enough.
speckleRange = 2
disp12MaxDiff = 0
stereo = cv.StereoSGBM_create(
P1=8 * 1 * block_size * block_size,
P2=32 * 1 * block_size * block_size,
disparity_SGBM = stereo.compute(img1_undistorted, img2_undistorted)
# Normalize the values to a range from 0..255 for a grayscale image
disparity_SGBM = cv.normalize(disparity_SGBM, disparity_SGBM, alpha=255,
beta=0, norm_type=cv.NORM_MINMAX)
disparity_SGBM = np.uint8(disparity_SGBM)
cv.imshow("Disparity", disparity_SGBM)
cv.imwrite("disparity_SGBM_norm.png", disparity_SGBM)

This comment has been minimized.

Copy link

@HarshitRaj112233 HarshitRaj112233 commented May 18, 2021

What is this img1_undistorted, img2_undistorted you never mentioned them it your code


This comment has been minimized.

Copy link
Owner Author

@andijakl andijakl commented May 18, 2021

These are just code snippets for embedding into the article - read the full article for the explanation and the complete code:

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment