当前位置:   article > 正文

双目视觉目标追踪及三维坐标获取—python(代码)_根据双目rgb获得相机坐标系中的坐标

根据双目rgb获得相机坐标系中的坐标

2022年九月更新:

在原来的基础上,我使用了yolov5代替了opencv的目标检测算法辅助相机进行三维坐标的获取,并成功用获取的坐标实时控制机械臂,感兴趣的话可以看我b站里的视频,视频下方也有开源的链接:【软核】我给自己开发了一条机械臂 双目视觉 目标检测_哔哩哔哩_bilibili


以下为原答案:

对着csdn和b站研究了几天双目视觉,算是能粗略的实现一些功能了。在这里记录一下思路,顺便记录一下遇到的坑。

先看一下最终成果吧,实现对物体的追踪和显示三维像素坐标:

 再说一下具体的步骤

一、相机标定

使用双目相机的前提都是先获取相机的内参和外参,有些贵一点的相机出厂时会把这些参数一起给你,比较普通的相机就需要我们自己标定了。我是通过matlab标定的,具体步骤可以看这篇博客:Matlab双目相机标定_indigo love的博客-CSDN博客_matlab双目相机标定 

里面讲的都很详细了,给的代码都可以直接运行,但是要注意一个细节。在matlab标定的界面,这个选项默认是给2个参数的,我们要手动勾选到三个参数,不然最后输出的相机参数就会不太一样

这里我们先把标定的结果放到一个叫stereoconfig.py的文件里,方便后面使用

  1. import numpy as np
  2. class stereoCamera(object):
  3. def __init__(self):
  4. # 左相机内参
  5. self.cam_matrix_left = np.array([[684.8165, 0, 637.2704], [0, 685.4432, 320.5347],
  6. [0, 0, 1]])
  7. # 右相机内参
  8. self.cam_matrix_right = np.array([[778.2081, 0, 602.9231], [0, 781.9883, 319.6632],
  9. [0, 0, 1]])
  10. # 左右相机畸变系数:[k1, k2, p1, p2, k3]
  11. self.distortion_l = np.array([[0.1342, -0.3101, 0, 0, 0.1673]])
  12. self.distortion_r = np.array([[0.4604, -2.3963, 0, 0, 5.2266]])
  13. # 旋转矩阵
  14. self.R = np.array([[0.9993, -0.0038, -0.0364],
  15. [0.0033, 0.9999, -0.0143],
  16. [0.0365, 0.0142, 0.9992]])
  17. # 平移矩阵
  18. self.T = np.array([[-44.8076], [5.7648], [51.7586]])
  19. # 主点列坐标的差
  20. self.doffs = 0.0
  21. # 指示上述内外参是否为经过立体校正后的结果
  22. self.isRectified = False
  23. def setMiddleBurryParams(self):
  24. self.cam_matrix_left = np.array([[684.8165, 0, 637.2704], [0, 685.4432, 320.5347],
  25. [0, 0, 1]])
  26. self.cam_matrix_right = np.array([[778.2081, 0, 602.9231], [0, 781.9883, 319.6632],
  27. [0, 0, 1]])
  28. self.distortion_l = np.array([[0.1342, -0.3101, 0, 0, 0.1673]])
  29. self.distortion_r = np.array([[0.4604, -2.3963, 0, 0, 5.2266]])
  30. self.R = np.array([[0.9993, -0.0038, -0.0364],
  31. [0.0033, 0.9999, -0.0143],
  32. [0.0365, 0.0142, 0.9992]])
  33. self.T = np.array([[-44.8076], [5.7648], [51.7586]])
  34. self.doffs = 131.111
  35. self.isRectified = True

 二、关于如何用python打开两个摄像头

其实这应该不算是重点,但是真的卡了我很久......所以还是说一说。

首先,双目摄像头虽然有两个摄像头,但他们用的是同一个串口号,也就是说camera = cv2.VideoCapture(0),给的id是0,那么它已经是打开了两个摄像头了,但是如果你只运行这一行代码你只能看到左摄像头,为什么呢?其实不是另一个摄像头没打开,而是你默认的窗口大小不够大,所以只能看到一个摄像头,对于2560×720的摄像头用下面的代码可以切割窗口,开两个窗口让两个摄像头都显示。1480的摄像头可以参考这篇博客,反正我主要也是复制的他的OpenCV 打开双目摄像头(python版)_一颗小树x的博客-CSDN博客_opencv打开双目摄像头

