方案基于Matlab2018,Python 2.7、Opencv 3.4实现,实现流程如下:
- 首先,使用Matlab,进行双目摄像头的标定;
- 其次,识别特定颜色;
- 最后,使用双目测距公式得到特征点的距离。
摄像头标定
首先进行摄像头的标定,具体标定流程,点击https://blog.csdn.net/suoxd123/article/details/79154170 查看
识别特定颜色物体
在cvt颜色空间中,使用颜色对应范围进行过滤,详细代码如下
def findTargetPoint(self,frameRectified):
hsvImg = cv2.cvtColor(frameRectified, cv2.COLOR_BGR2HSV)
maskImg = cv2.inRange(hsvImg, self.lower_range, self.upper_range)
# Detect contour for both left and right images
(_, cntsImg, _) = cv2.findContours(maskImg, cv2.RETR_EXTERNAL,
cv2.CHAIN_APPROX_SIMPLE)
# If the spot is out of view, then go to next frame
if len(cntsImg) == 0:
return (-1,-1,-1)
# find target obj
maxArea,maxIdx = 0,0
for idx in range(0,len(cntsImg)):
_,_,w,h = cv2.boundingRect(cntsImg[idx])
tmpArea = w * h
if tmpArea > maxArea:
maxArea = tmpArea
maxIdx = idx
# compute the center of the contour in the frame
M = cv2.moments(cntsImg[maxIdx])
if M["m00"] == 0:
cXTarget = cntsImg[maxIdx][0][0][0]
cYTarget = cntsImg[maxIdx][0][0][1]
else:
cXTarget = int(M["m10"] / M["m00"])
cYTarget = int(M["m01"] / M["m00"])
# draw the contour and center of the shape on the image
cv2.drawContours(frameRectified, cntsImg, maxIdx, (240, 0, 159), 1)
cv2.circle(frameRectified, (cXTarget, cYTarget), 1, (0, 0, 0), -1)
return (0,cXTarget,cYTarget)
测距公式计算
其计算原理如下图所示,计算公式为:实际距离=焦距×摄像头间距÷视差,opencv官网给的参考链接:https://docs.opencv.org/3.3.1/d9/d0c/group__calib3d.html