树莓派的操作系统为官网推荐的操作系统Raspbain,摄像头用的是手动调焦的USB网络摄像头,三十万像素。视觉图像处理采用OpenCV-3.4.1,至于如何在树莓派上装OpenCV,请自行百度,推荐链接https://blog.csdn.net/leaves_joe/article/details/67656340
PS:为了给树莓派装上OpenCV的开发环境是个艰难历程,前后花了两天时间,经历了各种坑,树莓派前后共不停的编译了9个小时才成功装上了OpenCV。
之前我在网上搜索查询时,大部分教程都采用了轮廓识别的方法进行单目测距的实现,但经实验发现,此方法极易受到复杂环境的干扰,如果要识别的物体的轮廓没有特别明显的特征,或者说背景杂物的轮廓特征比目标物体还要明显,那识别出来的结果肯定不准确,轮廓识别的方法推荐下面链接,建议看懂链接内容后再转回来继续阅读 https://blog.csdn.net/weixin_41695564/article/details/80454055
所以,我采用了颜色识别+轮廓检测的办法。先经过颜色识别提取,比如把明显的红色物体提取出来,屏蔽图片内掉其他非红色物体,此时,就大大减少了干扰物,最后再加上轮廓识别方法进行单目测距的计算,颜色提取方法推荐链接,建议看懂链接内容后再转回来继续阅读 http://www.php.cn/python-tutorials-391922.html
我要识别的物体是宽19cm的红旗,有两个好处:一是为方形的,容易进行轮廓计算。二是为鲜艳的红色,方便进行颜色提取。当然可以用其他物品,知道其长宽和RGB值颜色范围就行。
import numpy as np
import cv2
def find_marker(Img):
kernel_2 = np.ones((2,2),np.uint8)#2x2的卷积核
kernel_3 = np.ones((3,3),np.uint8)#3x3的卷积核
kernel_4 = np.ones((4,4),np.uint8)#4x4的卷积核
if Img is not None:#判断图片是否读入
HSV = cv2.cvtColor(Img, cv2.COLOR_BGR2HSV)#把BGR图像转换为HSV格式
'''
HSV模型中颜色的参数分别是:色调(H),饱和度(S),明度(V)
下面两个值是要识别的颜色范围
'''
Lower = np.array([0, 128, 46])#要识别红色颜色的下限
Upper = np.array([5, 255, 255])#要识别红色颜色的上限
#mask是把HSV图片中在颜色范围内的区域变成白色,其他区域变成黑色
mask = cv2.inRange(HSV, Lower, Upper)
#下面四行是用卷积进行滤波
erosion = cv2.erode(mask,kernel_4,iterations = 1)
erosion = cv2.erode(erosion,kernel_4,iterations = 1)
dilation = cv2.dilate(erosion,kernel_4,iterations = 1)
dilation = cv2.dilate(dilation,kernel_4,iterations = 1)
#target是把原图中的非目标颜色区域去掉剩下的图像
target = cv2.bitwise_and(Img, Img, mask=dilation)
#将滤波后的图像变成二值图像放在binary中
ret, binary = cv2.threshold(dilation,127,255,cv2.THRESH_BINARY)
#在binary中发现轮廓,轮廓按照面积从小到大排列
(_, cnts, _)= cv2.findContours(binary,cv2.RETR_EXTERNAL,cv2.CHAIN_APPROX_SIMPLE)
if cnts==[]:
return 0
c= max(cnts, key = cv2.contourArea)
return cv2.minAreaRect(c)
def distance_to_camera(knownWidth, focalLength, perWidth):
return (knownWidth * focalLength) / perWidth
KNOWN_DISTANCE = 102
KNOWN_WIDTH = 19
KNOWN_HEIGHT = 8.27
image = cv2.imread("/home/pi/Pictures/distanceTest.jpeg")
marker = find_marker(image)
focalLength = (marker[1][0] * KNOWN_DISTANCE) / KNOWN_WIDTH
camera = cv2.VideoCapture(0)
while camera.isOpened():
(grabbed, frame) = camera.read()
marker = find_marker(frame)
if marker == 0:
cv2.imshow("captureR", frame)
cv2.destroyWindow("captureR")
continue
inches = distance_to_camera(KNOWN_WIDTH, focalLength, marker[1][0])
box = cv2.boxPoints(marker)
box = np.int0(box)
cv2.drawContours(frame, [box], -1, (0, 255, 0), 2)
cv2.putText(frame, "%.2fcm" % (inches),
(frame.shape[1] - 600, frame.shape[0] - 20), cv2.FONT_HERSHEY_SIMPLEX,
2.0, (0, 255, 0), 3)
cv2.imshow("capture", frame)
if cv2.waitKey(1) & 0xFF == ord('q'):
break
camera.release()
cv2.destroyWindow("capture")
注:图1并非原图,不应该有绿色方框,但原图在树莓派系统里(此示例为在电脑上跑出的),树莓派已装入小车,不方便取出,用此图代替。
图1