我建议还是一个开两个窗口,分别显示左摄像头和右摄像头,当然你也可以让两个摄像头显示在一个窗口里,用相应的方法切割窗口就行,不细说。

  1. # -*- coding: utf-8 -*-
  2. import cv2
  3. import time
  4. AUTO = False # 自动拍照,或手动按s键拍照
  5. INTERVAL = 2 # 自动拍照间隔
  6. cv2.namedWindow("left")
  7. cv2.namedWindow("right")
  8. camera = cv2.VideoCapture(0)
  9. # 设置分辨率左右摄像机同一频率,同一设备ID;左右摄像机总分辨率2560x720;分割为两个1280x720
  10. camera.set(cv2.CAP_PROP_FRAME_WIDTH,2560)
  11. camera.set(cv2.CAP_PROP_FRAME_HEIGHT,720)
  12. counter = 0
  13. utc = time.time()
  14. folder = "./SaveImage/" # 拍照文件目录
  15. def shot(pos, frame):
  16. global counter
  17. path = folder + pos + "_" + str(counter) + ".jpg"
  18. cv2.imwrite(path, frame)
  19. print("snapshot saved into: " + path)
  20. while True:
  21. ret, frame = camera.read()
  22. print("ret:",ret)
  23. # 裁剪坐标为[y0:y1, x0:x1] HEIGHT * WIDTH
  24. left_frame = frame[0:720, 0:1280]
  25. right_frame = frame[0:720, 1280:2560]
  26. cv2.imshow("left", left_frame)
  27. cv2.imshow("right", right_frame)
  28. now = time.time()
  29. if AUTO and now - utc >= INTERVAL:
  30. shot("left", left_frame)
  31. shot("right", right_frame)
  32. counter += 1
  33. utc = now
  34. key = cv2.waitKey(1)
  35. if key == ord("q"):
  36. break
  37. elif key == ord("s"):
  38. shot("left", left_frame)
  39. shot("right", right_frame)
  40. counter += 1
  41. camera.release()
  42. cv2.destroyWindow("left")
  43. cv2.destroyWindow("right")

三、目标追踪的实现

本文的思路是先实现单目相机(即左相机)的目标追踪,实现目标追踪后左相机目标处的二维像素坐标就得到了,再把左相机目标处的二维像素坐标加上 “视差” 就得到了右相机目标处的像素二维坐标。得到两个坐标后再利用最小二乘法得到第三维的像素坐标。

总之,先贴出单目相机的目标追踪代码:

  1. import cv2
  2. vs = cv2.VideoCapture(0) # 参数0表示第一个摄像头
  3. cv2.namedWindow("Frame")
  4. # 判断视频是否打开
  5. if (vs.isOpened()):
  6. print('camera Opened')
  7. else:
  8. print('摄像头未打开')
  9. OPENCV_OBJECT_TRACKERS = {
  10. "csrt": cv2.TrackerCSRT_create, "kcf": cv2.TrackerKCF_create,
  11. "boosting": cv2.TrackerBoosting_create, "mil": cv2.TrackerMIL_create,
  12. "tld": cv2.TrackerTLD_create,
  13. "medianflow": cv2.TrackerMedianFlow_create, "mosse": cv2.TrackerMOSSE_create
  14. }
  15. trackers=cv2.MultiTracker_create()
  16. while True:
  17. frame=vs.read()
  18. frame=frame[1]
  19. if frame is None:
  20. break
  21. # 设置摄像头尺寸
  22. (h,w) = frame.shape[:2]
  23. width = 800
  24. r = width / float(w)
  25. dim = (width, int(h * r))
  26. frame = cv2.resize(frame, dim, interpolation = cv2.INTER_AREA)
  27. # 对做摄像头做目标识别初始化
  28. (success,boxes)=trackers.update(frame)
  29. # 画图的循环
  30. for box in boxes:
  31. (x,y,w,h)=[int(v) for v in box]
  32. cv2.rectangle(frame, (x, y), (x + w, y + h), (0, 255, 0), 2)
  33. cv2.imshow('Frame', frame)
  34. # 按键判断是否设置了新的目标
  35. key=cv2.waitKey(10) & 0xFF
  36. if key == ord('s'):
  37. box=cv2.selectROI('Frame', frame, fromCenter=False, showCrosshair=True)
  38. tracker=cv2.TrackerCSRT_create()
  39. print(type(box),type(box[0]),box[1],box)
  40. trackers.add(tracker, frame, box)
  41. elif key == 27:
  42. break
  43. vs.release()
  44. cv2.destroyAllWindows()

