Integrated Facial Software to Database and Main Program.

This commit is contained in:
Batuhan Berk Başoğlu 2021-01-24 10:55:36 -05:00
parent 9f7adf2762
commit e1f6e307fa
6 changed files with 117 additions and 110 deletions

View file

@ -9,6 +9,7 @@ try:
except ImportError: except ImportError:
import _pickle as cPickle # Python3. import _pickle as cPickle # Python3.
def enroll_face_dataset(): def enroll_face_dataset():
pwd = sys.path[0] pwd = sys.path[0]
PREDICTOR_PATH = pwd + '/Facial_models/shape_predictor_68_face_landmarks.dat' PREDICTOR_PATH = pwd + '/Facial_models/shape_predictor_68_face_landmarks.dat'
@ -18,7 +19,6 @@ def enroll_face_dataset():
shapePredictor = dlib.shape_predictor(PREDICTOR_PATH) shapePredictor = dlib.shape_predictor(PREDICTOR_PATH)
faceRecognizer = dlib.face_recognition_model_v1(FACE_RECOGNITION_MODEL_PATH) faceRecognizer = dlib.face_recognition_model_v1(FACE_RECOGNITION_MODEL_PATH)
faceDatasetFolder = pwd + '/Facial_images/face_rec/train/' faceDatasetFolder = pwd + '/Facial_images/face_rec/train/'
subfolders = [] subfolders = []
@ -27,7 +27,6 @@ def enroll_face_dataset():
if os.path.isdir(xpath): if os.path.isdir(xpath):
subfolders.append(xpath) subfolders.append(xpath)
nameLabelMap = {} nameLabelMap = {}
labels = [] labels = []
imagePaths = [] imagePaths = []
@ -43,12 +42,12 @@ def enroll_face_dataset():
i = 0 i = 0
faceDescriptors = None faceDescriptors = None
for imagePath in imagePaths: for imagePath in imagePaths:
#print("processing: {}".format(imagePath)) # print("processing: {}".format(imagePath))
img = cv2.imread(imagePath) img = cv2.imread(imagePath)
faces = faceDetector(cv2.cvtColor(img, cv2.COLOR_BGR2RGB)) faces = faceDetector(cv2.cvtColor(img, cv2.COLOR_BGR2RGB))
#print("{} Face(s) found".format(len(faces))) # print("{} Face(s) found".format(len(faces)))
for k, face in enumerate(faces): for k, face in enumerate(faces):
@ -58,12 +57,10 @@ def enroll_face_dataset():
faceDescriptor = faceRecognizer.compute_face_descriptor(img, shape) faceDescriptor = faceRecognizer.compute_face_descriptor(img, shape)
faceDescriptorList = [x for x in faceDescriptor] faceDescriptorList = [x for x in faceDescriptor]
faceDescriptorNdarray = np.asarray(faceDescriptorList, dtype=np.float64) faceDescriptorNdarray = np.asarray(faceDescriptorList, dtype=np.float64)
faceDescriptorNdarray = faceDescriptorNdarray[np.newaxis, :] faceDescriptorNdarray = faceDescriptorNdarray[np.newaxis, :]
if faceDescriptors is None: if faceDescriptors is None:
faceDescriptors = faceDescriptorNdarray faceDescriptors = faceDescriptorNdarray
else: else:
@ -73,6 +70,6 @@ def enroll_face_dataset():
i += 1 i += 1
# Write descriors and index to disk # Write descriors and index to disk
np.save(pwd+'/Facial_models/descriptors.npy', faceDescriptors) np.save(pwd + '/Facial_models/descriptors.npy', faceDescriptors)
with open(pwd+'/Facial_models/index.pkl', 'wb') as f: with open(pwd + '/Facial_models/index.pkl', 'wb') as f:
cPickle.dump(index, f) cPickle.dump(index, f)

View file

