Detecting Faces Using Python And Cascade Classifier

Introduction 

 
Hello Geeks! Welcome to the era of Machine Learning, Big Data, and Data Science. Image Processing is a very popular and interesting domain of Computer Science. Detecting objects was very difficult in the early days of Image processing. With the advancement in the field of Image Processing, things became easier and easier for the developers. Now a novice programmer with a basic understanding of python can write a code that can detect different objects in real-time and all this is possible only due to OpenCV, an image processing library for almost all the platforms and with different languages supports. 
 
What will we do today?
 
Today I am going to show you how you can detect human faces using python and a cascade classifier.
 
What is the prerequisite for this?
 
Almost nothing is a prerequisite for this but for better understanding, you must have:
  • Basic knowledge of Python
What is required to make this possible?
How to use the OpenCV library in python?
 
Go to your OpenCV installation folder. Usually, it is C:\ drive. Go to C:\opencv\build\python\2.7
 
The directory structure might be different for you depending upon your default installation location. I am using C:\ drive as an installation location.
 
Once you move there, you see two folders namely "x86" and "x64". Depending upon your computer architecture go to the folder. I am using "x64" so I am going to "x64" folder. There you will find "cv2.pyd" file. Copy it.
 
Now move to your python installation location. I have in C:\ drive. So move to C:\Python27\Lib\site-packages\ and paste the file there.
 
Now open python terminal and  type
  1. import cv2  
If you get no error then all is well. If you get an error like "module name not found" then you must have missed steps. Go back and pay attention.
 
How we will make it?
 
Detecting faces was not an easy job before the openCV and Cascade Classifier. There are billions of people in this world. And everyone's face is different from the other in structural patterns but contains the same features as one nose, two ears, two eyes and a pair of lips. With Cascade Classifier, you just downloaded is an XML file that already contains data of faces. This file is already trained on many different faces. So we do not need to train it again. We just provide this classifier and it will put boxes around the faces in the image.
 
We're getting ready for the dive into OpenCV and python journey in the Image Processing domain. Now the actual work starts.  I will take the code bit by bit and explain to you what is actually happening behind the scenes.
  1. import cv2  
  2. import sys  
Here we are simply importing the OpenCV module and sys module for image processing and system-related tasks.
  1. image = sys.argv[1]  
Here sys.argv is looking for an image on run time in which we want to detect faces.
  1. faceclassifier = cv2.CascadeClassifier("haarcascade_frontalface.xml")  
Here we create and initialize our classifier that will read through the XML and load the face data that we are going to use. Our input image features will be compared with the data in this classifier.
  1. actual_image = cv2.imread(image)  
  2. gray = cv2.cvtColor(actual_image, cv2.COLOR_BGR2GRAY)  
Here we are reading our image using imread function from the image variable and storing it in actual_image variable. In the next line, we convert our image to grayscale image because grayscale image contains less noise as compared to BGR images so detecting is easy on grayscale colored images. You can use a BGR image but the result might not according to your expectation.
  1. faces = faceclassifier.detectMultiScale(  
  2.     gray,  
  3.     scaleFactor=1.1,  
  4.     minNeighbors=5,  
  5.     minSize=(3030),  
  6. )  
Here is the main function detectMultiScale that actually detects objects (In our case it is detecting faces because we use it on face classifier).
  • grey: It is the grayscale image.
  • scaleFactor: It scales or descales your image according to your algorithm requirement. Some faces are big and some are very small and they produce problems for the algorithm to smoothly detect them.
  • minNeighbors: For the sake of understanding assume that detecting faces is not an easy task for computers. A classifier contains thousands of data of faces. Our given image is compared with the faces in the classifier. minNeighbors property is used to tell after how many equal images we can say we have found a face. If you set it to 5 as in our case it at a minimum requires 5 images that must match with our provided image to detect a  face.
  • minSize: minimum object size. If the object is smaller then this it will be ignored.
The above function returns a list of rectangles where our algorithm found the face.
  1. for (x, y, w, h) in faces:  
  2.     cv2.rectangle(actual_image, (x, y), (x+w, y+h), (0,0255), 2)  
Now iterating through the list each item of faces will provide us with 4 values of rectangle x,y,w,h.
  • x: location of the rectangle on the x-axis
  • y: location of the rectangle on the y-axis
  • w: width of the rectangle
  • h: height of the rectangle
What else we need to draw a rectangle? Nothing. Just give the image on which we want to draw a circle insert the values of the x,y,w,h, and boom
  1. cv2.imshow("Face Detected" ,actual_image)  
  2. cv2.waitKey(0)  
Now just display the image window in which image is displayed and rectangles are drawn on the image. Use the imshow function. 1st parameter is the title of the image window and the second is the image that we want to display.
 
In the second line wait for the user key to terminate the program.
 
Hurrah we have made it. Now we can detect faces on any image using the little python scripts that we write here.
 
Now for running our script open command prompt and type:
 
python <path-to-your-script> <path-to-your-image>
 
In my case it is:
 
python C:\face_detection.py C:\image.jpg
 
And the output is.
 
 
 
We have successfully detected all the faces in the image.
 
In future articles, I will be using real-time detection using a webcam.
 
Stay tuned for further fun projects using python and OpenCV.