这是我用来识别网络摄像头中的脸部的代码,但是一旦相机无法识别脸部,它就会停止录制,我希望它是连续的。
import cv2
import logging as log
from time import sleep
import datetime as dt
import numpy as np
cascPath = "haarcascade_frontalface_default.xml"
faceCascade = cv2.CascadeClassifier(cascPath)
cam = cv2.VideoCapture(0);
anterior = 0
log.basicConfig(filename='webcam.log',level=log.INFO)
rec = cv2.face.LBPHFaceRecognizer_create();
rec.read('recognizer/trainningData.yml')
id=0
font = cv2.FONT_HERSHEY_SIMPLEX
fontscale = 1
fontcolor = (255,255,255)
while(True):
if not cam.isOpened():
print('Unable to load camera.')
sleep(5)
pass
ret, img = cam.read();
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
faces = faceCascade.detectMultiScale(gray, scaleFactor=1.1,minNeighbors=5,minSize=(30, 30))
for(x, y, w, h) in faces:
cv2.rectangle(img, (x,y), (x+w, y+h), (0,255,0),2)
id, conf = rec.predict(gray[y:y+h,x:x+w])
if(id == 1):
id = "Nome do usuário detectado";
cv2.putText(img,str(id),(x,y-10),font,0.55,(0,255,0),1);
cv2.imshow("Face", img);
if(conf<=20):
if(id!=None):
cv2.putText(img,str(id),(x,y-10),font,0.55,(0,255,0),1);
else:
cv2.putText(img,"Unknown",(x,y+h-10),font,0.55, (0,255,0),1);
if anterior != len(faces):
anterior = len(faces)
log.info("ID: " + str(id) + " faces: "+str(len(faces))+" at "+str(dt.datetime.now()))
if(cv2.waitKey(1)==ord('q')):
break;
cam.release()
cv2.destroyAllWindows()
答案 0 :(得分:0)
仔细查看您的代码......您正在调用imshow()
方法,该方法负责在处理检测到的面部的for循环内显示图像。
这意味着如果未检测到faces,则不会执行for
循环,因此不会调用imshow()
。
如果要显示图像而不考虑检测结果,请将imshow()
调用移至while
循环