Real-Time Webcam Face Detection System using OpenCV in Python — Windows and macOS

Venkatesh Chandra
Analytics Vidhya
Published in
4 min readJan 2, 2020
Face detection via webcam

Face detection uses computer vision to extract information from images to recognize human faces. In this project, we will learn how to create a face detection system using python in easy steps. The input to the system will be in real-time via the webcam of the computer.

Libraries to be installed in pip (Windows + macOS)

  1. OpenCV (Open Source Computer Vision) library: It is built to help developers carry out tasks related to computer vision.
pip install opencv-python

Next, we need to install face recognition APIs

2. dlib library: dlib is built through pre-trained models to locate the facial landmarks.

pip install dlib

3. face_recognition library: face_recognition is an open-source project, which is also known as the most straightforwardAPI for facial recognition.

pip install face_recognition

Let’s get into some action in Python

Now, we have the required libraries installed. We will start implementing the codes as shown below. I have explained each block of code to help you understand what is happening in the background.

Feel free to skip to the end of this page to get the link to full code.

Step 1: Open Spyder

Step 2: Import the libraries

import cv2
import face_recognition

Step 3: Reference your system’s webcam

video_capture = cv2.VideoCapture(0)

Step 4: Initialize the required variables. These variables will be populated later on in the code

face_locations = []

Step 5: We divide our video (real-time) into different frames. In each frame, we detect the location of the face using the APIs which we have imported above. For each face detected, we locate the coordinates and draw a rectangle around it and release the video to the viewer.

The full code is shown below — explanations follow below the code

while True:
# Grab a single frame of video
ret, frame = video_capture.read()
# Convert the image from BGR color (which OpenCV uses) to RGB color (which face_recognition uses)
rgb_frame = frame[:, :, ::-1]
# Find all the faces in the current frame of video
face_locations = face_recognition.face_locations(rgb_frame)
# Display the results
for top, right, bottom, left in face_locations:
# Draw a box around the face
cv2.rectangle(frame, (left, top), (right, bottom), (0, 0, 255), 2)
# Display the resulting image
cv2.imshow(‘Video’, frame)
# Hit ‘q’ on the keyboard to quit!
if cv2.waitKey(1) & 0xFF == ord(‘q’):
break

Block 1:

# Grab a single frame of video
ret, frame = video_capture.read()
# Convert the image from BGR color (which OpenCV uses) to RGB color (which face_recognition uses)
rgb_frame = frame[:, :, ::-1]

Here, we process one frame at a time. The frame is extracted using cv2 library which captures the frame in BGR (Blue-Green-Red) colors, while the face recognition library uses RGB (Red-Green-Blue) format. Hence we flip the color code of the frame.

Block 2:

 face_locations = face_recognition.face_locations(rgb_frame)

Here, we locate the coordinates of the faces present in the frame. The list face_locations is populated with the x, y coordinates, and the width and height of the faces detected.

Block 3:

 for top, right, bottom, left in face_locations:
# Draw a box around the face
cv2.rectangle(frame, (left, top), (right, bottom), (0, 0, 255), 2)

Here, we draw a rectangle around each of the faces captured. The rectangle starts at the x and y coordinates (left and top in this case), and extend up to the width and height of the face detected (right and bottom in this case). The codes (0, 0, 255) represent the color codes in B-G-R sequence.

Block 4:

 cv2.imshow(‘Video’, frame) if cv2.waitKey(1) & 0xFF == ord(‘q’):
break

The resulting image (frame) is released to the viewer and the loop continues to run until the user hits the q key on the keyboard.

Step 6: All captured videos must be released.

video_capture.release()
cv2.destroyAllWindows()

Run the program in the command line

The next step is to save the file in .py format and run it in command line/Anaconda prompt.

I ran it in Anaconda prompt by first navigating to the folder using the command cd.

cd <folder path>

Run the python file

python filename.py

You will see a pop-up window and your webcam will turn on. Try moving your face or ask your friend(s) to join you in the frame. The face detection system will detect all the faces. You can experiment with pictures as well.

Voila! You have successfully built a real-time face detection system.

If you face any issues, let me know in the comments section.

Codes

https://github.com/chandravenky/Computer-Vision---Object-Detection-in-Python/tree/master

Related links

Face Detection on recorded videos in Python — Windows and macOS

Vehicle Detection in Python using OpenCV — Windows and macOS

Pedestrian Detection in Python using OpenCV— Windows and macOS

Saving output of object recognition in macOS

Where to find me 🤓

  1. Connect with me on LinkedIn/ GitHub / My website
  2. Feeling generous? Buy me a coffee here ☕️

--

--