Hi learners!! We always come across the problem face detection in machine learning and we always jut think that how we can create a face detection algorithm in the easiest and fastest way. Well here is the answer! we will use OpenCV library of python for detecting faces in the live video being fed using your webcam. For initial level we are using this library but next time we will be creating our own model from scratch and will train it and then test it in real time!!
OpenCV is a library of python which supports a built in model for detecting faces in an image using Haar Cascades. We can use OpenCV for extracting frames from a video then we will apply Haar Cascade onto those frames and will create square on the face being present in image.
NOTE: Before moving onto the code you will be needed to download the “haarcascade_frontalface_default.xml” for running this face detection algorithm. You can find it here. This file basically contains weights for detecting faces
[sourcecode language=”python” wraplines=”false” collapse=”false”]
#importing OpenCV and Time library
#Reading data from the CSV file we downloaded
face_cascade = cv2.CascadeClassifier(‘C:/Documents/MachineLearning/haarcascade_frontalface_default.xml’)
#Capturing Video from primary webcam, you can change number from 0 to any Integer
## for other webcams if you have many of them
cap = cv2.VideoCapture(0)
#Reading frame from the live video feed
ret, frame = cap.read()
#Converting frame into grayscale for better efficiency
gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
#Using Haar Cascade for detecting faces in an image
faces = face_cascade.detectMultiScale(gray, 1.3, 5)
#Creating the rectangle around face
for (x,y,w,h) in faces:
frame = cv2.rectangle(frame,(x,y),(x+w,y+h),(120,250,0),2)
#Displaying the captured frame in a window
#Applied 0.5 seconds delay such that a new frame will only be read every 0.5 seconds
#This decreases load on machine, because in general webcam captures 15 to 25 frames per second
if cv2.waitKey(20) & 0xFF == ord(‘q’):
Input – Output
The above algorithm was for starters!! In next tutorial we will be creating a face detection algorithm from scratch, then we will train it and use it!
Stay tuned for more learning!!