gpt4 book ai didi

python - 在 OpenCV 中检测重叠圆

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

我正在使用 Python 的 OpenCV 库来检测图像中的圆圈。作为测试用例,我使用下图:

jar 底:

enter image description here

我写了下面的代码,它应该显示检测前的图像,然后显示添加了检测到的圆圈的图像:

import cv2
import numpy as np

image = cv2.imread('can.png')
image_rgb = image.copy()
image_copy = cv2.cvtColor(image, cv2.COLOR_RGB2GRAY)
grayscaled_image = cv2.cvtColor(image_copy, cv2.COLOR_GRAY2BGR)

cv2.imshow("confirm", grayscaled_image)
cv2.waitKey(0)

cv2.destroyAllWindows()


circles = cv2.HoughCircles(image_copy, cv2.HOUGH_GRADIENT, 1.3, 20, param1=60, param2=33, minRadius=10,maxRadius=28)


if circles is not None:
print("FOUND CIRCLES")
circles = np.round(circles[0, :]).astype("int")
print(circles)
for (x, y, r) in circles:
cv2.circle(image, (x, y), r, (255, 0, 0), 4)
cv2.rectangle(image, (x - 5, y - 5), (x + 5, y + 5), (0, 128, 255), -1)
cv2.imshow("Test", image + image_rgb)
cv2.waitKey(0)

cv2.destroyAllWindows()

我明白了:结果图像

enter image description here

我觉得我的问题出在HoughCircles()函数的使用上。它的用法是:

cv2.HoughCircles(image, method, dp, minDist[, circles[, param1[, param2[, minRadius[, maxRadius]]]]])

其中 minDist 是一个大于 0 的值,要求检测到的圆圈彼此之间有一定距离。有了这个要求,我就不可能正确地检测到 jar 底的所有圆圈,因为每个圆圈的中心都在同一个地方。轮廓会是一个解决方案吗?如何将等高线转换为圆形,以便我可以使用它们中心点的坐标?我应该怎么做才能最好地检测 jar 底每个环的圆形物体?

最佳答案

通过对图像进行自适应阈值处理、找到轮廓,然后为面积大于阈值的轮廓拟合最小外接圆,可以检测到大部分圆

import cv2
import numpy as np

block_size,constant_c ,min_cnt_area = 9,1,400
img = cv2.imread('viMmP.png')
img_gray = cv2.cvtColor(img,cv2.COLOR_BGR2GRAY)
thresh = cv2.adaptiveThreshold(img_gray,255,cv2.ADAPTIVE_THRESH_GAUSSIAN_C, cv2.THRESH_BINARY_INV,block_size,constant_c)
thresh_copy = thresh.copy()
contours, hierarchy = cv2.findContours(thresh,cv2.RETR_TREE,cv2.CHAIN_APPROX_SIMPLE)
for cnt in contours:
if cv2.contourArea(cnt)>min_cnt_area:
(x,y),radius = cv2.minEnclosingCircle(cnt)
center = (int(x),int(y))
radius = int(radius)
cv2.circle(img,center,radius,(255,0,0),1)
cv2.imshow("Thresholded Image",thresh_copy)
cv2.imshow("Image with circles",img)
cv2.waitKey(0)

现在这个脚本产生结果:

enter image description here

enter image description here

但是有一些权衡,例如,如果 block_sizeconstant_c 分别更改为 11 和 2,那么脚本会产生:

enter image description here

enter image description here

您应该尝试使用具有适当形状的核的腐 eclipse 来分离阈值图像中的重叠圆

您可以查看以下链接以了解有关自适应阈值和轮廓的更多信息:

阈值示例:http://docs.opencv.org/3.1.0/d7/d4d/tutorial_py_thresholding.html

阈值引用:http://docs.opencv.org/2.4/modules/imgproc/doc/miscellaneous_transformations.html

轮廓示例: http://docs.opencv.org/3.1.0/dd/d49/tutorial_py_contour_features.html

关于python - 在 OpenCV 中检测重叠圆,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36995764/

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