Friday, July 31, 2020

Face Detection

Face detection is one of the fascinating applications of computer vision which makes it more realistic as well as futuristic. OpenCV has a built-in facility to perform face detection. We are going to use the Haar cascade classifier for face detection.

Haar Cascade Data

We need data to use the Haar cascade classifier. You can find this data in our OpenCV package. After installing OpenCv, you can see the folder name haarcascades. There would be .xml files for different application. Now, copy all of them for different use and paste then in a new folder under the current project.

Example

The following is the Python code using Haar Cascade to detect the face of Amitabh Bachan shown in the following image:


Import the OpenCV package as shown:

import cv2
import numpy as np


Now, use the HaarCascadeClassifier for detecting face:

face_detection = cv2.CascadeClassifier('D:/ProgramData/cascadeclassifier/haarcascade_frontalface_default.xml')

Now, for reading a particular image, use the imread() function:

img = cv2.imread('AB.jpg')

Now, convert it into grayscale because it would accept gray images:

gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)

Now, using face_detection.detectMultiScale, perform actual face detection

faces = face_detection.detectMultiScale(gray, 1.3, 5)

Now, draw a rectangle around the whole face:

for (x,y,w,h) in faces:
    img = cv2.rectangle(img,(x,y),(x+w, y+h),(255,0,0),3)
cv2.imwrite('Face_AB.jpg',img)


This Python program will create an image named Face_AB.jpg with face detection as shown:


The next post will be on Eye detection, which is another fascinating application of computer vision.
Share: