python opencv - blob检测或圆检测

时间:2017-02-13 12:19:32

标签: python opencv geometry blobs

我在检测圆圈区域时遇到问题。 我尝试使用opencv中的HoughCircles函数。然而,即使图像非常相似,功能的参数也必须不同以便检测圆圈。

我尝试的另一种方法是迭代每个像素并检查当前像素是否为白色。 如果是这种情况,则检查区域中是否存在blob对象(距离blob中心的距离小于阈值)。如果有,请将像素附加到blob,如果没有,则创建一个新blob。 这也没有成功。

有谁知道如何才能完成这项工作(90%检测)? 我附上了一个示例图像和另一个我标记了圆圈的图像。 谢谢!

example

example with arrows

更新 感谢您的帮助到目前为止! 这是我获取轮廓并按区域过滤它们的代码:

Main()
{
   Start different Threads calling myMethod
}

myMethod()
{
   lock on value of a Variable
   {
      some code...
   }
}

这很有效。我把它们画在图像上: contours_filtered_area

这是我通过圆度过滤的部分,它直接在我按区域过滤的代码下方:

im = cv2.imread('extract_blue.jpg')
imgray = cv2.cvtColor(im, cv2.COLOR_BGR2GRAY)
im_gauss = cv2.GaussianBlur(imgray, (5, 5), 0)
ret, thresh = cv2.threshold(im_gauss, 127, 255, 0)
# get contours
contours, hierarchy = cv2.findContours(thresh, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)

contours_area = []
# calculate area and filter into new array
for con in contours:
    area = cv2.contourArea(con)
    if 1000 < area < 10000:
        contours_area.append(con)

然而,新列表&#39; contours_cirles&#39;是空的。我打印了圆形&#39;在循环中,值都在10 000到100 000之间。

更新#2: 纠正丢失的括号后,它现在正在工作!

contours_cirles = []

# check if contour is of circular shape
for con in contours_area:
    perimeter = cv2.arcLength(con, True)
    area = cv2.contourArea(con)
    if perimeter == 0:
        break
    circularity = 4*math.pi*(area/perimeter*perimeter)
    print circularity
    if 0.8 < circularity < 1.2:
        contours_cirles.append(con)

非常感谢! :)

example_done

2 个答案:

答案 0 :(得分:5)

作为起点,您可以从:

开始
  
      
  • 使用cv2.findContours()
  • 查找给定图像中的所有轮廓   
  • 迭代每个轮廓:      
        
    • 计算面积,如果轮廓面积在给定范围内,则说70 < area < 150。这将过滤掉一些非常小的和   大轮廓。
    •   
    • 使用区域阈值过滤轮廓后,需要检查轮廓边缘的数量,可以使用以下方法完成:   cv2.approxPolyDP(),对于圆圈len(约),必须是&gt; 8但是&lt;或者你可以   在这里应用一些更复杂的操作来检测圆圈。
    •   
  •   

您应该尝试实现此方法,并使用您今后编写的代码更新问题。

修改 正如@Miki建议的那样,使用圆度= 4pi(面积/周长^ 2)检测几何形状是否为圆形是更好更清晰的方法,并确定一个阈值,如0.9,检查形状是否为圆形。对于完美的圆circularity == 1。您可以根据需要微调此阈值。

您可以咨询arcLength以找到轮廓的周长,并contourArea来获取计算圆度所需的轮廓区域。

答案 1 :(得分:1)

我们也可以尝试Hough Transformation来检测图像中的圆圈并使用阈值来获得所需的结果(在绿色边界线中检测到以红点为中心的圆圈):

import cv2
import numpy as np

img = cv2.imread('rbv2g.jpg',0)
img = cv2.medianBlur(img,5)
cimg = cv2.cvtColor(img,cv2.COLOR_GRAY2BGR)

circles = cv2.HoughCircles(img,cv2.HOUGH_GRADIENT,1,10,
                            param1=50,param2=12,minRadius=0,maxRadius=20)

circles = np.uint16(np.around(circles))
for i in circles[0,:]:
    # draw the outer circle
    cv2.circle(cimg,(i[0],i[1]),i[2],(0,255,0),2)
    # draw the center of the circle
    cv2.circle(cimg,(i[0],i[1]),2,(0,0,255),3)

cv2.imshow('detected circles',cimg)
cv2.waitKey(0)
cv2.destroyAllWindows()

enter image description here