如何自动检测图像中的正确圆圈

问题描述

enter image description here

我有一个像上面这样的图像,我想检测下图中蓝色的圆圈

enter image description here

但是,当我这样做时,

enter image description here

检测到红色圆圈。

enter image description here


我如何自动检测蓝色圆圈而不是红色圆圈? (无需遍历每个圆形轮廓)

解决方法

当您传递图像时,下面的代码将为您提供多个圆圈。此外,它会给你计数。您可以稍后编辑它。

import cv2

image = cv2.imread('image.png')
gray = cv2.cvtColor(image,cv2.COLOR_BGR2GRAY)
thresh = cv2.adaptiveThreshold(gray,255,cv2.ADAPTIVE_THRESH_GAUSSIAN_C,cv2.THRESH_BINARY_INV,27,3)

cnts = cv2.findContours(thresh,cv2.RETR_TREE,cv2.CHAIN_APPROX_SIMPLE)
cnts = cnts[0] if len(cnts) == 2 else cnts[1]
count = 0
for c in cnts:
    area = cv2.contourArea(c)
    x,y,w,h = cv2.boundingRect(c)
    ratio = w/h
    ((x,y),r) = cv2.minEnclosingCircle(c)
    if ratio > .85 and ratio < 1.20 and area > 50 and area < 120 and r < 7:
        cv2.circle(image,(int(x),int(y)),int(r),(36,12),-1)
        count += 1

print('Count: {}'.format(count))

cv2.imshow('thresh',thresh)
cv2.imshow('image',image)
cv2.waitKey()