Building a Generic Face Recognition Application in 2 Minutes
I’ve recently been on a journey to learn more about Deep Learning. I started off with a Deep Learning course on Udacity. It’s fairly long and does require some mathematical background but it was a good place to start.
However, if you want to start off lighter and simpler and introduce yourself to Deep Learning in a fun way, then this post is for you.
Let’s build an application (in literally 2 minutes) that can recognise faces. Here’s how I approached it using Python and a bunch of easy to use libraries.
1. Install OpenCV
As with most tutorials, a good starting point is to ensure you’ve got your environment set up. Download and install OpenCV for your OS of choice (and of course ensure you have Python installed too).
Now we can go ahead and follow a simple example from the OpenCV website to try and detect faces within your own supplied images.
2. Detecting your own face in an image
Create yourself a fresh directory and within it, place an image of yourself or a celebrity. There can be more than one person in the photo, but for this example, I just used a simple photo of myself.
We also need to copy in our Haar Cascades metadata file for detecting faces. The OpenCV download folder from the previous step contains a bunch of these for detecting different things such as eyes, ears etc. We want to detect the whole face so we will be using the
haarcascade_frontalface_default.xml. I found this within the following folder:
<open cv install dir>/opencv/opencv-<version number>/data/haarcascades/
Now we have our test image and our Haar Cascade file, we need to write a python application to detect the face. It’s a relatively simple application that looks as follows.
import sys# get paths for the image and haar cascade
imagePath = sys.argv
cascPath = sys.argv# Create the haar cascade
faceCascade = cv2.CascadeClassifier(cascPath)# Read the image and convert to gray
image = cv2.imread(imagePath)
gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)# now we can try to detect faces
faces = faceCascade.detectMultiScale(
flags = cv2.CASCADE_SCALE_IMAGE
)# Draw a rectangle around the faces and display on screen
for (x, y, w, h) in faces:
cv2.rectangle(image, (x, y), (x+w, y+h), (0, 255, 0), 2)cv2.imshow("Faces found", image)
I saved this in a file named
facerec.py. Run it with the following command to pass in firstly your test image, and then the Cascade file.
python facerec.py me.jpg haarcascade_frontalface_default.xml
I got the following output:
3. You’re Done!
As you can see, in very few lines of code, you can build an image detection application that is generic enough to detect a whole range of things. The only modification is the XML metadata file supplied at runtime.
Take a look at the different files within the Haarcascade folder and try passing them into your application instead and see what else you can detect using the same generic application.