Skip to content

Commit 8331522

Browse files
author
AdamMiltonBarker
committedJul 16, 2020
Preparing 0.1.0: Facial Authentication Server updated
1 parent b263dfa commit 8331522

22 files changed

+1061
-0
lines changed
 

‎Facial-Auth/Classes/Facenet.py

+126
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,126 @@
1+
############################################################################################
2+
#
3+
# Project: Peter Moss Acute Myeloid & Lymphoblastic Leukemia AI Research Project
4+
# Repository: ALL Detection System 2019
5+
# Project: Facial Authentication Server
6+
#
7+
# Author: Adam Milton-Barker (AdamMiltonBarker.com)
8+
# Contributors:
9+
# Title: Facenet Class
10+
# Description: Facenet class for the ALL Detection System 2019 Facial Authentication Server.
11+
# License: MIT License
12+
# Last Modified: 2020-07-16
13+
#
14+
############################################################################################
15+
16+
import os, json, cv2, dlib, imutils
17+
18+
import numpy as np
19+
20+
from imutils import face_utils
21+
from datetime import datetime
22+
23+
from Classes.Helpers import Helpers
24+
from Classes.OpenCV import OpenCV
25+
26+
27+
class Facenet():
28+
""" ALL Detection System 2019 Facenet Class
29+
30+
Facenet helper functions for the ALL Detection System 2019 Facial Authentication Server project.
31+
"""
32+
33+
def __init__(self, LogPath):
34+
""" Initializes the Facenet class. """
35+
36+
# Class settings
37+
self.Known = []
38+
39+
self.Helpers = Helpers()
40+
self.LogFile = self.Helpers.setLogFile(self.Helpers.confs["Server"]["Logs"]+"/Facenet")
41+
42+
# OpenCV settings
43+
self.OpenCV = OpenCV(self.Helpers)
44+
45+
# Dlib settings
46+
self.Detector = dlib.get_frontal_face_detector()
47+
self.Predictor = dlib.shape_predictor(self.Helpers.confs["Classifier"]["Dlib"])
48+
49+
def PreprocessKnown(self, ValidDir, Graph):
50+
""" Preprocesses known images. """
51+
52+
for validFile in os.listdir(ValidDir):
53+
if os.path.splitext(validFile)[1] in self.Helpers.confs["Classifier"]["ValidIType"]:
54+
self.Known.append({"File": validFile, "Score": self.Infer(cv2.resize(cv2.imread(ValidDir+validFile), (640, 480)), Graph)})
55+
56+
self.Helpers.logMessage(self.LogFile,
57+
"Facenet",
58+
"STATUS",
59+
str(len(self.Known)) + " known images found.")
60+
61+
def ProcessFrame(self, Frame):
62+
""" Preprocesses frame. """
63+
64+
Known = []
65+
66+
Frame = cv2.resize(cv2.imdecode(Frame, cv2.IMREAD_UNCHANGED), (640, 480))
67+
RawFrame = Frame.copy()
68+
Gray = cv2.cvtColor(Frame, cv2.COLOR_BGR2GRAY)
69+
70+
Path = "Data/Captured/" + datetime.now().strftime("%Y-%m-%d") + "/" + datetime.now().strftime("%H") + "/"
71+
FileName = datetime.now().strftime('%M-%S') + ".jpg"
72+
FileNameGray = datetime.now().strftime('%M-%S') + "-Gray.jpg"
73+
74+
self.OpenCV.SaveFrame(Path + "/", FileName, Frame)
75+
self.OpenCV.SaveFrame(Path + "/", FileNameGray, Gray)
76+
77+
return Frame
78+
79+
def LoadGraph(self):
80+
""" Loads Facenet graph. """
81+
82+
with open(self.Helpers.confs["Classifier"]["Graph"], mode='rb') as f:
83+
graphFile = f.read()
84+
85+
self.Helpers.logMessage(self.LogFile, "Facenet", "Status", "Loaded TASS Graph")
86+
87+
return graphFile
88+
89+
def Infer(self, face, graph):
90+
""" Runs the image through Facenet. """
91+
92+
graph.LoadTensor(self.PreProcess(face).astype(np.float16), None)
93+
output, userobj = graph.GetResult()
94+
95+
return output
96+
97+
def PreProcess(self, src):
98+
""" Preprocesses an image. """
99+
100+
NETWORK_WIDTH = 160
101+
NETWORK_HEIGHT = 160
102+
103+
preprocessed_image = cv2.resize(src, (NETWORK_WIDTH, NETWORK_HEIGHT))
104+
preprocessed_image = cv2.cvtColor(preprocessed_image, cv2.COLOR_BGR2RGB)
105+
preprocessed_image = self.OpenCV.whiten(preprocessed_image)
106+
107+
return preprocessed_image
108+
109+
def Compare(self, face1, face2):
110+
""" Determines whether two images are a match. """
111+
112+
if (len(face1) != len(face2)):
113+
self.Helpers.logMessage(self.LogFile, "Facenet", "!ERROR!", "Distance Missmatch")
114+
return False
115+
116+
tdiff = 0
117+
for index in range(0, len(face1)):
118+
diff = np.square(face1[index] - face2[index])
119+
tdiff += diff
120+
121+
if (tdiff < 1.3):
122+
self.Helpers.logMessage(self.LogFile, "Facenet", "Classification", "Calculated Match: " + str(tdiff))
123+
return True, tdiff
124+
else:
125+
self.Helpers.logMessage(self.LogFile, "Facenet", "Classification", "Calculated Mismatch: " + str(tdiff))
126+
return False, tdiff

