霍夫圆变换
目标
在这一章当中,
- 我们将学习使用霍夫变换来查找图像中的圆圈。
- 我们将了解这些函数: cv.HoughCircles()
理论
圆圈在数学上表示为$(x-x{center})^2 + (y - y{center})^2 = r^2$其中$(x{center},y{center})$是圆的中心,$r$ 是圆的半径。从这个公式来看,得知我们有三个参数,这样我们就需要一个三维度的累加器来做霍夫变换了,这样效率是非常低的。所以 OpenCV 用了更巧妙的方法Hough Gradient Method ,它利用了边缘的梯度信息。 我们在这里使用的函数是 cv.HoughCircles() 。它的参数非常的多,这些参数在文档中都有详细的解释。所以我们直接上代码吧。
import numpy as npimport cv2 as cvimg = cv.imread('opencv-logo-white.png',0)img = cv.medianBlur(img,5)cimg = cv.cvtColor(img,cv.COLOR_GRAY2BGR)circles = cv.HoughCircles(img,cv.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 circlecv.circle(cimg,(i[0],i[1]),i[2],(0,255,0),2)# draw the center of the circlecv.circle(cimg,(i[0],i[1]),2,(0,0,255),3)cv.imshow('detected circles',cimg)cv.waitKey(0)cv.destroyAllWindows()
结果如下所示:

