This is the code I am using to recognize faces in my webcam, but once the camera do not recognize a face, it is stopping to record and I want it countinuous.
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()
Look at your code closely...you're calling imshow()
method, which is responsible for showing the image, inside the for loop that is processing the detected faces.
This means that if faces are not detected, then that for
loop is not executed, and thus imshow()
is not called.
If you want to show the image regardless of detection result, move imshow()
call to the while
loop