Home  >  Blog  >   Python

Face Recognition with Python

Rating: 5
  1. Share:
Python Articles

Do you wonder anytime, that how technology can recognize a human face and gives authentication to the accessibility of various applications, services, and identification majors? Well, here we are going to decode the technology for you to understand how it works?

You must have heard about biometric, well face recognition simply maps the biometric feature of your face and identify the coordinates as a picture or in a form of video. The system works on comparing already available features into a database to identify the ideal match. 

It is a huge invention in the field of identity and authentication solutions provided by technology. Now your identity verification is not limited to figure prints you can scan your face to use it as an identifier of yours. 

If you want enrich your career and become a professional in python, then visit Mindmajix - a global online training platform : "python certification course"   This course will help you to achieve excellence in this domain

Many gadgets such as mobiles, laptops, security cameras are available in the market which supports and provides face recognition feature to use it as your authenticated password. It's also available in many types of commercial applications. 

The face recognition market was $4 billion in the year 2017 which is now growing at a high rate and it will be approximately $7.7 billion by 2022. It’s all because this technology can be used anywhere and everywhere for surveillance and marketing. 

Similar to your figure print your face print is also a form of data. If privacy is a major concern for you, you require some control over this. 

How the technology called Face Recognition works. 

Do you ever wonder how a human mind can remember so many faces? Think of 1 min when you forget to map the faces around you with your memory, definitely the situation will become dangerous. 

Our mind has n number of neurons which makes us able to Visualize, Map, Identify, Store and Recognise when the next time we see that particular features as an identical face or identity. Similar to that Face recognition works on N number of an algorithm written with the use of programming languages to program those steps for you to recognize the actual identity. 

When we see a face what we identify, we look at eyes, nose, lips, ears, a facial structure such as flat, oval, square, circle and the color, fair, dusky, brown and so on . for humans it's defined as appearance but for Face recognition technology is defined as data sets. Similar to that Face Recognition works of N number of data sets calculated, compared and matched with the database to give you the most realistic results. 

MindMajix Youtube Channel


OpenCV provides binding to Python, it’s one of the most popular open library developed in C/C++. OpenCV usages AI and ML techniques to identify faces such as in a group of faces in an image. Every face consists of some similar patterns and some of the different features. So there are thousands of small pattern which specifies an identical feature. All these features and pattern has to be exactly matched for a specific result. 

Machine learning algorithms break these features into smaller tasks such as a tiny bit. These smallest modules are easier to solve and technically called “classifiers”.

Approximately for a face, in general, you require 6000 plus classifiers to operate. All these classifiers must match with a specific feature of a face to get detected correctly. Because faces are very complicated it's not the easiest task to identify whether the face is matched or not. 

The recognition starts from the top left of the face and gradually goes down to the chin with a smaller block of captured data. It thoroughly scans each tiny block and compares whether that element matched or not. As there are 6000 tests per block its very obvious that you require billions of calculations to be done.  Your regular PC will exhaust of this stream of calculation so you require a pre-defined library which is easy to extend and use for those repetitive yes and No scenario of your algorithm. 

To help you deal with this problem OpenCV gives you” Cascades”, It simply means a waterfall or series of waterfalls. 

 OpenCV breaks the calculations of recognizing faces into multiple stages. Each block gets processes very intensely and carefully with maintaining the speed. Once the first block in the stream of block passes it simply enhances the intensity more effectively for extra tougher passage to the next block.

The algorithm can be identified as 30 to 50 of these kinds of transitions from one block to another. This transition can be simply called as stages or cascades. 

 The advantage of using OpenCV is that the majority of faces can be eliminated at a very early stage of this process resulting in which the rest 6000 features can be easily tested without wasting the time. Like traditionally done before, Face Recognition can be done in real-time nowadays in a more simplified setup. 

Cascades Implementation

Cascading may sound complicated but for those who run XML files, it’s the easiest job to do. Cascade if nothing but a bunch of files together written in the XML core language and contains OpenCV data used to detect face objects. Similar to other initialization processes in XML you initialize the cascade of your choice and you are ready to move. 

Installation and setup of OpenCV

Go to the Opencv site and download the exe file which supports your operating system

You may get unexpected errors due to 34/64 bit library support of your PC. Try downloading a 32-bit file first and if it doesn’t support go for the 64-bit file. 

Or else just create a Linux based Virtual Machine (VM) in your system and install the setup in the Linux environment. 

Once the .exe file is installed you can simply run a Python session code and check whether its working fine or not. 




Python Interview Questions and Answers

 If the above code runs fine, you can move ahead.

How to write your first Face recognition code 

Let’s understand the code into smaller segments, let's grab the code from a trusted source and break it into small steps to understand the functionality 


Let's import the required library CV2 (OpenCV library), sys as system library.

Python   >>>

import cv2
import sys

