【问题标题】:OpenCV Drawing Contour Error Assertion FailedOpenCV 绘制轮廓错误断言失败
【发布时间】:2019-11-23 07:29:27
【问题描述】:

所以我正在尝试遵循有关如何在https://www.pyimagesearch.com/2014/09/01/build-kick-ass-mobile-document-scanner-just-5-minutes/ 中扫描文档的指南 正是在我应该找到轮廓并将其绘制到图像的第 2 步过程中,在 drawContour 函数上出现“断言失败”错误

指南没有

screenCnt = 无

所以一开始我得到了错误,比如 screenCnt 不存在

在我添加它之后,得到了 Assertion Failed 代替 即使我使用了与指南相同的图像并尝试了另一张图像

#find contour
cnts = cv2.findContours(edged.copy(), cv2.RETR_LIST, cv2.CHAIN_APPROX_SIMPLE)
cnts = imutils.grab_contours(cnts)
cnts = cnts[0] if imutils.is_cv2() else cnts[1]
cnts = sorted(cnts, key=cv2.contourArea, reverse=True)[:5]
screenCnt = None

# loop over the contours
for c in cnts:
    peri = cv2.arcLength(c, True)
    approx = cv2.approxPolyDP(c, 0.02 * peri, True)
    if len(approx) == 4:
        screenCnt = approx
        break

#draw contour
cv2.drawContours(image, [screenCnt], -1, (0, 255, 0), 2)

这是我得到的:

Traceback(最近一次调用最后一次):文件 “C:/Users/User/PycharmProjects/learn/project/app.py”,第 218 行,在 cv2.drawContours(image, [screenCnt], -1, (0, 255, 0), 2)

cv2.error: OpenCV(4.1.0) C:\projects\opencv-python\opencv\modules\imgproc\src\drawing.cpp:2606: 错误:(-215:断言失败)reader.ptr != NULL in function 'cvDrawContours'

有什么解决办法吗?谢谢之前

【问题讨论】:

    标签: python opencv contour cv2 opencv-drawcontour


    【解决方案1】:

    尝试将所有输入打印到您提供的函数中。我想你可能会发现一些不对劲的地方。 请在下面的 cmets 中告诉我。

    【讨论】:

    • 似乎 approx 的长度永远不会达到 4,因为我试图打印我得到的这个 [[[ 87 452]]] [[[ 88 451]]] [[[ 90 453] ]] [[[ 90 455]]] [[[ 91 456]]]
    • 这就是问题所在。尝试删除 if 条件并将 screenCnt 的大小限制为 4。
    • 基本上你在你的图像周围拟合一个多项式。因此,当您不提供绘制 contrours 的点时,它会说空指针异常。要解决该错误,您可以在 screenCNT 中提供虚拟点(4 个点),它将得到解决。我想你可以从这里开始:)
    • 我仍然很困惑,如果我提供虚拟点,该函数如何在图像周围正确绘制矩形?对不起,如果我不能快速赶上,这是我第一次使用 Python
    【解决方案2】:

    尝试替换 screenCnt = 0 而不是 None。让我知道。 供大家参考,我提供小代码sn-p:

    (cnts, contours, heirarchy) = cv2.findContours(edged.copy(), 
    cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)
    
    cnts = contours[0]
    screenCnt = 0
    
    for contour in contours:
        # get rectangle bounding contour
        [x,y,w,h] = cv2.boundingRect(contour)
    
    # draw rectangle around contour on original image
    #cv2.rectangle(image,(x,y),(x+w,y+h),(255,0,255),2)
    
    ##### code added..for thresholding
    for c in cnts:
        # approximate the contour
        peri = cv2.arcLength(c, True)
        approx = cv2.approxPolyDP(c, 0.02 * peri, True)
    
        # if our approximated contour has four points, then
        # we can assume that we have found our screen
        if len(approx) == 4:
            screenCnt = approx
            break
    

    【讨论】:

    • x,y,w,h 是轮廓变量的一部分吗?由于这些原因,我遇到了错误
    • 不,那是注释部分。
    • 感谢我尝试了您的部分代码和其他一些指南,现在我可以随意放置轮廓了。无论如何,您从事 AI 相关主题的工作吗?我看到了你作为 AI 工程师的个人资料
    • 是的,我从 4 年开始就是 AI 工程师了
    猜你喜欢
    • 2019-07-05
    • 1970-01-01
    • 2013-09-15
    • 2017-07-14
    • 1970-01-01
    • 1970-01-01
    • 2018-05-20
    • 2021-09-07
    • 2017-10-26
    相关资源
    最近更新 更多