Repository navigation
Expand file tree
/
Copy pathGUI1.py
More file actions
1483 lines (1282 loc) · 57 KB
/
Copy pathGUI1.py
File metadata and controls
1483 lines (1282 loc) · 57 KB
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 csv
import threading
from threading import Thread
import numpy as np
import argparse
import cv2
import xlwt
import tkinter as tk
from tkinter import *
from tkinter import filedialog
from tkinter import ttk # Normal Tkinter.* widgets are not themed!
from ttkthemes import ThemedTk
from PIL import Image, ImageTk
from openpyxl import Workbook
import tkinter.font as font
import datetime
from tkinter.messagebox import showinfo
from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg
from matplotlib.figure import Figure
from openpyxl.styles import PatternFill
from Services.Historique_comptage import Historique_comptage
from Services.HistoriqueComtpageService import HistoriqueComtpageService
from Services.User import User
from Services.UserService import UserService
from Services.Video import Video
from Vue.MyDatePicker import MyDatePicker
from counting.Point import Point
from counting.centroidtracker import CentroidTracker
from counting.trackableobject import TrackableObject
def GUI1(window):
# Initialize the parameters
confThreshold = 0.6 # Confidence threshold
nmsThreshold = 0.4 # Non-maximum suppression threshold
inpWidth = 416 # Width of network's input image
inpHeight = 416 # Height of network's input image
# initialize the frame dimensions (we'll set them as soon as we read
# the first frame from the video)
W = None
H = None
# instantiate our centroid tracker, then initialize a list to store
# each of our dlib correlation trackers, followed by a dictionary to
# map each unique object ID to a TrackableObject
ct = CentroidTracker(maxDisappeared=40, maxDistance=50)
ct2 = CentroidTracker(maxDisappeared=40, maxDistance=50)
ct3 = CentroidTracker(maxDisappeared=40, maxDistance=50)
ct4 = CentroidTracker(maxDisappeared=40, maxDistance=50)
ct5 = CentroidTracker(maxDisappeared=40, maxDistance=50)
trackers = []
trackableObjects = {}
trackableObjects1 = {}
trackableObjects2 = {}
trackableObjects3 = {}
trackableObjects4 = {}
trackableObjects5 = {}
# initialize the total number of frames processed thus far, along
# with the total number of objects that have moved either up or down
totalDown = 0
totalUp = 0
totalDownCar = 0
totalUpCar = 0
totalDownBus = 0
totalUpBus = 0
totalDownTruck = 0
totalUpTruck = 0
totalDownMotor = 0
totalUpMotor = 0
showCar = True
showPerson = True
showTruck = True
showBus = True
showMotorBike = True
isEntree = False
isSortie = False
canDrawEnter = 0
canDrawOut = 0
# cap = cv2.VideoCapture("video.mp4")
# construct the argument parse and parse the arguments
ap = argparse.ArgumentParser()
ap.add_argument('-l', '--labels', type=str, default='model/coco.names', help='Path to label file')
# ap.add_argument('--video', help='Path to video file.', default='D:/Stage/67 HA/D2/DJI_0004.MP4')
args = ap.parse_args()
# initialize the list of class labels MobileNet SSD was trained to
# detect, then generate a set of bounding box colors for each class
CLASSES = ["background", "aeroplane", "bicycle", "bird", "boat",
"bottle", "bus", "car", "cat", "chair", "cow", "diningtable",
"dog", "horse", "motorbike", "person", "pottedplant", "sheep",
"sofa", "train", "tvmonitor"]
classesFile = open(args.labels).read().strip().split('\n')
# Give the configuration and weight files for the model and load the network using them.
modelConfiguration = "model/yolov3.cfg";
modelWeights = "model/yolov3.weights";
# load our serialized model from disk
net = cv2.dnn.readNetFromDarknet(modelConfiguration, modelWeights)
net.setPreferableBackend(cv2.dnn.DNN_BACKEND_OPENCV)
net.setPreferableTarget(cv2.dnn.DNN_TARGET_OPENCL)
COLORS = np.random.uniform(0, 255, size=(len(CLASSES), 3))
video = ""
cap = ""
fps = 0
frame_count = 0
duration = 0
userProfile = ""
videoList = []
canvasList = []
histoDataList = []
videoAttenteList = []
historiqueList=""
def getOutputsNames(net):
# Get the names of all the layers in the network
layersNames = net.getLayerNames()
# Get the names of the output layers, i.e. the layers with unconnected outputs
return [layersNames[i[0] - 1] for i in net.getUnconnectedOutLayers()]
def draw_bounding_boxes(image, boxes, confidences, classIDs, idxs, colors):
if len(idxs) > 0:
for i in idxs.flatten():
# extract bounding box coordinates
x, y = boxes[i][0], boxes[i][1]
w, h = boxes[i][2], boxes[i][3]
# draw the bounding box and label on the image
color = [int(c) for c in colors[classIDs[i]]]
cv2.rectangle(image, (x, y), (x + w, y + h), color, 2)
text = "{}: {:.4f}".format(classesFile[classIDs[i]], confidences[i])
cv2.putText(image, text, (x, y - 5), cv2.FONT_HERSHEY_SIMPLEX, 0.5, color, 2)
return image
# Draw the predicted bounding box
def drawPred(classId, conf, left, top, right, bottom, frame):
# Draw a bounding box.
global pointSortie1
global pointSortie2
if (classId == 0):
cv2.rectangle(frame, (left, top), (right, bottom), (0, 0, 255), 2)
if (classId == 2):
cv2.rectangle(frame, (left, top), (right, bottom), (255, 0, 0), 2)
if (classId == 6):
cv2.rectangle(frame, (left, top), (right, bottom), (0, 255, 0), 2)
if (classId == 5):
cv2.rectangle(frame, (left, top), (right, bottom), (0, 255, 255), 2)
if (classId == 3):
cv2.rectangle(frame, (left, top), (right, bottom), (0, 165, 255), 2)
# Draw a center of a bounding box
frameHeight = frame.shape[0]
frameWidth = frame.shape[1]
cv2.line(frame, (pointSortie1.x, pointSortie1.y), (pointSortie2.x, pointSortie2.y), (0, 47, 255), 2)
# cv2.line(frame, (0, frameHeight // 2 - 50), (frameWidth, frameHeight // 2 - 50), (0, 255, 255), 2)
cv2.circle(frame, (left + (right - left) // 2, top + (bottom - top) // 2), 3, (0, 0, 255), -1)
counter = []
coun = 0
if (top + (bottom - top) // 2 in range(frameHeight // 2 - 2, frameHeight // 2 + 2)):
coun += 1
# print(coun)
counter.append(coun)
# label = 'Pedestrians: '.format(str(counter))
text = "{}".format(classesFile[classId])
# cv2.putText(frame, text, (left, top - 5), cv2.FONT_HERSHEY_SIMPLEX, 0.7, (0, 0, 255), 1)
def getOnlyOnSegmentPoints(segment_first_extremity, segment_last_extremity, points, maximal_allowed_distance):
segment_first_point_x = segment_first_extremity.x
segment_first_point_y = segment_first_extremity.y
segment_last_point_x = segment_last_extremity.x
segment_last_point_y = segment_last_extremity.y
test_x = points.x
test_y = points.y
returned = True
k_numerator = (test_x - segment_first_point_x) * (segment_last_point_x - segment_first_point_x)
+ (test_y - segment_first_point_y) * (segment_last_point_y - segment_first_point_y)
k_denominator = (segment_last_point_x - segment_first_point_x) * (segment_last_point_x - segment_first_point_x)
+ (segment_last_point_y - segment_first_point_y) * (segment_last_point_y - segment_first_point_y);
k = k_numerator / k_denominator;
p = Point((k * (segment_last_point_x - segment_first_point_x) + (segment_first_point_x)),
(k * (segment_last_point_y - segment_first_point_y) + (segment_first_point_y)));
if (k < 0.0 and Point.distanceBetweenTwoPoint(points, segment_first_extremity) > maximal_allowed_distance):
return False
if (k >= 0.0 and k <= 1.0 and Point.distanceBetweenTwoPoint(points, p) > maximal_allowed_distance):
return False
if (k > 1.0 and Point.distanceBetweenTwoPoint(points, segment_last_extremity) > maximal_allowed_distance):
return False
return returned;
def postprocess2(frame, outs):
frameHeight = frame.shape[0]
frameWidth = frame.shape[1]
rects = []
# Scan through all the bounding boxes output from the network and keep only the
# ones with high confidence scores. Assign the box's class label as the class with the highest score.
classIds = []
confidences = []
boxes = []
for out in outs:
for detection in out:
scores = detection[5:]
classId = np.argmax(scores)
confidence = scores[classId]
if confidence > confThreshold:
center_x = int(detection[0] * frameWidth)
center_y = int(detection[1] * frameHeight)
width = int(detection[2] * frameWidth)
height = int(detection[3] * frameHeight)
left = int(center_x - width / 2)
top = int(center_y - height / 2)
classIds.append(classId)
confidences.append(float(confidence))
boxes.append([left, top, width, height])
# Perform non maximum suppression to eliminate redundant overlapping boxes with
# lower confidences.
indices = cv2.dnn.NMSBoxes(boxes, confidences, confThreshold, nmsThreshold)
for i in indices:
i = i[0]
box = boxes[i]
left = box[0]
top = box[1]
width = box[2]
height = box[3]
if classIds[i] == 2 and showCar:
rects.append((left, top, left + width, top + height))
objects2 = ct2.update(rects)
countingObject2(objects2, trackableObjects1, "car", frame)
drawPred(classIds[i], confidences[i], left, top, left + width, top + height, frame)
continue
if classIds[i] == 3 and showMotorBike:
rects.append((left, top, left + width, top + height))
objects3 = ct3.update(rects)
countingObject2(objects3, trackableObjects1, "motorbike", frame)
drawPred(classIds[i], confidences[i], left, top, left + width, top + height, frame)
continue
if classIds[i] == 5 and showBus:
rects.append((left, top, left + width, top + height))
# use the centroid tracker to associate the (1) old object
# centroids with (2) the newly computed object centroids
objects4 = ct4.update(rects)
countingObject2(objects4, trackableObjects1, "bus", frame)
drawPred(classIds[i], confidences[i], left, top, left + width, top + height, frame)
continue
if classIds[i] == 6 and showTruck:
rects.append((left, top, left + width, top + height))
# use the centroid tracker to associate the (1) old object
# centroids with (2) the newly computed object centroids
objects5 = ct5.update(rects)
countingObject2(objects5, trackableObjects1, "truck", frame)
drawPred(classIds[i], confidences[i], left, top, left + width, top + height, frame)
continue
def countingObject(objects, trackableObjectList, type, frame):
frameHeight = frame.shape[0]
frameWidth = frame.shape[1]
global totalDown
global totalUp
global totalUpCar
global totalUpBus
global totalUpMotor
global totalUpTruck
global totalDownCar
global totalDownBus
global totalDownTruck
global totalDownMotor
# loop over the tracked objects
for (objectID, centroid) in objects.items():
# check to see if a trackable object exists for the current
# object ID
to = trackableObjectList.get(objectID, None)
# if there is no existing trackable object, create one
if to is None:
to = TrackableObject(objectID, centroid)
# otherwise, there is a trackable object so we can utilize it
# to determine direction
else:
# the difference between the y-coordinate of the *current*
# centroid and the mean of *previous* centroids will tell
# us in which direction the object is moving (negative for
# 'up' and positive for 'down')
y = [c[1] for c in to.centroids]
direction = centroid[1] - np.mean(y)
to.centroids.append(centroid)
# check to see if the object has been counted or not
if not to.counted:
# if the direction is negative (indicating the object
# is moving up) AND the centroid is above the center
# line, count the object
if direction < 0 and centroid[1] in range(frameHeight // 2 - 30, frameHeight // 2 + 30):
if type is "person":
totalUp += 1
if type is "car":
totalUpCar += 1
if type is "bus":
totalUpBus += 1
if type is "motorbike":
totalDownMotor += 1
if type is "truck":
totalUpTruck += 1
to.counted = True
# if the direction is positive (indicating the object
# is moving down) AND the centroid is below the
# center line, count the object
elif direction > 0 and centroid[1] in range(frameHeight // 2 - 30, frameHeight // 2 + 30):
if type is "person":
totalDown += 1
if type is "car":
totalDownCar += 1
if type is "bus":
totalDownBus += 1
if type is "motorbike":
totalDownMotor += 1
if type is "truck":
totalDownTruck += 1
to.counted = True
# store the trackable object in our dictionary
trackableObjectList[objectID] = to
# draw both the ID of the object and the centroid of the
# object on the output frame
# text = "ID {}".format(objectID)
# cv.putText(frame, text, (centroid[0] - 10, centroid[1] - 10),
# cv.FONT_HERSHEY_SIMPLEX, 0.5, (0, 255, 0), 2)
cv2.circle(frame, (centroid[0], centroid[1]), 4, (0, 255, 0), -1)
# construct a tuple of information we will be displaying on the
# frame
# info = [
# ("Person :", str(totalUp) + "/" + str(totalDown)),
# ("Car :", str(totalUpCar) + "/" + str(totalDownCar)),
# ("Bus :", str(totalUpBus) + "/" + str(totalDownBus)),
# ("Motorbike :", str(totalUpMotor) + "/" + str(totalDownMotor)),
# ("Truck :", str(totalUpTruck) + "/" + str(totalDownTruck)),
# ]
# loop over the info tuples and draw them on our frame
# for (i, (k, v)) in enumerate(info):
# text = "{}: {}".format(k, v)
# cv2.putText(frame, text, (10, frameHeight - ((i * 60) + 60)),
# cv2.FONT_HERSHEY_SIMPLEX, 1, (0, 255, 255), 2)
def countingObject2(objects, trackableObjectList, type, frame):
frameHeight = frame.shape[0]
frameWidth = frame.shape[1]
global totalDown
global totalUp
global totalUpCar
global totalUpBus
global totalUpMotor
global totalUpTruck
global totalDownCar
global totalDownBus
global totalDownTruck
global totalDownMotor
# loop over the tracked objects
for (objectID, centroid) in objects.items():
# check to see if a trackable object exists for the current
# object ID
to = trackableObjectList.get(objectID, None)
# if there is no existing trackable object, create one
if to is None:
to = TrackableObject(objectID, centroid)
# otherwise, there is a trackable object so we can utilize it
# to determine direction
else:
# the difference between the y-coordinate of the *current*
# centroid and the mean of *previous* centroids will tell
# us in which direction the object is moving (negative for
# 'up' and positive for 'down')
y = [c[1] for c in to.centroids]
direction = centroid[1] - np.mean(y)
to.centroids.append(centroid)
# check to see if the object has been counted or not
if not to.counted:
# if the direction is negative (indicating the object
# is moving up) AND the centroid is above the center
# line, count the object
point = Point(centroid[0], centroid[1])
# if direction < 0 and centroid[1] in range(frameHeight // 2 - 30, frameHeight // 2 + 30):
if getOnlyOnSegmentPoints(pointEntree1, pointEntree2, point, 1.5):
print("Voici le type " + type + " Entrée")
print("x" + str(centroid[0]) + " y" + str(centroid[1]))
print("Entree1 x" + str(pointEntree1.x) + " y" + str(pointEntree1.y) + "|| x" + str(
pointEntree2.x) + " y" + str(pointEntree2.y))
# if type is "person":
# totalUp += 1
if type is "car":
totalUpCar += 1
if type is "bus":
totalUpBus += 1
if type is "motorbike":
totalDownMotor += 1
if type is "truck":
totalUpTruck += 1
to.counted = True
# if the direction is positive (indicating the object
# is moving down) AND the centroid is below the
# center line, count the object
# elif direction > 0 and centroid[1] in range(frameHeight // 2 - 30, frameHeight // 2 + 30)
elif getOnlyOnSegmentPoints(pointSortie1, pointSortie2, point, 1.5):
print("Voici le type " + type + " Sortie")
print("x" + str(centroid[0]) + " y" + str(centroid[1]))
print("Entree1 x" + str(pointSortie1.x) + " y" + str(pointSortie1.y) + "|| x" + str(
pointSortie2.x) + " y" + str(pointSortie2.y))
# if type is "person":
# totalDown += 1
# print("OjbectId"+str(objectID))
if type is "car":
totalDownCar += 1
print("OjbectId" + str(objectID))
if type is "bus":
totalDownBus += 1
if type is "motorbike":
totalDownMotor += 1
if type is "truck":
totalDownTruck += 1
to.counted = True
# else:
# print("OjbectId" + str(objectID) + " Centroid xy " + str(centroid[0]) + ":" + str(
# centroid[1]) + " IsCounted " + str(to.counted))
# store the trackable object in our dictionary
trackableObjectList[objectID] = to
# draw both the ID of the object and the centroid of the
# object on the output frame
# text = "ID {}".format(objectID)
# cv.putText(frame, text, (centroid[0] - 10, centroid[1] - 10),
# cv.FONT_HERSHEY_SIMPLEX, 0.5, (0, 255, 0), 2)
cv2.circle(frame, (centroid[0], centroid[1]), 4, (0, 255, 0), -1)
def search_video():
global video
global b1
global b2
global cap
global tkImage
global tree
global duration
video = filedialog.askopenfilename()
if (video):
b1.state(["active"])
b2["state"] = tk.NORMAL
b1.state(["active"])
cap = cv2.VideoCapture(video)
hasFrame, frame = cap.read()
frame = cv2.resize(frame, (800, 600))
cv2image = cv2.cvtColor(frame, cv2.COLOR_BGR2RGBA)
img = Image.fromarray(cv2image)
tkImage = ImageTk.PhotoImage(img)
canvas.create_image(0, 0, anchor=NW, image=tkImage)
fps = cap.get(cv2.CAP_PROP_FPS) # OpenCV2 version 2 used "CV_CAP_PROP_FPS"
frame_count = int(cap.get(cv2.CAP_PROP_FRAME_COUNT))
duration = frame_count / fps
tree.insert("", 'end', text="L1", values=(video, str(datetime.timedelta(seconds=duration)).split(".")[0]))
# cap = cv2.VideoCapture(video)
# show_frame()
def search_video2():
global videos
global b1
global b2
global cap
global tkImage
global tree
global duration
global videoList
global video
global indexVideo
indexVideo = 0
videos = filedialog.askopenfilenames()
if (videos):
b1.state(["active"])
b2["state"] = tk.NORMAL
b1.state(["active"])
for videoT in videos:
capT = cv2.VideoCapture(videoT)
# hasFrame, frame = capT.read()
# frame = cv2.resize(frame, (800, 600))
# cv2image = cv2.cvtColor(frame, cv2.COLOR_BGR2RGBA)
# img = Image.fromarray(cv2image)
# tkImage = ImageTk.PhotoImage(img)
# canvas.create_image(0, 0, anchor=NW, image=tkImage)
fps = capT.get(cv2.CAP_PROP_FPS) # OpenCV2 version 2 used "CV_CAP_PROP_FPS"
frame_count = int(capT.get(cv2.CAP_PROP_FRAME_COUNT))
durationT = frame_count / fps
videTmp = Video(videoT, "Non spécifié", str(datetime.timedelta(seconds=durationT)).split(".")[0],
"En attente")
videoList.append(videTmp)
tree.insert("", 'end', text="L1", values=(
videoT, "Non spécifié", str(datetime.timedelta(seconds=durationT)).split(".")[0], "En attente"))
# cap = cv2.VideoCapture(video)
video = videoList[0].chemin
capT = cv2.VideoCapture(videoList[0].chemin)
hasFrame, frame = capT.read()
frame = cv2.resize(frame, (800, 600))
cv2image = cv2.cvtColor(frame, cv2.COLOR_BGR2RGBA)
img = Image.fromarray(cv2image)
tkImage = ImageTk.PhotoImage(img)
canvas.create_image(0, 0, anchor=NW, image=tkImage)
fps = capT.get(cv2.CAP_PROP_FPS) # OpenCV2 version 2 used "CV_CAP_PROP_FPS"
frame_count = int(capT.get(cv2.CAP_PROP_FRAME_COUNT))
duration = frame_count / fps
def nextVideo():
global indexVideo
global cap
global tkImage
global tree
global duration
global videoList
global video
global indexVideo
global fps
global frame_count
global duration
if indexVideo + 1 < (len(videoList)):
indexVideo += 1
video = videoList[indexVideo].chemin
capT = cv2.VideoCapture(videoList[indexVideo].chemin)
hasFrame, frame = capT.read()
frame = cv2.resize(frame, (800, 600))
cv2image = cv2.cvtColor(frame, cv2.COLOR_BGR2RGBA)
img = Image.fromarray(cv2image)
tkImage = ImageTk.PhotoImage(img)
canvas.create_image(0, 0, anchor=NW, image=tkImage)
fps = capT.get(cv2.CAP_PROP_FPS) # OpenCV2 version 2 used "CV_CAP_PROP_FPS"
frame_count = int(capT.get(cv2.CAP_PROP_FRAME_COUNT))
durationT = frame_count / fps
# canvas.pack_forget()
def prevVideo():
global indexVideo
global tkImage
global tree
global duration
global videoList
global video
global indexVideo
if indexVideo - 1 >= 0:
indexVideo -= 1
video = videoList[indexVideo].chemin
capT = cv2.VideoCapture(videoList[indexVideo].chemin)
hasFrame, frame = capT.read()
frame = cv2.resize(frame, (800, 600))
cv2image = cv2.cvtColor(frame, cv2.COLOR_BGR2RGBA)
img = Image.fromarray(cv2image)
tkImage = ImageTk.PhotoImage(img)
canvas.create_image(0, 0, anchor=NW, image=tkImage)
fps = capT.get(cv2.CAP_PROP_FPS) # OpenCV2 version 2 used "CV_CAP_PROP_FPS"
frame_count = int(capT.get(cv2.CAP_PROP_FRAME_COUNT))
durationT = frame_count / fps
def insertData():
global historiqueList
histoService = HistoriqueComtpageService()
histo = Historique_comptage(0, "Chemin", "2000-12-02", "1:05:00", "FAKO", 2, 2, 2, 2, 8, 0)
histoService.insertIntoTable(histo)
# tree.insert("", 'end', text="L1",values=(, "Non spécifié", str(datetime.timedelta(seconds=duration)).split(".")[0], "En attente"))
refreshHisto()
def insertData2():
global historiqueList
histoService = HistoriqueComtpageService()
histo = Historique_comptage(0, "Chemin", "2000-12-02", "0:09:00", "TSY FAKO", 2, 4, 3, 2, 11, 0)
histoService.insertIntoTable(histo)
# tree.insert("", 'end', text="L1",values=(, "Non spécifié", str(datetime.timedelta(seconds=duration)).split(".")[0], "En attente"))
refreshHisto()
def insertHisto(comptage):
global historiqueList
histoService = HistoriqueComtpageService()
# histo=Historique_comptage(0,"Chemin","2000-12-02","0:07:00","67HA",7,8,5,9,6)
histoService.insertIntoTable(comptage)
# tree.insert("", 'end', text="L1",values=(, "Non spécifié", str(datetime.timedelta(seconds=duration)).split(".")[0], "En attente"))
refreshHisto()
def test_program_thread():
thread = threading.Thread(None, edit_item, None, (), {})
thread.start()
def edit_item():
global tree
focused = tree.focus()
x = input('Enter a Value you want to change')
tree.insert("", str(focused)[1:], values=("", str(x)))
tree.delete(focused)
def popup_bonus():
win = tk.Toplevel()
win.wm_title("Window")
win.geometry("400x50")
windowWidth = win.winfo_reqwidth()
windowHeight = win.winfo_reqheight()
# Gets both half the screen width/height and window width/height
positionRight = int(win.winfo_screenwidth() / 2 - windowWidth / 2)
positionDown = int(win.winfo_screenheight() / 2 - windowHeight / 2)
checkImg = PhotoImage(file="checked.png")
# Positions the window in the center of the page.
win.geometry("+{}+{}".format(positionRight, positionDown))
l2 = tk.Label(win, image=checkImg)
l2.place(x=10, y=10)
l = tk.Label(win, text="Comptage terminé, Veuillez retracer les lignes de comptage")
l.place(x=50, y=10)
def treeview_sort_column(tv, col, reverse):
l = [(tv.set(k, col), k) for k in tv.get_children('')]
l.sort(reverse=reverse)
# rearrange items in sorted positions
for index, (val, k) in enumerate(l):
tv.move(k, '', index)
# reverse sort next time
tv.heading(col, command=lambda: treeview_sort_column(tv, col, not reverse))
def select_files():
filetypes = (
('mp4', '*.mp4'),
('All files', '*.*')
)
filenames = filedialog.askopenfilenames(
title='Open files',
initialdir='/',
filetypes=filetypes)
showinfo(
title='Selected Files',
message=filenames[0]
)
def detect_objectsYolo():
global videoList
global indexVideo
global cap
global duration
global display1
while cap.isOpened():
global pointEntree1
global pointEntree2
global fps
hasFrame, frame = cap.read()
if hasFrame is False:
videoTmp = videoList[indexVideo]
# sheet["C2"] = totalUpCar + totalDownCar
# sheet["D2"] = totalUpBus + totalDownBus
# sheet["E2"] = totalUpTruck + totalDownTruck
comptageHisto = Historique_comptage(0, videoList[indexVideo].chemin, "2000-20-12",
videoList[indexVideo].duree, videoList[indexVideo].lieu,
totalUpCar + totalDownCar, totalUpBus + totalDownBus,
totalUpTruck + totalDownTruck, totalDownMotor + totalUpMotor,
totalDownCar + totalDownTruck + totalDownBus,
totalUpCar + totalUpTruck + totalUpBus)
insertHisto(comptageHisto)
break
frame = cv2.resize(frame, (800, 600), interpolation=cv2.INTER_AREA)
cv2.line(frame, (pointEntree1.x, pointEntree1.y), (pointEntree2.x, pointEntree2.y), (52, 235, 58), 2)
# Create a 4D blob from a frame.
blob = cv2.dnn.blobFromImage(frame, 1 / 255, (inpWidth, inpHeight), [0, 0, 0], 1, crop=False)
# Sets the input to the network
net.setInput(blob)
# Runs the forward pass to get output of the output layers
outs = net.forward(getOutputsNames(net))
# Remove the bounding boxes with low confidence
postprocess2(frame, outs)
t, _ = net.getPerfProfile()
# show the output image
cv2image = cv2.cvtColor(frame, cv2.COLOR_BGR2RGBA)
img = Image.fromarray(cv2image)
tkimage = ImageTk.PhotoImage(img)
display1.imgtk = tkimage # Shows frame for display 1
display1.configure(image=tkimage)
# boucle()
# threadDetection()
display1.update()
# display1.after(1, detect_objectsYolo)
canvas.pack()
threadNext()
threadP()
# detect_objectsYolo()
def initUser():
userService = UserService()
user = User(0, "root", "root", "thongsangchad@gmail.com")
userService.insertIntoTable(user)
# tree.insert("", 'end', text="L1",values=(, "Non spécifié", str(datetime.timedelta(seconds=duration)).split(".")[0], "En attente"))
refreshProfile()
def threadNext():
# Call work function
t1 = Thread(target=nextVideo())
t1.start()
def threadP():
# Call work function
t1 = Thread(target=popup_bonus())
t1.start()
def threadN():
# Call work function
t1 = Thread(target=threadExcel())
t1.start()
def threadExcel():
# Call work function
t1 = Thread(target=ExportExcel())
t1.start()
def threadSearch():
t2 = Thread(target=search_video())
t2.start()
def threadPlay():
t2 = Thread(target=Play())
t2.start()
def threadPause():
t2 = Thread(target=Pause())
t2.start()
def boucle():
te = Thread(target=detect_objectsYolo())
te.start()
def Pause():
display1.after_cancel(detect_objectsYolo)
def ExportExcel():
files = [('Excel Files', '*.xlsx')]
file = filedialog.asksaveasfile(filetypes=files, defaultextension=files)
workbook = Workbook()
sheet = workbook.active
totalEntree = 0
totalSortie = 0
sheet["A1"] = "LIEU"
sheet["B1"] = "VIDEO"
sheet["C1"] = "CAR"
sheet["D1"] = "BUS"
sheet["E1"] = "TRUCK"
sheet["F1"] = "DUREE CAPTURE"
sheet["G1"] = "ENTREE"
sheet["H1"] = "1H"
sheet["I1"] = "14H"
sheet["J1"] = "SORTIE"
sheet["K1"] = "1H"
sheet["L1"] = "14H"
sheet["M1"] = "TOTAL TRAFFIC"
sheet["A2"] = "LIEU"
sheet["B2"] = video
sheet["C2"] = totalUpCar + totalDownCar
sheet["D2"] = totalUpBus + totalDownBus
sheet["E2"] = totalUpTruck + totalDownTruck
sheet["F2"] = int(duration / 60)
sheet["G2"] = totalDownCar + totalDownTruck + totalDownBus
if totalDownCar != 0 or totalDownTruck != 0 or totalDownBus != 0:
totalEntree = int(((totalDownCar + totalDownTruck + totalDownBus) * 840) / int(duration / 60))
sheet["H2"] = int(((totalDownCar + totalDownTruck + totalDownBus) * 60) / int(duration / 60))
sheet["I2"] = totalEntree
else:
sheet["H2"] = 0
sheet["I2"] = 0
sheet["J2"] = totalUpCar + totalUpTruck + totalUpBus
if totalUpCar != 0 or totalUpTruck != 0 or totalUpBus != 0:
totalSortie = int(((totalUpCar + totalUpTruck + totalUpBus) * 840) / int(duration / 60))
sheet["K2"] = int(((totalUpCar + totalUpTruck + totalUpBus) * 60) / int(duration / 60))
sheet["L2"] = totalSortie
else:
sheet["K2"] = 0
sheet["L2"] = 0
##FFFF00 jaune
redFill = PatternFill(start_color='FFFF00',
end_color='FFFF00',
fill_type='solid')
sheet["M2"].fill = redFill
sheet["M2"] = totalSortie + totalEntree
workbook.save(filename=file.name)
def ExcelExport():
global historiqueList
global histoDataList
files = [('Excel Files', '*.xls')]
file = filedialog.asksaveasfile(filetypes=files, defaultextension=files)
workbook = xlwt.Workbook()
excelSheet = workbook.add_sheet("Resultat")
# print("taille",str(len(historiqueList.get_children())))
var = vars(histoDataList[0])
print("taille var", len(var))
indice = 0
tmp = 0
for index in range(len(var)):
print(index)
excelSheet.write(0, index, historiqueList.heading(index + 1)["text"])
for i, j in enumerate(historiqueList.get_children()):
values = historiqueList.item(j)["values"]
indice += 1
for k, m in enumerate(values):
excelSheet.write(indice, k, m)
workbook.save(file.name)
def CSVExport():
global historiqueList
global histoDataList
files = [('CSV Files', '*.csv')]
file = filedialog.asksaveasfile(filetypes=files, defaultextension=files)
with open(file.name, mode='w') as csv_file:
# writer = csv.DictWriter(csv_file, fieldnames=fieldnames)
csvwriter = csv.writer(csv_file, delimiter=',')
for row_id in historiqueList.get_children():
row = historiqueList.item(row_id)['values']
print('save row:', row)
csvwriter.writerow(row)
def createNewWindow():
newWindow = tk.Toplevel(window)
labelExample = tk.Label(newWindow, text="New Window")
buttonExample = Button(newWindow, text="Exporter Excel", command=threadExcel)
labelExample.pack()
buttonExample.pack()
# Set up GUI
window = ThemedTk(theme="adapta") # Makes main window
window.wm_title("Comptage de vehicule")
window.config(background="#FFFFFF")
window.resizable(True, True)
window.geometry("1366x800")
# imageFrame.pack(side=tk.LEFT,pady=5)
# window.config(menu=menubar)
notebook = ttk.Notebook(window)
notebook.pack(expand=True)
# create frames
menuFrame = ttk.Frame(notebook, width=1360, height=800)
historiqueFrame = ttk.Frame(notebook, width=1360, height=800)
profilFrame = ttk.Frame(notebook, width=1360, height=800)
menuFrame.pack(fill='both', expand=True)
historiqueFrame.pack(fill='both', expand=True)
profilFrame.pack(fill='both', expand=True)
# add frames to notebook
notebook.add(menuFrame, text='Comptage')
notebook.add(historiqueFrame, text='Historique')
notebook.add(profilFrame, text='Profil')
# Capture video frames
# cap = cv2.VideoCapture("video.mp4")
def print_selection():
global showCar
global showPerson
global showTruck
global showMotorBike
global showBus
global isEntree
global isSortie
global canDrawOut
global canDrawEnter
global c6
global c7
if (var1.get() == 1):
showPerson = True
elif (var1.get() == 0):
showPerson = False
if (var2.get() == 1):
showCar = True
elif (var2.get() == 0):
showCar = False
if (var3.get() == 1):
showTruck = True
elif (var3.get() == 0):
showTruck = False
if (var4.get() == 1):
showBus = True
elif (var4.get() == 0):
showBus = False
if (var5.get() == 1):
showMotorBike = True
elif (var5.get() == 0):
showMotorBike = False
if (var6.get() == 0):
isEntree = False
elif (var6.get() == 1):
isEntree = True
canDrawEnter = 1
isSortie = False
canDrawOut = 0
if (var7.get() == 0):
isSortie = False
elif (var7.get() == 1):
isSortie = True
canDrawOut = 1
isEntree = False
canDrawEnter = 0
# c6.deselect()
def RefreshLabel():
global label4
global label5
global label6
global label7
global label8
global label9
global label10
global label11
global label12
global label13
global label15
global label16
global fps
global duration
# valeurs
label4 = ttk.Label(canvas1, text=totalUp)
label5 = ttk.Label(canvas1, text=totalDown)
label6 = ttk.Label(canvas1, text=totalUpCar)
label7 = ttk.Label(canvas1, text=totalDownCar)
label8 = ttk.Label(canvas1, text=totalUpTruck)
label9 = ttk.Label(canvas1, text=totalDownTruck)
label10 = ttk.Label(canvas1, text=totalUpBus)
label11 = ttk.Label(canvas1, text=totalDownBus)
label12 = ttk.Label(canvas1, text=totalUpMotor)
label13 = ttk.Label(canvas1, text=totalDownMotor)
# label15 = Label(window, text="Durée : "+str(datetime.timedelta(seconds=duration)).split(".")[0], bg="white")
label1.place(x=10, y=10)
label2.place(x=100, y=10)