Face Detection Using Coloab in OpenCV

Face detection is used to identify the face of a human. For this project, we use har cascade XML files for the training data set.

Reny Jose
3 min readFeb 2, 2021

The problem of face detection is broken into multiple stages using OpenCV cascade. The algorithm detects a face if it passes all the 30 to 50 test stages. The cascade is a collection of an XML file and we use the specific ones based on the project

Steps

  1. Run a google collab

2. Download cascade haarcascade_frontalface_default.xml from the link https://github.com/anaustinbeing/haar-cascade-files Keep the file in the current directory

3. Import packages

4.Mount the drive

Here we are giving the path of the current working directory. Since I am working inside the OPENCV folder of Colab Notebooks the path is given like this. Please edit accordingly

5. Initialize and load cascade classifier. Here we are using both face and eye in order to detect both. Both the files are available in my OPENCV folder.

The XML file contains trained from a lot of positive (faces) and negative(non-faces) images.

6. Read the image and store in a variable

7. Convert the image to greyscale

cv2.COLOR_BGR2GRAY is used to convert the image to convert greyscale and to display we use plt.imshow()

8. Detect the face and draw a rectangle around it

Here we use detectMultiScale function available with face_cascade to detect the face. The parameters are the grey image. scaleFactor, which is used to scale an image, Since some part of the image is close to the camera. The minNeighbors is used to check how many points near in order to declare the face is found.

The for loop is used to draw a rectangle around the each identified faces. Also roi_gray and roi_color stores the region of interest in grey and in colour for further processing

9.Display the image

Note: To detect multiple faces from an image we can use the same code. Read an image contains multiple faces.

To detect a face from a webcam or a video in step 6 write the following code.

For video instead of zero as parameter give the path of the video.

Reference

[1] https://realpython.com/face-recognition-with-python/

[2] https://github.com/anaustinbeing/haar-cascade-files

[3]https://github.com/Itseez/opencv/blob/master/data/haarcascades/haarcascade_frontalface_default.xml

--

--

Reny Jose

Research Scholar, Interested in Artificial Intelligence , Machine Learning ,Deep Learning, Computer Vision