2017-01-10 556 views
0

我有一些代码检测圆形形状,但我无法理解它是如何工作的。OpenCV - 检测圆形形状

从这个代码:

  1. 我怎样才能找到圆的半径和中心点?
  2. `cv2.approxPolyDP'用于检测圆圈的行为是什么?

现在找到的轮廓在分段面具

contours, hierarchy = cv2.findContours(mask.copy(), cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_NONE) 

排序轮廓WRT轮廓矩形X

contours.sort(key = lambda x:cv2.boundingRect(x)[0]) 

for contour in contours: 
     approx = cv2.approxPolyDP(contour, 0.01*cv2.arcLength(contour,True), True) 
     if len(approx) > 8: 
      # Find the bounding rect of contour. 
      contour_bounding_rect = cv2.boundingRect(contour) 
      mid_point = contour_bounding_rect[0] + contour_bounding_rect[2]/2, contour_bounding_rect[1] + contour_bounding_rect[3]/2 
      print mid_point[1]/single_element_height, ", ", 

回答

1

查看文档所以我想通了回答你的第一个问题:确定图像在圈子的圆心和半径。

最初我找到图像中的所有轮廓。然后使用for loop,我发现中心半径使用cv2.minEnclosingCircle为图像中的每个轮廓。我将它们印在控制台屏幕上。

contours,hierarchy = cv2.findContours(thresh,2,1) 
print len(contours) 
cnt = contours 

for i in range (len(cnt)): 
    (x,y),radius = cv2.minEnclosingCircle(cnt[i]) 
    center = (int(x),int(y)) 
    radius = int(radius) 
    cv2.circle(img,center,radius,(0,255,0),2) 
    print 'Circle' + str(i) + ': Center =' + str(center) + 'Radius =' + str(radius) 

要回答你的第二个问题cv2.approxPolyDP();此函数根据名为'epsilon'的参数在图像中围绕对象绘制近似轮廓。 'epsilon'的值越高,轮廓就大致近似。对于较低的值epsilon,轮廓几乎会擦掉图像中物体的每个边缘。请访问THIS PAGE以获得更好的理解。

希望这有助于! :)

3

不要以为approxPolyDP是正确的方式去这里。

如果你有一个形象在你只有圈子,你想找到圆心和半径,尽量minEnclosingCircle()

如果你有,你有各种形状和你想找到圆的图像,尝试Hough变换(可能需要很长时间)或fitEllipse(),检查它返回的边界框是否为方形。

两个这些功能