Face Detection: With 6 simple steps in Python
This article aims to show how we can use an OpenCV library to detect faces in a given image with minimal steps
I’m using a Google Colab Notebook to write my Python program. But, you can use any editor of your choice, like VS Code, PyCharm, etc.
All I’m doing here is that I’m passing an image to the OpenCV library and using it against a trained model to detect faces.
Here are the steps :
Step 1
Open a new Google Colab Notebook, and import two essential libraries matplotlib.pyplot and cv2
We’re using matplotlib to access a given image’s properties and cv2 to access a trained model and use the given image against it to detect faces
If you’re using any other editor you can use pip to install the packages
Step 2
Upload an image that has a face. I preferred to use a group picture, but you can use any picture of your choice. You can find the picture I used here. And upload it in the notebook.
Now, that you have uploaded the picture, try to read it into a variable called img in the program.
Use the path to load the image into the variable using imread()
Step 3
Now, its time to load a model. For this, you need to download one of the XML files from haar cascades called haarcascade_frontalface_alt.xml. You will have to copy the XML content by switching it into Raw mode like this or you can even find it here.
Haar cascades have so many models to detect various parts of a human body like to detect eyes, frontal face, lower body, upper body, full body and so on. But we are just focusing on faces for now.
Now, load the model in a variable called model by copying the file’s path in cv2.CascadeClassifier()
Step 4
Now using one of the functionalities of OpenCV detectMultiScale(), detect all the faces in a given image and store it in a variable called faces
Step 5
Once we have faces, we can iterate them one by one and mark them drawing white rectangles individually
This loop might look tricky, but all it is doing is
- Get coordinates (x, y)and size (w, h) to draw a rectangle
- Set a color using RGB format for the rectangle. I’ve used white (255, 255, 255) here.
- Set thickness to the rectangle’s border. I’ve used 5 here.
All this work is done by using cv2.rectangle()
Final step
Display the image with rectangle marks around detected faces using imshow()
Here is how the image with markings looks like after running the final code
This is how the overall code looks like
You can find the code in my Colab Notebook here or even in this Github repository.
I hope it was useful!