运行之后弹出一个Frame窗口,按下按键“s”图像就会静止,可以用鼠标画一个框,然后再按空格就会开始目标追踪了。

四、z轴坐标的获取

这应该是比较核心的部分了,思路就是我在第三部分开头里说的。

(1)计算视差

这个函数会返回一个值disp,就是视差(disparity),视差的定义是disparity=ul-ur,即左图的像素坐标减去右图的像素坐标。视差越大,说明该点距离摄像头越近,这很好理解啊,把双目相机想象成你的眼睛,当你不停的闭一只眼,睁开另一只眼,你会发现视线里的物体会移动,且越近的物体移动的距离越大。是吧?

  1. # 视差计算
  2. def stereoMatchSGBM(left_image, right_image, down_scale=False):
  3. # SGBM匹配参数设置
  4. if left_image.ndim == 2:
  5. img_channels = 1
  6. else:
  7. img_channels = 3
  8. blockSize = 3
  9. paraml = {'minDisparity': 0,
  10. 'numDisparities': 64,
  11. 'blockSize': blockSize,
  12. 'P1': 8 * img_channels * blockSize ** 2,
  13. 'P2': 32 * img_channels * blockSize ** 2,
  14. 'disp12MaxDiff': 1,
  15. 'preFilterCap': 63,
  16. 'uniquenessRatio': 15,
  17. 'speckleWindowSize': 100,
  18. 'speckleRange': 1,
  19. 'mode': cv2.STEREO_SGBM_MODE_SGBM_3WAY
  20. }
  21. # 构建SGBM对象
  22. left_matcher = cv2.StereoSGBM_create(**paraml)
  23. paramr = paraml
  24. paramr['minDisparity'] = -paraml['numDisparities']
  25. right_matcher = cv2.StereoSGBM_create(**paramr)
  26. # 计算视差图
  27. size = (left_image.shape[1], left_image.shape[0])
  28. if down_scale == False:
  29. disparity_left = left_matcher.compute(left_image, right_image)
  30. disparity_right = right_matcher.compute(right_image, left_image)
  31. else:
  32. left_image_down = cv2.pyrDown(left_image)
  33. right_image_down = cv2.pyrDown(right_image)
  34. factor = left_image.shape[1] / left_image_down.shape[1]
  35. disparity_left_half = left_matcher.compute(left_image_down, right_image_down)
  36. disparity_right_half = right_matcher.compute(right_image_down, left_image_down)
  37. disparity_left = cv2.resize(disparity_left_half, size, interpolation=cv2.INTER_AREA)
  38. disparity_right = cv2.resize(disparity_right_half, size, interpolation=cv2.INTER_AREA)
  39. disparity_left = factor * disparity_left
  40. disparity_right = factor * disparity_right
  41. # 真实视差(因为SGBM算法得到的视差是×16的)
  42. trueDisp_left = disparity_left.astype(np.float32) / 16.
  43. trueDisp_right = disparity_right.astype(np.float32) / 16.
  44. return trueDisp_left, trueDisp_right

(2)目标处的左右像素点计算

得到了视差大小之后,就可以根据视差计算两边像素点的坐标了。disp是我们之前求出的视差的参数。注意这里是disp(yy,xx)而不是disp(xx,yy)   ,你看下disp的长度和宽度就知道了

  1. # 画图的循环,(x,y)和(x+w,y+h)是你画的框的左上角和右下角的两个坐标哈
  2. for box in boxes:
  3. (x, y, w, h)=[int(v) for v in box]
  4. cv2.rectangle(left_frame, (x, y), (x + w, y + h), (0, 255, 0), 2)
  5. # 转化成框框中点的坐标
  6. xx = round((2*x+w)/2)
  7. yy = round((2*y+h)/2)
  8. # xr和yr是右相机相应点的像素坐标
  9. xr = xx+disp[yy, xx]
  10. yr = yy

