Face Detection in Python

demg_dev

David Mendez Guardado

Posted on July 17, 2019

Face Detection in Python

Hi in this post i'll show you how to use OpenCV library to detect faces inside a picture, in a future post i'll show you how to detect in a Real-Time video that was amazing stuff to practice the visual recognition.

well let's start

Requirements

check your version of python or install python 3.6.

python--version
Enter fullscreen mode Exit fullscreen mode

then we need to install OpenCV library by searching in the official webpage, in my local environment i use the OpenCV v4.1 you can use instead a previous version v3.X, i recommend you to follow the official
instructions to install in the documentation.

Code the Face Detection solution

Now we start coding the face detection program. First need to import the OpenCV library and the system library(could be optional, i use this library to get a parameter when i run the python code).

import cv2
import sys
Enter fullscreen mode Exit fullscreen mode

Next to import statements, we need to get the parameter passed from the user, this parameter was the picture to test in the face detection program.

# Get user supplied values
imagePath = sys.argv[1]
Enter fullscreen mode Exit fullscreen mode

In the next part we need to add in our code the magic for face detection this part is called Haar Cascade feature; you maybe ask why is a haar cascade, well now i'll explain you what it is.

Object Detection using Haar feature-based cascade classifiers is an effective object detection method proposed by Paul Viola and Michael Jones in their paper, "Rapid Object Detection using a Boosted Cascade of Simple Features" in 2001. It is a machine learning based approach where a cascade function is trained from a lot of positive and negative images. It is then used to detect objects in other images. Here we will work with face detection. Initially, the algorithm needs a lot of positive images (images of faces) and negative images (images without faces) to train the classifier. Then we need to extract features from it. For this, haar features shown in below image are used. They are just like our convolutional kernel. Each feature is a single value obtained by subtracting sum of pixels under white rectangle from sum of pixels under black rectangle. Now we have an idea was the HaarCascade can continue with the code, i'm using the Haar cascade file created by Rainer Lienhart ( the file you found in the repository of the code), we need to add the file to the code.

  • by OpenCV docuentation
cascPath = "haarcascade_frontalface_default.xml"
Enter fullscreen mode Exit fullscreen mode

Next, we need to train the OpenCV classifier with the haar cascade file.

# Create the haar cascade
faceCascade = cv2.CascadeClassifier(cascPath)
Enter fullscreen mode Exit fullscreen mode

In the next step we need to read the image and set to gray color because OpenCV do better job with gray scale pictures with haar cascade classifier.

# Read the image
image = cv2.imread(imagePath)
gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
Enter fullscreen mode Exit fullscreen mode

In this part the magic is done, the OpenCV framework do the magic detecting the faces inside an image and return the position of the face in the image, you can adjust the parameters to get more detailed results or more crazy haha!!!.

# Detect faces in the image
faces = faceCascade.detectMultiScale(
    gray,
    scaleFactor = 1.05,
    minNeighbors = 5,
    minSize = (30, 30),
    flags = cv2.CASCADE_SCALE_IMAGE
)
Enter fullscreen mode Exit fullscreen mode

To finish our code for face detection just print the number of faces found in the image and then draw a rectangle with the face inside them, and show a windows with the images and the faces rounded; for close the window press any key.

print("Found {0} faces!".format(len(faces)))

# Draw a rectangle around the faces
for (x, y, w, h) in faces:
    cv2.rectangle(image, (x, y), (x + w, y + h), (0, 255, 0), 2)

height, width, channels = image.shape
cv2.imshow("{0} Faces found".format(len(faces)), image)
cv2.waitKey(0)
Enter fullscreen mode Exit fullscreen mode

This is an example of the result more accurate.

Lot people good quiality

Like you see in the image they recognize a hand like a face, that was some of the issues i found, i try to set more accurate values but it detect less faces you can play with it to see how it works.

And this is another example, like you see detect many faces in a low resolution picture but have a lot of errors, in this image and this configurations only 1 face is not detected.

Lot of people low quiality

Complete code

Here is the complete code, like you see only takes 33 lines with white spaces, it is a really short program with powerfull applications.

import cv2
import sys

# Get user supplied values
imagePath = sys.argv[1]
cascPath = "haarcascade_frontalface_default.xml"

# Create the haar cascade
faceCascade = cv2.CascadeClassifier(cascPath)

# Read the image
image = cv2.imread(imagePath)
gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)

# Detect faces in the image
faces = faceCascade.detectMultiScale(
    gray,
    scaleFactor = 1.05,
    minNeighbors = 5,
    minSize = (30, 30),
    flags = cv2.CASCADE_SCALE_IMAGE
)

print("Found {0} faces!".format(len(faces)))

# Draw a rectangle around the faces
for (x, y, w, h) in faces:
    cv2.rectangle(image, (x, y), (x + w, y + h), (0, 255, 0), 2)

height, width, channels = image.shape
cv2.imshow("{0} Faces found".format(len(faces)), image)
cv2.waitKey(0)
Enter fullscreen mode Exit fullscreen mode

Conclusion

For finish this post, like you see, if you use the actual solution the face detection you can develop a more detailed program like a doorbell or something like a cam in the traffic light to detect a face and maybe do a better
recognition of the person face.

Next to this you maybe try to do the same program but in a real video or wait for my next post to learn how to do it.

💖 💪 🙅 🚩
demg_dev
David Mendez Guardado

Posted on July 17, 2019

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related

Face Detection in Python
python Face Detection in Python

July 17, 2019