Face recognition Python

Face recognition Python

In the Face recognition python article, we are going to build a project using which anyone will be able to detect faces. Have you ever noticed that Facebook automatically tags your friends when you try to upload a group photo? It can identify an individual using their face and this is one of the exciting examples of face detection python. Let’s start building our face recognition project by getting some insights into what face recognition and detection are.

What is Face detection python?

Face detection python means the process of locating and extracting faces in an image by a face detection algorithm in python. The algorithm uses the location and size of features like eyes, and mouth, to detect the face using python. This is the first step in the face recognition process. You might have seen the application of face detection on mobile phones, when you try to take a selfie the camera detects the faces and highlights with square marks.

What is Face recognition python?

Face recognition python means the process of matching and identifying a person’s face from photos and videos using python. First, the model needs to be trained with the person’s face then it should be capable of face matching and identifying the person from another image. A good face recognition model should be able to recognize the person correctly even if the face direction and pose is altered in pictures.

A well-known example of face recognition is Google photos, it groups the pictures of each person using face recognition. Since facial Recognition verifies if two faces are the same it is used for security, biometrics, healthcare, personal safety, etc. Beyond just unlocking phones or laptops, the software behind facial recognition applications can accurately identify faces.

The steps involved in facial recognition are

  • Finds the face in an image(Face detection)
  • Analyze and extract facial features
  • Compare the features for the 2 input faces
  • Returns True if face matched or else False.

Setting up the development environment

