简体   繁体   English

如何在python中自动检测圆圈

[英]How to automatically detect Circles in python

I've been trying to count coins in an images with different backgrounds(not necessarily solid). 我一直在尝试计算具有不同背景(不一定是实心)的图像中的硬币。 this is a code I found here in an answer but the problem is I don't want to have to change parameters every image. 这是我在答案中找到的代码,但是问题是我不想更改每个图像的参数。 Is there a way to do this? 有没有办法做到这一点?

def CountCoins_V2(img):
    image_ori = cv2.cvtColor(img,cv2.COLOR_BGR2GRAY)
    lower_bound = np.array([0,0,10])
    upper_bound = np.array([255,255,195])
    image = img
    mask = cv2.inRange(img, lower_bound, upper_bound)
    #mask = cv2.adaptiveThreshold(image_ori,255,cv2.ADAPTIVE_THRESH_MEAN_C,\cv2.THRESH_BINARY_INV,33,2)
    kernel = np.ones((3, 3), np.uint8)
    mask = cv2.erode(mask, kernel, iterations=6)
    mask = cv2.dilate(mask, kernel, iterations=3)
    closing = cv2.morphologyEx(mask, cv2.MORPH_OPEN, kernel)
    contours = cv2.findContours(mask.copy(), cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)[1]
    contours.sort(key=lambda x:cv2.boundingRect(x)[0])
    array = []
    ii = 1
    for c in contours:
        (x,y),r = cv2.minEnclosingCircle(c)
        center = (int(x),int(y))
        r = int(r)
        if r >= 6 and r<=10:
            cv2.circle(image,center,r,(0,255,0),2)
            array.append(center)
    show_images([image_ori,mask])
    return len(contours)

There are 2 parameters in the code: 代码中有2个参数:

  • The first is lower_bound = np.array([0,0,10]) and upper_bound = np.array([255,255,195]) which threshold the image to get only the colors in the range between lower_bound and upper_bound . 第一个是lower_bound = np.array([0,0,10])upper_bound = np.array([255,255,195]) ,它们对图像进行阈值处理以仅获得在lower_boundupper_bound之间的范围内的颜色。 But in this code, the range is too broad [0,0,10] to [255,255,195] , so it makes no sense. 但是在此代码中,范围从[0,0,10][255,255,195]太宽,因此没有任何意义。 You should limit this range closer to the color of the circles you want to detect. 您应该将此范围限制为更接近要检测的圆圈的颜色。 You can read more about color spaces and threshold samples here . 您可以在此处阅读有关色彩空间和阈值样本的更多信息。
  • The second is r in (x,y),r = cv2.minEnclosingCircle(c) , which is the radius of the circle found in the image. 第二个是r(x,y),r = cv2.minEnclosingCircle(c) ,其是在图像中找到的圆的半径。 It is an important parameter and you need to do experiments to find the best range for all images. 这是一个重要的参数,您需要进行实验以找到所有图像的最佳范围。 My advice is to use ratio between the radius and the width or height of the image, so it will be independent of the resolution of the image. 我的建议是在图像的半径与宽度或高度之间使用比率,因此它与图像的分辨率无关。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM