跟踪白色背景中的白色球(Python/OpenCV)
问题描述:
我在Python 3中使用OpenCV来检测白色字段上的白色/黑色球,并给出它的确切(x,y,半径)和颜色。我使用函数cv2.Canny()和cv2.findContours()找到它,但问题是cv2.Canny()不总是检测到圆的完整形状(大部分时间只有3/4的圈)。 所以,当我使用cv2.findContours()它不检测它作为一个轮廓。跟踪白色背景中的白色球(Python/OpenCV)
请参阅:
和
这是最重要的代码:
gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
blurred = cv2.GaussianBlur(gray, (5, 5), 0)
edged = cv2.Canny(blurred, 10, 40) # 10 and 40 to be more perceptive
contours_canny= cv2.findContours(edged.copy(), cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)[-2]
之后,我使用: approx = cv2.approxPolyDP(contour,0.01*cv2.arcLength(contour,True),True)
所以,如果你能帮助我找到一个很好的解决方案! 也许有一个函数完成圆的形状,所以我可以检测到它?
答
我会建议你在使用canny检测之前应用一些中间色滤镜。这将确保canny边缘检测发生在球图像和场之间明确的边界上。
下面是一个使用trackbars让你可以自定义颜色阈值的Python代码:
cv2.namedWindow('temp')
cv2.createTrackbar('bl', 'temp', 0, 255, nothing)
cv2.createTrackbar('gl', 'temp', 0, 255, nothing)
cv2.createTrackbar('rl', 'temp', 0, 255, nothing)
cv2.createTrackbar('bh', 'temp', 255, 255, nothing)
cv2.createTrackbar('gh', 'temp', 255, 255, nothing)
cv2.createTrackbar('rh', 'temp', 255, 255, nothing)
bl_temp=cv2.getTrackbarPos('bl', 'temp')
gl_temp=cv2.getTrackbarPos('gl', 'temp')
rl_temp=cv2.getTrackbarPos('rl', 'temp')
bh_temp=cv2.getTrackbarPos('bh', 'temp')
gh_temp=cv2.getTrackbarPos('gh', 'temp')
rh_temp=cv2.getTrackbarPos('rh', 'temp')
thresh=cv2.inRange(frame,(bl_temp,gl_temp,rl_temp),(bh_temp,gh_temp,rh_temp))
+0
非常感谢!现在更容易。 –
答
您可以使用cv.HoughCircles估计最佳匹配完整的圆。跟踪球的好处在于,无论摄像机角度如何,球总是会在图像中显示为圆形。
你有没有试过Hough圈? –