Face Detection using Haar cascade
It is said that, Face detection is the primary step of image processing. It is very easy and fun to detect human face(s) by using simple computer program. In this tutorial, we will learn the process of face detection using Haar cascade classifier.
- we need to have opencv pre-installed in our computer.
- Python IDE
- A webcam
How Face detection works:
First of all, we have to know some basic things about image processing and face detection.To detect faces from any video or image, classifier is used. Classifier is a computer program that classifies the portions of any image/video into positive (face image) or negative(non-face image) .
Keep in mind that, Image that contains human face is a positive image. whereas, image that doesn’t contain any human face is a negative image.
Classifier is trained using hundreds/thousands of positive and negative images. You can learn about “How to train a HAAR Cascade” from our previous tutorial.
Two types of classifiers are provided by Opencv,
- HAAR Classifier
- LBP Classifier
In this tutorial we will use HAAR cascade classifier to detect faces.
What is HAAR Cascade Classifier:
In 2001, Paul Viola and Michael Jones proposed the method to detect objects (specially human faces) in their paper “Rapid Object Detection using a Boosted Cascade of Simple Features”. It is totally based on machine learning.
Here is the simple code that detects human face in milliseconds.
import cv2 import numpy as np faceDetector = cv2.CascadeClassifier("C:\Users\Desktop\Python\haarcascade_frontalface_default.xml"); cap = cv2.VideoCapture(0); while(True): _, frame = cap.read(); gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY) faces = faceDetector.detectMultiScale(gray, 1.2, 5) for(x, y, w, h) in faces: cv2.rectangle(frame, (x,y), (x+w, y+h), (0,255,0), 2) print (len(faces)) cv2.imshow("Face", frame) if(cv2.waitKey(1)== ord('c')): break cap.release() cv2.destroyAllWindows()
In this code we have to import opencv and numpy ,
import cv2 import numpy as np
XML file should be read correctly. For this we have to find the directory and put it here
faceDetector = cv2.CascadeClassifier("haarcascade_frontalface_default.xml");
If you want to capture the video from built in webcam in the laptop use “cv2.VideoCapture(0)” otherwise write “cv2.VideoCapture(1)”
this will capture video from external webcam..
To convert the video from BGR to Gray we have to use,
gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
len(faces) feature allows python to count faces in the video and shows the face number. If you don’t want to see the number of faces present, don’t add it.
You can read the post to learn in details about How to count faces using Haar Cascade classifier.