Now we have to set the development environment to build our project. For this project, we are going to build this face recognition python model in Google Colab (http://colab.research.google.com). For building this project in Google Colab, a few settings have to be updated in the software as follows.

Go to edit -> Notebook settings ->Change hardware accelerator to GPU

And yes! Now we are good to go with the installation of the required libraries. First, install the python face_recognition library using the below command

!pip install face_recognition

The face_recognition python library makes our process easy and we can build a model quickly with the help of that. It contains the implementation of various utilities that help in the process of face recognition.

Steps in building the Face recognition model

  • Prepare the dataset
  • Import the libraries
  • Image processing
  • Train the model
  • Test the model

Preparing the dataset

For developing the Face recognition Python project we are going to collect our custom dataset. You can download the required images online, but make sure to collect images with better quality. In our case, we took a few images of Indian cricketers for our project. Let’s create two directories, train, and test for storing the images for training and testing purposes. You can access the dataset used for the implementation of this project from here https://github.com/keerthanabuvan/face-recognition.

The training dataset used for the project contains the following images.

images of Indian cricketers for Face recognition Python
images of Indian cricketers for Face recognition Python

Importing the libraries

After installing the required libraries and preparing the dataset, let’s import the required modules into our project. We have already downloaded the face_recognition library, and other libraries such as OpenCV, and os are pre-downloaded in Google Colab, so we can directly import those libraries.

#Importing the required libraries
import face_recognition
import cv2
import os
from google.colab.patches import cv2_imshow

We are using the OpenCV library in our project which is an image processing library, that helps in face recognition, object recognition, medical image analysis, and so on.

Image processing in face recognition python

Image processing is a crucial step in our project which performs some operations on images to get enhanced images and extract the information needed for our model.

#Image processing
def img_resize(path):
img = cv2. imread(path)
(h, w) = img. shape[:2]
width = 500
ratio = width / float(w)
height = int(h * ratio)
#resizing the image with custom width and height
return cv2. resize(img, (width, height))

After resizing the images, let’s create two lists train_names and train_enc. One stores the names of the person in the image and the other stores the corresponding face encodings of images.

#list to store the face encodings
train_enc = []
#list to store the names of the person
train_names = []

Face encoding is a vector of values representing important measurements like the distance between the eyes, the width of the forehead, etc. It basically has the length between the distinguishing features of a face. Two different pictures of the same person would have similar encoding and two different people would have totally different encoding.

Training the model with face_recognition python

In training, we loop through each of the images in our training image directory, to extract the name of the person in the image and store the information in the train_names list. Then calculate its face encoding vector and store the information in the train_enc list.

#Training the model
training_images = 'train'
for file in os. listdir(training_images):
img = img_resize(training_images + '/' + file)
img_enc = face_recognition. face_encodings(img)[0]
train_enc. append(img_enc)
train_names. append(file.split('.')[0])

Testing the model with face_recognition python

To test our model we can use the images in the train directory. It contains of different images of the same person whose images we used for the training purpose.

#Testing the model
testing_images = 'test'
for file in os. listdir(testing_images):
img = img_resize(testing_images + '/' + file)
img_enc = face_recognition. face_encodings(img)[0]
outputs = face_recognition. compare_faces(train_enc, img_enc)

The face_recognition library provides a useful method called face_locations() which locates the coordinates (left, bottom, right, top) of every face detected in the image. With the help of those location values, we can easily find the face encodings.

We loop through each of the face locations and its encoding found in the image. Then we compare this encoding with the encodings of the faces from the train images. After that calculate the facial distance which is the similarity between the encoding of the test image and the train images. Now, we pick the minimum valued distance from it indicating that this face of the test image is one of the persons from the training images. Finally, draw a rectangle with the face location coordinates and display the name of the person using the methods from the cv2 module.

#Displaying the outcome
for i in range(len(outputs)):
if outputs[i]:
name = train_names[i]
(top, right, bottom, left) = face_recognition. face_locations(img)[0]
cv2. rectangle(img, (left, top), (right, bottom), (0, 0, 255), 2)
cv2. putText(img, name, (left+2, bottom+20), cv2. FONT_HERSHEY_PLAIN, 1, (255, 255, 255), 1)
cv2_imshow(img)

Output:

virat kohli face detection output
virat kohli face detection output

We can see from the output that our model has correctly recognized the face of the input image. This project can also be extended to detect live webcam images and faces in the videos.

Full code for Face detection python model

#Importing the libaries
import face_recognition
import cv2
import os
from google. colab. patches import cv2_imshow

#Image preprocessing
def img_resize(path):
 img = cv2. imread(path)
 (h, w) = img. shape[:2]
 width = 500
 ratio = width / float(w)
 height = int(h * ratio)
  #resizing the image with custom width and height
 return cv2. resize(img, (width, height))

#list to store the face encodings
train_enc = []
#list to store the names of person
train_names = []

#Training the model
training_images = 'train'
for file in os. listdir(training_images):
 img = img_resize(training_images + '/' + file)
 img_enc = face_recognition. face_encodings(img)[0]
 train_enc. append(img_enc)
 train_names. append(file.split('.')[0])

#Testing the model
testing_images = 'test'
for file in os. listdir(testing_images):
 img = img_resize(testing_images + '/' + file)
 img_enc = face_recognition. face_encodings(img)[0]
 outputs = face_recognition. compare_faces(train_enc, img_enc)

#Displaying the results
for i in range(len(outputs)):
 if outputs[i]:
  name = train_names[i]
  (top, right, bottom, left) = face_recognition.face_locations(img)[0]
  cv2. rectangle(img, (left, top), (right, bottom), (0, 0, 255), 2)
  cv2. putText(img, name, (left+2, bottom+20), cv2. FONT_HERSHEY_PLAIN, 1, (255, 255, 255), 1)
  cv2_imshow(img)

Applications of face recognition

Face recognition is one of the top trending technology that is attracting more business in various sectors. Facial recognition technology is most helpful to law enforcement officials trying to find criminals. The other applications of face Recognition include-

  • Face Unlock in Smartphones,
  • Face detection attendance systems,
  • Face recognition on social media apps,
  • Crime case uses facial recognition,
  • An application such as Emotion detection to classify the emotion on the face can also be developed with the help of face recognition.

Summary

In this project, we developed a Face detection python model using our custom dataset. As technology and innovation progress in daily life, more sectors will adopt this technology. It will be interesting to watch how it continues to evolve in various firms. Hope you enjoyed learning and developing this project.

Thank you for visiting our website.

Click here for more similar projects.


Also Read:

Share:

Author: Ayush Purawr