OpenCV:Canny边缘检测器获取minEnclosingCi

2024-04-26 21:17:24 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在使用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边缘检测器的结果格式错误,但我无法找到如何转换它,使其正常工作。在


Tags: inimportimgnotthiscv2opencv边缘
1条回答
网友
1楼 · 发布于 2024-04-26 21:17:24

这些函数的区别在于boundingRect作用于图像,而asminEnclosingCircle和{}作用于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)

相关问题 更多 >