学习目标
在本章中,将学习
- 使用霍夫变换来查找图像中的圆
- 函数:
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
是圆的半径。从等式中,可以看到我们有3个参数,因此需要3D累加器进行霍夫变换,这是非常低效的。因此,OpenCV使用更加技巧性的方法,即使用边缘的梯度信息的Hough梯度方法。
OpenCv中实现的函数是cv2.HoughCircles()
。它有很多参数。
circles = cv.HoughCircles( image, method, dp, minDist[, circles[, param1[, param2[, minRadius[, maxRadius]]]]] )
- image: 8-bit灰度输入图
- circles:输出找到的圆. 3 or 4 element floating-point vector (x,y,radius) or (x,y,radius,votes) .
- method:检测方法 HOUGH_GRADIENT
- dp:检测内侧圆心的累加器图像的分辨率于输入图像之比的倒数, 如dp=1,累加器和输入图像具有相同的分辨率,如果dp=2,累计器便有输入图像一半那么大的宽度和高度.
- minDist: 表示两个圆之间圆心的最小距离.
- param1:默认值100,它是method设置的检测方法的对应的参数,对当前唯一的方法霍夫梯度法cv2.HOUGH_GRADIENT,它表示传递给canny边缘检测算子的高阈值,而低阈值为高阈值的一半
- param2:默认值100,它是method设置的检测方法的对应的参数,对当前唯一的方法霍夫梯度法cv2.HOUGH_GRADIENT,它表示在检测阶段圆心的累加器阈值,它越小,就越可以检测到更多根本不存在的圆,而它越大的话,能通过检测的圆就更加接近完美的圆形了
- minRadius:默认值0,圆半径的最小值
- maxRadius:默认值0,圆半径的最大值
例子:
import cv2
import numpy as np
img = cv2.imread('origin.png', 0)
img = cv2.medianBlur(img, 5)
cimg = cv2.cvtColor(img, cv2.COLOR_GRAY2BGR)
circles = cv2.HoughCircles(img, cv2.HOUGH_GRADIENT, 1, 10, param1=50, param2=30, minRadius=0, maxRadius=0)
# param2越小,能找到的圆更多,
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('circle', cimg)
cv2.waitKey(0)
cv2.destroyAllWindows()
结果如下: