I have the code for live face detection:
import cv2
class FaceRec:
# Enable camera
cap = cv2.VideoCapture(0)
cap.set(3, 640)
cap.set(4, 420)
# import cascade file for facial recognition
faceCascade = cv2.CascadeClassifier(cv2.data.haarcascades + "haarcascade_frontalface_default.xml")
while True:
success, img = cap.read()
imgGray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
# Getting corners around the face
faces = faceCascade.detectMultiScale(imgGray, 1.3, 5) # 1.3 = scale factor, 5 = minimum neighbor
# drawing bounding box around face
for (x, y, w, h) in faces:
img = cv2.rectangle(img, (x, y), (x + w, y + h), (0, 255, 0), 3)
cv2.imshow('face_detect', img)
if cv2.waitKey(10) & 0xFF == ord('q'):
break
cap.release()
cv2.destroyWindow('face_detect')
This code uses the webcam to detect and draw a box around a face when it enters the frame. But I want it to run a code block once a face is detected. How would I go about doing so?
I tried to incorporate a while loop but the code in the loop ran before a face was detected when I want it to run ONLY when a face is detected.
The opencv documentation on cv2.CascadeClassifier.detectMultiScale
states that the function :
Detects objects of different sizes in the input image. The detected objects are returned as a list of rectangles.
Thus when no faces are detected, the list of rectangles returned is empty.
Your code can be as simple as
while True:
...
faces = faceCascade.detectMultiScale(imgGray, 1.3, 5)
if faces : # check if faces is not empty
... # do stuff
Obviously keep in mind that the test will have to be executed each loop to assert if there are still faces in front of the webcam or not.