(3)z轴坐标计算

我只知道视差越小,深度越深。视差转化为现实坐标的我也不太懂原理,这个是其他人的代码。

  1. def getDepthMapWithConfig(config : stereoconfig.stereoCamera) -> np.ndarray:
  2. fb = config.cam_matrix_left[0, 0] * (-config.T[0])
  3. doffs = config.doffs
  4. disparity=dot_disp
  5. depth = fb/(disparity + doffs)
  6. return depth

 五、最终结果

我把所有代码都贴一下吧

  1. import cv2
  2. import argparse
  3. import numpy as np
  4. import stereoconfig
  5. # 左相机内参
  6. leftIntrinsic = np.array([[684.8165, 0, 637.2704], [0, 685.4432, 320.5347],
  7. [0, 0, 1]])
  8. # 右相机内参
  9. rightIntrinsic = np.array([[778.2081, 0, 602.9231], [0, 781.9883, 319.6632],
  10. [0, 0, 1]])
  11. # 旋转矩阵
  12. leftRotation = np.array([[1, 0, 0], # 旋转矩阵
  13. [0, 1, 0],
  14. [0, 0, 1]])
  15. rightRotation = np.array([[0.9993, -0.0038, -0.0364],
  16. [0.0033, 0.9999, -0.0143],
  17. [0.0365, 0.0142, 0.9992]])
  18. # 平移矩阵
  19. rightTranslation = np.array([[-44.8076], [5.7648], [51.7586]])
  20. leftTranslation = np.array([[0], # 平移矩阵
  21. [0],
  22. [0]])
  23. def getDepthMapWithConfig(config : stereoconfig.stereoCamera) -> np.ndarray:
  24. fb = config.cam_matrix_left[0, 0] * (-config.T[0])
  25. doffs = config.doffs
  26. disparity=dot_disp
  27. depth = fb/(disparity + doffs)
  28. return depth
  29. # 预处理
  30. def preprocess(img1, img2):
  31. # 彩色图->灰度图
  32. if (img1.ndim == 3):
  33. img1 = cv2.cvtColor(img1, cv2.COLOR_BGR2GRAY) # 通过OpenCV加载的图像通道顺序是BGR
  34. if (img2.ndim == 3):
  35. img2 = cv2.cvtColor(img2, cv2.COLOR_BGR2GRAY)
  36. # 直方图均衡
  37. img1 = cv2.equalizeHist(img1)
  38. img2 = cv2.equalizeHist(img2)
  39. return img1, img2
  40. # 消除畸变
  41. def undistortion(image, camera_matrix, dist_coeff):
  42. undistortion_image = cv2.undistort(image, camera_matrix, dist_coeff)
  43. return undistortion_image
  44. # 获取畸变校正和立体校正的映射变换矩阵、重投影矩阵
  45. # @param:config是一个类,存储着双目标定的参数:config = stereoconfig.stereoCamera()
  46. def getRectifyTransform(height, width, config):
  47. # 读取内参和外参
  48. left_K = config.cam_matrix_left
  49. right_K = config.cam_matrix_right
  50. left_distortion = config.distortion_l
  51. right_distortion = config.distortion_r
  52. R = config.R
  53. T = config.T
  54. # 计算校正变换
  55. R1, R2, P1, P2, Q, roi1, roi2 = cv2.stereoRectify(left_K, left_distortion, right_K, right_distortion,
  56. (width, height), R, T, alpha=0)
  57. map1x, map1y = cv2.initUndistortRectifyMap(left_K, left_distortion, R1, P1, (width, height), cv2.CV_32FC1)
  58. map2x, map2y = cv2.initUndistortRectifyMap(right_K, right_distortion, R2, P2, (width, height), cv2.CV_32FC1)
  59. return map1x, map1y, map2x, map2y, Q
  60. # 畸变校正和立体校正
  61. def rectifyImage(image1, image2, map1x, map1y, map2x, map2y):
  62. rectifyed_img1 = cv2.remap(image1, map1x, map1y, cv2.INTER_AREA)
  63. rectifyed_img2 = cv2.remap(image2, map2x, map2y, cv2.INTER_AREA)
  64. return rectifyed_img1, rectifyed_img2
  65. # 视差计算
  66. def stereoMatchSGBM(left_image, right_image, down_scale=False):
  67. # SGBM匹配参数设置
  68. if left_image.ndim == 2:
  69. img_channels = 1
  70. else:
  71. img_channels = 3
  72. blockSize = 3
  73. paraml = {'minDisparity': 0,
  74. 'numDisparities': 64,
  75. 'blockSize': blockSize,
  76. 'P1': 8 * img_channels * blockSize ** 2,
  77. 'P2': 32 * img_channels * blockSize ** 2,
  78. 'disp12MaxDiff': 1,
  79. 'preFilterCap': 63,
  80. 'uniquenessRatio': 15,
  81. 'speckleWindowSize': 100,
  82. 'speckleRange': 1,
  83. 'mode': cv2.STEREO_SGBM_MODE_SGBM_3WAY
  84. }
  85. # 构建SGBM对象
  86. left_matcher = cv2.StereoSGBM_create(**paraml)
  87. paramr = paraml
  88. paramr['minDisparity'] = -paraml['numDisparities']
  89. right_matcher = cv2.StereoSGBM_create(**paramr)
  90. # 计算视差图
  91. size = (left_image.shape[1], left_image.shape[0])
  92. if down_scale == False:
  93. disparity_left = left_matcher.compute(left_image, right_image)
  94. disparity_right = right_matcher.compute(right_image, left_image)
  95. else:
  96. left_image_down = cv2.pyrDown(left_image)
  97. right_image_down = cv2.pyrDown(right_image)
  98. factor = left_image.shape[1] / left_image_down.shape[1]
  99. disparity_left_half = left_matcher.compute(left_image_down, right_image_down)
  100. disparity_right_half = right_matcher.compute(right_image_down, left_image_down)
  101. disparity_left = cv2.resize(disparity_left_half, size, interpolation=cv2.INTER_AREA)
  102. disparity_right = cv2.resize(disparity_right_half, size, interpolation=cv2.INTER_AREA)
  103. disparity_left = factor * disparity_left
  104. disparity_right = factor * disparity_right
  105. # 真实视差(因为SGBM算法得到的视差是×16的)
  106. trueDisp_left = disparity_left.astype(np.float32) / 16.
  107. trueDisp_right = disparity_right.astype(np.float32) / 16.
  108. return trueDisp_left, trueDisp_right
  109. # 将h×w×3数组转换为N×3的数组
  110. def hw3ToN3(points):
  111. height, width = points.shape[0:2]
  112. points_1 = points[:, :, 0].reshape(height * width, 1)
  113. points_2 = points[:, :, 1].reshape(height * width, 1)
  114. points_3 = points[:, :, 2].reshape(height * width, 1)
  115. points_ = np.hstack((points_1, points_2, points_3))
  116. return points_
  117. def getDepthMapWithQ(disparityMap: np.ndarray, Q: np.ndarray) -> np.ndarray:
  118. points_3d = cv2.reprojectImageTo3D(disparityMap, Q)
  119. depthMap = points_3d[:, :, 2]
  120. reset_index = np.where(np.logical_or(depthMap < 0.0, depthMap > 65535.0))
  121. depthMap[reset_index] = 0
  122. return depthMap.astype(np.float32)
  123. def getDepthMapWithConfig(config : stereoconfig.stereoCamera) -> np.ndarray:
  124. fb = config.cam_matrix_left[0, 0] * (-config.T[0])
  125. doffs = config.doffs
  126. disparity=dot_disp
  127. depth = fb/(disparity + doffs)
  128. return depth
  129. vs = cv2.VideoCapture(0) # 参数0表示第一个摄像头
  130. cv2.namedWindow("Frame")
  131. # 分配摄像头分辨率
  132. vs.set(cv2.CAP_PROP_FRAME_WIDTH, 2560)
  133. vs.set(cv2.CAP_PROP_FRAME_HEIGHT, 720)
  134. # 判断视频是否打开
  135. if (vs.isOpened()):
  136. print('camera Opened')
  137. else:
  138. print('摄像头未打开')
  139. OPENCV_OBJECT_TRACKERS = {
  140. "csrt": cv2.TrackerCSRT_create, "kcf": cv2.TrackerKCF_create,
  141. "boosting": cv2.TrackerBoosting_create, "mil": cv2.TrackerMIL_create,
  142. "tld": cv2.TrackerTLD_create,
  143. "medianflow": cv2.TrackerMedianFlow_create, "mosse": cv2.TrackerMOSSE_create
  144. }
  145. trackers=cv2.MultiTracker_create()
  146. # 读取相机内参和外参
  147. # 使用之前先将标定得到的内外参数填写到stereoconfig.py中的StereoCamera类中
  148. config = stereoconfig.stereoCamera()
  149. config.setMiddleBurryParams()
  150. print(config.cam_matrix_left)
  151. while True:
  152. frame=vs.read()
  153. frame=frame[1]
  154. if frame is None:
  155. break
  156. # 设置右摄像头尺寸
  157. right_frame = frame[0:720, 1280:2560]
  158. (h,w) = right_frame.shape[:2]
  159. width = 800
  160. r = width / float(w)
  161. dim = (width, int(h * r))
  162. right_frame = cv2.resize(right_frame, dim, interpolation = cv2.INTER_AREA)
  163. # 设置左摄像头尺寸
  164. left_frame = frame[0:720, 0:1280]
  165. (h,w) = left_frame.shape[:2]
  166. width = 800
  167. r = width / float(w)
  168. dim = (width, int(h * r))
  169. left_frame = cv2.resize(left_frame, dim, interpolation = cv2.INTER_AREA)
  170. # 对做摄像头做目标识别初始化
  171. (success,boxes)=trackers.update(left_frame)
  172. # 画图的循环
  173. for box in boxes:
  174. (x, y, w, h)=[int(v) for v in box]
  175. cv2.rectangle(left_frame, (x, y), (x + w, y + h), (0, 255, 0), 2)
  176. # 转化成框框中点的坐标
  177. xx = round((2*x+w)/2)
  178. yy = round((2*y+h)/2)
  179. # 读取一帧图片
  180. iml = left_frame # 左图
  181. imr = right_frame # 右图
  182. height, width = iml.shape[0:2]
  183. # 立体校正
  184. map1x, map1y, map2x, map2y, Q = getRectifyTransform(height, width,
  185. config) # 获取用于畸变校正和立体校正的映射矩阵以及用于计算像素空间坐标的重投影矩阵
  186. iml_rectified, imr_rectified = rectifyImage(iml, imr, map1x, map1y, map2x, map2y)
  187. print(Q)
  188. # 立体匹配
  189. iml_, imr_ = preprocess(iml, imr) # 预处理,一般可以削弱光照不均的影响,不做也可以
  190. disp, _ = stereoMatchSGBM(iml, imr, False) # 这里传入的是未经立体校正的图像,因为我们使用的middleburry图片已经是校正过的了
  191. dot_disp=disp[yy][xx]
  192. cv2.imwrite('disaprity.jpg', disp * 4)
  193. # xr和yr是右相机相应点的像素坐标
  194. z=getDepthMapWithConfig(config)
  195. text = str(xx)+','+str(yy)+','+str(z)
  196. cv2.putText(left_frame, text, (x, y), cv2.FONT_HERSHEY_COMPLEX, 0.6, (0, 0, 255), 1)
  197. # 显示两个框
  198. cv2.imshow("right", right_frame)
  199. cv2.imshow('Frame', left_frame)
  200. # 按键判断是否设置新的目标
  201. key=cv2.waitKey(10) & 0xFF
  202. if key == ord('s'):
  203. box=cv2.selectROI('Frame', left_frame, fromCenter=False, showCrosshair=True)
  204. tracker=cv2.TrackerCSRT_create()
  205. print(type(box),type(box[0]),box[1],box)
  206. trackers.add(tracker, left_frame, box)
  207. elif key == 27:
  208. break
  209. vs.release()
  210. cv2.destroyAllWindows()

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/凡人多烦事01/article/detail/152790?site
推荐阅读
相关标签
  

闽ICP备14008679号