使用 OpenCV 进行圆检测 [英] Circle detection with OpenCV

查看:44
本文介绍了使用 OpenCV 进行圆检测的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何提高以下圆圈检测代码的性能

How can I improve the performance of the following circle-detection code

from matplotlib.pyplot import imshow, scatter, show
import cv2

image = cv2.imread('points.png', 0)
_, image = cv2.threshold(image, 254, 255, cv2.THRESH_BINARY)
image = cv2.Canny(image, 1, 1)
imshow(image, cmap='gray')

circles = cv2.HoughCircles(image, cv2.HOUGH_GRADIENT, 2, 32)
x = circles[0, :, 0]
y = circles[0, :, 1]

scatter(x, y)
show()

使用以下源图片:

我已尝试调整 HoughCircles 函数的参数,但它们会导致误报过多或误报过多.特别是,我无法在两个斑点之间的间隙中检测到虚假圆圈:

I have tried adjusting the parameters of the HoughCircles function but they result in either too many false positives or too many false negatives. In particular, I am having trouble with spurious circles being detected in the gap between the two blobs:

推荐答案

@Carlos,在您所描述的情况下,我并不是 Hough Circles 的忠实粉丝.老实说,我觉得这个算法很不直观.在您的情况下,我建议使用 findContour() 函数,然后计算质心.因此,我稍微调整了霍夫的参数以获得合理的结果.在 Canny 之前,我还使用了一种不同的预处理方法,因为除了那个特定的情况之外,我看不出该阈值在任何其他情况下如何工作.

@Carlos, I'm not really a big fan of Hough Circles in situations like the one you've described. To be honest, I find this algorithm very unintuitive. What I would recommend in your case is using findContour() function and then calculating mass centers. Thus said, I tuned the Hough's parameters a bit to get reasonable results. I also used a different method for preprocessing before Canny, since I don't see how that thresholding would work in any other case than that particular one.

霍夫法:

寻找质心:

还有代码:

from matplotlib.pyplot import imshow, scatter, show, savefig
import cv2

image = cv2.imread('circles.png', 0)
#_, image = cv2.threshold(image, 254, 255, cv2.THRESH_BINARY)
image = cv2.GaussianBlur(image.copy(), (27, 27), 0)
image = cv2.Canny(image, 0, 130)
cv2.imshow("canny", image)
cv2.waitKey(0)
imshow(image, cmap='gray')

circles = cv2.HoughCircles(image, cv2.HOUGH_GRADIENT, 22, minDist=1, maxRadius=50)
x = circles[0, :, 0]
y = circles[0, :, 1]

scatter(x, y)
show()
savefig('result1.png')
cv2.waitKey(0)

_, cnts, _ = cv2.findContours(image.copy(), cv2.RETR_EXTERNAL,
    cv2.CHAIN_APPROX_SIMPLE)

# loop over the contours
for c in cnts:
    # compute the center of the contour
    M = cv2.moments(c)
    cX = int(M["m10"] / M["m00"])
    cY = int(M["m01"] / M["m00"])

    #draw the contour and center of the shape on the image
    cv2.drawContours(image, [c], -1, (125, 125, 125), 2)
    cv2.circle(image, (cX, cY), 3, (255, 255, 255), -1)

cv2.imshow("Image", image)
cv2.imwrite("result2.png", image)
cv2.waitKey(0)

这两种方法都需要一些更精细的调整,但我希望这能给你更多的工作.

Both methods require some more fine tuning but I hope that gives you something more to work with.

来源:这个答案pyimagesearch.

这篇关于使用 OpenCV 进行圆检测的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