How to do it...

  1. Import the necessary packages:
import cv2 
import numpy as np 
  1. Load the face cascade file:
frontalface_cascade= cv2.CascadeClassifier('haarcascade_frontalface_alt.xml') 
  1. Check whether the face cascade file has been loaded:
if frontalface_cascade.empty(): 
  raiseIOError('Unable to load the face cascade classifier xml file') 
  1. Initialize the video capture object:
capture = cv2.VideoCapture(0) 
  1. Define the scaling factor:
scale_factor = 0.5 
  1. Perform the operation until the Esc key is pressed:
# Loop until you hit the Esc key 
while True: 
  1. 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) 
  1. Convert the image frame into grayscale:
  gray_image = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY) 
  1. Run the face detector on the grayscale image:
  face_rectangle = frontalface_cascade.detectMultiScale(gray_image, 1.3, 5)
  1. 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) 
  1. Display the output image:
    cv2.imshow('Face Detector', frame) 
  1. Check whether the Esc key has been pressed for operation termination:
  a = cv2.waitKey(1) 
  if a == 10: 
    break 
  1. Stop the video capturing and terminate the operation:
capture.release() 
cv2.destroyAllWindows() 

The result obtained in the human face detection system is shown here:

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.17.174.0