我正在尝试使用下面的代码显示的视差图来计算视差。我目前得到一个 如何将所选像素限制在x,y轴上的特定区域以及所选像素的视差值中。
当前,当我打印视差时,我得到了一个矩阵,无法用于计算视差。我使用公式D = bf / d,其中D是距离,b是基线,f是焦距,d是视差。我知道基线,焦距和实际距离,但使用视差图无法获得正确的距离。
如何在我的代码中实现呢?
如果有帮助,我可以通过相机校准获得k矩阵,但是我不知道如何在代码中使用它。
from __future__ import print_function
import numpy as np
import cv2 as cv
from PIL import Image
from matplotlib import pyplot as plt
def main():
print('loading images...')
imgL = cv.imread('00004l.png')
imgR = cv.imread('00004r.png')
#Disparity settings
window_size = 5
min_disp = 16
num_disp = 112-min_disp
matcher_left = cv.StereoSGBM_create(
blockSize = 5,
numDisparities = num_disp,
minDisparity = min_disp,
P1 = 8*3*window_size**2,
P2 = 32*3*window_size**2,
disp12MaxDiff = 10,
uniquenessRatio = 10,
speckleWindowSize = 100,
speckleRange = 5,
preFilterCap=1,
mode=cv.STEREO_SGBM_MODE_SGBM_3WAY
)
matcher_right = cv.ximgproc.createRightMatcher(matcher_left)
# Filter
lmbda = 80000 #org 80000
sigma = 1.2 #org 1.2
visual_multiplier = 1.0
wls_filter = cv.ximgproc.createDisparityWLSFilter(matcher_left=matcher_left)
wls_filter.setLambda(lmbda)
wls_filter.setSigmaColor(sigma)
print('computing disparity...')
disp = matcher_left.compute(imgL, imgR).astype(np.float32) / 16
displ = matcher_left.compute(imgL, imgR).astype(np.float32) / 16
dispr = matcher_right.compute(imgR, imgL).astype(np.float32) / 16
displ = np.int16(displ)
dispr = np.int16(dispr)
filteredImg = wls_filter.filter(displ, imgL, None, dispr)
# Display the result
filteredImg = cv.normalize(src=filteredImg, dst=filteredImg, beta=0, alpha=255, norm_type=cv.NORM_MINMAX, dtype=cv.CV_8U);
filteredImg = np.uint8(filteredImg)
#print distance
b = 120
f = 510
D = b * f / d
print (disp)
print (D)
plt.imshow(filteredImg, 'gray')
plt.show()
cv.waitKey()
print('Done')
if __name__ == '__main__':
main()
cv.destroyAllWindows(1)