‎Facial-Auth/Classes/Helpers.py

+69
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,69 @@
1+
############################################################################################
2+
#
3+
# Project: Peter Moss Acute Myeloid & Lymphoblastic Leukemia AI Research Project
4+
# Repository: ALL Detection System 2019
5+
# Project: Facial Authentication Server
6+
#
7+
# Author: Adam Milton-Barker (AdamMiltonBarker.com)
8+
# Contributors:
9+
# Title: Helper Class
10+
# Description: Helper class for the ALL Detection System 2019.
11+
# License: MIT License
12+
# Last Modified: 2020-07-14
13+
#
14+
############################################################################################
15+
16+
import json
17+
import time
18+
19+
from datetime import datetime
20+
21+
22+
class Helpers():
23+
""" ALL Detection System 2019 Helper Class
24+
25+
Common helper functions for the ALL Detection System 2019 Facial Authentication Server project.
26+
"""
27+
28+
def __init__(self):
29+
""" Initializes the Helper class. """
30+
31+
self.confs = self.loadConfs()
32+
33+
def loadConfs(self):
34+
""" Loads the configuration. """
35+
36+
confs = {}
37+
with open('Required/confs.json') as confs:
38+
confs = json.loads(confs.read())
39+
return confs
40+
41+
def currentDateTime(self):
42+
""" Gets the current date and time in words. """
43+
44+
return datetime.now().strftime("%Y-%m-%d %H:%M:%S")
45+
46+
def timerStart(self):
47+
""" Starts the timer. """
48+
49+
return str(datetime.now()), time.time()
50+
51+
def timerEnd(self, start):
52+
""" Ends the timer. """
53+
54+
return time.time(), (time.time() - start), str(datetime.now())
55+
56+
def setLogFile(self, path):
57+
""" Ends a log file path. """
58+
59+
return path + datetime.fromtimestamp(time.time()).strftime('%Y-%m-%d-%H-%M-%S') + ".txt"
60+
61+
def logMessage(self, logfile, process, messageType, message, hide=False):
62+
""" Logs a message to a log file. """
63+
64+
logString = datetime.fromtimestamp(time.time()).strftime(
65+
'%Y-%m-%d %H:%M:%S') + "|" + process + "|" + messageType + ": " + message
66+
with open(logfile, "a") as logLine:
67+
logLine.write(logString+'\r\n')
68+
if hide == False:
69+
print(logString)

‎Facial-Auth/Classes/Movidius.py

