大佬教程收集整理的这篇文章主要介绍了如何解决 cv2.drawContours() 错误?,大佬教程大佬觉得挺不错的,现在分享给大家,也给大家做个参考。
我想在相机视频中找到轮廓并用轮廓画线
但是我的代码出现错误:|
file ".\Contour.py",line 28,in <module>
cv2.drawContours(frame,contours[i],1,(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,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'
蟒蛇:'3.7.0'
摄像头:笔记本电脑内置摄像头
:D
cv2.drawContours
需要一个列表以及您要绘制的列表中的索引。在您的代码中,列表只有一项,因此 1 超出范围。
您可以使用以下代码修复该问题:
for i in range(len(contours):
cv2.drawContours(frame,[contours[i]],(0,255),3)
如果要绘制所有轮廓,只需将所有轮廓传递给函数:
cv2.drawContours(frame,contours,-1,3)
作为旁注,由于 cv2.drawContours
覆盖了输入图像(您代码中的 frame
),我建议在绘制轮廓之前创建一个副本,以便您可以保留原始图像以供进一步处理如果需要:
output = frame.copy()
cv2.drawContours(output,3)
以上是大佬教程为你收集整理的如何解决 cv2.drawContours() 错误?全部内容,希望文章能够帮你解决如何解决 cv2.drawContours() 错误?所遇到的程序开发问题。
如果觉得大佬教程网站内容还不错,欢迎将大佬教程推荐给程序员好友。
本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。