OpenCV版本4.1.0 drawContours

发布于 2021-01-29 15:05:58

我有以下与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:断言失败)函数’drawContours’中的npoints>
0

关注者
0
被浏览
45
1 个回答
  • 面试哥
    面试哥 2021-01-29
    为面试而生,有面试问题,就找面试哥。

    根据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]
    


知识点
面圈网VIP题库

面圈网VIP题库全新上线,海量真题题库资源。 90大类考试,超10万份考试真题开放下载啦

去下载看看