【问题标题】:This piece of code is showing error while working with openCV webcam这段代码在使用 openCV 网络摄像头时显示错误
【发布时间】:2019-11-28 04:51:01
【问题描述】:

我正在使用 haarcascade face detection 使用 opencv。但是这个错误正在蔓延,我无法得到这个。所以请指导我。

OpenCV(4.1.0) C:\projects\opencv-python\opencv\modules\imgproc\src\color.cpp:182: 错误: (-215:Assertion failed) !_src.empty() in function ' cv::cvtColor'

import cv2
def videoCam():
    cap=cv2.VideoCapture(0)
    face_cascade=cv2.CascadeClassifier("haarcascade_frontalface_alt.xml")
    while (True):
        ret,frame=cap.read()
        gray_frame=cv2.cvtColor(frame,cv2.COLOR_BGR2GRAY)
        if (ret==False):
            continue
        faces=face_cascade.detectMultiScale(gray_frame,1.3,5)
        for(x,y,w,h) in faces:
            cv2.rectangle(frame,(x,y),(x+w,y+h),(255,0,0),2)
        cv2.imshow("Video Frame",frame)
        key_pressed=cv2.waitKey(1) & 0xff
        if(key_pressed==ord('q')):
            break

    cap.release()
    cv2.destroyAllWindows()
videoCam()

【问题讨论】:

    标签: opencv webcam


    【解决方案1】:

    您遇到了上述错误,因为 framecv2.cvtColor 函数中是 None。请验证cv2.VideoCapture 函数的输入。这是一个设备索引,它只是指定哪个相机的数字。您上面没有提到您使用的是哪个相机,即内部或外部相机。从here 了解要使用的设备索引。您可以在cv2.VideoCapture 函数之后使用print(cap.isOpened()) 检查VideoCapture() 方法是否已经初始化了您的相机对象。如果成功初始化您的相机对象,它将返回True

    还有,为什么要这样做

    if (ret==False):
        continue
    

    cv2.cvtColor 之后。这样做的主要目的是检查帧是否被正确读取。如果图像被正确读取,ret 将是 True,否则为 False。所以,你应该在使用cv2.cvtColor函数之前检查这个,如果它返回False,那么你应该从循环中break,而不是使用continue,否则while循环将继续无限运行。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-03-06
      • 2016-07-22
      • 1970-01-01
      • 2011-02-05
      • 2012-08-08
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多