openCV 3中轮廓区域的兼容性问题

2024-04-18 05:50:42 发布

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

我试图做一个简单的面积计算轮廓,我从findContours。 我的openCv版本是3.1.0

我的代码是:

cc = cv2.findContours(im_bw.copy(), cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)
cv2.contourArea(cc[0])

error: 'C:\\builds\\master_PackSlaveAddon-win32-vc12-static\\opencv\\modules\\imgproc\\src\\shapedescr.cp...: error: (-215) npoints >= 0 && (depth == CV_32F || depth == CV_32S) in function cv::contourArea\n'

似乎无法解决它,我有一种感觉,它只是一种排版,尽管我希望findContours的结果与轮廓区域的类型相匹配

谢谢:)

编辑:我需要用findContours的第二个参数

 im2, cc, hierarchy = cv2.findContours(im_bw.copy(), cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)

Tags: treechainerrorsimplecv2轮廓ccbw
3条回答

在Opencv 3 API版本中,cv2.findContours()返回3objects

  • 图像
  • 等高线
  • 层次结构

所以你需要把你的陈述改写为:

image, contours, hierarchy = cv2.findContours(im_bw.copy(), cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)

根据OpenCV版本的不同,cv2.findContours()具有不同的返回签名。

在OpenCV 3.4.X中,^{}返回3个项

image, contours, hierarchy = cv.findContours(image, mode, method[, contours[, hierarchy[, offset]]])

在OpenCV 2.X和4.1.X中,^{}返回2个项

contours, hierarchy = cv.findContours(image, mode, method[, contours[, hierarchy[, offset]]])

无论是哪种版本,您都可以轻松获得轮廓:

cnts = cv2.findContours(image, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
cnts = cnts[0] if len(cnts) == 2 else cnts[1]

这个问题是由不同OpenCV版本中cv2.findContours的返回值不同引起的。

在OpenCV 4.0.0中,这个错误可能看起来像cv2.error: OpenCV(4.0.0) C:\projects\opencv-python\opencv\modules\imgproc\src\convhull.cpp:137: error: (-215:Assertion failed) total >= 0 && (depth == CV_32F || depth == CV_32S) in function 'cv::convexHull'

您可以在这里找到详细的解释和解决方案:How to use `cv2.findContours` in different OpenCV versions?

相关问题 更多 >