# 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:
# 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()
Results:
Sources:
Data Science & AI Literacy Training Specialist @ LSE | AI, Data & EdTech
5 个月I thought I recognised the face! ??