Chaotic Productions LLC

Bringing You The Future Of Design and Technology

FACIAL RECOGNITION


With this tutorial we will explore the basics of machine learning by creating our own facial recognition program using approximately 22 lines of Python code. For this tutorial you will need a working webcam, a Python IDE and OpenCV installed.

Conspiracies | Game Design | Illustrations | Random Generators | Science and Technology | Secret History | Tutorials


Facial Recognition Using Python and OpenCV

In this tutorial we will explore basic machine learning concepts by developing a simple facial recognition program in under 22 lines of code, using a webcam, Python 2.7, and the open source library OpenCV v2. OpenCV is a popular library for computer vision, which was originally written in C/C++, but now provides bindings for Python. This tutorial is based on Shantnu Tiwari's python blog, which can be found at https://realpython.com/blog/python/face-detection-in-python-using-a-webcam/.

In a future tutorial we will build our own cascades in OpenCV and teach it how to recognize other objects such as cars, bananas and toys. The task of recognizing individual faces is surprisingly difficult, but is possible using machine learning algorithms as described here.


Components and Software

Components and Software:

For this tutorial you will need a working webcam, OpenCV and a Python editor.

OpenCV, short for Open Source Computer Vision Library, can be found here. OpenCV is released under a BSD license and is free for both academic and commercial use. It has C++, C, Python, Java and MATLAB interfaces and supports Windows, Linux, Mac OS, iOS and Android systems. OpenCV was designed for computational efficiency and with a strong focus on real-time applications.

I use the PyCharm IDE by JetBrains for this project. PyCharm provides smart code completion, code inspections, on-the-fly error highlighting and quick-fixes, along with automated code refactorings and rich navigation capabilities.


The Code

import cv2

print("Booting...")
face = cv2.CascadeClassifier('haarcascades\haarcascade_frontalface_index.xml')
camera = cv2.VideoCapture(0)
while True:
# Capture images frame-by-frame
ret, frame = camera.read()

gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)

faces = face.detectMultiScale(
gray,
scaleFactor=1.2,
minNeighbors=5,
)
print "Found {0} faces!".format(len(faces))

# Draw a rectangle around each face
for (x, y, w, h) in faces:
cv2.rectangle(frame, (x, y), (x + w, y + h), (255, 0, 0), 0)

# Display the resulting frames
cv2.imshow('Video', frame)

if cv2.waitKey(1) & 0xFF == 27: # escape key
break
# When everything is done, release the capture
print("releasing camera and destroying windows")
camera.release()
cv2.destroyAllWindows()
Johnathan Nicolosi - 23 Sept 2017