OpenCV version 4.1.0 drawContours error: (-215:Assertion failed) npoints > 0 in function 'drawContours'

OpenCV version 4.1.0 drawContours error: (-215:Assertion failed) npoints > 0 in function 'drawContours'

我有以下代码在 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: error: (-215:Assertion failed) npoints > 0 in function 'drawContours'

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

在 OpenCV 3.4.X, cv2.findContours() returns 3 项

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

在 OpenCV 4.1.X, cv2.findContours() returns 2 项

contours, hierarchy = cv2.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]

由于最后两个值始终相同,我们可以使用 [-2:] 进一步将其压缩成一行,以从 cv2.findContours() 编辑的元组 return 中提取轮廓cv2.findContours()

cnts, _ = cv2.findContours(image, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)[-2:]

无论您 system/environment 中安装的 OpenCV 版本如何,以下代码片段都可以工作,并且还将所有元组存储在单个变量中。

首先,安装 OpenCV 的版本(我们不希望整个版本只是主版本号 3 或 4 ) :

import cv2
version = cv2.__version__[0]

根据版本,将执行以下两个语句之一并填充相应的变量:

if version == str(4):
    contours, hierarchy = cv2.findContours(binary_img, cv2.RETR_TREE, cv.CHAIN_APPROX_SIMPLE)

elif version == str(3):
    im, contours, hierarchy = cv2.findContours(binary_img, cv2.RETR_TREE, cv.CHAIN_APPROX_SIMPLE)

两种情况下从函数返回的轮廓将存储在contours

Note: the above snippet is written assuming either version 3 or 4 of OpenCV is installed. For older versions, please refer to the documentation or update to the latest.