python - OpenCV 绘制轮廓错误断言失败

标签 python opencv contour cv2 opencv-drawcontour

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

导游没有

screenCnt = None



所以起初我得到了错误,比如 screenCnt 不存在

在我添加它之后,得到了断言失败
即使我使用与指南相同的图像并尝试了另一张图像
#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 (most recent call last): File "C:/Users/User/PycharmProjects/learn/project/app.py", line 218, in 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: error: (-215:Assertion failed) reader.ptr != NULL in function 'cvDrawContours'



有什么解决方案吗?之前谢谢

最佳答案

尝试替换 screenCnt = 0 而不是 None。让我知道。
供您引用,我提供了小代码片段:

(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

关于python - OpenCV 绘制轮廓错误断言失败,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57025443/

相关文章:

opencv - 如何将 pyplot.contour(..) 转换为等效的 opencv?

python - 在 Python 中的绘图中创建自定义刻度标签

python - 无法将 Jupyter 笔记本导出到 Azure ML Studio 中的 Python 脚本

matlab - 阅读未压缩的yuv视频文件的帧?

python - 如何使用 Opencv 捕获帧

r - 在contour() 中没有指定正确的 'z' 矩阵

python - SQLAlchemy 是否与 Django 的 get_or_create 等效?

python - 如何将 Faktory 与 ruby​​ 作业和 python 作业一起使用?

python - 在 generic.UpdateView 中传递上下文变量

c++ - OpenCV 中心单应