Face detection in Python - On your own in few lines of code
Tags: python, opensource, tutorial, terminal
Published: 2021-11-02 21:51:22

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] (https://github.com/blobcity/ai-seed/blob/main/Audio%20Visual/Problems/FaceDetection_OpenCV.ipynb). 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](https://brew.sh). 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 <code>facevirtual</code> environment so your command prompt will look like this.

```
(facevirtual) username@123 facevirtual % 
```

##Install needed Libraries
Create in <code>facevirtual</code> directory txt file named <code>requirements.txt</code> 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](https://github.com/opencv/opencv/tree/master/data/haarcascades) and look for <code>haarcascade_frontalface_default.xml</code>. Easier for you to save this [click this link](https://raw.githubusercontent.com/opencv/opencv/master/data/haarcascades/haarcascade_frontalface_default.xml) and press save as to download file into <code>facevirtual</code> 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](https://en.wikipedia.org/wiki/Syndics_of_the_Drapers%27_Guild#/media/File:Rembrandt_-_De_Staalmeesters-_het_college_van_staalmeesters_(waardijns)_van_het_Amsterdamse_lakenbereidersgilde_-_Google_Art_Project.jpg) to save this image into <code>facevirtual</code> directory as <code>test.jpg</code>. 

Now create a python file. Let's name it <code>face-recognition.py</code> 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 <code>cv2.CascadeClassifier('haarcascade_frontalface_default.xml')</code> load Cascade Classifier and it is responsible for detecting frontal faces on our source picture. The last thing to know that <code>img = cv2.imread('test.jpg')</code> load the image we already saved from Wikipedia to process.

```python
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 <code>requirements.txt</code> 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](https://en.wikipedia.org/wiki/Syndics_of_the_Drapers%27_Guild#/media/File:Rembrandt_-_De_Staalmeesters-_het_college_van_staalmeesters_(waardijns)_van_het_Amsterdamse_lakenbereidersgilde_-_Google_Art_Project.jpg) for the cover image.