OpenCV:Canny边缘检测器获取最小外接圆。

3
我正在使用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个回答

4
这些函数的区别在于 boundingRect 适用于图像,而 minEnclosingCircleminAreaRect 适用于2D点集。如果要从Canny的输出中获取一个点集,则可以按照这个教程中建议的使用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)

3
我想补充一下,提供的 cv.findContours 函数适用于 OpenCV 版本 3.x.x。从 OpenCV 4.0.0 开始,该函数已更改为 contours, hierarchy = cv.findContours(...),请参见文档获取更多信息。 - HansHirse
谢谢@Hans,我已经在答案中包含了它。 - Cris Luengo

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接