Face detection in Python - On your own in few lines of code
Stan Kukučka
Posted on November 2, 2021
Let's do some face detection to a picture you would love to play with. It can be even a painting from Wikipedia you have already downloaded. In this brief tutorial, I'll go step by step to provide you solution to such a recognition potential that python as a programming language and its libraries have.
Inspiration and part of the source of code comes from this jupiter notebook file. The purpose of this article was to enrich the whole process with steps I have been missing and can be helpful for the reader or tester of this detection to easily pass through.
I would like to go step by step with this installation, cos if you'll try to do this on a fresh system there will be missing quite a lot of installing libraries to have this all properly working for you. So let's start with brew.
Let's Install Brew installation environment
The easiest way how to install all that's needed is to start with Brew. It installs the stuff you need that Apple didn’t. Copy and paste a bunch of the long code from this website and execute it.
/bin/bash -c "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/HEAD/install.sh)"
Then after just simply update all installation.
brew update
Let's Install Python3
Now we can install Python3 cos what? Cos we have brew already installed and that's why it will be super easy. The next step is to update pip into pip3 cos we have python3 installation finalised. With sudo it will ask for a system password, so just simply provide your pwd.
brew install python3
sudo pip3 install --upgrade pip
Install Environment
For the next work, we'll need a virtual environment. To understand what it is try to imagine some virtual container where all installations will go into.
pip3 install virtualenv
Create Virtualenv
We will start with directory creation to where all next installations will go to.
mkdir facevirtual
cd facevirtual
virtualenv facevirtual
source facevirtual/bin/activate
After execution of the last command, you'll activate facevirtual
environment so your command prompt will look like this.
(facevirtual) username@123 facevirtual %
Install needed Libraries
Create in facevirtual
directory txt file named requirements.txt
and paste inside this bunch of the code.
cycler==0.10.0
kiwisolver==1.3.2
matplotlib==3.4.3
numpy==1.21.2
opencv-python==4.5.3.56
Pillow==8.3.2
pyparsing==2.4.7
python-dateutil==2.8.2
six==1.16.0
These are necessary to work with the script correctly and have all, that it ask for. To execute it just type into the terminal this simple command.
pip3 install -r requirements.txt
This will help you to execute the script, we will create, withou asking for additional installation.
How To Create Cascade Classifier
Now we need Haar-cascade Classifier. It's a machine-learning algorithm already trained with tons of images. We gonna use a classifier that considers the human frontal faces to recognize in our target image.
Open this link and look for haarcascade_frontalface_default.xml
. Easier for you to save this click this link and press save as to download file into facevirtual
directory
We need image and script
Let's download image from the internet. It will be Rembrandt's painting Syndics of the Drapers. Here is a link to the image to save this image into facevirtual
directory as test.jpg
.
Now create a python file. Let's name it face-recognition.py
and save into this for now empty file this bunch of the code you see hereunder.
No need to edit anything in script just be knowledged that cv2.CascadeClassifier('haarcascade_frontalface_default.xml')
load Cascade Classifier and it is responsible for detecting frontal faces on our source picture. The last thing to know that img = cv2.imread('test.jpg')
load the image we already saved from Wikipedia to process.
import cv2 #For importing OpenCV library
import matplotlib.pyplot as plt #For plotting the image
# Read Cascade Classifier
face_cascade = cv2.CascadeClassifier('haarcascade_frontalface_default.xml')
# Reading source image to process, update name of image with your own
img = cv2.imread('test.jpg')
# Detect faces
faces = face_cascade.detectMultiScale(image = img, scaleFactor = 1.1, minNeighbors = 5)
# Draw bounding box around the faces
for (x, y, w, h) in faces:
cv2.rectangle(img, (x, y), (x+w, y+h), (255, 0, 0), 1)
# Showing number of faces detected in the image
print(len(faces),"faces are detected!")
# In this step it does plotting the image with faces detected
finalimg = cv2.cvtColor(img, cv2.COLOR_RGB2BGR)
plt.figure(figsize=(12,12))
plt.imshow(finalimg)
plt.axis("off")
plt.show()
Execute the script and see results.
In this final step just type into a terminal command to execute the script we already created and wait for a while for the result. No need to install anything else cos we already fulfil his requirements with help of requirements.txt
file to install all necessary libraries.
python3 face-recognition.py
You should be rewarded with an image where all faces on the painting are marked with a blue square. In the terminal, you'll find information on how many faces has been marked so the text will be as hereunder.
6 faces are detected!
Thanks to Wikipedia for the cover image.
Posted on November 2, 2021
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.