Face Detection using Webcam in Python
OpenCV is a Library which is used to carry out image processing using programming languages like python. This project utilizes OpenCV Library to make a Real-Time Face Detection using your webcam as a primary camera.
OpenCV is built to provide a common infrastructure for computer vision applications and to accelerate the use of machine perception in the commercial products. Being a BSD-licensed product, OpenCV makes it easy for businesses to utilize and modify the code.
Following are the requirements for it:-
1 Python 2.7
2 OpenCV
3 Numpy
4 Haar Cascade Frontal face classifiers
Approach/Algorithms used:
This project uses LBPH (Local Binary Patterns Histograms) Algorithm to detect faces. It labels the pixels of an image by thresholding the neighborhood of each pixel and considers the result as a binary number.
LBPH uses 4 parameters :
(i) Radius: the radius is used to build the circular local binary pattern and represents the radius around the
central pixel.
(ii) Neighbors : the number of sample points to build the circular local binary pattern.
(iii) Grid X : the number of cells in the horizontal direction.
(iv) Grid Y : the number of cells in the vertical direction.
The model built is trained with the faces with tag given to them, and later on, the machine is given a test data and machine decides the correct label for it.
Code :
# Creating database
# It captures images and stores them in datasets
# folder under the folder name of sub_data
import cv2, sys, numpy, os
haar_file = 'haarcascade_frontalface_default.xml'
# All the faces data will be
# present this folder
datasets = 'datasets'
# These are sub data sets of folder,
# for my faces I've used my name you can
# change the label here
sub_data = 'vivek'
path = os.path.join(datasets, sub_data)
if not os.path.isdir(path):
os.mkdir(path)
# defining the size of images
(width, height) = (130, 100)
#'0' is used for my webcam,
# if you've any other camera
# attached use '1' like this
face_cascade = cv2.CascadeClassifier(haar_file)
webcam = cv2.VideoCapture(0)
# The program loops until it has 30 images of the face.
count = 1
while count < 30:
(_, im) = webcam.read()
gray = cv2.cvtColor(im, cv2.COLOR_BGR2GRAY)
faces = face_cascade.detectMultiScale(gray, 1.3, 4)
for (x, y, w, h) in faces:
cv2.rectangle(im, (x, y), (x + w, y + h), (255, 0, 0), 2)
face = gray[y:y + h, x:x + w]
face_resize = cv2.resize(face, (width, height))
cv2.imwrite('% s/% s.png' % (path, count), face_resize)
count += 1
cv2.imshow('OpenCV', im)
key = cv2.waitKey(10)
if key == 27:
break
0 Comments