Coders Packet

Face detection using Python and OpenCV

By Pragya Mukherjee

This tutorial will help you learn to code a simple face detection tool using Python Programming language and OpenCV, which is an amazing computer vision library.

In this project I am going to use Python programming language with OpenCV, so make sure you have an updated Python version installed in your machine and also OpenCV installed using pip.

Before diving into the core section of this project, I would highly recommend you to use Jupyter Notebook to complete this tutorial.

So, let's get started with the project step-by-step:

Create an empty folder on your desktop and save an image (make sure the image has some faces) in this folder.

Now from Jupyter Notebook, open this desktop folder and then go to New file (towards top-left) and then click on Python3.

Create a new Jupyter NotebookThis will create a new Notebook for you to work on.

Let's now dive into the coding section of our project.

 

First of all, we need to import the necessary libraries - OpenCV(cv2) and matplotlib.

Importing libraries

The next step should be to read the image (again make sure you saved the image in this working folder). Note that OpenCV interprets an image in the form of BGR color format, so we need to convert it to RGB color format. The code below depicts the way to do so.

read image

So good so far.

OpenCV has some classifiers which are pre-trained, so we will use haar cascade classifier for face detection purpose. Download this XML file in your working folder. Follow the code below:

Haar_cascade_Classifier

Our work is almost done. Now we need the coordinates of the faces, which can be done using the detectMultiScale() function under this classifier. It will return the coordinates of the faces detected. The detectMultiScale() function accepts some parameters among these most important used here are - image, scaleFactor, and minNeighbors. You can know more about this here. Till then play around with the values of scaleFactor and minNeighbors as a self exercise.

Finally, using a for loop, draw colored (here we will use green color) rectangles using OpenCV through the co-ordinates returned by the detectMultiScale(), so that the detected face is properly visible. Then display the final image.

The code follows here:

Detect faces

And here we go! The faces have been detected perfectly.

Final output

For complete source code make sure to download the zipped folder.

Happy Learning!!

Download project

Reviews Report

Submitted by Pragya Mukherjee (MPragya)

Download packets of source code on Coders Packet