【问题标题】:compatibility issue with contourArea in openCV 3openCV 3中contourArea的兼容性问题
【发布时间】:2017-01-21 08:32:25
【问题描述】:

我正在尝试对从 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)

【问题讨论】:

  • 你检查过 cc[0] 是否为空吗?
  • 挖多了才发现,原来我需要得到findContours的第二个参数

标签: python opencv opencv3.0


【解决方案1】:

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

  • 图片
  • 轮廓
  • 层次结构

所以你需要将你的陈述重写为:

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

【讨论】:

  • 拯救了我的夜晚,tks!
【解决方案2】:

这个问题是由于不同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?

【讨论】:

    【解决方案3】:

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

    在 OpenCV 3.4.X 中,cv2.findContours() 返回 3 个项目

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

    在 OpenCV 2.X 和 4.1.X 中,cv2.findContours() 返回 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]
    

    【讨论】:

      【解决方案4】:

      感谢@ZdaR; 顺便说一句,您可以在 OpenCV 4.1 中执行以下操作:

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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2021-03-16
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多