benim bonkers
benim bonkers

Reputation: 61

Calculate depth disparity map using opencv

I have trouble calculating depth from disparity map using opencv. I know that the distance in two stereo images is calculated with z = (baseline * focal) / (disparity * p) but I can not figure out how to calculate the disparity using the map. The code I use if the following, providing me with a disparity map of the two images.

import numpy as np
import cv2

# Load the left and right images in gray scale
imgLeft = cv2.imread('logga.png', 0)
imgRight = cv2.imread('logga1.png', 0)

# Initialize the stereo block matching object 
stereo = cv2.StereoBM_create(numDisparities=16, blockSize=5)

# Compute the disparity image
disparity = stereo.compute(imgLeft, imgRight)

# Normalize the image for representation
min = disparity.min()
max = disparity.max()
disparity = np.uint8(6400 * (disparity - min) / (max - min))



# Display the result
cv2.imshow('disparittet', np.hstack((imgLeft, imgRight, disparity)))
cv2.waitKey(0)
cv2.destroyAllWindows()

Upvotes: 3

Views: 10444

Answers (1)

Gopiraj
Gopiraj

Reputation: 657

For calculating the depth from disparity, OpenCV has the function reprojectImageTo3d.

You need the disparity-to-depth matrix (Q) from stereo rectification (or you can create it as given in the link). You can learn more about the Q matrix here.

After getting the Q matrix, you can simply reproject the disparity map to 3D

depth = cv2.reprojectImageTo3D(disparity, Q)

Upvotes: 2

Related Questions