学习目标
- 我们使用霍夫变换寻找图像中的圆。
- 学习函数:
cv2.HoughCircles()
.
理论
圆的表达式通常为: ( x − x c e n t e r ) 2 + ( y − y c e n t e r ) 2 = r 2 (x - x_{center})^2 + (y - y_{center})^2 =r^2 (x−xcenter)2+(y−ycenter)2=r2,其中 ( x c e n t e r , y c e n t e r ) (x_{center},y_{center}) (xcenter,ycenter)是圆的中心, r r r是圆的半径。从该方程中,我们可以看到3个参数,所以我们需要3D累加器,这可能非常低效。而OpenCV使用更加棘手的方法,霍夫梯度方法(Hough Gradient Method),使用边界的梯度信息。
函数为: cv2.HoughCircles()
. 示例代码如下,
img = cv2.imread('opencv_logo.png', 0)
img = cv2.medianBlur(img, 5)
cimg = cv2.cvtColor(img, cv2.COLOR_GRAY2BGR)
circles = cv2.HoughCircles(img, cv2.HOUGH_GRADIENT, 1, 20,
param1=50, param2=30, minRadius=0, maxRadius=0)
circles = np.uint16(np.around(circles))
for i in circles[0, :]:
# draw the outer circle
cv2.circle(cimg, (i[0], i[1]), i[2], (0, 255, 0), 2)
# draw the center of the circle
cv2.circle(cimg, (i[0], i[1]), 2, (0, 0, 255), 3)
cv2.imshow('detected circles', cimg)
cv2.waitKey(0)
cv2.destroyAllWindows()
结果如下: