# 22 Real-Time Face Detector with OpenCV

# 22 Real-Time Face Detector with OpenCV

Today, we will use the same concepts discussed in the previous article and build a real-time face detector. The code is really simple to replicate.

A brief recap on Haar Cascade:

This classifier is a machine learning-based approach used for object detection in images or videos. It works by training a cascade function on a set of positive and negative images. The classifier then uses features derived from Haar-like rectangular patterns to identify objects in new images or video frames.

Github:

  1. Installation and loading of the Haar Cascade Model

# Install the library 
%pip install opencv-python

# Importing the OpenCV library 
import cv2

# Load the Haar Cascade model 
face_classifier = cv2.CascadeClassifier(
    cv2.data.haarcascades + "haarcascade_frontalface_default.xml")        

2. Giving Permission to the webcam

# Giving access to the webcam 
video_capture = cv2.VideoCapture(0) # 0 parameter here means "use the default camera"        

3. Function for face detection

Note that here we are taking four key measurements for the face: x-axis, y-axis, width and height. These will help us in creating a bounding box around the face.

# Function to detect faces in the video stream and draw a bounding box around them 
def detect_bounding_box(vid): 
  gray_image = cv2.cvtColor(vid, cv2.COLOR_BGR2GRAY)
  faces = face_classifier.detectMultiScale(gray_image, 1.1, 5, minSize=(20,20))
  for (x, y, w, h) in faces: # x axis, y axis, width, height
    cv2.rectangle(vid, (x, y), (x + w, y + h), (0, 255, 0), 4)
  return faces        

4. The final loop which combines all functionalities

# A loop for Real-time Face Detection 
while True: 
  result, video_frame = video_capture.read()
  if result is False: 
    break # Terminate the loop if the frame is not read successfully 
  
  faces = detect_bounding_box(
      video_frame
  ) # apply the function we created to the video frame 

  cv2.imshow(
      "Face Detection Project", video_frame 
  ) # display the processed frame in a window named "My Face Detection Project

  if cv2.waitKey(1) & 0xFF == ord("q"):
    break 

video_capture.release()
cv2.destroyAllWindows()        

Full Code (Click Here)

Results:

Sources:

  1. Datacamp Article


Saqib Safdar

Data Science & AI Literacy Training Specialist @ LSE | AI, Data & EdTech

5 个月

I thought I recognised the face! ??

要查看或添加评论,请登录

社区洞察

其他会员也浏览了