【问题标题】:How to automatically detect Circles in python如何在python中自动检测圆圈
【发布时间】:2018-12-09 22:13:04
【问题描述】:

我一直在尝试计算具有不同背景(不一定是实心)的图像中的硬币。这是我在答案中找到的代码,但问题是我不想更改每个图像的参数。有没有办法做到这一点?

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)

【问题讨论】:

    标签: python image-processing hough-transform opencv-contour


    【解决方案1】:

    代码中有2个参数:

    • 第一个是lower_bound = np.array([0,0,10])upper_bound = np.array([255,255,195]),它们对图像进行阈值处理以仅获取lower_boundupper_bound之间范围内的颜色。但是在这段代码中,[0,0,10][255,255,195] 的范围太广了,所以没有意义。您应该将此范围限制为更接近您要检测的圆圈的颜色。您可以阅读更多关于色彩空间和阈值样本的信息here
    • 第二个是r中的(x,y),r = cv2.minEnclosingCircle(c),即图片中找到的圆的半径。这是一个重要参数,您需要进行实验以找到所有图像的最佳范围。我的建议是使用图像的半径和宽度或高度之间的比率,这样它就与图像的分辨率无关。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-03-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多