# Python+OpenCV calculates the depth map of the image scene (principle and code implementation)

2022-09-09 04:09:47

# 原理介绍 上图包含等效三角形,and has the following equation： # StereoBM_create()

## 原型

cv.StereoBM_create( [, numDisparities[, blockSize]] ) -> retval

## 参数

• numDisparities：disparity的搜索范围. 对于每个像素,The algorithm will find from 0（Default minimum parallax）到numDisparitiesbest parallax.之后,The search range can be changed by changing the minimum parallax,见StereoSGBM_create().
• blockSize：Linear size of the block.Size should be odd（Because the block is at the center of the current pixel）.Larger block size means smoother,But less accurate disparity maps.A smaller block size will give a more detailed disparity map,But the algorithm has a higher chance of finding the wrong correspondence.

## 返回值

• retval：StereoBM（block match）对象.可以通过该对象的compute()方法.

# StereoBM.compute()

## 原型

cv.StereoMatcher.compute(left, right[, disparity]) -> disparity

## 参数

• left：8bit单通道图像,左图.
• right：8bit单通道图像,右图.

## 输出

• disparity：视差图,与输入图像的大小相同.StereoBM或StereoSGBM计算16Fixed-point disparity map（where each disparity value has 4个小数位）,while other algorithms output32Bit float disparity map.

# OpenCV代码

``````import cv2

def estimate_depth(left_path, right_path, show=True):
# Read the left and right images
img_left = cv2.imread(left_path, 0)
img_right = cv2.imread(right_path, 0)
height, width = img_left.shape[:2]

# 初始化stereo block match对象
stereo = cv2.StereoBM_create(numDisparities=16, blockSize=15)

# Get a disparity map
disparity = stereo.compute(img_left, img_right)

if show:
# Normalize the disparity map
# min_val = disparity.min()
# max_val = disparity.max()
# disparity = np.uint8(6400 * (disparity - min_val) / (max_val - min_val))

# 显示视差图
cv2.imshow('disparity image', disparity)
cv2.imwrite('disparity.jpg', disparity)
cv2.waitKey(0)

estimate_depth('images/view1.png', 'images/view5.png')
``````

# 结果   