OpenCV版本4.1.0 drawContours

use*_*662 4 python opencv image-processing computer-vision

我有以下与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
Run Code Online (Sandbox Code Playgroud)

错误是

cv2.error:OpenCV(4.1.0)/io/opencv/modules/imgproc/src/drawing.cpp:2509:错误:(-215:断言失败)函数'drawContours'中的npoints> 0

nat*_*ncy 5

取决于OpenCV版本,cv2.findContours()具有不同的返回签名。

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

image, contours, hierarchy = cv.findContours(image, mode, method[, contours[, hierarchy[, offset]]])
Run Code Online (Sandbox Code Playgroud)

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

contours, hierarchy = cv.findContours(image, mode, method[, contours[, hierarchy[, offset]]])
Run Code Online (Sandbox Code Playgroud)

无论使用哪种版本,都可以轻松获取轮廓:

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