OpenCV 4.1.0版drawContours

Posted

技术标签:

【中文标题】OpenCV 4.1.0版drawContours【英文标题】:OpenCV version 4.1.0 drawContours error: (-215:Assertion failed) npoints > 0 in function 'drawContours' 【发布时间】:2019-09-15 05:05:39 【问题描述】:

我的以下代码在 OpenCV 3.4.1 上运行良好,但现在不适用于 OpenCV 4.1.0 并出现错误。我不知道如何使代码适应较新的版本,你能帮我吗?非常感谢

def ImageProcessing(image):
    image = cv2.absdiff(image, background)
    h, gray = cv2.threshold(image, 65, 255, cv2.THRESH_BINARY_INV);
    gray = cv2.medianBlur(gray,5)

    kernel = np.ones((3,3), np.uint8)

    gray = cv2.erode(gray, kernel, iterations=1)#1

    des = cv2.bitwise_not(gray)
    tmp = cv2.findContours(des,cv2.RETR_CCOMP,cv2.CHAIN_APPROX_SIMPLE)
    contour, hier = tmp[1], tmp[0]

    for cnt in contour:
        cv2.drawContours(des,[cnt],0,255,-1)

    gray = cv2.bitwise_not(des)

    gray = cv2.dilate(gray, kernel, iterations=1)#1

    return gray

错误是

cv2.error: OpenCV(4.1.0) /io/opencv/modules/imgproc/src/drawing.cpp:2509: 错误: (-215:Assertion failed) npoints > 0 in function 'drawContours'

【问题讨论】:

尝试打印出 [cnt]。是点列表吗? contour, hier = tmp[1], tmp[0] -- 错了。结果元组的第一个元素是轮廓,第二个是层次结构。阅读documentation。 【参考方案1】:

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

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

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

在 OpenCV 4.1.X 中,cv2.findContours() 返回 2 个项目

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

无论版本如何,您都可以轻松获取轮廓:

tmp = cv2.findContours(des,cv2.RETR_CCOMP,cv2.CHAIN_APPROX_SIMPLE)
contours = tmp[0] if len(tmp) == 2 else tmp[1]

【讨论】:

以上是关于OpenCV 4.1.0版drawContours的主要内容,如果未能解决你的问题,请参考以下文章

链接 OpenCV 4.1.0,包括工作,库不

OpenCV版本4.1.0 drawContours

错误:OpenCV(4.1.0) 错误:(-215:Assertion failed) !ssize.empty() in function 'cv::resize'

发布 | OpenCV 4.1.0来啦!

类 DescriptorExtractor 在适用于 Android 的 opencv 4.1.0 中不可用

OpenCV 4.1.0 + Visual Studio 2019 开发环境搭建 超级简单