OpenCV:Canny边缘检测器获取minEnclosingCircle

时间:2019-05-13 19:55:05

标签: python opencv image-processing

我正在使用Canny边缘检测器来检测白色背景上的物体,并想在其周围绘制一个矩形和一个圆形。我可以获取边界矩形的坐标,但无法获取OpenCV函数minAreaRectminEnclosingCircle的坐标。

import cv2
import numpy as np

img = cv2.imread(image.path, 0)
edges = cv2.Canny(img, 100, 200)

#Bounding Rectangle works
x, y, w, h = cv2.boundingRect(edges)

#This does not work
(x,y),radius = cv2.minEnclosingCircle(edges)

#This also does not work
rect = cv2.minAreaRect(edges)

错误:

Traceback (most recent call last):
  File "/home/hschneider/workspace/onspiration/website/venv/lib/python3.6/site-packages/IPython/core/interactiveshell.py", line 3296, in run_code
    exec(code_obj, self.user_global_ns, self.user_ns)
  File "<ipython-input-28-f9e34ac01335>", line 1, in <module>
    cv2.minEnclosingCircle(edges)
cv2.error: OpenCV(4.1.0) /io/opencv/modules/imgproc/src/shapedescr.cpp:160: error: (-215:Assertion failed) count >= 0 && (depth == CV_32F || depth == CV_32S) in function 'minEnclosingCircle'

我猜是因为Canny边缘检测器的结果格式错误,但我找不到如何对其进行转换以使其起作用的方法。

1 个答案:

答案 0 :(得分:2)

这些功能之间的区别在于boundingRect适用于图像,而minEnclosingCircleminAreaRect适用于2D点集。要从Canny的输出中获取一个点集,可以按照this tutorial中的建议,我们findCountours

# im2, contours, hierarchy = cv.findContours(thresh, 1, 2) # OpenCV 3.x
contours, hierarchy = cv.findContours(thresh, 1, 2)        # OpenCV 4.x
cnt = contours[0]

rect = cv.minAreaRect(cnt)

(x,y),radius = cv.minEnclosingCircle(cnt)