- Import the necessary packages:
import cv2 import numpy as np
- Load the face cascade file:
frontalface_cascade= cv2.CascadeClassifier('haarcascade_frontalface_alt.xml')
- Check whether the face cascade file has been loaded:
if frontalface_cascade.empty(): raiseIOError('Unable to load the face cascade classifier xml file')
- Initialize the video capture object:
capture = cv2.VideoCapture(0)
- Define the scaling factor:
scale_factor = 0.5
- Perform the operation until the Esc key is pressed:
# Loop until you hit the Esc key while True:
- Capture the current frame and resize it:
ret, frame = capture.read() frame = cv2.resize(frame, None, fx=scale_factor, fy=scale_factor, interpolation=cv2.INTER_AREA)
- Convert the image frame into grayscale:
gray_image = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
- Run the face detector on the grayscale image:
face_rectangle = frontalface_cascade.detectMultiScale(gray_image, 1.3, 5)
- Draw the rectangles box:
for (x,y,w,h) in face_rectangle: cv2.rectangle(frame, (x,y), (x+w,y+h), (0,255,0), 3)
- Display the output image:
cv2.imshow('Face Detector', frame)
- Check whether the Esc key has been pressed for operation termination:
a = cv2.waitKey(1) if a == 10: break
- Stop the video capturing and terminate the operation:
capture.release() cv2.destroyAllWindows()
The result obtained in the human face detection system is shown here: