-
Notifications
You must be signed in to change notification settings - Fork 2
/
IPC.py
1685 lines (1388 loc) · 69.9 KB
/
IPC.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
import os
import matplotlib
import matplotlib.pyplot as plt
import tensorflow as tf # Version 1.0.0 (some previous versions are used in past commits)
from sklearn import metrics
import random
from random import randint
import argparse
import logging
import time
import struct
import operator
import imutils
import cv2
import numpy as np
import math
from tf_pose.estimator import TfPoseEstimator
from tf_pose.networks import get_graph_path, model_wh
from itertools import chain, count
from sklearn.neighbors import NearestNeighbors
from collections import defaultdict
import winsound
import darknet.json as dk
import facerec.recognize as fr
# import deepface.deepface as df
import security
## Input management
CAMERA = [] # Default value, if no camera is given, switch to video mode
VIDEO = "utilities/test_vid.mp4"
REAL_FPS = 30
PROC_FPS = 3 # Proc is surely < Real
SKIP_FRAME = round(REAL_FPS/PROC_FPS) - 1
# 5th is face camera. Remove to use cailing cams cropped by FREG.
# CAMERA = [0]
# CAMERA = [0, 1]
# CAMERA = [cv2.CAP_DSHOW + 0] # Using directshow to fix black bar
# CAMERA = ["rtsp://167.205.66.187:554/onvif1"]
# CAMERA = [ "rtsp://167.205.66.147:554/onvif1",
# "rtsp://167.205.66.148:554/onvif1",
# "rtsp://167.205.66.149:554/onvif1",
# "rtsp://167.205.66.150:554/onvif1",
# cv2.CAP_DSHOW + 1 ]
FPSLIM = 0 # Set to 0 for unlimited
# Size of the images, act as a boundary
IMAGE = [1024,576]
SUBIM = [512,288]
# ROTATE = [0, 0, 0, 0]
ROTATE = [180, 180, 180, 180, 90]
# Face camera, the fifth camera on the list
FCAMDS = 1 # Face camera downscale
FCAMCP = [0.2, 1-0.5, 0.2, 1-0.2] # Crop fraction from top, bottom, left, right
FCOFF = SUBIM # Center location of face camera
## System-wide parameters
# Disable/Enable the actual systems and not just visual change
SYS_OPOSE = True
SYS_ACT = SYS_OPOSE and True
SYS_DARK = True
SYS_FACEREC = True
## LSTM Parameters
# N_STEPS = 8
N_STEPS = 5
# DATASET_PATH = "data/"
# DATASET_PATH = "data/Overlap_fixed/"
# DATASET_PATH = "data/Overlap_fixed4/"
# DATASET_PATH = "data/Overlap_fixed4_separated/"
# DATASET_PATH = "data/2a_Amplify/"
# DATASET_PATH = "data/Direct2a/"
# DATASET_PATH = "data/Direct2a/Normalize/"
# DATASET_PATH = "data/Direct2a/NormalizePoint/"
DATASET_PATH = "data/Direct2a/NormalizeOnce/"
LAYER = 2 # 1: Default [36,36] # 2: Simpler [36]
## Preprocessing schemes, only applies right before the poses loaded to LSTM.
# No effect to the original pose data.
# Group A, main preprocessing:
# 1: Amplify - Poses emulated as if there's a big border between sub-images
# 2: Normalize - Individual pose returned to origin
# 3: NormalizeOnce - Every pose in a gesture will be relative to the first in the gesture
# 4: NormalizePoint - Every point in a gesture will be relative to the first point in the gesture
# 5: Reverse - Poses in 4 sub-images emulated as if happening in a single image
# Other: No preprocessing
POSEAMP = 1000 # [Amplify] Value added if a pose is over the sub-image boundary
# Group B, idle management:
# 1: Null - Unmoving gestures (average) are forced to be all null
# Other: No preprocessing
IDLETH = int(IMAGE[0]/100) # Max distance (in coord) a gesture forced to be idling
PREPROC = [3,1]
## Label id selection schemes
# No effect to the original pose data. Based on the index:
# 0: Weighted - Positive poses receive boosted confidence (lowering false "suspicious").
# 1: Grouped - Big gesture (DR, UR, DL, UL, ND) will be groups, averaged, max obtained.
# Labels in losing groups will be totally ignored (zero)
# After: Max confidence
LABSEL = [True,False]
# Label weight for weighted label scheme, multiplied to the base confidence
LABWEI = np.array([1,1,1,1, 0,0,0,0, 0,0,0,0, 0,0,0,0, 0]) * 0.2 + 1
# LABWEI = np.array([1,1,1,1, 0,0,0,0, 0,0,0,0, 0,0,0,0]) * 0.2 + 1
LABGRO = [ [0,4,8,12],
[1,5,9,13],
[2,6,10,14],
[3,7,11,15],
[16]]
LABELS = [
"jalan_DR", "jalan_UR", "jalan_DL", "jalan_UL",
"barang2_DR", "barang2_UR", "barang2_DL", "barang2_UL",
"barang1l_DR", "barang1l_UR", "barang1l_DL", "barang1l_UL",
"barang1r_DR", "barang1r_UR", "barang1r_DL", "barang1r_UL",
"diam_ND"
]
# LABELS = [
# "jalan_NE", "jalan_NW", "jalan_SE", "jalan_SW",
# "menyapu_NE", "menyapu_NW", "menyapu_SE", "menyapu_SW",
# "barang_NE", "barang_NW", "barang_SE", "barang_SW",
# "diam_NE", "diam_NW", "diam_SE", "diam_SW"
# ]
# LABELS = ["normal", "anomaly"]
## Security Parameters
N_HIST = 10
FRPARAM = 0.3 # Individual frame parameter, depending on the post processing used.
HISTH = 0.8 # Historical threshold for final trigger.
## Postprocessing schemes, historical level calculation
# Before: N_HIST frames collected, each having percentage of positive detections vs. all detections
# 0: Count threshold - Percentage of frames above PARAM threshold vs. all frames.
# 1: Average - Average all frames (no PARAM required)
# 2: Percentile - Calculate the PARAM percentile from all frames
# After: Check against historical threshold
POSTPROC = 2
# Alarms & indicators
ALDUR = 2 # Alarm duration in seconds (using the file duration if it's shorter)
ALAUTH = 5 # Authorized state duration, if there's any known face
ALSND = "utilities/alarm.wav" # Alarm sound directory
## Utilities
# Prevent face blinking, hold prev result if new result is empty
HFACE = 3
# Prescale & Pratical face_reg region
FPSCALE = 1 # The face image prescale divisor
FUP = 2 # Facerec model upsample
# Cropping ceiling cams for face recog region
# FREG = [0, 200, 250, 800] # Face region, for single SW camera [y1, y2, x1, x2], 1024x576 single image
# FREG = [288+0, 288+100, 512+125, 512+340] # Face region, for SW camera in 2x2 [y1, y2, x1, x2], 1024x576 four images
# FREG = [0, 576, 0, 1024]
FREG = [350, 510, 400, 600]
# Masking areas to NOT be detected by openpose.
# Used to hide noisy area unpassable by human. (Masks are not shown during preview)
# The mask is a polygon, specify the vertices location.
DOMASK = 1
DRAWMASK = 1 # Preview the masking or keep it hidden
# PMASK = [ np.array([[610,520],[770,430],[960,576],[660,576]], np.int32), # SW
# np.array([[185,430],[255,470],[70,570],[0,575],[0,530]], np.int32), # SE
# np.array([[760,200],[880,288],[1024,134],[985,44]], np.int32), # NW
# np.array([[260,190],[50,50],[136,53],[327,157]], np.int32) # NE
# ]
PMASK = [ np.array([[290,200],[0,0],[512,0],[350,180]], np.int32), # NE
np.array([[650,200],[800,288],[1024,288],[1024,0],[985,44]], np.int32), # NW
np.array([[185,430],[255,470],[70,570],[0,575],[0,300]], np.int32), # SE
np.array([[610,520],[700,420],[770,380],[960,576],[660,576]], np.int32), # SW
np.array([[950,400],[1024,400],[1024,500]], np.int32)] # SW
# PMASK = [ np.array([[0,0],[1024,0],[1024,576],[0,576]], np.int32) ]
DUMMY = False
SKX = [0, 2, 4, 6, 8, 10, 12, 14, 16, 18, 20, 22, 24, 26, 28, 30, 32, 34]
SKY = [1, 3, 5, 7, 9, 11, 13, 15, 17, 19, 21, 23, 25, 27, 29, 31, 33, 35]
class mainhuman_activity:
# Pre-processing for every image
def preprocess(raws, rots):
imgs = []
for img, rot in zip(raws, rots):
img = cv2.resize(img, dsize=(SUBIM[0], SUBIM[1]), interpolation=cv2.INTER_CUBIC) # 16:9
# img = cv2.resize(img, dsize=(1024, 576), interpolation=cv2.INTER_CUBIC) # 16:9
# img = cv2.resize(img, dsize=(512, 288), interpolation=cv2.INTER_CUBIC) # 16:9
# img = cv2.resize(img, dsize=(256, 144), interpolation=cv2.INTER_CUBIC) # 16:9
# img = cv2.resize(img, dsize=(464, 288), interpolation=cv2.INTER_CUBIC) # 16:10
# img = cv2.resize(img, dsize=(640, 480), interpolation=cv2.INTER_CUBIC) # 4:3
# img = cv2.resize(img, dsize=(320, 240), interpolation=cv2.INTER_CUBIC) # 4:3
# img = cv2.resize(img, dsize=(160, 120), interpolation=cv2.INTER_CUBIC) # 4:3
img = imutils.rotate_bound(img, rot)
imgs.append(img)
if len(imgs) == 1:
image = imgs[0]
if len(imgs) >= 2: # Two images side-by-side
image = np.hstack((imgs[0], imgs[1]))
if len(imgs) >= 4: # Four images boxed
image2 = np.hstack((imgs[2], imgs[3]))
image = np.vstack((image, image2))
return imgs, image
def __init__(self, camera=CAMERA,rotate=ROTATE, security_threshold=HISTH):
self.fps = 1
frame_time = 0
hisfps = [] # Historical FPS data
self.alprev = 0 # Prev alarm time
self.altrig = 0 # Alarm triggered, -1 authorized, 0 neutral, 1 triggered
freg = []
if len(camera) > 0:
from webcamvideostream import WebcamVideoStream
cams = [WebcamVideoStream(src=cam, resolution=(1280,720)).start() for cam in camera]
imgs = []
for i, cam in enumerate(cams):
# cam.set(cv2.CAP_PROP_BUFFERSIZE, 1) # Internal buffer will now store only x frames
img = cam.read()
# If no image is acquired
if (img is None):
# Black image
imgs.append(np.zeros((100,100,3), np.uint8))
elif (img.size == 0):
imgs.append(np.zeros((100,100,3), np.uint8))
else:
imgs.append(img)
# TEST, 4 camera simulation
# for i in range(3):
# imgs.append(img)
imgs, image = mainhuman_activity.preprocess(imgs, rotate)
# Face camera, not rendered on main image
if len(imgs) == 5:
im_h, im_w = imgs[4].shape[:2]
imf = imgs[4][round(im_h*FCAMCP[0]): round(im_h*FCAMCP[1]), round(im_w*FCAMCP[2]): round(im_w*FCAMCP[3])] # Crop
im_h, im_w = imf.shape[:2]
imf = cv2.resize(imf, dsize=(round(im_w/FCAMDS), round(im_h/FCAMDS)), interpolation=cv2.INTER_CUBIC) # Downsample
im_h, im_w = imf.shape[:2]
ky = 0 if im_h % 2 == 0 else 1
kx = 0 if im_w % 2 == 0 else 1
freg = [round(FCOFF[1]-im_h/2), round(FCOFF[1]+im_h/2)+ky, round(FCOFF[0]-im_w/2), round(FCOFF[0]+im_w/2)+kx]
else:
freg = FREG # Use cropped ceiling cams for face
else:
cams = []
print("No camera given, trying to use video instead.")
cap = cv2.VideoCapture(VIDEO, cv2.CAP_FFMPEG)
time.sleep(1)
if cap.isOpened() is False:
print("Error opening video stream or file")
return None
frame = 0
frame_skipped = 0
ret_val, image = cap.read()
freg = FREG # Use ceiling cams for face
self.im_h, self.im_w = image.shape[:2]
# h, w, c = image_raw.shape
# h2, w2, c2 = image2_raw.shape
# print(h, w, c, h2, w2, c2)
###print("\n######################## Darknet")
if SYS_DARK:
dark = dk.darknet_recog()
###print(dark.performDetect(image))
###print("\n######################## LSTM")
if SYS_ACT:
act = activity_human()
act.test()
###print("\n######################## Openpose")
if SYS_OPOSE:
opose = openpose_human(image)
# print("\n######################## Deepface")
# dface = df.face_recog()
# print(dface.run(image))
###print("\n######################## Facerec")
if SYS_FACEREC:
facer = fr.face_recog(face_dir="./facerec/face/")
hold_face = 0
act_labs = []
act_confs = []
act_locs = []
sec_hist = []
if DUMMY:
# Dummy pose
dimg = cv2.imread("images/TestPose.jpg")
doff_x = 0
doff_y = 30
rimg = cv2.imread("images/Background.png")
# For FPS calculation
ptime = time.time()
# Main loop
try:
f = open(r'\\.\pipe\testing', 'r+b',0)
d = 0 # mode in communication
alarmmode = True # False mode deactive True mode active
mode = True # False normal mode True recognition mode
face_tolerance = 0.4
while True:
# imgs = [mainhuman_activity.read2(cam) for cam in cams]
n = struct.unpack('I', f.read(4))[0] # Read str length
s = f.read(n).decode('ascii') # Read str
f.seek(0)
print ('Accept from C#', s)
if (s == 'AlarmDeactive'):
d = 7
elif (s == 'AlarmActive'):
d = 6
elif (s == 'FaceInput'):
d = 5
elif (s == 'Normal'):
d = 4
elif (s == 'Recognition'):
d = 3
elif (s == 'Start'):
d = 2
elif (s == 'Stop'):
d = 1
elif (s == 'Received'):
d = 0
else:
s='Go'
f.write(struct.pack('I', len(s)) + s.encode('ascii')) # Write str length and str
f.seek(0)
print ('Sending to C#:', s)
if (d == 7):
alarmmode = False # False mode deactive True mode active
s='Go'
f.write(struct.pack('I', len(s)) + s.encode('ascii')) # Write str length and str
f.seek(0)
print ('Sending to C#:', s)
elif (d == 6):
alarmmode = True # False mode deactive True mode active
s='Go'
f.write(struct.pack('I', len(s)) + s.encode('ascii')) # Write str length and str
f.seek(0)
print ('Sending to C#:', s)
elif (d == 5):
s='Go'
f.write(struct.pack('I', len(s)) + s.encode('ascii')) # Write str length and str
f.seek(0)
print ('Sending to C#:', s)
n = struct.unpack('I', f.read(4))[0] # Read str length
facename = f.read(n).decode('ascii') # Read str
f.seek(0)
print ('Accept from C#', facename)
imgs = []
if len(camera) > 0:
for i, cam in enumerate(cams):
# Grab the frames AND do the heavy preprocessing for each camera
# ret_val, img = cam.read()
# For better synchronization on multi-cam setup:
# Grab the frames first without doing the heavy stuffs (decode, demosaic, etc)
# ret_val = cam.grab()
# The FIFO nature of the buffer means we can't get the latest frame
# Thus skip the earlier frames. Delay stats: 7s 8fps +artifact >>> 2s 3fps
# for i in range(5):
# ret_val = cam.grab()
# Multi-threading using WebcamVideoStream
img = cam.read()
###print(cam.grabbed)
# If no image is acquired
if (img is None):
# Black image
imgs.append(np.zeros((100,100,3), np.uint8))
elif (img.size == 0):
imgs.append(np.zeros((100,100,3), np.uint8))
else:
imgs.append(img)
# for i, cam in enumerate(cams):
# # Decode the captured frames
# ret_val, img = cam.retrieve()
# imgs.append(img)
# Skip frame if there's nothing
if (imgs is [None]):
continue
# # TEST, 4 camera simulation
# for i in range(3):
# imgs.append(img)
imgs, image = mainhuman_activity.preprocess(imgs, ROTATE)
# Face camera, not seen on main image
if len(imgs) == 5:
im_h, im_w = imgs[4].shape[:2]
imf = imgs[4][round(im_h*FCAMCP[0]): round(im_h*FCAMCP[1]), round(im_w*FCAMCP[2]): round(im_w*FCAMCP[3])] # Crop
im_h, im_w = imf.shape[:2]
imf = cv2.resize(imf, dsize=(round(im_w/FCAMDS), round(im_h/FCAMDS)), interpolation=cv2.INTER_CUBIC) # Downsample
im_h, im_w = imf.shape[:2]
ky = 0 if im_h % 2 == 0 else 1
kx = 0 if im_w % 2 == 0 else 1
freg = [round(FCOFF[1]-im_h/2), round(FCOFF[1]+im_h/2)+ky, round(FCOFF[0]-im_w/2), round(FCOFF[0]+im_w/2)+kx]
else:
# Video mode
ret_val, image = cap.read()
# Skip frames to get realtime data representation
if frame_skipped < SKIP_FRAME:
frame += 1
frame_skipped += 1
continue
frame += 1
frame_skipped = 0
# Special smaller image for face recognition, reduces memory
if len(imgs) == 5:
imface = imf # Use face camera
else:
# Use cropped ceiling cams
imface = image[freg[0]:freg[1], freg[2]:freg[3]]
###print("\n######################## Facerec")
if SYS_FACEREC:
face_locs_tp, face_names_tp = facer.runinference(imface, tolerance=face_tolerance, prescale=1/FPSCALE, upsample=FUP)
# print(face_locs_tp, face_names_tp)
else:
face_locs_tp = []
face_names_tp = []
# Prevent face blinking, apply the result if the new result is not empty.
if face_locs_tp or hold_face <= 0:
face_locs = face_locs_tp # Apply the results
face_names = face_names_tp
hold_face = HFACE # Reset counter
else:
hold_face -= 1
# Facerec display
for (top, right, bottom, left), face in zip(face_locs, face_names):
print(face)
if (face == "Unknown"):
bounds = [FREG[2]+FPSCALE*left, FREG[0]+FPSCALE*top, FPSCALE*(right-left), FPSCALE*(bottom-top)]
image = image[int(bounds[1]):int(bounds[1]+bounds[3]), int(bounds[0]):int(bounds[0]+bounds[2])]
cv2.imwrite('facerec/face/'+facename+'.jpg', image)
print("\n######################## Facerec")
s='Go'
f.write(struct.pack('I', len(s)) + s.encode('ascii')) # Write str length and str
f.seek(0)
print ('Sending to C#:', s)
elif (d == 4):
mode = False # False normal mode True recognition mode
s='Go'
f.write(struct.pack('I', len(s)) + s.encode('ascii')) # Write str length and str
f.seek(0)
print ('Sending to C#:', s)
elif (d == 3):
mode = True # False normal mode True recognition mode
s='Go'
f.write(struct.pack('I', len(s)) + s.encode('ascii')) # Write str length and str
f.seek(0)
print ('Sending to C#:', s)
elif (d == 2):
from webcamvideostream import WebcamVideoStream
for i, cam in enumerate(cams):
# cam.set(cv2.CAP_PROP_BUFFERSIZE, 1) # Internal buffer will now store only x frames
cam.stop()
camera = []
rotate = []
s='Go'
f.write(struct.pack('I', len(s)) + s.encode('ascii')) # Write str length and str
f.seek(0)
print ('Sending to C#:', s)
n = struct.unpack('I', f.read(4))[0] # Read str length
camnumber = f.read(n).decode('ascii') # Read str
f.seek(0)
try:
cam_number = int(camnumber)
except ValueError:
pass
print ('Accept from C#', camnumber)
for x in range(cam_number):
s='Go'
f.write(struct.pack('I', len(s)) + s.encode('ascii')) # Write str length and str
f.seek(0)
print ('Sending to C#:', s)
n = struct.unpack('I', f.read(4))[0] # Read str length
camtemp = f.read(n).decode('ascii') # Read str
f.seek(0)
try:
camera.append(int(camtemp))
rotate.append(180)
except ValueError:
camera.append(camtemp)
rotate.append(180)
pass
print ('Accept from C#', camtemp)
s='Go'
f.write(struct.pack('I', len(s)) + s.encode('ascii')) # Write str length and str
f.seek(0)
print ('Sending to C#:', s)
n = struct.unpack('I', f.read(4))[0] # Read str length
facetolerancetemp = f.read(n).decode('ascii') # Read str
f.seek(0)
if (facetolerancetemp!=" "):
try:
face_tolerance = float(facetolerancetemp)
except ValueError:
pass
print ('Accept from C#', facetolerancetemp)
s='Go'
f.write(struct.pack('I', len(s)) + s.encode('ascii')) # Write str length and str
f.seek(0)
print ('Sending to C#:', s)
n = struct.unpack('I', f.read(4))[0] # Read str length
securitythresholdtemp = f.read(n).decode('ascii') # Read str
f.seek(0)
if (securitythresholdtemp!=" "):
try:
security_threshold = float(securitythresholdtemp)
except ValueError:
pass
print ('Accept from C#', securitythresholdtemp)
s='Go'
f.write(struct.pack('I', len(s)) + s.encode('ascii')) # Write str length and str
f.seek(0)
print ('Sending to C#:', s)
n = struct.unpack('I', f.read(4))[0] # Read str length
camtemp = f.read(n).decode('ascii') # Read str
f.seek(0)
if (camtemp!=" "):
try:
camera.append(cv2.CAP_DSHOW + int(camtemp))
rotate.append(90)
except ValueError:
camera.append(camtemp)
rotate.append(90)
pass
print ('Accept from C#', camtemp)
cams = [WebcamVideoStream(src=cam, resolution=(1280,720)).start() for cam in camera]
s='Go'
f.write(struct.pack('I', len(s)) + s.encode('ascii')) # Write str length and str
f.seek(0)
print ('Sending to C#:', s)
elif(d == 1):
s='Wait'
f.write(struct.pack('I', len(s)) + s.encode('ascii')) # Write str length and str
f.seek(0)
print ('Sending to C#:', s)
elif(d == 0):
imgs = []
if len(camera) > 0:
for i, cam in enumerate(cams):
# Grab the frames AND do the heavy preprocessing for each camera
# ret_val, img = cam.read()
# For better synchronization on multi-cam setup:
# Grab the frames first without doing the heavy stuffs (decode, demosaic, etc)
# ret_val = cam.grab()
# The FIFO nature of the buffer means we can't get the latest frame
# Thus skip the earlier frames. Delay stats: 7s 8fps +artifact >>> 2s 3fps
# for i in range(5):
# ret_val = cam.grab()
# Multi-threading using WebcamVideoStream
img = cam.read()
###print(cam.grabbed)
# If no image is acquired
if (img is None):
# Black image
imgs.append(np.zeros((100,100,3), np.uint8))
elif (img.size == 0):
imgs.append(np.zeros((100,100,3), np.uint8))
else:
imgs.append(img)
# for i, cam in enumerate(cams):
# # Decode the captured frames
# ret_val, img = cam.retrieve()
# imgs.append(img)
# Skip frame if there's nothing
if (imgs is [None]):
continue
# # TEST, 4 camera simulation
# for i in range(3):
# imgs.append(img)
imgs, image = mainhuman_activity.preprocess(imgs, rotate)
# Face camera, not seen on main image
if len(imgs) == 5:
im_h, im_w = imgs[4].shape[:2]
imf = imgs[4][round(im_h*FCAMCP[0]): round(im_h*FCAMCP[1]), round(im_w*FCAMCP[2]): round(im_w*FCAMCP[3])] # Crop
im_h, im_w = imf.shape[:2]
imf = cv2.resize(imf, dsize=(round(im_w/FCAMDS), round(im_h/FCAMDS)), interpolation=cv2.INTER_CUBIC) # Downsample
im_h, im_w = imf.shape[:2]
ky = 0 if im_h % 2 == 0 else 1
kx = 0 if im_w % 2 == 0 else 1
freg = [round(FCOFF[1]-im_h/2), round(FCOFF[1]+im_h/2)+ky, round(FCOFF[0]-im_w/2), round(FCOFF[0]+im_w/2)+kx]
else:
# Video mode
ret_val, image = cap.read()
# Skip frames to get realtime data representation
if frame_skipped < SKIP_FRAME:
frame += 1
frame_skipped += 1
continue
frame += 1
frame_skipped = 0
# Special smaller image for face recognition, reduces memory
if len(imgs) == 5:
imface = imf # Use face camera
else:
# Use cropped ceiling cams
imface = image[freg[0]:freg[1], freg[2]:freg[3]]
# Special masked image for openpose, reduce environment noise.
# Draw a polygon mask around unwanted area, for 4 cam mode
impose = image.copy()
if DOMASK:
for pmask in PMASK:
cv2.fillPoly(impose, [pmask], color=(200,200,288))
# cv2.fillPoly(impose, [pmask], color=(0,0,0))
# Dummy image
if DUMMY:
impose[0:IMAGE[1], 0:IMAGE[0]] = rimg
if (doff_x >= 0) and (doff_y >= 0) and (doff_x+dimg.shape[1] < IMAGE[0]) and (doff_y+dimg.shape[0] < IMAGE[1]):
impose[doff_y:doff_y+dimg.shape[0], doff_x:doff_x+dimg.shape[1]] = dimg
impose[doff_y+288:doff_y+dimg.shape[0]+288, 1024-(doff_x+dimg.shape[1]):1024-doff_x] = cv2.flip(dimg.copy(), 1)
else:
doff_x = 0
doff_y = 30
doff_x += int(round((1024-dimg.shape[1])/(3*4)))
# doff_y += int(round((576-dimg.shape[0])/(3*4)))
###print("\n######################## Openpose")
if SYS_OPOSE:
human_keypoints, human_ids, humans = opose.runopenpose(impose)
# print(humans, human_keypoints)
else:
human_keypoint = {0: [np.zeros(36)]}
human_ids = {0: 0}
humans = []
###print("\n######################## Darknet")
if SYS_DARK:
dobj = dark.performDetect(image)
###print(dobj)
else:
dobj = []
###print("\n######################## Facerec")
if SYS_FACEREC:
face_locs_tp, face_names_tp = facer.runinference(imface, tolerance=face_tolerance, prescale=1/FPSCALE, upsample=FUP)
### print(face_locs_tp, face_names_tp)
else:
face_locs_tp = []
face_names_tp = []
# Prevent face blinking, apply the result if the new result is not empty.
if face_locs_tp or hold_face <= 0:
face_locs = face_locs_tp # Apply the results
face_names = face_names_tp
hold_face = HFACE # Reset counter
else:
hold_face -= 1
# print("\n######################## LSTM")
act_labs = []
act_confs = []
act_locs = []
if SYS_ACT:
for key, human_keypoint in human_keypoints.items():
###print(key, human_keypoint)
if(len(human_keypoint)==N_STEPS):
act.runinference(human_keypoint)
act_labs.append(act.action)
act_confs.append(act.conf)
loc = openpose_human.average([human_keypoint[N_STEPS-1]])
# loc here is produced with format [[x,y]], so must be passing [0]
act_locs.append(loc[0])
###print("\n######################## Maths")
securityalert = True
if alarmmode:
sec_lv, sec_flv = self.sec_calc(sec_hist, act_labs, act_confs, dobj, face_names)
###print(sec_lv)
securityalert = self.alert(sec_lv, sec_flv, security_threshold)
###print("\n######################## Display")
# Main drawing procedure
if DRAWMASK:
# Draw openpose mask & face region
self.display_all(impose, imface, sec_lv, humans, human_ids, act_labs, act_confs, act_locs, dobj, face_locs, face_names, security_threshold, mode, freg)
else:
self.display_all(image, imface, sec_lv, humans, human_ids, act_labs, act_confs, act_locs, dobj, face_locs, face_names, security_threshold, mode, freg)
########## NEED CHANGES #######################
if(securityalert):
s='Image'
f.write(struct.pack('I', len(s)) + s.encode('ascii')) # Write str length and str
f.seek(0)
print ('Sending to C#:', s)
else:
s='Alert'
f.write(struct.pack('I', len(s)) + s.encode('ascii')) # Write str length and str
f.seek(0)
print ('Sending to C#:', s)
# s='Image'
# f.write(struct.pack('I', len(s)) + s.encode('ascii')) # Write str length and str
# f.seek(0)
# print ('Sending to C#:', s)
# Frame management stuffs, counted before frame limited
frame_time = time.time() - ptime
# FPS limiter
if FPSLIM > 0:
time.sleep(max(1./FPSLIM - (frame_time), 0))
# FPS display & log, counted after frame limited
self.fps = 1.0 / (time.time() - ptime)
hisfps.append(self.fps)
ptime = time.time()
if cv2.waitKey(1) == 27:
break
except FileNotFoundError :
raise
cv2.destroyAllWindows()
# Output FPS history
fh = open("fps.txt", "w")
for fps in hisfps:
fh.write("%.3f \n" % fps)
fh.close()
def alert(self, sec_lv, sec_flv, security_threshold):
# Alert & indicator about level below threshold
if self.altrig == 0 and sec_lv < security_threshold:
winsound.PlaySound(None, winsound.SND_ASYNC)
winsound.PlaySound(ALSND, winsound.SND_ASYNC | winsound.SND_ALIAS)
self.altrig = 1
self.alprev = time.time()
return False
if self.altrig == 1:
if time.time() > self.alprev + ALDUR:
self.altrig = 0
winsound.PlaySound(None, winsound.SND_ASYNC)
if self.altrig == -1:
if time.time() > self.alprev + ALAUTH:
self.altrig = 0
# Check authorization, nullify any security result if there's known face
if sec_flv > 0:
winsound.PlaySound(None, winsound.SND_ASYNC)
self.altrig = -1
self.alprev = time.time()
return True
def sec_calc(self, history, act_labs, act_confs, dobj, face_names):
# Pass components used for security level calculations
# TODO: implement threshold, constants, etc as variables
sec = security.Frame(act_labs, act_confs, dobj, face_names)
sec.calc()
# Add to historical record
# Base calculations from N latest data
history.append(sec)
if (len(history) > N_HIST):
# Remove the last, only the view changed, no copy created
history.pop(0)
all_hist = len(history)
# Calculation
lvs = []
for s in history:
lvs.append(s.level)
print("%.3f " % s.level, end="")
print("| | ", end ="")
lvs = np.array(lvs)
if all_hist >= N_HIST:
if POSTPROC == 0: # Count if
sec_lv = len(lvs[lvs >= FRPARAM])/N_HIST
elif POSTPROC == 1: # Average
sec_lv = sum(lvs)/N_HIST
elif POSTPROC == 2: # Percentile
sec_lv = np.percentile(lvs, FRPARAM*100)
else:
sec_lv = 1.0
# print("%d/%d %.2f | " % (all_neg, all_hist, sec_lv), end="")
print("%.2f | " % (sec_lv), end="")
# Print latest labels & confidence
for act, conf in zip(act_labs, act_confs):
print("%s[%.2f]," % (act, conf), end="")
print()
# Authorization, just need one positive to trigger
sec_flv = 0
for face in face_names:
if face != "Unknown":
sec_flv += 1
# Percentage
return sec_lv, sec_flv
def display_all(self, image, imface, sec_lv, humans, human_ids, act_labs, act_confs, act_locs, objs, face_locs, face_names, security_threshold, mode, freg=[]):
# try:
# from skimage import io, draw
# import numpy as np
# print("*** "+str(len(detections))+" Results, color coded by confidence ***")
if(mode):
vt = 10 # Vertical positioning
# Face camera display
image[freg[0]:freg[1], freg[2]:freg[3]] = imface # Insert to the center
# Face region display
if freg != []:
cv2.rectangle(image, (freg[2], freg[0]), (freg[3], freg[1]), color=(64,64,64), thickness=1)
# Openpose display
image = TfPoseEstimator.draw_humans(image, humans, imgcopy=False)
# Security level display
color = (0, int(255 * sec_lv), int(255 * (1 - sec_lv)))
cv2.rectangle(image, (10, vt), (self.im_w-10,vt+10), (255, 255, 255), thickness=1)
cv2.rectangle(image, (10, vt), (int(round((self.im_w-20)*sec_lv)+10), vt+10), color, cv2.FILLED)
cv2.rectangle(image, (int(round((self.im_w-20)*security_threshold)+10-1), vt-5), (int(round((self.im_w-20)*security_threshold)+10)+1,vt+10+5), (0, 0, 255), cv2.FILLED)
vt += 30
# Visual triggered indicator
if self.altrig == 1:
cv2.rectangle(image, (0, 0), (self.im_w, self. im_h), (0, 0, 255), thickness=8)
# Visual authorized indicator
if self.altrig == -1:
cv2.rectangle(image, (0, 0), (self.im_w, self. im_h), (0, 255, 0), thickness=8)
cv2.putText(image,
"SECURITY: %.0f%%" % (sec_lv*100),
(10, vt), cv2.FONT_HERSHEY_SIMPLEX, 0.5,
(0, 255, 0), 2)
vt += 20
cv2.putText(image,
"FPS: %.2f" % self.fps,
(10, vt), cv2.FONT_HERSHEY_SIMPLEX, 0.5,
(0, 255, 0), 2)
vt += 20
# LSTM display
for (act_lab, act_conf, act_loc, id_val) in zip(act_labs, act_confs, act_locs, human_ids.values()):
###print(act_lab, act_conf, act_loc, id_val)
cv2.putText(image,
" %d: %s %.2f" % (id_val, act_lab, act_conf),
(int(round(act_loc[0])), int(round(act_loc[1]))), cv2.FONT_HERSHEY_SIMPLEX, 0.5,
(0, 255, 0), 2)
# vt += 20
# Darknet display
for obj in objs:
###print(obj)
label = obj[0]
dconf = obj[1]
bounds = obj[2]
image, color = openpose_human.draw_box(image, 1, bounds, label, dconf)
# Facerec display
for (top, right, bottom, left), face in zip(face_locs, face_names):
###print(face)
label = face
# bounds = [4*left, 4*top, 4*(right-left), 4*(bottom-top)]
bounds = [freg[2]+FPSCALE*left, freg[0]+FPSCALE*top, FPSCALE*(right-left), FPSCALE*(bottom-top)]
image, color = openpose_human.draw_box(image, 0, bounds, label, loc=1)
cv2.imwrite('./IPC CS/bin/Release/display_sharp.jpg', image)
class openpose_human:
# def __init__(self, camera=0,resize='0x0',resize_out_ratio=4.0,model='mobilenet_thin',show_process=False):
def __init__(self, image, resize='1024x576',model='mobilenet_v2_small'):
self.logger = logging.getLogger('TfPoseEstimator-WebCam')
self.logger.setLevel(logging.DEBUG)
self.ch = logging.StreamHandler()
self.ch.setLevel(logging.DEBUG)
self.formatter = logging.Formatter('[%(asctime)s] [%(name)s] [%(levelname)s] %(message)s')
self.ch.setFormatter(self.formatter)
self.logger.addHandler(self.ch)
##self.logger.debug('initialization %s : %s' % (model, get_graph_path(model)))
self.w, self.h = model_wh(resize)
if self.w > 0 and self.h > 0:
self.e = TfPoseEstimator(get_graph_path(model), target_size=(self.w, self.h))
else:
self.e = TfPoseEstimator(get_graph_path(model), target_size=(432, 368))
##self.logger.debug('cam read+')
# cam = cv2.VideoCapture(camera)
# ret_val, image = cam.read()
self.im_h, self.im_w = image.shape[:2]
# logger.info('cam image=%dx%d' % (image.shape[1], image.shape[0]))
self.videostep = 0
self.human_keypoint = {0: [np.zeros(36)]}
self.human_ids = {0: 0}
def runopenpose(self, image, resize_out_ratio=4.0):
# ret_val, image = cam.read()
##self.logger.debug('image process+')
humans = self.e.inference(image, resize_to_default=(self.w > 0 and self.h > 0), upsample_size=resize_out_ratio)
skeletoncount = 0
skels = np.array([np.zeros(36)])
for human in humans:
if skeletoncount == 0: # Initialize by adding N_STEPS of empty skeletons
skels = np.array([openpose_human.write_coco_json(human, self.im_w,self.im_h)])
else: # Append the rest
skels = np.vstack([skels, np.array(openpose_human.write_coco_json(human, self.im_w,self.im_h))])
skeletoncount = skeletoncount + 1
# if skeletoncount == 1: # Just assume it's the same prson if there's only one
# self.human_keypoint[0].append(skels)
if skeletoncount > 0:
self.human_keypoint, self.human_ids = openpose_human.push(self.human_keypoint, self.human_ids, skels)
else:
# No human actually detected (humans is empty, thus skcount = 0)
self.human_keypoint = {0: [np.zeros(36)]}
self.human_ids = {0: 0}
tf.reset_default_graph() # Reset the graph
# self.logger.debug('finished+')
return (self.human_keypoint, self.human_ids, humans)
# Basically, human_keypoint store a string of poses, length N_STEPS, and tracked.
# Humans is the result of a single inference, formatting still raw.
def draw_box(image, coord_type, bounds, text='', conf=1, loc=0, thickness=3):
# Based on the input detection coordinate
if coord_type == 0:
# Input (x, y) describes the top-left corner of detection