如何解决cv2.drawContours()错误?

2024-04-25 18:14:07 发布

您现在位置:Python中文网/ 问答频道 /正文

我想在摄像机视频中找到轮廓,并用轮廓画出轮廓线

但我的代码有点错误:|

File ".\Contour.py", line 28, in <module>
    cv2.drawContours(frame, contours[i], 1, (0, 0, 255), 3)     
cv2.error: OpenCV(4.5.1) C:\Users\appveyor\AppData\Local\Temp\1\pip-req-build-r2ue8w6k\opencv\modules\imgproc\src\drawing.cpp:2490: error: 
(-215:Assertion failed) 0 <= contourIdx && contourIdx < (int)last in function 'cv::drawContours'

在这种情况下我该怎么办

我的完整代码

import cv2
import sys
import time
import numpy as np

cap = cv2.VideoCapture(0)

while True:
    # if cap.isOpened() == False:
    #     print("Cant Open The Camera")
    #     sys.exit(1)

    ret, frame = cap.read()

    # if ret == False:
    #     print("Can't load the Camera")
    #     sys.exit(1)
    
    gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
    thresh, binary = cv2.threshold(gray, 100, 255, cv2.THRESH_BINARY)
    contours = cv2.findContours(binary, cv2.RETR_CCOMP, cv2.CHAIN_APPROX_NONE)

    print(len(contours))
    
    if len(contours) > 0:
        # cnt = contours[len(contours) - 1]
        for i in range(len(contours)):
            cv2.drawContours(frame, contours[i], 1, (0, 0, 255), 3)     


    key = cv2.waitKey(1)

    cv2.imshow("frame", frame)
    # cv2.imshow("gray", gray)
    # cv2.imshow("binary", binary)
    time.sleep(0.5)
    if key == 27:
        break

cap.release()
cv2.destroyAllWindows()

我的环境

openCV:'4.5.1'

python:'3.7.0'

摄像头:笔记本电脑内置摄像头

:D


Tags: inimportlenifsyscv2frame轮廓
1条回答
网友
1楼 · 发布于 2024-04-25 18:14:07

cv2.drawContours需要一个列表和要打印的列表中的索引。在代码中,列表只有一项,因此1超出范围。 您可以使用以下代码修复此问题:

for i in range(len(contours):
    cv2.drawContours(frame, [contours[i]], 0, (0,0,255), 3)

如果要绘制所有轮廓,只需将所有轮廓传递给函数:

cv2.drawContours(frame, contours, -1, (0, 0, 255), 3)

作为旁注,由于cv2.drawContours会覆盖输入图像(frame在代码中),我建议在绘制轮廓之前创建一个副本,以便您可以保留原始图像,以便在需要时进行进一步处理:

output = frame.copy()
cv2.drawContours(output, contours, -1, (0, 0, 255), 3)

相关问题 更多 >