您应该注意的主要参数是minDist
, minRadius
and maxRadius
.
首先分析半径:您有一个宽 12 个圆、高 8 个圆的图像,这给您的直径大约为width/12
对于每个圆,或半径(width/12)/2
。您使用的约束允许算法检测比所需更大或更小的圆圈,因此您应该使用更适合您的图像的参数化。在这种情况下,我使用了间隔[0.9 * radius, 1.1 * radius]
.
由于没有重叠,你可以说两个圆之间的距离至少是直径,所以minDist
可以设置为类似的东西2*minRadius
.
这个实现与你的基本相同,只是更新了这 3 个参数:
%matplotlib inline
import cv2
import numpy as np
import matplotlib.pyplot as plt
image = cv2.imread('data/balls.jpg')
output = image.copy()
height, width = image.shape[:2]
maxRadius = int(1.1*(width/12)/2)
minRadius = int(0.9*(width/12)/2)
gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
circles = cv2.HoughCircles(image=gray,
method=cv2.HOUGH_GRADIENT,
dp=1.2,
minDist=2*minRadius,
param1=50,
param2=50,
minRadius=minRadius,
maxRadius=maxRadius
)
if circles is not None:
# convert the (x, y) coordinates and radius of the circles to integers
circlesRound = np.round(circles[0, :]).astype("int")
# loop over the (x, y) coordinates and radius of the circles
for (x, y, r) in circlesRound:
cv2.circle(output, (x, y), r, (0, 255, 0), 4)
plt.imshow(output)
else:
print ('No circles found')
结果是: