繁体   English   中英

opencv 在 python 显示错误未读取视频帧

[英]opencv in python showing a error not read video frame

使用 cv2 读取视频捕获帧但随时显示错误

错误是:

回溯(最近调用最后):文件“d:\pythonprojects\gym\demo.py”,第 33 行,在 <module> gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) cv2.error: OpenCV(4.7.0 ) D:\a\opencv-python\opencv-python\opencv\modules\imgproc\src\color.cpp:182: 错误: (-215:Assertion failed)._src:empty() in function 'cv::cvtColor '

代码是

<import cv2
import numpy as np
import os
from PIL import Image
from Attendance import attendance
from datetime import datetime
from database import\*

def getProfile(Id):
query="SELECT \* FROM users WHERE id="+str(Id)
cursor=mycursor.execute(query)
profile = mycursor.fetchone()
\# profile=None
\# for row in cursor:
\#     profile=row
\# con.close()
return profile

\# os.chdir(os.getcwd())

detector = cv2.CascadeClassifier('haarcascade_frontalface_default.xml')

recognizer = cv2.face.LBPHFaceRecognizer_create()
recognizer.read("face-trainner.yml")

cap = cv2.VideoCapture(0) #Get vidoe feed from the Camera
cap.set(3, 640)
cap.set(4, 480)
font = cv2.FONT_HERSHEY_COMPLEX
while(True):
ret, img = cap.read()
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
faces = detector.detectMultiScale(gray, 1.3, 5)
for (x,y,w,h) in faces:

        cv2.rectangle(img, (x,y), (x+w, y+h), (0,255,0), 2)
        roi_gray = gray[y:y+h, x:x+w]
        roi_color = img[y:y+h, x:x+w]
        
        nbr_predicted, conf = recognizer.predict(gray[y:y+h, x:x+w])
        print(nbr_predicted, conf)
        if(conf < 80):  
            profile=getProfile(nbr_predicted)
            if profile != None:
                time_now=datetime.now()
                newdate=time_now.strftime('%Y-%m-%d') 
                newtime=time_now.strftime('%H:%M:%S')
                attendance(nbr_predicted,newtime,newdate)
                cv2.putText(img, "Name: "+str(profile[4]), (x, y+h+30), font, 0.4, (0, 0, 255), 1)
                cv2.putText(img, "Gender: " + str(profile[7]), (x, y + h + 50), font, 0.4, (0, 0, 255), 1)
        else:
            cv2.putText(img, "Name: Unknown", (x, y + h + 30), font, 0.4, (0, 0, 255), 1)
    
        cv2.rectangle(img,(x,y),(x+w,y+h),(0,255,0),2)
    
    cv2.imshow('Preview',img) #Display the Video
    cv2.waitKey(1)
    
    # When everything done, release the capture
    cap.release()
    cv2.destroyAllWindows()

此错误似乎是由于img变量为 None 或为空。 不确定为什么在你的情况下它是 None 。 可能是摄像头未正确连接、未安装摄像头驱动程序、权限问题等多种原因。

您可以在cap.read()调用后添加一个条件:

...

while True:
    ret, img = cap.read()

    if img is None:
        print("Could not read frame from the source.")
        break

    gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)

...

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM