Building a Generic Face Recognition Application in 2 Minutes

Just 24 Lines of Code and You’re Done!

Image for post
Image for post
Face Recognition (image source)

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).

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.

import cv2
import sys
# get paths for the image and haar cascade
imagePath = sys.argv[1]
cascPath = sys.argv[2]
# 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(
gray,
scaleFactor=1.1,
minNeighbors=5,
minSize=(30, 30),
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)
cv2.waitKey(0)
cv2.destroyAllWindows()
python facerec.py me.jpg haarcascade_frontalface_default.xml
Image for post
Image for post

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.

Written by

Data and Productivity Writer — Data Architect at easyfundraising.org.uk

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store