Introduction
We will build a fast and exciting project with real-time face detection using the Haar cascade classifier in OpenCV. Python OpenCV helps us in image processing, such as blurring, focusing, etc. You Can visit the website to read the documentation. We will need an XML file called haar cascade file In which the data is stored. The problem is not very difficult to understand the given image, and we have to detect the region in which the face in that image lies.
We want to do this because once we identify the region in which the face lies, We could then read it to the face detection algorithm or maybe an emotion detector. The good thing about this project is that we can easily modify our project with different use cases like detecting hand detecting eyes or detecting nose etc.
So let's see how we are going to do this. We will be using the Haar cascade classifier available in OpenCV. The Haar cascade classifier is a relatively old technique made famous by Paul Viola and Michael Jones. So we have to make sure that we have Python and an OpenCV installed in the system. If not, write '!pip install OpenCV-python' to install it. Once we do that, let's open the text editor and start writing some code.
Implementation
- Step 1- Import an open CV just by writing cv2 shortcuts.
import cv2
- Step 2- Instantiating an object to capture the video From the webcam and passing the default argument as 0.
cap = cv2.VideoCapture(0)
-
Step 3- Calling a cascade classifier from an open CV. The cascade classifiers take in the XML file and extract the details and features from it.
-
Step 4- We will write the entire code inside the while loop which runs an infinite number of times. Hence, we can stop whenever we want to.
This can be achieved by pressing any key(say q) as shown in the code.
I am providing a waitkey function with a delay of 1 millisecond for each frame.
faceCascade = cv2.CascadeClassifier("haarcascade_frontalface_default.xml")
#We want to show each frame per second that we captured.
while(True):
# Capture frame-by-frame
ret, frame = cap.read()
# Our operations on the frame come here
gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
# Let's detect face one by one
faces = faceCascade.detectMultiScale(
gray,
scaleFactor=1.1,
minNeighbors=5,
minSize=(30, 30)
#flags = cv2.CV_HAAR_SCALE_IMAGE
)
print("Found {0} faces!".format(len(faces)))
# Now we will tell the Python program to form a rectangle around the face.
# Here X and Y the coordinates of the image,and w is the width, H is the height.
for (x, y, w, h) in faces:
cv2.rectangle(frame, (x, y), (x+w, y+h), (0, 255, 0), 2)
# Display the resulting frame
cv2.imshow('frame', frame)
if cv2.waitKey(1) & 0xFF == ord('q'):
break
- Step 5- When everything is done, release the capture.
cap.release()
cv2.destroyAllWindows()
Output
Also read, Sampling and Quantization