主要实现的功能是能实时识别视频中的绿色圆,并返回圆心位置,这既是对前面所学知识的总结,也是为下一步摄像头的追踪打下基础。
前期准备
摄像头为原装摄像头(非USB外接),环境为RaspberryPi,python2,代码如下:
import numpy as np
import cv2
cap = cv2.VideoCapture(0)
font = cv2.FONT_HERSHEY_SIMPLEX # 设置字体样式
kernel = np.ones((5, 5), np.uint8) # 卷积核
if cap.isOpened() is True: # 检查摄像头是否正常启动
while(True):
ret, frame = cap.read()
frame = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB) # 转换为RGB通道
gray = cv2.cvtColor(frame, cv2.COLOR_RGB2GRAY) # 转换为灰色通道
hsv = cv2.cvtColor(frame, cv2.COLOR_RGB2HSV) # 转换为HSV空间
lower_green = np.array([30, 100, 100]) # 设定绿色的阈值下限
upper_green = np.array([80, 255, 255]) # 设定绿色的阈值上限
# 消除噪声
mask = cv2.inRange(hsv, lower_green, upper_green) # 设定掩膜取值范围
bila = cv2.bilateralFilter(mask, 10, 200, 200) # 双边滤波消除噪声
opening = cv2.morphologyEx(bila, cv2.MORPH_OPEN, kernel) # 形态学开运算
closing = cv2.morphologyEx(opening, cv2.MORPH_CLOSE, kernel) # 形态学开运算
edges = cv2.Canny(closing, 50, 100) # 边缘识别
# 识别圆形
circles = cv2.HoughCircles(
edges, cv2.cv.CV_HOUGH_GRADIENT, 1, 100, param1=100, param2=10, minRadius=10, maxRadius=500)
if circles is not None: # 如果识别出圆
for circle in circles[0]:
# 获取圆的坐标与半径
x = int(circle[0])
y = int(circle[1])
r = int(circle[2])
cv2.circle(frame, (x, y), r, (0, 0, 255), 3) # 标记圆
cv2.circle(frame, (x, y), 3, (255, 255, 0), -1) # 标记圆心
text = 'x: '+str(x)+' y: '+str(y)
cv2.putText(frame, text, (10, 30), font, 1, (0, 255, 0), 2) # 显示圆心位置
else:
# 如果识别不出,显示圆心不存在
cv2.putText(frame, 'x: None y: None', (10, 30), font, 1, (0, 255, 0), 2)
cv2.imshow('frame', frame)
cv2.imshow('mask', mask)
cv2.imshow('edges', edges)
k = cv2.waitKey(5) & 0xFF
if k == 27:
break
cap.release()
cv2.destroyAllWindows()
else:
print('cap is not opened!')
结果如下: