Commit 259ef50c by shan ali malik

Update README.md

parent 070cfa3f
Showing with 201 additions and 0 deletions
Face recognition Based home alarm system
The Face Recognition process in this tutorial is divided into three steps.
#Prepare training data: In this step we will read training images for each person/subject along with their labels, detect faces from each image and assign each detected face an integer label of the person it belongs to.
#Train Face Recognizer: In this step we will train OpenCV's LBPH face recognizer by feeding it the data we prepared in step 1.
#Testing: In this step we will pass some test images to face recognizer and see if it predicts them correctly.
*****************************************
Requirements
*****************************************
You need Python 3.6 64bit to run facerecognition Dlib libraries as these are not available in version latest then 3.6.
******************************
Installations Quick start
******************************
Import Required Modules
import OpenCV module
import cv2
import os module for reading training data directories and paths
import os
import numpy to convert python lists to numpy arrays as
it is needed by OpenCV face recognizers
import numpy as np
matplotlib for display our images
import matplotlib.pyplot as plt
%matplotlib inline
py -m pip install numpy
py -m pip install opencv-python
py -m pip install matplotib
py -m pip install pytesseract
*******************************************************
For Alarm use
*******************************************************
pip install py-notifier
For example
from pynotifier import Notification
Notification(
title='Notification Title',
description='Notification Description',
icon_path='path/to/image/file/icon.png', # On Windows .ico is required, on Linux - .png
duration=5, # Duration in seconds
urgency=Notification.URGENCY_CRITICAL
).send()
**************************************
#Detector
***************************************
Loading Recognizer Lets start the main loop and do the following basic steps Starts capturing frames from the camera object Convert it to Gray Scale Detect and extract faces from the images Use the recognizer to recognize the Id of the user Put predicted Id/Name and Rectangle on detected face.
#function to detect face using OpenCV
def detect_face(img):
#convert the test image to gray image as opencv face detector expects gray images
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
#return only the face part of the image
return gray[y:y+w, x:x+h], faces[0]
********************************************************************************************
Main complete code
********************************************************************************************
{
import os
import cv2
import face_recognition as fr
import numpy as np
from pynotifier import Notification
import win10toast
def get_encoded_faces(folder="./faces"):
"""
looks through the faces folder and encodes all
the faces
:return: dict of (name, image encoded)
"""
encoded = {}
for dirpath, dnames, fnames in os.walk(folder):
for f in fnames:
if f.endswith(".jpg") or f.endswith(".png"):
face = fr.load_image_file("faces/" + f)
encoding = fr.face_encodings(face)[0]
encoded[f.split(".")[0]] = encoding
# normally face_encodings check if face is on image - and it can get empty result
return encoded
def classify_face(im):
"""
will find all of the faces in a given image and label
them if it knows what they are
:param im: str of file path
:return: list of face names
"""
faces = get_encoded_faces()
faces_encoded = list(faces.values())
known_face_names = list(faces.keys())
cap = cv2.VideoCapture(0)
while True:
status, img = cap.read()
#print('status:', status)
face_locations = fr.face_locations(img)
unknown_face_encodings = fr.face_encodings(img, face_locations)
face_names = []
for location, face_encoding in zip(face_locations, unknown_face_encodings): # I moved `zip()` in this place
# See if the face is a match for the known face(s)
matches = fr.compare_faces(faces_encoded, face_encoding)
name = "Unknown"
# use the known face with the smallest distance to the new face
face_distances = fr.face_distance(faces_encoded, face_encoding)
best_match_index = np.argmin(face_distances)
if matches[best_match_index]:
name = known_face_names[best_match_index]
face_names.append(name)
top, right, bottom, left = location
# Draw a box around the face
cv2.rectangle(img, (left-20, top-20), (right+20, bottom+20), (255, 0, 0), 2)
# Draw a label with a name below the face
cv2.rectangle(img, (left-20, bottom -15), (right+20, bottom+20), (255, 0, 0), cv2.FILLED)
font = cv2.FONT_HERSHEY_DUPLEX
cv2.putText(img, name, (left -20, bottom + 15), font, 1.0, (255, 255, 255), 2)
if name == "Swami" or "shan":
Notification(
title = 'Known Person',
description = 'Door can be accessed',
duration = 10,
urgency = Notification.URGENCY_CRITICAL
).send()
print("Door open")
else:
Notification(
title = 'Unknown Person',
description = 'Access Denied',
duration = 10,
urgency = Notification.URGENCY_CRITICAL
).send()
print("Door access denied")
cv2.imshow('Video', img)
if cv2.waitKey(1) & 0xFF == ord('q'):
return face_names
# --- main ---
print(classify_face("test-image"))
cv2.destroyAllWindows()
}
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or sign in to comment