+-
OpenCV版本4.1.0 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.drawContours(des,[cnt],0,255,-1)
cv2.error: OpenCV(4.1.0) /io/opencv/modules/imgproc/src/drawing.cpp:2509: error: (-215:Assertion failed) npoints > 0 in function 'drawContours'
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]