【问题标题】:findContours and drawContours errors in opencv 3 beta/pythonopencv 3 beta/python 中的 findContours 和 drawContours 错误
【发布时间】:2019-10-05 08:58:19
【问题描述】:

我尝试从here 运行一个示例。

import numpy as np
import cv2
img = cv2.imread('final.jpg')
imgray = cv2.cvtColor(img,cv2.COLOR_BGR2GRAY)
ret,thresh = cv2.threshold(imgray,127,255,0)
contours, hierarchy = cv2.findContours(thresh,cv2.RETR_TREE,cv2.CHAIN_APPROX_SIMPLE)
cv2.drawContours(img, contours, -1, (0,255,0), 3)

错误是

 Traceback (most recent call last):
   File "E:\PC\opencv3Try\findCExample.py", line 7, in <module>
contours, hierarchy = cv2.findContours(thresh,cv2.RETR_TREE,cv2.CHAIN_APPROX_SIMPLE)
 ValueError: too many values to unpack (expected 2)

如果我删除“层次结构”,drawContours 中会出现错误:

TypeError: contours is not a numpy array, neither a scalar

如果我在 drawContours 中使用轮廓 [0]

cv2.error: E:\opencv\opencv\sources\modules\imgproc\src\drawing.cpp:2171: error: (-215) npoints > 0 in function cv::drawContours

这里可能有什么问题?

【问题讨论】:

    标签: python opencv


    【解决方案1】:

    opencv 3 这里有一个略changed syntax,返回值不同:

    cv2.findContours(image, mode, method[, contours[, hierarchy[, offset]]]) → image, contours, hierarchy
    

    【讨论】:

    • OpenCV 3.0 的 Python 文档目前很难找到(上面的链接目前失败),所以我只是尝试了 3.0 中的 findContours() 是否仍然修改图像。确实如此,并且根据is,传递的图像和返回的图像是相同的。
    • Here's OpenCV 3.0.0-dev 文档的工作链接,其中显示了 Python 版本的 findContours 的三个返回值。
    【解决方案2】:

    按照 berak 的回答,只需将 [-2:] 添加到 findContours() 调用即可使其适用于 OpenCV 2.4 和 3.0:

    contours, hierarchy = cv2.findContours(...)[-2:]
    

    【讨论】:

      【解决方案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]
      for c in cnts:
          ...
      

      【讨论】:

        【解决方案4】:

        我之前遇到过同样的问题,我使用这段代码来修复它。 反正我用的是 3.1。

        (_,contours,_) = cv2.findContours(
          thresh.copy(),
          cv2.RETR_LIST,
          cv2.CHAIN_APPROX_SIMPLE
        )
        

        【讨论】:

          猜你喜欢
          • 2020-12-21
          • 2019-02-01
          • 2016-04-15
          • 2016-06-25
          • 1970-01-01
          • 2012-12-14
          • 2018-03-04
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多