You need to start with three main initial supply things, an image, haarcascade_frontalface_default.xml. pass the image and cascade name into the command line argument, use the image and the default cascade to detect faces provided by OpenCV.

Python    >>>

# Get user-supplied values

imagePath = sys.argv[1]

cascPath = "haarcascade_frontalface_default.xml"

Once the cascade is created, initialize the cascade as your face cascade. This process will load the cascade into memory to proceed further. Cascade in an XML file that stores the data for calculation

Python  >>>

# Create the haar cascade

faceCascade = cv2.CascadeClassifier(cascPath)

Now, read the image from the OpenCV library and convert it into grayscale. Most of the processes in OpenCV happens in grayscale. 

Python  >>>

# Read the image

image = cv2.imread(imagePath)

gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)

This function detects the faces for you and now you are ready to detect your first-ever image using face recognition technique. You need to define the scale factor, in neighbor and minSize of the image.

Python    >>>
# Detect faces in the image

faces = faceCascade.detectMultiScale(




    minSize=(30, 30)

    #flags = cv2.CV_HAAR_SCALE_IMAGE

print("Found {0} faces!".format(len(faces)))

Once the face is read, draw the rectangle to find out the coordinates for face match. This function returns some lists of the rectangle which helps to identify the manipulation blocks. The next step is to loop over the function where it seems to be found a matching block. The four values or you called as parameters passed in for loop(x, y, w, h) gives you the exact location of the rectangle and height, width of the same.

x,y= Rectangle location 

w= width 

h= height 

Python >>>

# Draw a rectangle around the faces

for (x, y, w, h) in faces:

    cv2.rectangle(image, (x, y), (x+w, y+h), (0, 255, 0), 2)

cv2.imshow("Faces found", image)


Imshow function returns the found image as an output of your code.

Who are the users of Facial Recognition? 

There are so many usages of facial recognition technology in the field of surveillance and identity authentication.

Mobile/ laptop Industries 

Apple is the first company that launched iPhone X with the advanced features of face identification and authentication techniques. Mobile users were very fond of these new features which allow them to access their device making sure it's one and only owner of the product who can access the device. 

It's quite simple, just keep your phone in front of your face and here you are ready to go. 

Social Media platforms

Well, we all upload pictures on our Facebook wall, no wonder that we can tag with their names and facebook detects the name through the images. It also sends you a notification when someone tags you saying “somebody tags a photo of your”. Facebook usage the face recognition technology at its optimum to give you the best user experiences. 

Highly restricted areas and business hubs 

Security and surveillance are some of the major industries served by this technology. Many highly secured places including offices and government organizations are practicing security majors using this technique. 

Airlines and departure security 

Airports are also using surveillance to identify people after all airports is a very sensitive place with a huge crowd gathering. Keeping an eye on each entry and exit is very crucial for the airport authorities. Face recognition serves their need by identifying people with high-quality output methods. Huge investigations have been carried forward and get a breakthrough with the help of this technique. 

With n numbers of advantages, there are few disadvantages of using Face Recognition 

  • Storing your data or keeping your image without your permission 
  • Creating opportunity for the hacker to track your data
  • Allowing your facial signature to N number of people without your knowledge 
  • There can be matching coordinates of two person’s faces and face recognition cannot assurance the techniques to identify the right person. Security officials may land up pointing out the wrong person. 

The face recognition industry is setting a bigger path for those who want to build a carrier using the technique. You can process it as an image scientist, image processing/pattern recognition, and ML developer as well. This easy to learn techniques can be implemented into many programming languages using R python, java, c, c++, C#, Matlab. Python is the most prominent and widely practiced programming language for those who are building face recognition and pattern processing applications.

If you are interested learn python and build a career in it ? Then checkout our python training near your cities

Python Training Chennai  Python Training New York  Python Training in Bangalore  Python Training in Dallas

These courses are incorporated with Live instructor-led training, Industry Use cases, and hands-on live projects. This training program will make you an expert in Microsoft Azure and help you to achieve your dream job.

Join our newsletter

Stay updated with our newsletter, packed with Tutorials, Interview Questions, How-to's, Tips & Tricks, Latest Trends & Updates, and more ➤ Straight to your inbox!

Course Schedule
Python TrainingMay 25 to Jun 09View Details
Python TrainingMay 28 to Jun 12View Details
Python TrainingJun 01 to Jun 16View Details
Python TrainingJun 04 to Jun 19View Details
Last updated: 03 Apr 2023
About Author

Anjaneyulu Naini is working as a Content contributor for Mindmajix. He has a great understanding of today’s technology and statistical analysis environment, which includes key aspects such as analysis of variance and software,. He is well aware of various technologies such as Python, Artificial Intelligence, Oracle, Business Intelligence, Altrex, etc. Connect with him on LinkedIn and Twitter.

read more
Recommended Courses

1 / 15