@ -1,14 +1,14 @@
import os,sys,time import os, sys, time
import dlib import dlib
import cv2 import cv2
import numpy as np import numpy as np
import DBHelper
try: try:
import cPickle # Python 2 import cPickle # Python 2
except ImportError: except ImportError:
import _pickle as cPickle # Python 3 import _pickle as cPickle # Python 3
pwd = sys.path[0] pwd = sys.path[0]
PREDICTOR_PATH = pwd + '/Facial_models/shape_predictor_68_face_landmarks.dat' PREDICTOR_PATH = pwd + '/Facial_models/shape_predictor_68_face_landmarks.dat'
FACE_RECOGNITION_MODEL_PATH = pwd + '/Facial_models/dlib_face_recognition_resnet_model_v1.dat' FACE_RECOGNITION_MODEL_PATH = pwd + '/Facial_models/dlib_face_recognition_resnet_model_v1.dat'
@ -20,16 +20,17 @@ faceDetector = dlib.get_frontal_face_detector()
shapePredictor = dlib.shape_predictor(PREDICTOR_PATH) shapePredictor = dlib.shape_predictor(PREDICTOR_PATH)
faceRecognizer = dlib.face_recognition_model_v1(FACE_RECOGNITION_MODEL_PATH) faceRecognizer = dlib.face_recognition_model_v1(FACE_RECOGNITION_MODEL_PATH)
index = np.load(pwd+'/Facial_models/index.pkl', allow_pickle=True) index = np.load(pwd + '/Facial_models/index.pkl', allow_pickle=True)
faceDescriptorsEnrolled = np.load(pwd+'/Facial_models/descriptors.npy') faceDescriptorsEnrolled = np.load(pwd + '/Facial_models/descriptors.npy')
cam = cv2.VideoCapture(0)
cam = cv2.VideoCapture(1)
count = 0 count = 0
x1 = x2 = y1 = y2 = 0 x1 = x2 = y1 = y2 = 0
while True: cond = False
while DBHelper.get_power() == "on":
t = time.time() t = time.time()
success, im = cam.read() success, im = cam.read()
@ -37,7 +38,6 @@ while True:
print('cannot capture input from camera') print('cannot capture input from camera')
break break
if (count % SKIP_FRAMES) == 0: if (count % SKIP_FRAMES) == 0:
img = cv2.cvtColor(im, cv2.COLOR_BGR2RGB) img = cv2.cvtColor(im, cv2.COLOR_BGR2RGB)
@ -67,22 +67,21 @@ while True:
argmin = np.argmin(distances) # index argmin = np.argmin(distances) # index
minDistance = distances[argmin] # minimum distance minDistance = distances[argmin] # minimum distance
if minDistance <= THRESHOLD: if minDistance <= THRESHOLD:
label = index[argmin] label = DBHelper.get_firstname(index[argmin]) + "_" + DBHelper.get_lastname(index[argmin])
cond = True
else: else:
label = 'unknown' label = 'unknown'
cond = False
#print("time taken = {:.3f} seconds".format(time.time() - t)) # print("time taken = {:.3f} seconds".format(time.time() - t))
cv2.rectangle(im, (x1, y1), (x2, y2), (0, 255, 0), 2) cv2.rectangle(im, (x1, y1), (x2, y2), (0, 255, 0), 2)
font_face = cv2.FONT_HERSHEY_SIMPLEX font_face = cv2.FONT_HERSHEY_SIMPLEX
font_scale = 0.8 font_scale = 0.8
text_color = (0, 255, 0) text_color = (0, 255, 0)
printLabel = '{} {:0.4f}'.format(label, minDistance) printLabel = '{} {:0.4f}'.format(label, minDistance)
cv2.putText(im, printLabel, (int(x1), int(y1)) , font_face, font_scale, text_color, thickness=2) cv2.putText(im, printLabel, (int(x1), int(y1)), font_face, font_scale, text_color, thickness=2)
cv2.imshow('img', im) cv2.imshow('img', im)
@ -91,4 +90,13 @@ while True:
break break
count += 1 count += 1
if cond:
DBHelper.set_motor("on")
DBHelper.set_alarm("off")
elif not cond:
DBHelper.set_motor("off")
DBHelper.set_alarm("on")
DBHelper.set_alarm("off")
DBHelper.set_motor("off")
cv2.destroyAllWindows() cv2.destroyAllWindows()

View file

@ -4,6 +4,7 @@ import math
import cv2 import cv2
import Facial_Recognition_Enrollment import Facial_Recognition_Enrollment
def register_your_face(label): def register_your_face(label):
num_cap = 50 num_cap = 50
@ -37,6 +38,6 @@ if __name__ == "__main__":
register_your_face(label) register_your_face(label)
print("Data saved! Starting enrollment...") print("Data saved! Starting enrollment...")
print() print()
Facial_Recognition_Enrollment.enroll_face_dataset() #Need discuss and modify after intergrate with database. Facial_Recognition_Enrollment.enroll_face_dataset() # Need discuss and modify after intergrate with database.
print("Face registration completed!") print("Face registration completed!")
print() print()

View file

@ -1,5 +1,6 @@
import DBHelper import DBHelper
import Facial_Recognition_Registration import Facial_Recognition_Registration
import Facial_Recognition_Enrollment
def upload_your_face(firstname, lastname, email, phone): def upload_your_face(firstname, lastname, email, phone):
@ -13,6 +14,7 @@ def upload_your_face(firstname, lastname, email, phone):
count += 1 count += 1
DBHelper.upload_data("User_" + str(count), firstname, lastname, email, phone) DBHelper.upload_data("User_" + str(count), firstname, lastname, email, phone)
Facial_Recognition_Registration.register_your_face("User_" + str(count)) Facial_Recognition_Registration.register_your_face("User_" + str(count))
Facial_Recognition_Enrollment.enroll_face_dataset()
for i in range(20): for i in range(20):
DBHelper.upload_user_photo("User_" + str(count) + "/" + str(i) + ".jpg") DBHelper.upload_user_photo("User_" + str(count) + "/" + str(i) + ".jpg")
except: except:

Binary file not shown.

View file

@ -1,6 +1,6 @@
import os import os
import DBHelper import DBHelper
import Facial_Recognition_Wrapper import Facial_Recognition_Inference
def start(): def start():
@ -32,8 +32,7 @@ def start():
print("Success.") print("Success.")
except: except:
print("No Thieves are registered.") print("No Thieves are registered.")
Facial_Recognition_Wrapper.training_recognizer("LBPH") Facial_Recognition_Inference
Facial_Recognition_Wrapper.face_recognition_inference("LBPH")
if __name__ == "__main__": if __name__ == "__main__":