Face Detection with Python and OpenCV

Recently I started playing with OpenCV and Python to experience ML & AI. I wrote a small Python program for face detection using OpenCV and Face detection API.

I don’t necessarily understand what’s going on behind the scene and something I’ll continue to explore but it was really quick and easy to bring these libraries together to detect faces.

This is program is written in Python3 and requires following libraries:

pip3 install opencv-python
pip3 install dlib
pip3 install face_recoginition

Here’s the program that will detect faces from computer’s video cam. The code is self-explanatory:

import cv2
import face_recognition

video = cv2.VideoCapture(0)

face_locations = []

while True:

ret, frame = video.read()

rgb_frame = frame[:,:,::-1]
face_locations = face_recognition.face_locations(rgb_frame)

for top, right, bottom, left in face_locations:
cv2.rectangle(frame,(left, top),(right, bottom),(255, 0, 0), 2)

cv2.namedWindow('face detector', cv2.WINDOW_NORMAL)
cv2.imshow('face detector', frame)

if cv2.waitKey(1) & 0xFF == ord('x'):


Here’s the output when you run the program with face detected in blue rectangle:


Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s