gpt4 book ai didi

python - 使用 OpenCV 进行圆检测

转载 作者:太空宇宙 更新时间:2023-11-03 21:16:17 25 4
gpt4 key购买 nike

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

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()

使用以下源图像:

enter image description here

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

enter image description here

最佳答案

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

霍夫法: enter image description here

寻找质量中心: enter image description here

还有代码:

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)

这两种方法都需要进行一些更精细的调整,但我希望能为您提供更多有用的东西。

资料来源:this answerpyimagesearch

关于python - 使用 OpenCV 进行圆检测,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42658653/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com