-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathrun.py
2952 lines (2187 loc) · 106 KB
/
run.py
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
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# -*- encoding: utf-8 -*-
"""
Copyright (c) 2019 - present AppSeed.us
"""
import os
from flask_migrate import Migrate
from flask_minify import Minify
from sys import exit
from apps.config import config_dict
from apps import create_app, db
from datetime import date
# WARNING: Don't run with debug turned on in production!
DEBUG = (os.getenv('DEBUG', 'False') == 'True')
# The configuration
get_config_mode = 'Debug' if DEBUG else 'Production'
try:
# Load the configuration using the default values
app_config = config_dict[get_config_mode.capitalize()]
except KeyError:
exit('Error: Invalid <config_mode>. Expected values [Debug, Production] ')
app = create_app(app_config)
Migrate(app, db)
if not DEBUG:
Minify(app=app, html=True, js=False, cssless=False)
if DEBUG:
app.logger.info('DEBUG = ' + str(DEBUG) )
app.logger.info('FLASK_ENV = ' + os.getenv('FLASK_ENV') )
app.logger.info('Page Compression = ' + 'FALSE' if DEBUG else 'TRUE' )
app.logger.info('DBMS = ' + app_config.SQLALCHEMY_DATABASE_URI)
app.logger.info('ASSETS_ROOT = ' + app_config.ASSETS_ROOT )
# app.logger.info('DATA_ROOT = ' + app_config.DATA_ROOT )
################################################################################
############# Auto Annotation tool ##################
from flask import Flask, render_template, request, json, session, Response, url_for, send_file, redirect,stream_with_context,escape,flash
import os, base64, random
from datetime import timedelta, datetime
from os.path import join, dirname, realpath
import time
from datetime import date
import threading
from autoAnnotation.DlibTracker import DlibTracker
from pathlib import Path
from pascal_voc_writer import Writer
from PyQt5.QtGui import QImage
from autoAnnotation.pascal_voc_io import PascalVocWriter
from autoAnnotation.pascal_voc_io import PascalVocReader
from autoAnnotation.yolo_io import YoloReader
from autoAnnotation.yolo_io import YOLOWriter
import os.path
import sys
import subprocess
import torch
import glob
import cv2
import shutil
import inspect
# subprocess.Popen(['gnome-terminal', '-e', 'python3 apitest.py'])
# subprocess.Popen(['gnome-terminal', '-e', 'python3 boothapi.py'])
# def ffmpegfeedall():
# subprocess.Popen(['python3','feed1.py'])
#subprocess.Popen(['gnome-terminal', '-e', 'python3 ffmpegfeed/feed1.py'])
# subprocess.Popen(['gnome-terminal', '-e', 'python3 ffmpegfeed/feed2.py'])
# subprocess.Popen(['gnome-terminal', '-e', 'python3 apitest.py'])
# subprocess.Popen(['gnome-terminal', '-e', 'python3 boothapi.py'])
# ffmpegfeedall()
#####################################################
roi_x = 0
roi_y = 0
roi_w = 0
rou_h = 0
gTracker = None
gLabel = ''
gPath = os.getcwd()
from flask_login import (
current_user,
login_user,
logout_user
)
global current_loggin_user
class VideoCamera():
def __init__(self, url):
# cityList=db.execute("SELECT * FROM User_camera_sources order by username ")
self.video = cv2.VideoCapture(url)
self.url = url
self.error_count = 0
def __del__(self):
self.video.release()
def reset(self):
self.video.release()
self.video = cv2.VideoCapture(self.url)
self.error_count = 0
def get_frame(self):
global gTracker, gLabel
success, image = self.video.read()
if success:
if gTracker is not None:
rgb = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)
gTracker.update(rgb)
track_pos = gTracker.getPos()
x1 = round(track_pos.left())
x2 = round(track_pos.right())
y1 = round(track_pos.top())
y2 = round(track_pos.bottom())
width = (int(x2) - int(x1))
height = (int(y2) - int(y1))
if len(gLabel) > 0: # save tracking result
writer = Writer(gPath + "/" + gLabel + "_" +
str(gTracker.cnt)+".jpg", width, height)
writer.addObject(gLabel, int(
x1), int(y1), int(x2), int(y2))
writer.save(gPath + "/" + gLabel + "_" +
str(gTracker.cnt)+".xml")
cv2.imwrite(gPath + "/" + gLabel+"_" +
str(gTracker.cnt)+'.jpg', image)
# draw tracking result
cv2.rectangle(image, (x1, y1), (x2, y2), (0, 0, 255), 2)
#ret, jpeg = cv2.imencode('.jpg', cv2.resize(image, (160, 90)))
ret, jpeg = cv2.imencode('.jpg', image)
return jpeg.tobytes(), True
else:
return None, False
def gen(camera):
global gTracker
gTracker = None
while True:
try:
frame, suc = camera.get_frame()
if suc:
camera.error_count = 0
else:
camera.error_count += 1
if camera.error_count > 5:
camera.reset()
return
elif camera.error_count > 50:
ret, jpeg = cv2.imencode('.jpg', cv2.imread(
'static/images/no connected.jpg'))
frame = jpeg.tobytes()
except:
camera.error_count += 1
if camera.error_count > 5:
camera.reset()
return
elif camera.error_count > 50:
ret, jpeg = cv2.imencode('.jpg', cv2.imread(
'static/images/no connected.jpg'))
frame = jpeg.tobytes()
if frame is not None:
yield (b'--frame\r\n'
b'Content-Type: image/jpeg\r\n\r\n' + frame + b'\r\n\r\n')
@app.route('/autoLabel.html' ,methods=["POST","GET"])
def autoLabel():
return render_template('home/autoLabel.html', User_camera_sources=User_camera_sources_record.query.filter_by(username=current_user.username))
############################ Camera Stream API Url ############################
@app.route('/video_feed1')
def fr_video_feed2():
url = request.args.get('url')
return Response(gen(VideoCamera(url)), mimetype='multipart/x-mixed-replace; boundary=frame')
#### Set label and tracking region ########
@app.route('/api/addLabel', methods=['POST'])
def api_addLabel():
current_loggin_user = current_user.username
print("---Add label---")
x = request.form.get('x', type=int)
y = request.form.get('y', type=int)
w = request.form.get('w', type=int)
h = request.form.get('h', type=int)
label = request.form.get('label')
global gTracker
gTracker = DlibTracker()
gTracker.reset(x, y, w, h)
global gLabel, gPath
gLabel = label
gPath = str(os.getcwd())+"/Users_slab/"+current_loggin_user+"/"+gLabel
print(gPath)
Path(gPath).mkdir(parents=True, exist_ok=True)
Path(gPath + "/Images")
Path(gPath + "/Labels")
global dataset_path
dataset_path = (str(os.getcwd()) +'/'+ gLabel)
print("Spliting", gPath)
Path(gPath).mkdir(parents=True, exist_ok=True)
Path(gPath + "/model").mkdir(parents=True, exist_ok=True)
Path(gPath + "/data").mkdir(parents=True, exist_ok=True)
Path(gPath + "/data/images").mkdir(parents=True, exist_ok=True)
Path(gPath + "/data/labels").mkdir(parents=True, exist_ok=True)
Path(gPath + "/data/images/train").mkdir(parents=True, exist_ok=True)
Path(gPath + "/data/images/valid").mkdir(parents=True, exist_ok=True)
Path(gPath + "/data/labels/train").mkdir(parents=True, exist_ok=True)
Path(gPath + "/data/labels/valid").mkdir(parents=True, exist_ok=True)
with open(gPath + "/data/" + 'data.yaml', 'w') as data:
data.write('train:'+' '+gPath + "/data/images/train" + '\n')
data.write('val:'+' '+gPath + "/data/images/valid" + '\n')
data.write('\n')
data.write('nc: 1')
data.write('\n')
data.write('names: [' + "'" + gLabel + "'" ']')
data.write('\n')
# data.write('NC: 1')
# data.write('\n')
data.write('SAVE_VALID_PREDICTION_IMAGES: True')
with open(gPath + '/' + 'classes.txt', 'w') as data1:
data1.write(gLabel)
return json.dumps({
'status': 200,
'msg': 'ok'
})
print(gPath)
@app.route('/convert')
def convertYolo():
current_loggin_user = current_user.username
imgFolderPath = str(os.getcwd())+"/Users_slab/"+current_loggin_user
print("---Convert---")
print(gLabel)
print(imgFolderPath)
for file in os.listdir(imgFolderPath+"/"+gLabel):
print(gLabel)
if file.endswith(".xml"):
print(gPath)
print("Convert", file)
annotation_no_xml = os.path.splitext(file)[0]
imagePath = os.path.join(
imgFolderPath + "/" + gLabel, annotation_no_xml + ".jpg")
print("Image path:", imagePath)
image = QImage()
image.load(imagePath)
imageShape = [image.height(), image.width(),
1 if image.isGrayscale() else 3]
imgFolderName = os.path.basename(imgFolderPath + "/" + gLabel)
imgFileName = os.path.basename(imagePath)
writer = YOLOWriter(imgFolderName, imgFileName,
imageShape, localImgPath=imagePath)
# Read classes.txt
classListPath = imgFolderPath + "/" + gLabel + "/" + "classes.txt"
classesFile = open(classListPath, 'r')
classes = classesFile.read().strip('\n').split('\n')
classesFile.close()
# Read VOC file
filePath = imgFolderPath + "/" + gLabel + "/" + file
tVocParseReader = PascalVocReader(filePath)
shapes = tVocParseReader.getShapes()
num_of_box = len(shapes)
for i in range(num_of_box):
label = classes.index(shapes[i][0])
xmin = shapes[i][1][0][0]
ymin = shapes[i][1][0][1]
x_max = shapes[i][1][2][0]
y_max = shapes[i][1][2][1]
writer.addBndBox(xmin, ymin, x_max, y_max, label, 0)
writer.save(targetFile=imgFolderPath + "/" +
gLabel + "/" + annotation_no_xml + ".txt")
return "Nothing"
percentage_test = 20
p = percentage_test/100
def split():
current_loggin_user = current_user.username
dataset_path = str(os.getcwd())+"/Users_slab/"+current_loggin_user+"/"+gLabel
for pathAndFilename in glob.iglob(os.path.join(dataset_path, "*.jpg")):
title, ext = os.path.splitext(os.path.basename(pathAndFilename))
#print("for", gLabel)
if random.random() <= p:
print("for", gPath)
os.system(
f"cp {dataset_path}/{title}.jpg {dataset_path}/data/images/train")
os.system(
f"cp {dataset_path}/{title}.txt {dataset_path}/data/labels/train")
else:
os.system(
f"cp {dataset_path}/{title}.jpg {dataset_path}/data/images/valid")
os.system(
f"cp {dataset_path}/{title}.txt {dataset_path}/data/labels/valid")
def move_modelfile():
global current_loggin_user,target_dir
# user = Users.query.filter_by(username=LoginForm.username).first()
if current_user.is_authenticated:
current_loggin_userid = current_user.get_id() # return username in get_id()
current_loggin_user = current_user.username
print(current_loggin_userid)
print(current_loggin_user )
#custom_models = os.path.join(str(getcwd()+"/Users_slab/"+current_loggin_user+"/Models/"),gLabel)
#os.makedirs(custom_models)
source_dir = str(getcwd()+"/yolov5/runs/train/"+gLabel+"/")
target_dir = str(getcwd()+"/Users_slab/"+current_loggin_user+'/'+gLabel+'/model')
file_names = os.listdir(source_dir)
#shutil.move(os.path.join(source_dir), target_dir)
for file_name in file_names:
shutil.move(os.path.join(source_dir, file_name), target_dir)
print("Model file is successfully move at user folder")
source_dir1 = str(getcwd()+"/Users_slab/"+current_loggin_user+'/'+gLabel+'/model/weights/'+gLabel+'.pt')
target_dir1 = str(getcwd()+"/Users_slab/"+current_loggin_user+'/Models/')
shutil.move(source_dir1, target_dir1)
today = date.today()
genrated_on= today.strftime("%B %d, %Y")
add_model =User_Models_record(username=current_loggin_user,user_id=current_loggin_userid, model_name=gLabel,generated_date=genrated_on)
db.session.add(add_model)
db.session.commit()
print("Model is stored in database successfully !!")
def rename_modelfile():
source_filepath = (str(os.getcwd())+"/yolov5/runs/train/"+gLabel+"/weights/best.pt")
rename_filepath =(str(os.getcwd())+"/yolov5/runs/train/"+gLabel+"/weights/"+gLabel+".pt")
renamed_file=os.rename(source_filepath,rename_filepath)
print("Successfully rename the model file name")
print("model genrated on ")
move_modelfile()
return None
@app.route('/trainingModel')
def training():
split()
current_loggin_user = current_user.username
dataset_path = str(os.getcwd())+"/Users_slab/"+current_loggin_user+"/"+gLabel
data1 = dataset_path + "/data/" +'data.yaml'
subprocess.run(['python3','yolov5/train.py','--data', data1, '--name', gLabel])
#subprocess.run(['python3','-m','torch.distributed.run','--nproc_per_node','2','yolov5/train.py','--data', data1, '--name', gLabel,'--device','0,1'])
rename_modelfile()
return "None"
model_path = (str(os.getcwd()))
@app.route('/downloadModel')
def download():
Path = (model_path+"/Users_slab/"+current_loggin_user+"/Models/"+gLabel+'.pt')
print(Path)
return send_file(Path, as_attachment=True)
import io
import os
from PIL import Image
import numpy as np
loadModel = (str(os.getcwd()))
from io import BytesIO
class Objdetection():
def __init__(self, url):
self.video = cv2.VideoCapture(url)
self.url = url
self.error_count = 0
# self.model = torch.hub.load('yolov5', 'custom', path=loadModel + "/yolov5/runs/" + "/" + "train" + "/" + gLabel + "/" + "weights" + "/" + gLabel+".pt", source='local', force_reload=True)
self.model = torch.hub.load('yolov5', 'custom', path=loadModel + '/yolov5/runs/train/'+gLabel+'/weights/'+gLabel+'.pt', source='local', force_reload=True)
def __del__(self):
self.video.release()
def get_frame(self):
path_model = loadModel + "/yolov5/train/" + gLabel + "/" + "weights" + "/" + gLabel+'.pt'
print("model pARTHHH", path_model)
# model = torch.hub.load("ultralytics/yolov5", "custom", path = "/home/torque/Desktop/Torque-AI/Rampage/Intact-core/Rampage_AI/yolov5/runs/train/2/weights/best.pt",force_reload=True)
# model = torch.hub.load('yolov5', 'custom', path=loadModel + "/yolov5/runs/" + "/" + "train" + "/" + gLabel + "/" + "weights" + "/" + "best.pt", source='local', force_reload=True)
# model = torch.hub.load('yolov5', 'custom', path='/home/torque/Desktop/Torque-AI/Rampage/Intact-core/Rampage_AI/yolov5/runs/train/a12/weights/a12.pt', source='local', force_reload=True)
# Set Model Settings
self.model.eval()
self.model.conf = 0.6 # confidence threshold (0-1)
self.model.iou = 0.45 # NMS IoU threshold (0-1)
# Capture frame-by-fram ## read the camera frame
success, frame = self.video.read()
if success == True:
ret,buffer=cv2.imencode('.jpg',frame)
frame=buffer.tobytes()
#print(type(frame))
img = Image.open(io.BytesIO(frame))
results =self.model(img, size=640)
results.print() # print results to screen
#convert remove single-dimensional entries from the shape of an array
img = np.squeeze(results.render()) #RGB
# read image as BGR
img_BGR = cv2.cvtColor(img, cv2.COLOR_RGB2BGR) #BGR
frame = cv2.imencode('.jpg', img_BGR)[1].tobytes()
return frame
def gen_det(camera):
while True:
frame = camera.get_frame()
yield (b'--frame\r\n'
b'Content-Type: image/jpeg\r\n\r\n' + frame + b'\r\n\r\n')
@app.route('/video_feed_det')
def det_video_feed():
url = request.args.get('url')
return Response(gen_det(Objdetection(url)), mimetype='multipart/x-mixed-replace; boundary=frame')
#######################################################################################################################
############################### load model ############################################################################
@app.route("/load_model")
def load_model():
return render_template("home/loadmodel.html", User_camera_sources=User_camera_sources_record.query.filter_by(username=current_user.username),User_Models_record=User_Models_record.query.filter_by(username=current_user.username))
class Objdetection_with_load_model():
def __init__(self, url,model):
self.video = cv2.VideoCapture(url)
self.url = url
self.modelnme = model
self.error_count = 0
current_loggin_user = current_user.username
if self.modelnme != "yolo5s":
# self.model = torch.hub.load('yolov5', 'custom', path=loadModel + "/yolov5/runs/" + "/" + "train" + "/" + gLabel + "/" + "weights" + "/" + gLabel+".pt", source='local', force_reload=True)
self.model = torch.hub.load('yolov5', 'custom', path=loadModel +'/Users_slab/' +current_loggin_user+'/Models/'+self.modelnme+'.pt', source='local', force_reload=True, device='cpu')
else :
self.model = torch.hub.load('yolov5', 'custom', path=loadModel+"/yolov5/yolov5s.pt" , source='local', force_reload=True, device='cpu')
def __del__(self):
self.video.release()
def get_frame(self):
global Row
# model = torch.hub.load("ultralytics/yolov5", "custom", path = "/home/torque/Desktop/Torque-AI/Rampage/Intact-core/Rampage_AI/yolov5/runs/train/2/weights/best.pt",force_reload=True)
# model = torch.hub.load('yolov5', 'custom', path=loadModel + "/yolov5/runs/" + "/" + "train" + "/" + gLabel + "/" + "weights" + "/" + "best.pt", source='local', force_reload=True)
# model = torch.hub.load('yolov5', 'custom', path='/home/torque/Desktop/Torque-AI/Rampage/Intact-core/Rampage_AI/yolov5/runs/train/a12/weights/a12.pt', source='local', force_reload=True)
# Set Model Settings
self.model.eval()
self.model.conf = 0.6 # confidence threshold (0-1)
self.model.iou = 0.45 # NMS IoU threshold (0-1)
# Capture frame-by-fram ## read the camera frame
success, frame = self.video.read()
if success == True:
ret, buffer = cv2.imencode('.jpg', frame)
frame = buffer.tobytes()
# print(type(frame))
img = Image.open(io.BytesIO(frame))
results = self.model(img, size=640)
results.print() # print results to screen
# convert remove single-dimensional entries from the shape of an array
img = np.squeeze(results.render()) # RGB
# read image as BGR
img_BGR = cv2.cvtColor(img, cv2.COLOR_RGB2BGR) # BGR
frame = cv2.imencode('.jpg', img_BGR)[1].tobytes()
return frame
def gen_det_with_load_model(camera):
while True:
frame = camera.get_frame()
yield (b'--frame\r\n'
b'Content-Type: image/jpeg\r\n\r\n' + frame + b'\r\n\r\n')
@app.route('/video_feed_det_with_loadmodel')
def det_loadmodel_video_feed():
url = request.args.get('url')
return Response(gen_det_with_load_model(Objdetection_with_load_model(url,select_model)), mimetype='multipart/x-mixed-replace; boundary=frame')
@app.route('/video_feed_det_with_loadmodel_fetch')
def det_loadmodel_video_feed_fetch():
global select_model
select_model=request.args.get('model')
print(select_model)
return select_model
#################################################################################################################################
@app.route("/BWphotos")
def bwPhotos():
binderList = os.listdir("/home/torquehq/torquehq-io/Github/Torque-AI/Users_slab/test/a1")
binderList = ['test/a1/' + image for image in binderList]
return render_template("images.html", binderList=binderList)
#####################fr candidate addon####################
from flask import Flask, Response, json, render_template
from werkzeug.utils import secure_filename
from flask import request
from os import path, getcwd
import time
import os
import cv2
from mtcnn import MTCNN
import numpy as np
##############################
roi_x = 0
roi_y = 0
roi_w = 0
rou_h = 0
gTracker = None
gLabel = ''
gPath = os.getcwd()
class FR_candidate_addon(object):
def __init__(self, url):
self.video = cv2.VideoCapture(0)
self.url = url
self.error_count = 0
def __del__(self):
self.video.release()
def get_frame(self):
fn_haar = 'haarcascade_frontalface_default.xml'
haar_cascade = cv2.CascadeClassifier(fn_haar)
success, frame = self.video.read()
print("hello")
if success:
count = 0
size = 4
# fn_haar = 'haarcascade_frontalface_default.xml'
fn_dir = str(os.getcwd())+'/database/'
fn_name = gLabel
print(fn_name )
path = os.path.join(fn_dir, fn_name)
# if not os.path.isdir(path):
# os.mkdir(path)
(im_width, im_height) = (112, 112)
# haar_cascade = cv2.CascadeClassifier(fn_haar)
frame= cv2.flip(frame, 1, 0)
gray = cv2.cvtColor(frame, cv2.IMREAD_COLOR)
mini = cv2.resize(gray,(gray.shape[1]//size, gray.shape[0]//size))
faces = haar_cascade.detectMultiScale(mini)
faces = sorted(faces, key=lambda x: x[3])
if faces:
face_i = faces[0]
(x, y, w, h) = [v * size for v in face_i]
face = gray[y:y + h, x:x + w]
face_resize = cv2.resize(face, (im_width, im_height))
pin=sorted([int(n[:n.find('.')]) for n in os.listdir(path)
if n[0]!='.' ]+[0])[-1] + 1
cv2.imwrite('%s/%s.png' % (path, pin), face_resize)
cv2.rectangle(frame, (x, y), (x + w, y + h), (0, 255, 0), 3)
cv2.putText(frame, fn_name, (x - 10, y - 10), cv2.FONT_HERSHEY_PLAIN,
1,(0, 255, 0))
time.sleep(0.38)
count += 1
print(str(count) + " images taken and saved to " + fn_name +" folder in database ")
#ret, jpeg = cv2.imencode('.jpg', cv2.resize(image, (160, 90)))
ret, jpeg = cv2.imencode('.jpg', frame)
return jpeg.tobytes(), True
else:
return None, False
def gen_frca(camera):
while True:
frame, suc = camera.get_frame()
yield (b'--frame\r\n'
b'Content-Type: image/jpeg\r\n\r\n' + frame + b'\r\n\r\n')
@app.route('/video_feed_frca')
def frc_video_feed():
url = request.args.get('url')
return Response(gen_frca(FR_candidate_addon(url)), mimetype='multipart/x-mixed-replace; boundary=frame')
@app.route('/api/addLabelfrca', methods=['POST'])
def api_addLabelfrca():
print("---Add label---")
label = request.form.get('label')
global gTracker
gTracker = DlibTracker()
global gLabel, gPath
gLabel = label
gPath = str(os.getcwd())+"/database/" + gLabel
print(gPath)
Path(gPath).mkdir(parents=True, exist_ok=True)
Path(gPath + "/Images")
return json.dumps({
'status': 200,
'msg': 'ok'
})
###################frca model training##################
from FR.generate_face_embeddings import GenerateFaceEmbedding
from FR.facial_recognition_model_training import TrainFaceRecogModel
@app.route('/frca_modeltrain')
def frca_modeltrain():
gfe = GenerateFaceEmbedding()
gfe.genFaceEmbedding(gPath)
frmt = TrainFaceRecogModel()
frmt.trainKerasModelForFaceRecognition()
return 'Train completed'
################## Face recognition ####################
from mtcnn import MTCNN
import warnings
import sys
import dlib
from keras.models import load_model
import numpy as np
import pickle
import cv2
from imutils.video import FPS
import os
from FR import face_model
##################
class FacePredictor():
def __init__(self,url):
self.video = cv2.VideoCapture(0)
self.url = url
self.error_count = 0
self.frame_width = int(self.video.get(3))
self.frame_height = int(self.video.get(4))
print(str(self.frame_width) + " : " + str(self.frame_height))
self.save_width = 800
self.save_height = int(800 / self.frame_width * self.frame_height)
def detectFace(self):
size = 4
haar_file = 'haarcascade_frontalface_default.xml'
(width, height) = (128, 128)
face_cascade = cv2.CascadeClassifier(haar_file)
embeddings = os.path.sep.join(
[str(os.getcwd()), "FR/faceEmbeddingModels/embeddings.pickle"])
le = os.path.sep.join(
[str(os.getcwd()), "FR/faceEmbeddingModels/le.pickle"])
# Load embeddings and labels
data = pickle.loads(open(embeddings, "rb").read())
le = pickle.loads(open(le, "rb").read())
embeddings = np.array(data['embeddings'])
labels = le.fit_transform(data['names'])
# Load the classifier model
model = load_model(os.path.sep.join(
[str(os.getcwd()), "FR/faceEmbeddingModels/my_model.h5"]))
success ,im = self.video.read()
if success:
im = cv2.resize(im, (self.save_width, self.save_height))
gray = cv2.cvtColor(im, cv2.COLOR_BGR2GRAY)
faces = face_cascade.detectMultiScale(gray, 1.3, 5)
for (x, y, w, h) in faces:
cv2.rectangle(im, (x, y), (x + w, y + h), (255, 0, 0), 2)
face = gray[y:y + h, x:x + w]
face_resize = cv2.resize(face, (width, height))
# Try to recognize the face
prediction = model.predict(face_resize)
j = np.argmax(prediction)
cv2.rectangle(im, (x, y), (x + w, y + h), (0, 255, 0), 3)
if prediction[1] < 500:
name = le.classes_[j]
text = "{}".format(name)
cv2.putText(im,text, (x - 10, y - 10), cv2.FONT_HERSHEY_PLAIN, 1, (0, 255, 0))
else:
cv2.putText(im, 'not recognized', (x - 10, y - 10), cv2.FONT_HERSHEY_PLAIN, 1, (0, 255, 0))
ret, jpeg = cv2.imencode('.jpg', im)
return jpeg.tobytes(), True
else:
return None, False
def gen_fr(camera):
while True:
frame, suc = camera.detectFace()
yield (b'--frame\r\n'
b'Content-Type: image/jpeg\r\n\r\n' + frame + b'\r\n\r\n')
@app.route('/video_feed_fr')
def fr_video_feed():
url = request.args.get('url')
return Response(gen_fr(FacePredictor(url)), mimetype='multipart/x-mixed-replace; boundary=frame')
############### Person Counter #############################################
######import required libraries ####################
import cv2
import datetime
import imutils
import numpy as np
from scipy.spatial import distance as dist
from collections import OrderedDict
import numpy as np
import os
from imutils.video import FPS
from person_counter.nms import non_max_suppression_fast
##############3import pretrained models###############
prototxtPath = os.path.sep.join(
[str(os.getcwd()), "face_detector/customai.prototxt"])
weightsPath = os.path.sep.join(
[str(os.getcwd()), "face_detector/customai.caffemodel"])
detector = cv2.dnn.readNetFromCaffe(
prototxt=prototxtPath, caffeModel=weightsPath)
#######################Main code of person Counter######################
CLASSES = ["background", "aeroplane", "bicycle", "bird", "boat",
"bottle", "bus", "car", "cat", "chair", "cow", "diningtable",
"dog", "horse", "motorbike", "person", "pottedplant", "sheep",
"sofa", "train", "tvmonitor"]
import cv2
import threading
class RecordingThread (threading.Thread):
def __init__(self, name, camera):
threading.Thread.__init__(self)
self.name = name
self.isRunning = True
self.cap = camera
fourcc = cv2.VideoWriter_fourcc(*'MJPG')
self.out = cv2.VideoWriter('./static/video.avi',fourcc, 20.0, (640,480))
def run(self):
while self.isRunning:
ret, frame = self.cap.read()
if ret:
self.out.write(frame)
self.out.release()
def stop(self):
self.isRunning = False
def __del__(self):
self.out.release()
class CentroidTracker:
def __init__(self, maxDisappeared=50, maxDistance=50):
# initialize the next unique object ID along with two ordered
# dictionaries used to keep track of mapping a given object
# ID to its centroid and number of consecutive frames it has
# been marked as "disappeared", respectively
self.nextObjectID = 0
self.objects = OrderedDict()
self.disappeared = OrderedDict()
self.bbox = OrderedDict() # CHANGE
# store the number of maximum consecutive frames a given
# object is allowed to be marked as "disappeared" until we
# need to deregister the object from tracking
self.maxDisappeared = maxDisappeared
# store the maximum distance between centroids to associate
# an object -- if the distance is larger than this maximum
# distance we'll start to mark the object as "disappeared"
self.maxDistance = maxDistance
def register(self, centroid, inputRect):
# when registering an object we use the next available object
# ID to store the centroid
self.objects[self.nextObjectID] = centroid
self.bbox[self.nextObjectID] = inputRect # CHANGE
self.disappeared[self.nextObjectID] = 0
self.nextObjectID += 1
def deregister(self, objectID):
# to deregister an object ID we delete the object ID from
# both of our respective dictionaries <li class="nav-item"><a class="nav-link" href="autoannotation.html">
del self.objects[objectID]
del self.disappeared[objectID]
del self.bbox[objectID] # CHANGE
def update(self, rects):
# check to see if the list of input bounding box rectangles
# is empty
if len(rects) == 0:
# loop over any existing tracked objects and mark them
# as disappeared
for objectID in list(self.disappeared.keys()):
self.disappeared[objectID] += 1
# if we have reached a maximum number of consecutive
# frames where a given object has been marked as
# missing, deregister it
if self.disappeared[objectID] > self.maxDisappeared:
self.deregister(objectID)
# return early as there are no centroids or tracking info
# to update
# return self.objects
return self.bbox
# initialize an array of input centroids for the current frame
inputCentroids = np.zeros((len(rects), 2), dtype="int")
inputRects = []
# loop over the bounding box rectangles
for (i, (startX, startY, endX, endY)) in enumerate(rects):
# use the bounding box coordinates to derive the centroid
cX = int((startX + endX) / 2.0)
cY = int((startY + endY) / 2.0)
inputCentroids[i] = (cX, cY)
inputRects.append(rects[i]) # CHANGE
# if we are currently not tracking any objects take the input
# centroids and register each of them
if len(self.objects) == 0:
for i in range(0, len(inputCentroids)):
self.register(inputCentroids[i], inputRects[i]) # CHANGE
# otherwise, are are currently tracking objects so we need to
# try to match the input centroids to existing object
# centroids
else:
# grab the set of object IDs and corresponding centroids
objectIDs = list(self.objects.keys())
objectCentroids = list(self.objects.values())
# compute the distance between each pair of object
# centroids and input centroids, respectively -- our
# goal will be to match an input centroid to an existing
# object centroid
D = dist.cdist(np.array(objectCentroids), inputCentroids)
# in order to perform this matching we must (1) find the
# smallest value in each row and then (2) sort the row
# indexes based on their minimum values so that the row
# with the smallest value as at the *front* of the index
# list
rows = D.min(axis=1).argsort()
# next, we perform a similar process on the columns by
# finding the smallest value in each column and then
# sorting using the previously computed row index list
cols = D.argmin(axis=1)[rows]
# in order to determine if we need to update, register,
# or deregister an object we need to keep track of which
# of the rows and column indexes we have already examined
usedRows = set()
usedCols = set()
# loop over the combination of the (row, column) index
# tuples
for (row, col) in zip(rows, cols):
# if we have already examined either the row or
# column value before, ignore it
if row in usedRows or col in usedCols:
continue