Skip to content

Instantly share code, notes, and snippets.

Last active November 20, 2019 02:19
Show Gist options
  • Save aabhassenapati/41299405553ff76109115e2f8dc25ee3 to your computer and use it in GitHub Desktop.
Save aabhassenapati/41299405553ff76109115e2f8dc25ee3 to your computer and use it in GitHub Desktop.
Smart Security Camera Project
# python --cascade haarcascade_frontalface_default.xml --encodings encodings.pickle
#import the necessary packages
from __future__ import print_function
from xlrd import open_workbook
from import VideoStream
from import FPS
from xlutils.copy import copy
import face_recognition
import argparse
import imutils
import pickle
import time
import datetime
import cv2
import xlwt
import xlrd
import RPi.GPIO as GPIO
import time
# construct the argument parser and parse the arguments
ap = argparse.ArgumentParser()
ap.add_argument("-c", "--cascade", required=True,
help = "path to where the face cascade resides")
ap.add_argument("-e", "--encodings", required=True,
help="path to serialized db of facial encodings")
args = vars(ap.parse_args())
# load the known faces and embeddings along with OpenCV's Haar
# cascade for face detection
print("[INFO] loading encodings + face detector...")
data = pickle.loads(open(args["encodings"], "rb").read())
detector = cv2.CascadeClassifier(args["cascade"])
# initialize the video stream and allow the camera sensor to warm up
print("[INFO] starting video stream...")
vs = VideoStream(src=0).start()
# vs = VideoStream(usePiCamera=True).start()
# start the FPS counter
fps = FPS().start()
wb = xlwt.Workbook()
count = 1
ws = wb.add_sheet("My Sheet")
# loop over frames from the video file stream
while True:
# grab the frame from the threaded video stream and resize it
# to 500px (to speedup processing)
frame =
frame = imutils.resize(frame, width=500)
cv2.imshow("Frame", frame)
key = cv2.waitKey(1) & 0xFF
# convert the input frame from (1) BGR to grayscale (for face
# detection) and (2) from BGR to RGB (for face recognition)
gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
rgb = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)
# detect faces in the grayscale frame
rects = detector.detectMultiScale(gray, scaleFactor=1.1,
minNeighbors=5, minSize=(30, 30),
# OpenCV returns bounding box coordinates in (x, y, w, h) order
# but we need them in (top, right, bottom, left) order, so we
# need to do a bit of reordering
boxes = [(y, x + w, y + h, x) for (x, y, w, h) in rects]
# compute the facial embeddings for each face bounding box
encodings = face_recognition.face_encodings(rgb, boxes)
names = []
# loop over the facial embeddings
for encoding in encodings:
# attempt to match each face in the input image to our known
# encodings
cv2.imshow("Frame", frame)
key = cv2.waitKey(1) & 0xFF
matches = face_recognition.compare_faces(data["encodings"],
name = "Unknown" + str(count)
name1 = "Unknown" + str(count)
# check to see if we have found a match
if True in matches:
# find the indexes of all matched faces then initialize a
# dictionary to count the total number of times each face
# was matched
matchedIdxs = [i for (i, b) in enumerate(matches) if b]
counts = {}
# loop over the matched indexes and maintain a count for
# each recognized face face
for i in matchedIdxs:
name = data["names"][i]
counts[name] = counts.get(name, 0) + 1
cv2.imshow("Frame", frame)
key = cv2.waitKey(1) & 0xFF
# determine the recognized face with the largest number
# of votes (note: in the event of an unlikely tie Python
# will select first entry in the dictionary)
name = max(counts, key=counts.get)
# update the list of names
# loop over the recognized faces
for ((top, right, bottom, left), name) in zip(boxes, names):
# draw the predicted face name on the image
cv2.rectangle(frame, (left, top), (right, bottom),
(0, 255, 0), 2)
y = top - 15 if top - 15 > 15 else top + 15
cv2.putText(frame, name, (left, y), cv2.FONT_HERSHEY_SIMPLEX,
0.75, (0, 255, 0), 2)
# display the image to our screen
cv2.imshow("Frame", frame)
key = cv2.waitKey(1) & 0xFF
#update_sheet("Face_Recognition" , name)
if (name==name1) :
cv2.imwrite(name+".jpg", frame)
x = copy(open_workbook('book2.xls'))
ws.write(row, 0, name)
x.get_sheet(0).write(1, 2, count2)
ws.write(row, 1, str( )"myworkbook.xls")
w = copy(open_workbook('myworkbook.xls'))
w.get_sheet(0).write(row,1, str('book2.xls')
# if the `q` key was pressed, break from the loop
if key == ord("q"):
# update the FPS counter
# stop the timer and display FPS information
print("[INFO] elasped time: {:.2f}".format(fps.elapsed()))
print("[INFO] approx. FPS: {:.2f}".format(fps.fps()))
# do a bit of cleanup
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment