Face Detection using OpenCV & Python
In this quick post I wanted to share a very popular and easy way of detecting faces using Haar cascades in an image and save all the faces in a folder using OpenCV and Python.
First of all make sure you have OpenCV installed. You can install it using pip:
Face detection using Haar cascades is a machine learning based approach where a cascade function is trained with a set of input data. It returns coordinates of the faces, using those coordinates can be saved faces as a file.
You need to download the haar cascade classifier (haarcascade_frontalface_default.xml), which is available in OpenCv’s GitHub repository. Save it to your working location.
Source Code
A few things to remember:
The detection works only on grayscale images. So it is important to convert the color image to grayscale. (line 7)
detectMultiScale function (line 9) is used to detect the faces. It takes 3 arguments — the input image, scaleFactor and minNeighbours. scaleFactor specifies how much the image size is reduced with each scale. minNeighbours specifies how many neighbors each candidate rectangle should have to retain it.
faces contains a list of coordinates for the rectangular regions where faces were found. We use these coordinates to draw the rectangles in our image. and save the all cropped faces inside faces folder using imwrite function.
Results:
Saved images:
Leave a Comment