-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathmain.py
1693 lines (1428 loc) · 98.9 KB
/
main.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 sys
from pathlib import Path
#lock dashboard supaya tidak muncul banyak tab
lock_file = Path("app.lock")
if lock_file.exists():
print("Application already running.")
sys.exit()
# Buat file lock untuk memastikan hanya satu instance
lock_file.touch()
import cv2
import os
import sqlite3
import tkinter as tk
from tkinter import Tk, Label, Entry, Button, StringVar, Frame, messagebox, simpledialog
from PIL import Image, ImageTk
from collections import deque
from ultralytics import YOLO, solutions
from ultralytics.solutions import speed_estimation
from time import time
import numpy as np
from collections import defaultdict
#from ocr_library import process_image # ngga jadi dipake, proses dipindah ke webased javascrpt
from datetime import datetime
import math
import threading
import queue
#variable global untuk config
glob_integral = 0.00
glob_span_time = 0.00
glob_width_in_pixel = 900
glob_width_in_meter = 7 #meter
glob_actual_time = 5.00
glob_yolo_time = 15.00
glob_calibration_factor = 2.0
glob_model = "yolov8x.pt"
#glob_slash = "/" #linux
glob_slash = "\\" #windows
glob_slash_html = "/"
def get_current_time():
now = datetime.now()
return now.strftime("%d-%m-%Y %H-%M-%S")
def recursive_output(current_string, repeat_count):
# Base case: Jika repeat_count sudah 0, kembalikan current_string
if repeat_count <= 0:
return current_string
else:
# Rekursi: Tambahkan string baru ke current_string dan ulangi
new_string = current_string + " " + get_current_time()
return recursive_output(new_string, repeat_count - 1)
def detect_seatbelt(output_queue, frame, track_id, model_path="seat_belt_5.pt", retries=5):
# Inisialisasi model YOLOv8
model = YOLO(model_path)
# Loop untuk mencoba deteksi dengan batasan retry
for attempt in range(retries):
# Melakukan deteksi menggunakan YOLOv8
results = model.predict(source=frame)
class_ids = results[0].boxes.cls.numpy().tolist()
output_folder = 'database'+ glob_slash + 'static'+ glob_slash + 'Seatbelt'
os.makedirs(output_folder, exist_ok=True)
print(model.model.names)
# Jika ada objek yang terdeteksi, lanjutkan dengan cropping
if len(results[0].boxes) > 0:
cropped_image_paths = []
for i, result in enumerate(results[0].boxes):
# Dapatkan koordinat bounding box
x1, y1, x2, y2 = map(int, result.xyxy[0])
# Crop gambar berdasarkan bounding box
save_frame = frame
cropped_image = frame[y1:y2, x1:x2]
print(model.model.names[int(class_ids[i])])
if model.model.names[int(class_ids[i])] == 'NoSeatBelt':
text = "no-seatbelt"
#print(text)
output_queue.put((cropped_image, track_id, text))
return
output_queue.put((None, track_id, "")) # Indikasi bahwa tidak ada helm terdeteksi
else:
print(f"No objects detected on attempt {attempt + 1}. Retrying...")
# Jika tidak ada objek yang terdeteksi setelah retries selesai
print("No objects detected after maximum retries.")
output_queue.put((None, track_id, ""))
def detect_helmet(output_queue, frame, track_id, model_path="helmet_9.pt", retries=5):
# Inisialisasi model YOLOv8
model = YOLO(model_path)
# Loop untuk mencoba deteksi dengan batasan retry
for attempt in range(retries):
# Melakukan deteksi menggunakan YOLOv8
results = model.predict(source=frame)
class_ids = results[0].boxes.cls.numpy().tolist()
print(model.model.names)
output_folder = 'database'+ glob_slash + 'static'+ glob_slash + 'Helmet'
os.makedirs(output_folder, exist_ok=True)
# Jika ada objek yang terdeteksi, lanjutkan dengan cropping
if len(results[0].boxes) > 0:
cropped_image_paths = []
for i, result in enumerate(results[0].boxes):
# Dapatkan koordinat bounding box
x1, y1, x2, y2 = map(int, result.xyxy[0])
# Crop gambar berdasarkan bounding box
save_frame = frame
cropped_image = frame[y1:y2, x1:x2]
if model.model.names[int(class_ids[i])] == 'no-helm':
text = "no-helm"
output_queue.put((cropped_image, track_id, text))
return
output_queue.put((None, track_id, "")) # Indikasi bahwa tidak ada helm terdeteksi
else:
print(f"No objects detected on attempt {attempt + 1}. Retrying...")
# Jika tidak ada objek yang terdeteksi setelah retries selesai
print("No objects detected after maximum retries.")
output_queue.put((None, track_id, ""))
def detect_plat_and_crop_with_retries(output_queue, string_dir, frame_, track_id, model_path="plat_license.pt", retries=4):
# Inisialisasi model YOLOv8
model_ = YOLO(model_path)
print(model_.model.names)
# Loop untuk mencoba deteksi dengan batasan retry
for attempt in range(retries):
# Melakukan deteksi menggunakan YOLOv8
#frame_ = cv2.resize(frame_, (416, 620), interpolation=cv2.INTER_AREA)
results = model_.predict(source=frame_)
class_ids = results[0].boxes.cls.numpy().tolist()
output_folder = 'database'+ glob_slash + 'static'+ glob_slash + "plat_number_" + str(string_dir)
os.makedirs(output_folder, exist_ok=True)
print(class_ids)
# Jika ada objek yang terdeteksi, lanjutkan dengan cropping
if len(results[0].boxes) > 0:
cropped_image_paths = []
for i, result in enumerate(results[0].boxes):
# Dapatkan koordinat bounding box
class_ids = results[0].boxes.cls.numpy().tolist()
# Crop gambar berdasarkan bounding box
save_frame = results[0].plot()
#text_result = process_image(save_frame)
if model_.model.names[int(class_ids[i])] == '.':
print("detected")
initial_time_final_string = get_current_time()
final_string = recursive_output(initial_time_final_string, 0) # contoh rekursi 0 kali
name_file = final_string + "_" + str(track_id) + ".jpg"
output_path = os.path.join(output_folder, name_file)
x1, y1, x2, y2 = map(int, result.xyxy[0])
cropped_image = frame_[y1:y2, x1:x2]
cv2.imwrite(output_path, cropped_image)
#cv2.imwrite("test"+output_path, cropped_image)
output_queue.put((final_string, track_id))
return
# Simpan gambar yang sudah di-crop
#print(model.model.names)
output_queue.put(("", track_id))
else:
print(f"No objects detected on attempt {attempt + 1}. Retrying...")
# Jika tidak ada objek yang terdeteksi setelah retries selesai
print("No objects detected after maximum retries.")
return "", track_id
class VideoApp:
def __init__(self, root):
self.root = root
self.root.title("Interactive AI YOLO Dashboard")
self.cropped_images = []
self.ip_input = StringVar()
self.status = StringVar()
self.location = ""
self.model = ""
self.use_camera = False
self.use_yolo = False
self.use_distance_detector = False
self.speed_obj = None
self.detected_values = {1, 2, 3, 5, 7} # 1: 'bicycle', 2: 'car', 3: 'motorcycle', 5: 'bus', 7: 'truck'
self.detected_values_non_motorcycle = {2, 5, 7} # 1: 'bicycle', 2: 'car', 3: 'motorcycle', 5: 'bus', 7: 'truck'
self.max_speed = 80 # Initialize max_speed variable default
self.width_in_pixel = 900
self.width_in_meter = 7 #meter
self.actual_time = 5.00
self.yolo_time = 15.00
self.constant = 0.0
self.max_track_id = 0
self.save_left_specific_val_id = []
self.save_right_specific_val_id = []
self.last_track_id = []
self.save_id = []
self.array_time = []
self.get_point_A_B = []
self.point_get_category = []
self.moving_right_dir_id = []
self.moving_left_dir_id = []
self.get_violence_helm_id = []
self.get_violence_seatbelt_id = []
self.get_first_point_for_speed = []
self.get_violence_overspeed_id = []
self.get_violence_overtaking_id = []
self.get_violence_wrong_dir_id = []
self.get_violence_helm_date = []
self.get_violence_seatbelt_date = []
self.get_violence_overtaking_date = []
self.get_violence_wrong_dir_date = []
self.get_violence_helm_flag = []
self.get_violence_seatbelt_flag = []
# Array untuk menyimpan track_id, direct_x, direct_y, dan speeds
self.track_id_array = []
self.class_ids = []
self.direct_array = []
self.sum_array = []
self.last_speed = []
Label(root, textvariable=self.status).pack(side="top", fill="x", pady=5)
self.canvas = tk.Canvas(root, width=1600, height=900)
self.canvas.pack()
self.coordinates_label = tk.Label(root, text="Mouse Coordinates:")
self.coordinates_label.pack()
self.areas = []
self.lines = []
self.current_line = None
self.ip_path = ""
#config init
self.conn = sqlite3.connect('database'+ glob_slash + 'configuration.db')
self.conn_data = sqlite3.connect('database'+ glob_slash + 'datalog.db')
self.save_ip = sqlite3.connect('save_ip.db')
self.create_table()
self.init_config()
self.load_data() #load data
self.ip_path = str(self.load_ip_from_db())
#print("self.ip_path", self.ip_path)
# Frame for input and buttons
control_frame = tk.Frame(root)
control_frame.pack(side="top", fill="x", pady=5)
# Status Label
# Input IP and video path
Label(control_frame, text="Enter IP :").grid(row=0, column=0, padx=5)
self.ip_input.set(str(self.ip_path))
Entry(control_frame, textvariable=self.ip_input, width=40).grid(row=0, column=1, padx=5)
# Connect Button
Button(control_frame, text="Connect to Camera", command=self.connect_camera, width=15).grid(row=0, column=2, padx=5)
# Toggle YOLO Button
Button(control_frame, text="Toggle AI (YOLO)", command=self.toggle_yolo, width=15).grid(row=0, column=3, pady=5)
# Save Distance Detector
Button(control_frame, text="Distance Detector", command=self.toggle_detect_distance, width=15).grid(row=0, column=4, pady=5)
#Button(control_frame, text="Save Photo", command=self.capture_photo, width=15).grid(row=0, column=4, pady=5)
Button(control_frame, text="Add Area", command=self.add_area, width=15).grid(row=0, column=5, padx=5)
Button(control_frame, text="Draw Line", command=self.draw_line, width=15).grid(row=0, column=6, padx=5)
Button(control_frame, text="Undo Last Area", command=self.undo_last_area, width=15).grid(row=0, column=7, padx=5)
Button(control_frame, text="Undo Last Line", command=self.undo_last_line, width=15).grid(row=0, column=8, padx=5)
#configuration button
Button(control_frame, text="Configuration", command=self.open_config, width=15).grid(row=0, column=9, pady=5)
# Exit Button
Button(control_frame, text="Exit", command=root.quit, width=15).grid(row=0, column=10, pady=5)
# Bind event klik mouse ke fungsi mark_coordinate
self.canvas.bind("<Button-1>", self.mark_coordinate)
# Bind event gerakan mouse untuk melacak koordinat
self.canvas.bind("<Motion>", self.track_mouse)
# Video Stream Label
self.video_label = Label(root)
self.video_label.pack(expand=True)
self.reference_image = None
self.reference_imgtk = None
# Other variables and objects
self.camera = None
self.model_yolo = YOLO(str(self.model))
self.frame_buffer = deque(maxlen=100) # Main buffer
self.alt_buffer = deque(maxlen=100) # Alternative buffer
self.last_frame = None
self.track_points = {} # Dictionary to store points based on track_id
self.track_history = defaultdict(lambda: [])
def create_table(self):
with self.conn:
self.conn.execute('''CREATE TABLE IF NOT EXISTS areas (
id INTEGER PRIMARY KEY AUTOINCREMENT,
name TEXT NOT NULL,
coordinates TEXT NOT NULL
)''')
self.conn.execute('''CREATE TABLE IF NOT EXISTS lines (
id INTEGER PRIMARY KEY ,
name TEXT NOT NULL,
x1 INTEGER,
y1 INTEGER,
x2 INTEGER,
y2 INTEGER
)''')
self.conn.execute('''CREATE TABLE IF NOT EXISTS config (
id INTEGER PRIMARY KEY,
calibration_factor REAL,
max_speed REAL,
width_in_pixel REAL,
width_in_meter REAL,
actual_time REAL,
yolo_time REAL,
location type TEXT NOT NULL,
Model type TEXT NOT NULL
)''')
with self.conn_data:
self.conn_data.execute('''CREATE TABLE IF NOT EXISTS datalog (
id INTEGER PRIMARY KEY,
track_id TEXT NOT NULL,
date TEXT NOT NULL,
plat_license TEXT NOT NULL,
speed TEXT NOT NULL,
max_speed TEXT NOT NULL,
violence_category TEXT NOT NULL,
vehicle TEXT NOT NULL,
location TEXT NOT NULL,
open_photo TEXT NOT NULL
)''')
with self.save_ip:
self.save_ip.execute('''CREATE TABLE IF NOT EXISTS save_ip (
IP TEXT NOT NULL
)''')
def mark_coordinate(self, event):
# Dapatkan koordinat klik
x, y = event.x, event.y
# Tandai titik pada kanvas
self.canvas.create_oval(x-3, y-3, x+3, y+3, fill="blue")
# Tambahkan teks koordinat di titik tersebut
self.canvas.create_text(x + 10, y, text=f"({x}, {y})", anchor=tk.W, fill="blue")
# Tampilkan koordinat di label
self.coordinates_label.config(text=f"Mouse Clicked at: ({x}, {y})")
def add_area(self):
coords_str = simpledialog.askstring("Input", "Enter coordinates (x1,y1,x2,y2,x3,y3,...):")
area_name = simpledialog.askstring("Input", "Enter area name:")
coords_list = list(map(int, coords_str.split(',')))
#print(len(coords_list))
if int(len(coords_list)) % 2 == 0 and int(len(coords_list)) > 2:
if coords_str and area_name:
coords = list(map(int, coords_str.split(',')))
area = self.canvas.create_polygon(coords, outline="red", fill="")
self.areas.append((area, area_name, coords_str))
self.save_area_to_db(area_name, coords_str)
def save_area_to_db(self, name, coordinates):
with self.conn:
self.conn.execute("INSERT INTO areas (name, coordinates) VALUES (?, ?)", (name, coordinates))
def calculate_distance(self, x1, y1, x2, y2):
return math.sqrt((x2 - x1) ** 2 + (y2 - y1) ** 2)
def draw_line(self):
self.start_x = None
self.start_y = None
self.canvas.bind("<ButtonPress-1>", self.on_button_press)
self.canvas.bind("<B1-Motion>", self.on_mouse_drag)
self.canvas.bind("<ButtonRelease-1>", self.on_button_release)
def on_button_press(self, event):
self.start_x = event.x
self.start_y = event.y
def on_mouse_drag(self, event):
if self.start_x and self.start_y:
self.canvas.delete("current_line")
self.current_line = self.canvas.create_line(self.start_x, self.start_y, event.x, event.y, fill="green", width=2, tags="current_line")
def on_button_release(self, event):
if self.start_x and self.start_y:
line_name = simpledialog.askstring("Input", "Enter line name:")
if line_name:
line_id = self.canvas.create_line(self.start_x, self.start_y, event.x, event.y, fill="green", width=2)
distance = round(self.calculate_distance(self.start_x, self.start_y, event.x, event.y), 1)
line_draw = str(distance)
self.canvas.create_text((self.start_x + event.x) / 2, (self.start_y + event.y) / 2, text=line_draw, anchor=tk.CENTER, fill="black")
self.lines.append((line_id, line_name, self.start_x, self.start_y, event.x, event.y))
self.save_line_to_db(line_name, self.start_x, self.start_y, event.x, event.y)
# Check for collisions with other lines
for line in self.lines:
if line[0] != line_id: # Pastikan kita tidak mengecek garis yang sama
f_collision_x, f_collision_y = self.check_line_collision((self.start_x, self.start_y, event.x, event.y), (line[2], line[3], line[4], line[5]))
if f_collision_x is not None and f_collision_y is not None:
collision_x = round(f_collision_x, 1)
collision_y = round(f_collision_y, 1)
self.canvas.create_text(collision_x, collision_y, text=f"x={collision_x}, y={collision_y}", fill="black")
self.canvas.delete("current_line")
self.start_x = None
self.start_y = None
def check_line_collision(self, line1, line2):
x1, y1, x2, y2 = line1
x3, y3, x4, y4 = line2
def det(a, b, c, d):
return a * d - b * c
denominator = det(x1 - x2, y1 - y2, x3 - x4, y3 - y4)
if denominator == 0:
return None, None
t = det(x1 - x3, y1 - y3, x3 - x4, y3 - y4) / denominator
u = det(x1 - x3, y1 - y3, x1 - x2, y1 - y2) / denominator
if 0 <= t <= 1 and 0 <= u <= 1:
intersection_x = x1 + t * (x2 - x1)
intersection_y = y1 + t * (y2 - y1)
return intersection_x, intersection_y
return None, None
def save_line_to_db(self, name, x1, y1, x2, y2):
with self.conn:
self.conn.execute("INSERT INTO lines (name, x1, y1, x2, y2) VALUES (?, ?, ?, ?, ?)", (name, x1, y1, x2, y2))
def save_datalog(self, track_id, date, plat_license, speed, max_speed, violence_category, vehicle, location, open_photo):
with self.conn_data:
self.conn_data.execute("INSERT INTO datalog (track_id, date, plat_license, speed, max_speed, violence_category, vehicle, location, open_photo) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)", (track_id, date, plat_license, speed, max_speed, violence_category, vehicle, location, open_photo))
def save_string_ip(self, str_in):
with self.save_ip:
cursor = self.save_ip.cursor()
# Cek apakah tabel sudah memiliki data
cursor.execute("SELECT COUNT(*) FROM save_ip")
row_count = cursor.fetchone()[0]
if row_count == 0:
# Jika tabel kosong, lakukan INSERT
cursor.execute("INSERT INTO save_ip (IP) VALUES (?)", (str(str_in),))
else:
# Jika tabel sudah ada data, lakukan UPDATE di baris pertama
cursor.execute("UPDATE save_ip SET IP = ? WHERE ROWID = (SELECT ROWID FROM save_ip LIMIT 1)", (str(str_in),))
self.save_ip.commit() # Commit perubahan
def load_ip_from_db(self):
# Menggunakan with untuk memastikan cursor ditutup dengan benar
with self.save_ip: # 'self.save_ip' adalah koneksi yang sudah ada
cursor = self.save_ip.cursor()
cursor.execute("SELECT IP FROM save_ip")
ip_addresses = cursor.fetchall() # Mengambil semua hasil
for row in ip_addresses:
if row[0] is not None:
#print("test", row[0]) # Mengakses elemen pertama dari setiap tuple (yaitu string '5.mp4')
return row[0]
def delete_datalog_from_db(self, track_id):
with self.conn:
self.conn.execute("DELETE FROM areas WHERE track_id = ?", (track_id,))
def undo_last_area(self):
if self.areas:
last_area, last_name, last_coords_str = self.areas.pop()
self.canvas.delete(last_area)
self.delete_area_from_db(last_name)
if not self.lines and not self.areas: # Jika tidak ada garis tersisa, hapus semua
self.canvas.delete("all")
def undo_last_line(self):
if self.lines:
last_line = self.lines.pop()
self.canvas.delete(last_line[0])
self.delete_line_from_db(last_line[1])
if not self.lines and not self.areas: # Jika tidak ada garis tersisa, hapus semua
self.canvas.delete("all")
def delete_area_from_db(self, name):
with self.conn:
self.conn.execute("DELETE FROM areas WHERE name = ?", (name,))
def delete_line_from_db(self, name):
with self.conn:
self.conn.execute("DELETE FROM lines WHERE name = ?", (name,))
def check_value_in_column(self, column_name, value_to_check):
with self.conn_data:
# Membuat cursor untuk mengeksekusi query SQL
cursor = self.conn_data.cursor()
# Query untuk mengecek nilai berdasarkan nama kolom yang diberikan
query = f"SELECT * FROM datalog WHERE {column_name} = ?"
# Mengeksekusi query dengan nilai yang ingin dicari
cursor.execute(query, (value_to_check,))
# Mengambil semua hasil query
result = cursor.fetchall()
# Mengecek apakah hasil ditemukan
if result:
print(f"Data dengan {column_name} = '{value_to_check}' ditemukan:")
return True
else:
print(f"Data dengan {column_name} = '{value_to_check}' tidak ditemukan")
return False
def find_max_track_id(self):
# Cek apakah koneksi sudah ditutup, jika iya, buka kembali
with self.conn_data:
# Membuat cursor untuk mengeksekusi query SQL
cursor = self.conn_data.cursor()
# Query untuk mencari nilai maksimal di kolom track_id
# CAST digunakan untuk mengonversi string menjadi FLOAT agar bisa dibandingkan
query = "SELECT MAX(CAST(track_id AS FLOAT)) FROM datalog"
# Mengeksekusi query
cursor.execute(query)
# Mengambil hasil query (nilai maksimal)
max_value = cursor.fetchone()[0]
if max_value is not None:
print(f"Nilai maksimal dalam track_id: {max_value}")
return max_value
else:
print("Tidak ada data dalam track_id")
return 0
def get_row_by_column_value(self, column_name, value_to_check):
with self.conn_data:
# Membuat cursor untuk mengeksekusi query SQL
cursor = self.conn_data.cursor()
# Query untuk mendapatkan baris berdasarkan nama kolom dan nilai
query = f"SELECT * FROM datalog WHERE {column_name} = ?"
# Mengeksekusi query dengan nilai yang ingin dicari
cursor.execute(query, (value_to_check,))
# Mengambil semua baris yang cocok dengan kondisi
rows = cursor.fetchall()
if rows:
print(f"Data ditemukan berdasarkan {column_name} = '{value_to_check}':")
return rows
else:
print(f"Tidak ada data yang cocok dengan {column_name} = '{value_to_check}'")
return []
def set_value_once(self, array, new_item): #self.array_time
id_found = False
# Loop through the array to check if the id already exists
for i, item in enumerate(array):
if item[0] == new_item[0]:
id_found = True
break
# If the id was not found, append the new item to the array
if not id_found:
array.append(new_item)
def get_single_value_by_id(self, array, search_id):
for item in array:
if isinstance(item, (tuple, list)) and len(item) >= 2: # Cek apakah item adalah tuple/list
if int(item[0]) == int(search_id):
return item[1]
return 0.0 # Jika id t
def get_single_string_value_by_id(self, array, search_id):
for item in array:
if isinstance(item, (tuple, list)) and len(item) >= 2: # Cek apakah item adalah tuple/list
if int(item[0]) == int(search_id):
return item[1]
return "" # Jika id t
def get_multi_value_by_id(self, array, search_id):
for item in array:
if isinstance(item, (tuple, list)) and len(item) >= 2: # Cek apakah item adalah tuple/list
if int(item[0]) == int(search_id):
return item[1]
return [] # Jika id t
def check_values_by_track_id(self, track_id, data_array):
results = []
for track_id in track_id:
found = False
for item in data_array:
if track_id in item:
results.append(item)
found = True
break
if not found:
results.append(f"ID {track_id} not found")
return results
def update_or_append_tuples(self, array, new_item): #self.array_time
id_found = False
# Loop through the array to check if the id already exists
for i, item in enumerate(array):
if item[0] == new_item[0]:
# If id found, update the value
array[i] = new_item
id_found = True
break
# If the id was not found, append the new item to the array
if not id_found:
array.append(new_item)
def update_or_append_tuples_and_sum(self, array, new_item): #self.array_time
id_found = False
# Loop through the array to check if the id already exists
for i, item in enumerate(array):
if item[0] == new_item[0]:
# If id found, update the value
array[i] = new_item[0], (new_item[1] + 1.0)
id_found = True
break
# If the id was not found, append the new item to the array
if not id_found:
array.append(new_item)
def update_or_append_single_var(self, array, new_item): #self.array_time
id_found = False
# Loop through the array to check if the id already exists
for i, item in enumerate(array):
if item == new_item:
# If id found, update the value
array[i] = new_item
id_found = True
break
# If the id was not found, append the new item to the array
if not id_found:
array.append(new_item)
def load_data(self):
with self.conn:
# Load areas
cursor = self.conn.execute("SELECT name, coordinates FROM areas")
for row in cursor:
name, coords_str = row
coords = list(map(int, coords_str.split(',')))
area = self.canvas.create_polygon(coords, outline="red", fill="")
self.areas.append((area, name, coords_str))
# Load lines
cursor = self.conn.execute("SELECT name, x1, y1, x2, y2 FROM lines")
for row in cursor:
name, x1, y1, x2, y2 = row
line_id = self.canvas.create_line(x1, y1, x2, y2, fill="green", width=2)
self.lines.append((line_id, name, x1, y1, x2, y2))
distance = round(self.calculate_distance(x1, y1, x2, y2), 1)
line_draw = str(distance)
self.canvas.create_text((x1 + x2) / 2, (y1 + y2) / 2, text=line_draw, anchor=tk.CENTER, fill="black")
# Setelah menambahkan garis, lakukan pengecekan collision dengan garis lain
for line in self.lines:
if line[0] != line_id: # Pastikan tidak mengecek garis yang sama
f_collision_x, f_collision_y = self.check_line_collision(
(x1, y1, x2, y2),
(line[2], line[3], line[4], line[5]))
if f_collision_x is not None and f_collision_y is not None:
collision_x = round(f_collision_x, 1)
collision_y = round(f_collision_y, 1)
self.canvas.create_text(collision_x, collision_y, text=f"x={collision_x}, y={collision_y}", fill="black")
def track_mouse(self, event):
x, y = event.x, event.y
self.coordinates_label.config(text=f"Mouse Coordinates: ({x}, {y})")
mouse_in_any_area = False
for area, name, coords_str in self.areas:
if self.is_in_area(x, y, area):
#print(x,y, area)
self.coordinates_label.config(text=f"Mouse in '{name}' Area at: ({x}, {y})")
mouse_in_any_area = True
break
if not mouse_in_any_area:
for line in self.lines:
if self.is_near_line(line, x, y):
self.coordinates_label.config(text=f"Mouse near line '{line[1]}' at: ({x}, {y})")
mouse_in_any_area = True
break
if not mouse_in_any_area:
self.coordinates_label.config(text=f"Mouse is not in any Area: ({x}, {y})")
def is_in_area(self, x, y, area):
coords = self.canvas.coords(area)
return self.is_point_in_polygon(x, y, coords)
def is_point_in_polygon(self, x, y, coords):
n = len(coords) // 2
inside = False
p1x, p1y = coords[0], coords[1]
for i in range(n + 1):
p2x, p2y = coords[2 * (i % n)], coords[2 * (i % n) + 1]
if y > min(p1y, p2y):
if y <= max(p1y, p2y):
if x <= max(p1x, p2x):
if p1y != p2y:
xinters = (y - p1y) * (p2x - p1x) / (p2y - p1y) + p1x
if p1x == p2x or x <= xinters:
inside = not inside
p1x, p1y = p2x, p2y
return inside
def is_near_line(self, line, x, y):
x1, y1, x2, y2 = line[2:6]
devider = (((y2 - y1) ** 2 + (x2 - x1) ** 2) ** 0.5)
if devider == 0:
devider = 1
distance = abs((y2 - y1) * x - (x2 - x1) * y + x2 * y1 - y2 * x1) / devider
return distance < 5 # Adjust tolerance as needed
def on_closing(self):
self.conn.close()
self.root.destroy()
def init_config(self):
c = self.conn.cursor()
c.execute("SELECT * FROM config WHERE id=1")
config = c.fetchone()
#self.max_track_id = self.find_max_track_id()
global glob_calibration_factor, glob_width_in_meter, glob_width_in_pixel, glob_actual_time, glob_yolo_time, glob_model
if config is None:
# Default config
self.calibration_factor = 2.0
self.max_speed = 80 # Initialize max_speed variable default
self.width_in_pixel = 900
self.width_in_meter = 7 #meter
self.actual_time = 5.00
self.yolo_time = 15.00
self.location = "Indonesia"
self.model = "yolov8x.pt"
glob_calibration_factor = self.calibration_factor
glob_width_in_meter = self.width_in_meter
glob_width_in_pixel = self.width_in_pixel
glob_actual_time = self.actual_time
glob_yolo_time = self.yolo_time
glob_model = self.model
c.execute("INSERT INTO config (id, calibration_factor, max_speed, width_in_pixel, width_in_meter, actual_time, yolo_time, location, Model) VALUES (1, ?, ?, ?, ?, ?, ?, ?, ?)",
(self.calibration_factor, self.max_speed, self.width_in_pixel, self.width_in_meter, self.actual_time, self.yolo_time, self.location, self.model))
self.conn.commit()
else:
self.calibration_factor, self.max_speed, self.width_in_pixel, self.width_in_meter, self.actual_time, self.yolo_time, self.location, self.model = config[1:]
glob_calibration_factor = self.calibration_factor
glob_width_in_meter = self.width_in_meter
glob_width_in_pixel = self.width_in_pixel
glob_actual_time = self.actual_time
glob_yolo_time = self.yolo_time
glob_model = self.model
def select_row_model(self, input):
if input == "yolov8x.pt":
output = 0
elif input == "yolov8l.pt":
output = 1
elif input == "yolov8m.pt":
output = 2
elif input == "yolov8s.pt":
output = 3
elif input == "yolov8n.pt":
output = 4
else:
output = 0
return output
def select_model(self, input):
if input == "super":
output = "yolov8x.pt"
elif input == "large":
output = "yolov8l.pt"
elif input == "medium":
output = "yolov8m.pt"
elif input == "small":
output = "yolov8s.pt"
elif input == "nano":
output = "yolov8n.pt"
else:
output = "yolov8x.pt"
return output
def open_config(self):
config_window = tk.Toplevel(self.root)
config_window.title("Configuration")
tk.Label(config_window, text="Calibration Factor (e.g., 2.0):").grid(row=0, column=0)
calibration_factor_entry = tk.Entry(config_window)
calibration_factor_entry.grid(row=0, column=1)
calibration_factor_entry.insert(0, str(self.calibration_factor))
tk.Label(config_window, text="Maximum Speed (e.g., 80.0):").grid(row=1, column=0)
max_speed_entry = tk.Entry(config_window)
max_speed_entry.grid(row=1, column=1)
max_speed_entry.insert(0, str(self.max_speed))
tk.Label(config_window, text="Width in Pixel:").grid(row=2, column=0)
width_in_pixel_entry = tk.Entry(config_window)
width_in_pixel_entry.grid(row=2, column=1)
width_in_pixel_entry.insert(0, str(self.width_in_pixel))
tk.Label(config_window, text="Width in Meter:").grid(row=3, column=0)
width_in_meter_entry = tk.Entry(config_window)
width_in_meter_entry.grid(row=3, column=1)
width_in_meter_entry.insert(0, str(self.width_in_meter))
tk.Label(config_window, text="Actual Time:").grid(row=4, column=0)
actual_time_entry = tk.Entry(config_window)
actual_time_entry.grid(row=4, column=1)
actual_time_entry.insert(0, str(self.actual_time))
tk.Label(config_window, text="Yolo Time:").grid(row=5, column=0)
yolo_time_entry = tk.Entry(config_window)
yolo_time_entry.grid(row=5, column=1)
yolo_time_entry.insert(0, str(self.yolo_time))
tk.Label(config_window, text="Location:").grid(row=6, column=0)
location_entry = tk.Entry(config_window)
location_entry.grid(row=6, column=1)
location_entry.insert(0, self.location)
tk.Label(config_window, text="Model AI:").grid(row=7, column=0)
# Define the available options
options = ["super", "large", "medium", "small", "nano"]
# Create a StringVar to hold the selected option
selected_option = tk.StringVar(config_window)
print(self.model)
get_row = int(self.select_row_model(str(self.model)))
print(get_row)
selected_option.set(options[get_row]) # Set default value
# Create OptionMenu and place it in the grid
model_option = tk.OptionMenu(config_window, selected_option, *options)
model_option.grid(row=7, column=1)
model_option.config(width=15)
self.model = self.select_model(str(selected_option.get()))
print(self.model)
#save ke database config
def save_config():
global glob_calibration_factor, glob_width_in_meter, glob_width_in_pixel, glob_actual_time, glob_yolo_time, glob_model
self.calibration_factor = float(calibration_factor_entry.get())
self.max_speed = float(max_speed_entry.get())
self.width_in_pixel = float(width_in_pixel_entry.get())
self.width_in_meter = float(width_in_meter_entry.get())
self.actual_time = float(actual_time_entry.get())
self.yolo_time = float(yolo_time_entry.get())
self.location = str(location_entry.get())
self.model = str(self.select_model(str(selected_option.get())))
print(selected_option.get())
print(self.model)
glob_calibration_factor = self.calibration_factor
glob_width_in_meter = self.width_in_meter
glob_width_in_pixel = self.width_in_pixel
glob_actual_time = self.actual_time
glob_yolo_time = self.yolo_time
glob_model = self.model
c = self.conn.cursor()
c.execute("UPDATE config SET calibration_factor=?, max_speed=?, width_in_pixel=?, width_in_meter=?, actual_time=?, yolo_time=?, location=?, Model=? WHERE id=1",
(self.calibration_factor, self.max_speed, self.width_in_pixel, self.width_in_meter, self.actual_time, self.yolo_time, self.location, self.model))
self.conn.commit()
self.model_yolo = YOLO(str(self.model)) #update model yolo
config_window.destroy()
save_button = tk.Button(config_window, text="Save", command=save_config)
save_button.grid(row=8, column=0, columnspan=2)
def dir_checker(self, file_path, dir_plat_image_html):
file_path_read ='database' + glob_slash + 'static' + glob_slash + file_path
if os.path.isfile(file_path_read):
return dir_plat_image_html
else:
return "Not Detected"
#connect ke kamera
def connect_camera(self):
self.use_camera = not self.use_camera
#print(self.use_camera)
if self.use_camera == True:
self.camera = cv2.VideoCapture(str(self.ip_input.get()))
self.save_string_ip(str(self.ip_input.get()))
#print(self.ip_input.get())
if not self.camera.isOpened():
self.status.set(f"Failed to connect to camera at {self.ip_input.get() }")
else:
self.status.set("Connected to camera")
self.capture_and_process_frames()
else:
self.camera.release()
#itung jarak antar titik
def uclidean_vector(self, x, y, x0, y0):
dx = x - x0
dy = y - y0
distance = math.sqrt(dx ** 2 + dy ** 2)
return distance
def draw_line_with_text(self, image, start_point, end_point, color, thickness, text):
# Menggambar garis
cv2.line(image, start_point, end_point, color, thickness)
# Menghitung posisi tengah garis
mid_point = ((start_point[0] + end_point[0]) // 2, (start_point[1] + end_point[1]) // 2)
# Menambahkan teks di tengah garis
font = cv2.FONT_HERSHEY_SIMPLEX
font_scale = 0.5
font_thickness = 2
text_size = cv2.getTextSize(text, font, font_scale, font_thickness)[0]
# Menghitung posisi kiri bawah teks agar teks berada di tengah
text_position = (mid_point[0] - text_size[0] // 2, mid_point[1] + text_size[1] // 2)
cv2.putText(image, text, text_position, font, font_scale, color, font_thickness)
def toggle_yolo(self):
self.use_yolo = not self.use_yolo
self.status.set(f"YOLO Enabled: {self.use_yolo}" + f", Distance Detector Enabled: {self.use_distance_detector}")
def toggle_detect_distance(self):
self.use_distance_detector = not self.use_distance_detector
self.status.set(f"YOLO Enabled: {self.use_yolo}" + f", Distance Detector Enabled: {self.use_distance_detector}")
def capture_and_process_frames(self):
global glob_integral, glob_span_time, glob_width_in_meter, glob_width_in_pixel, glob_actual_time, glob_yolo_time
success, frame_get = self.camera.read()
detect_once = False
# Inisialisasi list untuk menyimpan gambar yang di-crop
cropped_images_seatbelt = []
cropped_images_overspeed = []
cropped_images_wrong_dir = []
cropped_motor_cycle = []
if success:
# Store the frame in both buffers
frame_get = cv2.resize(frame_get, (1600, 900), interpolation=cv2.INTER_AREA)
frame = frame_get
self.frame_buffer.append(frame_get)
self.alt_buffer.append(frame_get)
# Process frame
if self.frame_buffer:
frame = self.frame_buffer.popleft()
fps = self.camera.get(cv2.CAP_PROP_FPS)
#print(self.max_speed)
#print("test_id", self.use_yolo)
if self.use_yolo:
#print("cek id1")
#print(self.model_yolo.model.names)
#print(self.speed_cor)
speed_show = 0
last_x, last_y = 0, 0
present_track_id = []
#print("cek id2")
results = self.model_yolo.track(frame, persist=True, verbose=False)
#print("cek id3")
boxes = results[0].boxes.xyxy.cpu()
#print("cek id4")
# Track objects in the frame
#frame = results[0].plot()