Uncategorized

Face Detection using OpenCV in Live Video

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

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

Code

[sourcecode language=”python” wraplines=”false” collapse=”false”]
#importing OpenCV and Time library
import cv2
import time

#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)

while (True):
#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
cv2.imshow(‘gray’,frame)

#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
time.sleep(0.5)
print(“sleep done!!”)
if cv2.waitKey(20) & 0xFF == ord(‘q’):
break

cap.release()
cv2.destroyAllWindows()
[/sourcecode]

Input – Output

Teen girl excited      test2

 

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!!

 

Leave a Reply

Back To Top

Discover more from Machine Learning For Analytics

Subscribe now to keep reading and get access to the full archive.

Continue reading