forked from Mactacs/face-recognition-on-browser
-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.html
440 lines (395 loc) · 16.1 KB
/
index.html
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
<!DOCTYPE html>
<html>
<head>
<title> Face Recognition </title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.0/css/bootstrap.min.css">
<link rel="stylesheet" type="text/css" href="style.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.0/js/bootstrap.min.js"></script>-
<script src="face-api.js"></script>
</head>
<body>
<div id="parent1">
<div class="margin" style="position: relative; float:left; margin-left: 10px; margin-top: 50px; border: 3px solid black;">
<video id="vidDisplay" style="height: 800px; width: 1200px; display: inline-block; vertical-align: baseline;" onloadedmetadata="onPlay(this)" autoplay="true"></video>
<canvas id="overlay" style="position: absolute; top: 0; left: 0;" width = "1200" height = "800"/>
</div>
<div id="parent2" style="float:left;">
<br><br>
<button id="register" class="button button1" style="margin-left: 180px; margin-top: 80px"> Register </button>
<button id="login" class="button button1" style="margin-left: 30px;"> Log In</button>
<br><br><br><br>
<span style="margin-left: 120px; font-size: 30px; font-family:Lucida Console,Monaco,monospace; font-weight: bold;"> Employee Information </span><br></br>
<img id = "prof_img" style="margin-left: 210px; height:200px; width: 200px; border: 3px solid black; border-radius: 10px;" ></img><br><br>
<div id="reg_disp" style="display: none;">
<input id = "fname" style="margin-left:50px; width:500px; height: 30px; border-radius: 5px; border:1px solid black;" type="text" placeholder="First Name : "></input><br></br>
<input id = "lname" style="margin-left:50px; width:500px; height: 30px; border-radius: 5px; border:1px solid black;" type="text" placeholder="Last Name : "></input><br></br><br>
<button id="capture" class="button button1" style="margin-left: 220px;height:80px;"> Capture Image</button><br><br><br><br>
<div id="tries" style="margin-left: 80px; font-size: 23px; font-family:Lucida Console,Monaco,monospace; font-weight: bold;">Trials Left : </div>
</div>
<div id="log_disp">
<br></br>
<div id="logname" style="font-size: 35px; font-weight: bold; margin-left: 40px; width: 570px; white-space: pre-wrap; text-align: center;"></div><br>
<div style="margin-left: 40px; width: 570px; border: 3px solid black;"></div><br>
</div>
</div>
</div>
</body>
<script>
var waitingDialog = waitingDialog || (function ($) {
var $dialog = $(
'<div class="modal fade" data-backdrop="static" data-keyboard="false" tabindex="-1" role="dialog" aria-hidden="true" style="padding-top:15%; overflow-y:visible;">' +
'<div class="modal-dialog modal-m">' +
'<div class="modal-content">' +
'<div class="modal-header"><h3 style="margin:0;"></h3></div>' +
'<div class="modal-body">' +
'<div class="progress progress-striped active" style="margin-bottom:0;"><div class="progress-bar" style="width: 100%"></div></div>' +
'</div>' +
'</div></div></div>');
return {
show: function (message, options) {
if (typeof options === 'undefined') {
options = {};
}
if (typeof message === 'undefined') {
message = 'Loading';
}
var settings = $.extend({
dialogSize: 'm',
progressType: '',
onHide: null
}, options);
$dialog.find('.modal-dialog').attr('class', 'modal-dialog').addClass('modal-' + settings.dialogSize);
$dialog.find('.progress-bar').attr('class', 'progress-bar');
if (settings.progressType) {
$dialog.find('.progress-bar').addClass('progress-bar-' + settings.progressType);
}
$dialog.find('h3').text(message);
if (typeof settings.onHide === 'function') {
$dialog.off('hidden.bs.modal').on('hidden.bs.modal', function (e) {
settings.onHide.call($dialog);
});
}
$dialog.modal();
},
hide: function () {
$dialog.modal('hide');
}
};
})(jQuery);
</script>
<script>
//----------------------------GLOBAL VARIABLE FOR FACE MATCHER------------------------------------
var faceMatcher = undefined
//----------------------------------------------------------------------------------------------
waitingDialog.show('Initializing data....', {dialogSize: 'sm', progressType: 'success'})
$("#parent1").hide();
$("#parent2").hide();
Promise.all([
faceapi.nets.faceRecognitionNet.loadFromUri('/models'),
faceapi.nets.faceLandmark68Net.loadFromUri('/models'),
faceapi.nets.ssdMobilenetv1.loadFromUri('/models'),
faceapi.nets.tinyFaceDetector.loadFromUri('/models')
]).then(start)
async function start() {
$.ajax({
datatype: 'json',
url: "http://localhost/fetch.php",
data: ""
}).done(async function(data) {
if(data.length > 2){
var json_str = "{\"parent\":" + data + "}"
content = JSON.parse(json_str)
for (var x = 0; x < Object.keys(content.parent).length; x++) {
for (var y = 0; y < Object.keys(content.parent[x]._descriptors).length; y++) {
var results = Object.values(content.parent[x]._descriptors[y])
content.parent[x]._descriptors[y] = new Float32Array(results)
}
}
faceMatcher = await createFaceMatcher(content);
}
waitingDialog.hide()
$('#parent1').show()
$('#parent2').show()
run();
});
}
// Create Face Matcher
async function createFaceMatcher(data) {
const labeledFaceDescriptors = await Promise.all(data.parent.map(className => {
const descriptors = [];
for (var i = 0; i < className._descriptors.length; i++) {
descriptors.push(className._descriptors[i]);
}
return new faceapi.LabeledFaceDescriptors(className._label, descriptors);
}))
return new faceapi.FaceMatcher(labeledFaceDescriptors,0.6);
}
async function onPlay() {
const videoEl = $('#vidDisplay').get(0)
if(videoEl.paused || videoEl.ended )
return setTimeout(() => onPlay())
$("#overlay").show()
const canvas = $('#overlay').get(0)
if($("#register").hasClass('active'))
{
const options = getFaceDetectorOptions()
const result = await faceapi.detectSingleFace(videoEl, options)
if (result) {
const dims = faceapi.matchDimensions(canvas, videoEl, true)
dims.height = 800
dims.width = 1200
canvas.height = 800
canvas.width = 1200
const resizedResult = faceapi.resizeResults(result, dims)
faceapi.draw.drawDetections(canvas, resizedResult)
}
else{
$("#overlay").hide()
}
}
if($("#login").hasClass('active'))
{
if(faceMatcher != undefined){
//--------------------------FACE RECOGNIZE------------------
const input = document.getElementById('vidDisplay')
const displaySize = { width: 1200, height: 800 }
faceapi.matchDimensions(canvas, displaySize)
const detections = await faceapi.detectAllFaces(input).withFaceLandmarks().withFaceDescriptors()
const resizedDetections = faceapi.resizeResults(detections, displaySize)
const results = resizedDetections.map(d => faceMatcher.findBestMatch(d.descriptor))
results.forEach((result, i) => {
const box = resizedDetections[i].detection.box
const drawBox = new faceapi.draw.DrawBox(box, { label: result.toString() })
drawBox.draw(canvas)
var str = result.toString()
rating = parseFloat(str.substring(str.indexOf('(') + 1,str.indexOf(')')))
str = str.substring(0, str.indexOf('('))
str = str.substring(0, str.length - 1)
if(str != "unknown"){
if(rating < 0.5){
if(str == $("#log_name").text()){
console.log("Match TRUE!")
match = true;
//$("#logname").html(str)
//$("#prof_img").attr('src',"http://localhost/data/" + str + "/image0.png")
}
}
}
})
//---------------------------------------------------------------------
}
}
setTimeout(() => onPlay())
}
async function run() {
const stream = await navigator.mediaDevices.getUserMedia({ video: {} })
const videoEl = $('#vidDisplay').get(0)
videoEl.srcObject = stream
}
// tiny_face_detector options
let inputSize = 160
let scoreThreshold = 0.4
function getFaceDetectorOptions() {
return new faceapi.TinyFaceDetectorOptions({ inputSize, scoreThreshold });
}
async function load_neural(){
waitingDialog.show('Initializing neural data....', {dialogSize: 'sm', progressType: 'success'})
$.ajax({
datatype: 'json',
url: "http://localhost/fetch.php",
data: ""
}).done(async function(data) {
if(data.length > 2){
var json_str = "{\"parent\":" + data + "}"
content = JSON.parse(json_str)
console.log(content)
for (var x = 0; x < Object.keys(content.parent).length; x++) {
for (var y = 0; y < Object.keys(content.parent[x]._descriptors).length; y++) {
var results = Object.values(content.parent[x]._descriptors[y]);
content.parent[x]._descriptors[y] = new Float32Array(results);
}
}
faceMatcher = await createFaceMatcher(content);
}
waitingDialog.hide()
});
}
</script>
<script>
$(document).ready(async function(){
var counter = 5;
const descriptions = [];
// -------------Initialize---------------
$("#login").css('background-color','yellow');
$("#login").addClass('active');
$("#register").css('background-color','white');
$("#register").removeClass('active');
if($("#login").hasClass('active')){
$("#reg_disp").hide();
$("#log_disp").show();
}
else if($("#register").hasClass('active')){
$("#reg_disp").show();
$("#log_disp").hide();
}
//---------------------------------------
$("#login").click(function(){
$.ajax({
datatype: 'json',
url: "http://localhost/fetch.php",
data: ""
}).done(function(data) {
labeled = JSON.parse(data)
});
$(this).css('background-color','yellow')
$("#register").css('background-color','white')
$(this).addClass('active')
$("#register").removeClass('active')
$("#reg_disp").hide()
$("#log_disp").show()
$("#prof_img").removeAttr('src')
$("#fname").val('')
$("#lname").val('')
$("#logname").html('')
$("#fname").prop("readonly", false)
$("#lname").prop("readonly", false)
counter = 5
description = []
$("#tries").html("Trials left : " + counter)
});
$("#register").click(function(){
$(this).css('background-color','yellow')
$("#login").css('background-color','white')
$(this).addClass('active')
$("#login").removeClass('active')
$("#reg_disp").show()
$("#log_disp").hide()
$("#prof_img").removeAttr('src')
$("#fname").val('')
$("#lname").val('')
$("#logname").html('')
$("#fname").prop("readonly", false)
$("#lname").prop("readonly", false)
counter = 5
description = []
$("#tries").html("Trials left : " + counter)
});
$("#tries").html("Trials left : " + counter)
$("#capture").click(async function(){
var data = $("#lname").val() + "," + $("#fname").val();
const label = data;
if($("#fname").hasClass('active') && $("#lname").hasClass('active') && $("#fname").val() && $("#lname").val()){
if($("#register").hasClass('active')){
$("#fname").prop("readonly", true)
$("#lname").prop("readonly", true)
if(counter <= 5 && counter >= 0 ){
var canvas = document.createElement('canvas');
var context = canvas.getContext('2d');
var video = document.getElementById('vidDisplay');
context.drawImage(video, 0, 0, 600, 350);
var capURL = canvas.toDataURL('image/png');
var canvas2 = document.createElement('canvas');
canvas2.width = 1200;
canvas2.height = 800;
var ctx = canvas2.getContext('2d');
ctx.drawImage(video, 0, 0, 1200, 800);
var new_image_url = canvas2.toDataURL();
var img = document.createElement('img');
img.src = new_image_url;
document.getElementById("prof_img").src = img.src;
const detections = await faceapi.detectSingleFace(img).withFaceLandmarks().withFaceDescriptor();
if( detections != null){
descriptions.push(detections.descriptor);
var descrip = descriptions;
counter--;
$("#tries").html("Trials left : " + counter)
if(counter == 0){
// Save Image
$.ajax({
type: "POST",
url: "http://localhost/ajax.php",
data: {image: img.src ,path: data}
}).done(function(o) {
console.log('Image Saved');
});
waitingDialog.show('Processing data.............', {dialogSize: 'sm', progressType: 'success'})
var postData = new faceapi.LabeledFaceDescriptors(label, descrip);
$.ajax({
url: 'json.php',
type: 'POST',
data: { myData: JSON.stringify(postData) },
datatype: 'json'
})
.done(async function (data) {
load_neural()
alert("Done!")
console.log("Success!")
waitingDialog.hide()
counter = 5
$("#tries").html("Trials left : " + counter)
$("#fname").val('')
$("#lname").val('')
$("#prof_img").removeAttr('src')
$("#fname").prop("readonly", false)
$("#lname").prop("readonly", false)
})
.fail(function (jqXHR, textStatus, errorThrown) {
alert("Error due to internet connection! Please try again!");
});
const descriptions = [];
}
}
else{
alert("No FACE detected!");
}
}
else{
alert("Done Learning!");
counter = 5;
const descriptions = [];
}
}
}
else{
if(!$("#fname").val() || !$("#fname").hasClass('active')){
$("#fname").css('border','1px solid red');
$("#fname").removeClass('active')
}
if(!$("#lname").val() || !$("#lname").hasClass('active')){
$("#lname").css('border','1px solid red');
$("#lname").removeClass('active')
}
}
});
var format = /[!@#$%^&*()_+\-=\[\]{};':"\\|,.<>\/?]/;
$("#fname").keyup(function(){
var str = $(this).val().toUpperCase();
$(this).val(str);
if(format.test(str) && str == ""){
$(this).css('border','1px solid red');
$(this).removeClass('active')
}
else{
$(this).css('border','3px solid black');
$(this).addClass('active')
}
});
$("#lname").keyup(function(){
var str = $(this).val().toUpperCase();
$(this).val(str);
if(format.test(str) || str == ""){
$(this).css('border','1px solid red');
$(this).removeClass('active')
}
else{
$(this).css('border','3px solid black')
$(this).addClass('active')
}
});
});
</script>
</html>