DEV Community

Cover image for Face Recognition in Python
Aditya Chaudhary👨‍💻
Aditya Chaudhary👨‍💻

Posted on

Face Recognition in Python

In this article, we are going to take a look at how we can detect faces using Python and OpenCV.
To those who don't know what OpenCV is and what things it can do, must check out the previous post here.

OpenCV uses Machine Learning algorithms to detect faces. For a dumb machine like Computer, faces are too complex when represented in Computer understandable language. There is no simple test to detect faces. One has to match thousands of patterns. Using the divide and conquer rule these big processes are broken down into small task which is also known as Classifiers.

OpenCV uses cascades to detect faces. Cascades are nothing but a bunch of XML files that has all necessary OpenCV data to search for specific object in an image. OpenCV comes with built-in cascades for face-recognition but if you were to detect any other object you might have to create your own custom cascade. Creating custom cascade is a deep and complex process. Fortunately, we won't be going deep into it since we don't have to create any custom cascade for face detection.

To get started make sure you have OpenCV installed. To install OpenCV, type the following command in the terminal:
pip install opencv-python

If you don't encounter any problem while installing OpenCV, you can proceed to the next part.

The next step is to import OpenCV Module. This is how you can import the OpenCV module:

import cv2
Enter fullscreen mode Exit fullscreen mode

In the next step, we have to read the image in which we want to detect the face. We also need to convert the image into a grayscale image since it is faster to do operations with grayscale images.

img = cv2.imread('man.png') # must pass valid file directory
gray_img = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)  #converting the image into grayscale image
Enter fullscreen mode Exit fullscreen mode

Next step is to initialize the Cascade Classifier. To do this you will need to download the haarcascade_frontalface_default.xml file from here

# Initializing the haar cascade
face_cascade = cv2.CascadeClassifier("haarcascade_frontalface_default.xml")
Enter fullscreen mode Exit fullscreen mode

The next step is the most important step in this process.

faces = face_cascade.detectMultiScale(gray_img, scaleFactor = 1.05, minNeighbors=5)

Enter fullscreen mode Exit fullscreen mode

The detectMultiScale function detects the object. Here the first argument is the image itself (the grayscale image), second argument is scaleFactor which is mainly responsible to adjust some discrepancies. Some faces in the image can be small while some can be bigger and this is where scaleFactor plays its role. The algorithm requires a moving window to detect objects. minNeighbors defines how many objects are detected near the current one before it declares the face found.

Remember, all these values are generally used values. You might have to experiment around these values depending upon your need.

The next step is to draw a rectangle on the image with the help of the data in faces .

for x, y, w, h in faces:
    img = cv2.rectangle(img, (x,y), (x+w,y+h), (255, 255, 250),3)

Enter fullscreen mode Exit fullscreen mode

Remember that we are drawing the rectangle on the original image and not on the grayscale image.

You are almost done!
Just display the image:

cv2.imshow("ImageWindow", img) # displaying the image
cv2.waitKey(0) #waitKey is set to 0, that means the image window will close as soon as any key is pressed.
cv2.destroyAllWindows() 
Enter fullscreen mode Exit fullscreen mode

Let's test the results!
Alt Text

Congratulations! You made the dumb machine to recognize a face!

Top comments (9)

Collapse
 
alphaolomi profile image
Alpha Olomi

Hey @aditya . Is there a Repo or gist with complete code?

Collapse
 
itsaditya profile image
Aditya Chaudhary👨‍💻

Hey there!
I will be soon pushing my codes to github. I will let you know when it will be done. Thanks!

Collapse
 
alphaolomi profile image
Alpha Olomi

Thanks in advance.

Thread Thread
 
itsaditya profile image
Aditya Chaudhary👨‍💻 • Edited

Done!
github.com/AdityaChaudhary0005/Fac...

Sorry for being a bit late..
I was suffering from school exams . Haha

Collapse
 
itsaditya profile image
Aditya Chaudhary👨‍💻

:)

Collapse
 
alphaolomi profile image
Alpha Olomi

Wooow, impressive 🤩

Collapse
 
itsaditya profile image
Aditya Chaudhary👨‍💻

Thank you :)

Collapse
 
phlash profile image
Phil Ashby

Nice! Have you compared to the very popular 'face_recognition' package from Adam Geitgey (github.com/ageitgey/face_recognition), which uses a different set of models (HOG or CNN)?

Collapse
 
itsaditya profile image
Aditya Chaudhary👨‍💻

Not yet. I didn't know that it was possible with other libraries too.. Thanks for mentioning it.
I will look into it