+57
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,57 @@
1+
############################################################################################
2+
#
3+
# Project: Peter Moss Acute Myeloid & Lymphoblastic Leukemia AI Research Project
4+
# Repository: ALL Detection System 2019
5+
# Project: Facial Authentication Server
6+
#
7+
# Author: Adam Milton-Barker (AdamMiltonBarker.com)
8+
# Contributors:
9+
# Title: Movidius Class
10+
# Description: Movidius class for the ALL Detection System 2019 Facial Authentication Server.
11+
# License: MIT License
12+
# Last Modified: 2020-07-16
13+
#
14+
############################################################################################
15+
16+
import os, json, cv2
17+
18+
from mvnc import mvncapi as mvnc
19+
20+
from Classes.Helpers import Helpers
21+
22+
23+
class Movidius():
24+
""" ALL Detection System 2019 Movidius Class
25+
26+
Movidius helper functions for the ALL Detection System 2019 Facial Authentication Server project.
27+
"""
28+
29+
def __init__(self, LogPath):
30+
""" Initializes the Movidius class. """
31+
32+
self.Helpers = Helpers()
33+
self.LogFile = self.Helpers.setLogFile(LogPath+"/Movidius")
34+
35+
self.ncsDevices = None
36+
self.ncsDevice = None
37+
38+
def checkNCS(self):
39+
""" Checks for NCS devices and returns True if devices are found. """
40+
41+
self.ncsDevices = mvnc.EnumerateDevices()
42+
43+
if len(self.ncsDevices) == 0:
44+
self.Helpers.logMessage(self.LogFile, "Movdius", "Status", "No NCS devices found, TASS exiting!")
45+
quit()
46+
47+
self.ncsDevice = mvnc.Device(self.ncsDevices[0])
48+
self.ncsDevice.OpenDevice()
49+
50+
self.Helpers.logMessage(self.LogFile, "Movdius", "Status", "Connected To NCS")
51+
52+
def allocateGraph(self, graphfile):
53+
""" Allocates the NCS graph. """
54+
55+
self.Graph = self.ncsDevice.AllocateGraph(graphfile)
56+
57+
self.Helpers.logMessage(self.LogFile, "Movdius", "Status", "Graph Allocated")

‎Facial-Auth/Classes/OpenCV.py

+73
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,73 @@
1+
############################################################################################
2+
#
3+
# Project: Peter Moss Acute Myeloid & Lymphoblastic Leukemia AI Research Project
4+
# Repository: ALL Detection System 2019
5+
# Project: Facial Authentication Server
6+
#
7+
# Author: Adam Milton-Barker (AdamMiltonBarker.com)
8+
# Contributors:
9+
# Title: OpenCV Class
10+
# Description: OpenCV class for the ALL Detection System 2019 Facial Authentication Server.
11+
# License: MIT License
12+
# Last Modified: 2020-07-16
13+
#
14+
############################################################################################
15+
16+
import os, json, cv2, time
17+
import numpy as np
18+
from datetime import datetime
19+
20+
21+
class OpenCV():
22+
""" ALL Detection System 2019 OpenCV Class
23+
24+
OpenCV helper functions for the ALL Detection System 2019 Facial Authentication Server project.
25+
"""
26+
27+
def __init__(self, helpers):
28+
""" Initializes the OpenCV class. """
29+
30+
self.Helpers = helpers
31+
32+
def SaveFrame(self, path, fileName, frame):
33+
""" Saves an image. """
34+
35+
if not os.path.exists(path):
36+
os.makedirs(path)
37+
38+
currentImage=path+'/'+datetime.now().strftime('%M-%S')+'.jpg'
39+
cv2.imwrite(currentImage, frame)
40+
41+
return currentImage
42+
43+
def loadImage(self, imgID):
44+
""" Loads an image. """
45+
46+
imgLoadStart = time.time()
47+
48+
img = cv2.imread("data/captured/"+str(imgID)+'.png')
49+
50+
imgLoadEnd = (imgLoadStart - time.time())
51+
52+
return img
53+
54+
def whiten(self, source_image):
55+
""" Creates a whitened image. """
56+
57+
source_mean = np.mean(source_image)
58+
source_standard_deviation = np.std(source_image)
59+
std_adjusted = np.maximum(source_standard_deviation, 1.0 / np.sqrt(source_image.size))
60+
whitened_image = np.multiply(np.subtract(source_image, source_mean), 1 / std_adjusted)
61+
return whitened_image
62+
63+
def preprocess(self, src):
64+
""" Preprocesses an image. """
65+
66+
NETWORK_WIDTH = 160
67+
NETWORK_HEIGHT = 160
68+
69+
preprocessed_image = cv2.resize(src, (NETWORK_WIDTH, NETWORK_HEIGHT))
70+
preprocessed_image = cv2.cvtColor(preprocessed_image, cv2.COLOR_BGR2RGB)
71+
preprocessed_image = self.whiten(preprocessed_image)
72+
73+
return preprocessed_image
File renamed without changes.

0 commit comments

Comments
 (0)