Face Detection using Python and OpenCV with webcam

 Face Detection using Python and OpenCV with webcam



How to use :

  1. Create a directory in your pc and name it (say project)
  2. Create two python files named create_data.py and face_recognize.py, copy the first source code and second source code in it respectively.
  3. Copy haarcascade_frontalface_default.xml to the project directory, you can get it in opencv or from
    here.


  1. You are ready to now run the following codes.
create_data.py

# 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 = 'G:\PARAS\datasets' //make datasets as new folder like i did in this path then sub

# These are sub data sets of folder,
# for my faces I've used my name you can
# change the label here akhi is a sub folder insde datasets where web image will store by webcamera

sub_data = 'akhi'

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
Datasets Storage :


face_recognize.py
# It helps in identifying the faces
import cv2, sys, numpy, os

size = 4
haar_file = 'haarcascade_frontalface_default.xml'
datasets = r'G:\PARAS\datasets'

# Part 1: Create fisherRecognizer
print('Recognizing Face Please Be in sufficient Lights...')

# Create a list of images and a list of corresponding names
(images, lables, names, id) = ([], [], {}, 0)
for (subdirs, dirs, files) in os.walk(datasets):
for subdir in dirs:
names[id] = subdir
subjectpath = os.path.join(datasets, subdir)
for filename in os.listdir(subjectpath):
path = subjectpath + '/' + filename
lable = id
images.append(cv2.imread(path, 0))
lables.append(int(lable))
id += 1
(width, height) = (130, 100)

# Create a Numpy array from the two lists above
(images, lables) = [numpy.array(lis) for lis in [images, lables]]

# OpenCV trains a model from the images
# NOTE FOR OpenCV2: remove '.face'
model = cv2.face.LBPHFaceRecognizer_create()
model.train(images, lables)

# Part 2: Use fisherRecognizer on camera stream
face_cascade = cv2.CascadeClassifier(haar_file)
webcam = cv2.VideoCapture(0, cv2.CAP_DSHOW) #captureDevice = camera
while True:
(_, im) = webcam.read()
gray = cv2.cvtColor(im, cv2.COLOR_BGR2GRAY)
faces = face_cascade.detectMultiScale(gray, 1.3, 5)
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))
# Try to recognize the face
prediction = model.predict(face_resize)
cv2.rectangle(im, (x, y), (x + w, y + h), (0, 255, 0), 3)

if prediction[1] < 500:

cv2.putText(im, '% s - %.0f' %
(names[prediction[0]], prediction[1]), (x - 10, y - 10),
cv2.FONT_HERSHEY_PLAIN, 1, (0, 255, 0))
else:
cv2.putText(im, 'not recognized',
(x - 10, y - 10), cv2.FONT_HERSHEY_PLAIN, 1, (0, 255, 0))

cv2.imshow('OpenCV', im)

key = cv2.waitKey(10)
if key == 27:
break
Opencv Python program for Face Detection
  1. Put the haarcascade_eye.xml & haarcascade_frontalface_default.xml files in the same folder
# OpenCV program to detect face in real time
# import libraries of python OpenCV
# where its functionality resides
import cv2

# load the required trained XML classifiers
# https://github.com/Itseez/opencv/blob/master/
# data/haarcascades/haarcascade_frontalface_default.xml
# Trained XML classifiers describes some features of some
# object we want to detect a cascade function is trained
# from a lot of positive(faces) and negative(non-faces)
# images.
face_cascade = cv2.CascadeClassifier('haarcascade_frontalface_default.xml')

# https://github.com/Itseez/opencv/blob/master
# /data/haarcascades/haarcascade_eye.xml
# Trained XML file for detecting eyes
eye_cascade = cv2.CascadeClassifier('haarcascade_eye.xml')

# capture frames from a camera
cap = cv2.VideoCapture(0)

# loop runs if capturing has been initialized.
while 1:

# reads frames from a camera
ret, img = cap.read()

# convert to gray scale of each frames
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)

# Detects faces of different sizes in the input image
faces = face_cascade.detectMultiScale(gray, 1.3, 5)

for (x, y, w, h) in faces:
# To draw a rectangle in a face
cv2.rectangle(img, (x, y), (x + w, y + h), (255, 255, 0), 2)
roi_gray = gray[y:y + h, x:x + w]
roi_color = img[y:y + h, x:x + w]

# Detects eyes of different sizes in the input image
eyes = eye_cascade.detectMultiScale(roi_gray)

# To draw a rectangle in eyes
for (ex, ey, ew, eh) in eyes:
cv2.rectangle(roi_color, (ex, ey), (ex + ew, ey + eh), (0, 127, 255), 2)

# Display an image in a window
cv2.imshow('img', img)

# Wait for Esc key to stop
k = cv2.waitKey(30) & 0xff
if k == 27:
break

# Close the window
cap.release()

# De-allocate any associated memory usage
cv2.destroyAllWindows()

Comments

Popular posts from this blog

Python to automate What's App messages

Building RESTful APIs with Flask in PyCharm

Redirecting to another page with button click in Python-flask