Face Recognition System Using Google Colab

Original article was published by Abhayparashar31 on Artificial Intelligence on Medium


Face Recognition System Using Google Colab

With the help of the face_recognition library in just under 35 lines of code

Photo by Ayo Ogunseinde on Unsplash

In this blog, we will look at a very simple way to get started with face recognition using python and open cv.

Open cv

Open cv is the most popular library in computer vision. It is originally written in C and C++, now it is available in python also. It is originally developed by intel. the library is a cross-platform open-source library. It is free to use. Open cv library is a highly optimized library with its main focus on real-time applications.

The library has more than 2500 optimized algorithms. which can be used to detect and recognize faces, identify objects, classify human actions using videos, tracking camera movements, tracking moving objects, extracting 3D models of objects, stitch images together to produce a high-resolution image of an entire scene, find similar images from an image database, remove red eyes from images taken using flash, follow eye movements, etc

It has around 47 thousand people of users community and an estimated number of downloads exceeding 18 million. Many big companies like google, amazon, Tesla, Microsoft, Honda, etc. uses Open cv to make their products better and more AI-driven.

Face Recognition

Face recognition is a technique is recognition the name of the person available in the picture. It comprises of two steps. the first step is to detect the faces and the second step is to recognize the faces.

face_recognition is a library in python developed by Adam Geitgey. This library provides us one of the easiest and simplest methods to detect and recognize faces. This library generates a total number of 128 digital prints for each face it detects. later these prints are encoded in some vector encodings that can be used later to decode the prints and compare them to fetch the label(name) of the person.

You can read more about the library and deep concepts in Adam’s explanatory medium post.

Let’s start by creating a face recognition for ourselves. In this blog, we are mainly focusing on recognizing faces from an image. We are going to use Google Colab, so if you don’t have an account on google collab go an create one.

First, we need some Known Images and Some Unknown Images threw which we are going to detect and recognize faces.

Choose your own images from local computer and upload them to colab or simply Go to Google and copy the link of any 3–4 images of known persons and then download 3–4 more images for testing of the same persons.

Create a new code shell in google colab and copy the code below in the code shell to create two directories one is known and another one is unknown. Remember we need to rename the known person images as their names.

!mkdir known!wget https://upload.wikimedia.org/wikipedia/commons/e/ed/Elon_Musk_Royal_Society.jpg -O known/elon.jpg!wget https://pbs.twimg.com/profile_images/988775660163252226/XpgonN0X_400x400.jpg -O known/bill.jpg!wget https://pmcvariety.files.wordpress.com/2017/05/mark-zuckerberg.jpg?w=681&h=383&crop=1 -O known/mark.jpg

Now let’s create a directory for the unknown here we don’t need to rename anything because we are going to test our code on these images.

!mkdir unknown!wget https://cdn.vox-cdn.com/thumbor/4QtOwnOxCdwESvt1-CpQSTZvHHA=/1400x1400/filters:format(jpeg)/cdn.vox-cdn.com/uploads/chorus_asset/file/19932738/1206292068.jpg -O unknown/1.jpg!wget  https://upload.wikimedia.org/wikipedia/commons/a/a0/Bill_Gates_2018.jpg -O unknown/2.jpg!wget https://api.time.com/wp-content/uploads/2019/04/mark-zuckerberg-time-100-2019.jpg?quality=85&zoom=2 -O unknown/3.jpg

The next step is to install the library in the notebook. using pip we can install the library easily in the notebook environment.

!pip install face_recognition

Importing all the required libraries

import face_recognition   ##Detecting and recogniting facesimport cv2     ## intracting with imagesimport os       ## For Reading the file namefrom google.colab.patches import cv2_imshow ## we are importing cv2_imshow from google.colab.patches because google colab doesn't support cv2.imshow() funciton.

Now We will create a function that can be used to read and reshape the images. It only takes the file path as an input.

def read_img(path):
img = cv2.imread(path) ## reading image
(h,w) = img.shape[:2] ## fetching height and width
width = 500 ## hard coding width
ratio = width / float(w) ## preparing a ration for height
height = int(h * ratio) ## generating new height
return cv2.resize(img,(width,height)) ##return the reshaped image

The Face_recognition library recognizes faces by generating different-different encodings for each known face and unknown face and then both the encodings get compared and whichever encoding is matched it shows the label name as output.

Preparing encodings for Known Faces

known_encodings = [] 
known_names = []
known_dir = 'known' ##Known directory path
for file in os.listdir(known_dir):
img = read_img(known_dir + '/' + file) ##Reading all the images
img_enc = face_recognition.face_encodings(img)[0] ##face encodings
known_encodings.append(img_enc)
known_names.append(file.split('.')[0])
print(known_names) ## Printing all the known labels

The next and the final step is to prepare encodings for unknown faces, comparing them with known encoding and drawing a rectangle on the unknown faces with the known name.

unknown_dir = 'unknown' ##UNknown Images Directoryfor file in os.listdir(unknown_dir): print("Processing",file) img = read_img(unknown_dir + '/' + file)##reading images img_enc = face_recognition.face_encodings(img)[0]##Encodings results = face_recognition.compare_faces(known_encodings,img_enc)
##Comparing Known Encodings with Unknown encoding
print(face_recognition.face_distance(known_encodings,img_enc))
## Printing Face Distances
res = [i for i, val in enumerate(results) if val]
name = known_names[res[0]]

'''
Drawing a rectangle box around the faces of unknown images using face_locations function in library
'''
(top,right,bottom,left) = face_recognition.face_locations(img)[0] cv2.rectangle(img,(left,top),(right,bottom),(255,255,100),2)
##Drawing Rectangle
cv2.putText(img,name,(left+2,bottom+20),cv2.FONT_HERSHEY_PLAIN,3, (100,0,255),2) ##Putting labels(names) on the rectangle cv2_imshow(img) ##showing images
“Output-Image By Author”

Thanks For Reading😀

If you have and error or related questions then feel free to ask them in the comment section.

FULL CODE

Future Readings