使用OpenCV进行圆检测

use*_*284 2 python geometry opencv computer-vision feature-detection

如何提高以下循环检测代码的性能

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()
Run Code Online (Sandbox Code Playgroud)

使用以下源图像:

在此输入图像描述

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

在此输入图像描述

m3h*_*h0w 7

@Carlos,在你所描述的情况下,我并不是Hough Circles的忠实粉丝.说实话,我发现这个算法非常不直观.在你的情况下,我建议使用findContour()函数,然后计算质量中心.如上所述,我调整了Hough的参数以获得合理的结果.我还在Canny之前使用了一种不同的预处理方法,因为我没有看到该阈值处理在任何其他情况下是如何工作的.

霍夫方法: 在此输入图像描述

寻找群众中心: 在此输入图像描述

和代码:

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)
Run Code Online (Sandbox Code Playgroud)

这两种方法都需要更精细的调整,但我希望能为您提供更多功能.

来源:这个答案pyimagesearch.