-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain_en.py
1112 lines (952 loc) · 51.9 KB
/
main_en.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
from PySide6.QtWidgets import QApplication, QMainWindow, QFileDialog, QMenu
from PySide6.QtGui import QImage, QPixmap, QColor
from PySide6.QtCore import QTimer, QThread, Signal, QObject, QPoint, Qt
from ui.CustomMessageBox import MessageBox
from ui.home import Ui_MainWindow
from UIFunctions import *
from core_en import YoloPredictor
from pathlib import Path
from utils.rtsp_win import Window
import traceback
import json
import sys
import cv2
import os
class MainWindow(QMainWindow, Ui_MainWindow):
main2yolo_begin_sgl = Signal() # Signal to send execution signal from main window to YOLO instance
def __init__(self, parent=None):
super(MainWindow, self).__init__(parent)
# Basic interface setup
self.setupUi(self)
self.setAttribute(Qt.WA_TranslucentBackground) # Rounded corners and transparency
self.setWindowFlags(Qt.FramelessWindowHint) # Set window flags: hide window border
UIFuncitons.uiDefinitions(self) # Custom interface definitions
# Initial page setup
self.task = ''
self.PageIndex = 1
self.content.setCurrentIndex(self.PageIndex)
self.pushButton_detect.clicked.connect(self.button_detect)
self.pushButton_pose.clicked.connect(self.button_pose)
self.pushButton_classify.clicked.connect(self.button_classify)
self.pushButton_segment.clicked.connect(self.button_segment)
self.pushButton_track.clicked.connect(self.button_track)
self.src_home_button.setEnabled(False)
self.src_file_button.setEnabled(False)
self.src_img_button.setEnabled(False)
self.src_cam_button.setEnabled(False)
self.src_rtsp_button.setEnabled(False)
self.src_home_button.clicked.connect(self.return_home)
#################################### Image or Video ####################################
# Display module shadow
UIFuncitons.shadow_style(self, self.Class_QF, QColor(162, 129, 247))
UIFuncitons.shadow_style(self, self.Target_QF, QColor(251, 157, 139))
UIFuncitons.shadow_style(self, self.Fps_QF, QColor(170, 128, 213))
UIFuncitons.shadow_style(self, self.Model_QF, QColor(64, 186, 193))
# YOLO-v8 thread
overrides = {'batch': 1} # Preset batch size (default 16)
self.yolo_predict = YoloPredictor(cfg=DEFAULT_CFG, overrides=overrides) # Create YOLO instance
self.select_model = self.model_box.currentText() # Default model
self.yolo_thread = QThread() # Create YOLO thread
self.yolo_predict.yolo2main_pre_img.connect(lambda x: self.show_image(x, self.pre_video, 'img'))
self.yolo_predict.yolo2main_res_img.connect(lambda x: self.show_image(x, self.res_video, 'img'))
self.yolo_predict.yolo2main_status_msg.connect(lambda x: self.show_status(x))
self.yolo_predict.yolo2main_fps.connect(lambda x: self.fps_label.setText(x))
self.yolo_predict.yolo2main_class_num.connect(lambda x: self.Class_num.setText(str(x)))
self.yolo_predict.yolo2main_target_num.connect(lambda x: self.Target_num.setText(str(x)))
self.yolo_predict.yolo2main_progress.connect(lambda x: self.progress_bar.setValue(x))
self.main2yolo_begin_sgl.connect(self.yolo_predict.run)
self.yolo_predict.moveToThread(self.yolo_thread)
self.Qtimer_ModelBox = QTimer(self) # Timer: monitor model file changes every 2 seconds
self.Qtimer_ModelBox.timeout.connect(self.ModelBoxRefre)
self.Qtimer_ModelBox.start(2000)
# Model parameters
self.model_box.currentTextChanged.connect(self.change_model)
self.iou_spinbox.valueChanged.connect(lambda x: self.change_val(x, 'iou_spinbox')) # IOU text box
self.iou_slider.valueChanged.connect(lambda x: self.change_val(x, 'iou_slider')) # IOU slider
self.conf_spinbox.valueChanged.connect(lambda x: self.change_val(x, 'conf_spinbox')) # Confidence text box
self.conf_slider.valueChanged.connect(lambda x: self.change_val(x, 'conf_slider')) # Confidence slider
self.speed_spinbox.valueChanged.connect(lambda x: self.change_val(x, 'speed_spinbox')) # Speed text box
self.speed_slider.valueChanged.connect(lambda x: self.change_val(x, 'speed_slider')) # Speed slider
# Initialize hint window
self.Class_num.setText('--')
self.Target_num.setText('--')
self.fps_label.setText('--')
self.Model_name.setText(self.select_model)
# Select folder source
self.src_file_button.clicked.connect(self.open_src_file) # Select local file
# Single file
self.src_img_button.clicked.connect(self.open_src_img) # Select local file
# Start test button
self.run_button.clicked.connect(self.run_or_continue) # Pause/Start
self.stop_button.clicked.connect(self.stop) # Stop
# Other function buttons
self.save_res_button.toggled.connect(self.is_save_res) # Save image option
self.save_txt_button.toggled.connect(self.is_save_txt) # Save label option
#################################### Image or Video ####################################
#################################### Camera ####################################
# Display cam module shadow
UIFuncitons.shadow_style(self, self.Class_QF_cam, QColor(162, 129, 247))
UIFuncitons.shadow_style(self, self.Target_QF_cam, QColor(251, 157, 139))
UIFuncitons.shadow_style(self, self.Fps_QF_cam, QColor(170, 128, 213))
UIFuncitons.shadow_style(self, self.Model_QF_cam, QColor(64, 186, 193))
# YOLO-v8-cam thread
overrides = {'batch': 1} # Preset batch size (default 16)
self.yolo_predict_cam = YoloPredictor(cfg=DEFAULT_CFG, overrides=overrides) # Create YOLO instance
self.select_model_cam = self.model_box_cam.currentText() # Default model
self.yolo_thread_cam = QThread() # Create YOLO thread
self.yolo_predict_cam.yolo2main_pre_img.connect(lambda c: self.cam_show_image(c, self.pre_cam))
self.yolo_predict_cam.yolo2main_res_img.connect(lambda c: self.cam_show_image(c, self.res_cam))
self.yolo_predict_cam.yolo2main_status_msg.connect(lambda c: self.show_status(c))
self.yolo_predict_cam.yolo2main_fps.connect(lambda c: self.fps_label_cam.setText(c))
self.yolo_predict_cam.yolo2main_class_num.connect(lambda c: self.Class_num_cam.setText(str(c)))
self.yolo_predict_cam.yolo2main_target_num.connect(lambda c: self.Target_num_cam.setText(str(c)))
self.yolo_predict_cam.yolo2main_progress.connect(self.progress_bar_cam.setValue(0))
self.main2yolo_begin_sgl.connect(self.yolo_predict_cam.run)
self.yolo_predict_cam.moveToThread(self.yolo_thread_cam)
self.Qtimer_ModelBox_cam = QTimer(self) # Timer: monitor model file changes every 2 seconds
self.Qtimer_ModelBox_cam.timeout.connect(self.ModelBoxRefre)
self.Qtimer_ModelBox_cam.start(2000)
# Cam model parameters
self.model_box_cam.currentTextChanged.connect(self.cam_change_model)
self.iou_spinbox_cam.valueChanged.connect(lambda c: self.cam_change_val(c, 'iou_spinbox_cam')) # IOU text box
self.iou_slider_cam.valueChanged.connect(lambda c: self.cam_change_val(c, 'iou_slider_cam')) # IOU slider
self.conf_spinbox_cam.valueChanged.connect(lambda c: self.cam_change_val(c, 'conf_spinbox_cam')) # Confidence text box
self.conf_slider_cam.valueChanged.connect(lambda c: self.cam_change_val(c, 'conf_slider_cam')) # Confidence slider
self.speed_spinbox_cam.valueChanged.connect(lambda c: self.cam_change_val(c, 'speed_spinbox_cam')) # Speed text box
self.speed_slider_cam.valueChanged.connect(lambda c: self.cam_change_val(c, 'speed_slider_cam')) # Speed slider
# Initialize hint window
self.Class_num_cam.setText('--')
self.Target_num_cam.setText('--')
self.fps_label_cam.setText('--')
self.Model_name_cam.setText(self.select_model_cam)
# Select detection source
self.src_cam_button.clicked.connect(self.cam_button) # Select camera
# Start test button
self.run_button_cam.clicked.connect(self.cam_run_or_continue) # Pause/Start
self.stop_button_cam.clicked.connect(self.cam_stop) # Stop
# Other function buttons
self.save_res_button_cam.toggled.connect(self.cam_is_save_res) # Save image option
self.save_txt_button_cam.toggled.connect(self.cam_is_save_txt) # Save label option
#################################### Camera ####################################
#################################### RTSP ####################################
self.src_rtsp_button.clicked.connect(self.rtsp_button)
#################################### RTSP ####################################
self.ToggleBotton.clicked.connect(lambda: UIFuncitons.toggleMenu(self, True)) # Left navigation button
# Initialization
self.load_config()
def return_home(self):
# 0: image/video page
# 1: home page
# 2: camera page
if self.PageIndex != 1:
self.PageIndex = 1
self.content.setCurrentIndex(1)
self.yolo_predict_cam.source = ''
self.src_home_button.setEnabled(False)
self.src_file_button.setEnabled(False)
self.src_img_button.setEnabled(False)
self.src_cam_button.setEnabled(False)
self.src_rtsp_button.setEnabled(False)
# Terminate thread if running
self.yolo_thread_cam.quit()
self.cam_stop()
self.yolo_thread.quit()
self.stop()
self.show_status("Welcome to the YOLOv8 detection system, please select Mode")
def button_classify(self):
self.task = 'Classify'
self.yolo_predict.task = self.task
self.yolo_predict_cam.task = self.task
if self.PageIndex != 0:
self.PageIndex = 0
self.content.setCurrentIndex(0)
self.src_home_button.setEnabled(True)
self.src_file_button.setEnabled(True)
self.src_img_button.setEnabled(True)
self.src_cam_button.setEnabled(True)
self.src_rtsp_button.setEnabled(True)
self.settings_button.clicked.connect(lambda: UIFuncitons.settingBox(self, True)) # Top right settings button
# Load model directory
self.pt_list = os.listdir('./models/classify/')
self.pt_list = [file for file in self.pt_list if file.endswith(('.pt', 'onnx', 'engine'))]
self.pt_list.sort(key=lambda x: os.path.getsize('./models/classify/' + x)) # Sort by file size
self.model_box.clear()
self.model_box.addItems(self.pt_list)
self.yolo_predict.new_model_name = "./models/classify/%s" % self.select_model
self.yolo_predict_cam.new_model_name = "./models/classify/%s" % self.select_model_cam
# Load camera model directory
self.pt_list_cam = os.listdir('./models/classify/')
self.pt_list_cam = [file for file in self.pt_list_cam if file.endswith(('.pt', 'onnx', 'engine'))]
self.pt_list_cam.sort(key=lambda x: os.path.getsize('./models/classify/' + x)) # Sort by file size
self.model_box_cam.clear()
self.model_box_cam.addItems(self.pt_list_cam)
self.show_status("Current page: image or video detection page, Mode: Classify")
def button_detect(self):
self.task = 'Detect'
self.yolo_predict.task = self.task
self.yolo_predict_cam.task = self.task
self.yolo_predict.new_model_name = "./models/detect/%s" % self.select_model
self.yolo_predict_cam.new_model_name = "./models/detect/%s" % self.select_model_cam
if self.PageIndex != 0:
self.PageIndex = 0
self.content.setCurrentIndex(0)
self.src_home_button.setEnabled(True)
self.src_file_button.setEnabled(True)
self.src_img_button.setEnabled(True)
self.src_cam_button.setEnabled(True)
self.src_rtsp_button.setEnabled(True)
self.settings_button.clicked.connect(lambda: UIFuncitons.settingBox(self, True)) # Top right settings button
# Load model directory
self.pt_list = os.listdir('./models/detect/')
self.pt_list = [file for file in self.pt_list if file.endswith(('.pt', 'onnx', 'engine'))]
self.pt_list.sort(key=lambda x: os.path.getsize('./models/detect/' + x)) # Sort by file size
self.model_box.clear()
self.model_box.addItems(self.pt_list)
self.yolo_predict.new_model_name = "./models/detect/%s" % self.select_model
self.yolo_predict_cam.new_model_name = "./models/detect/%s" % self.select_model_cam
# Load camera model directory
self.pt_list_cam = os.listdir('./models/detect/')
self.pt_list_cam = [file for file in self.pt_list_cam if file.endswith(('.pt', 'onnx', 'engine'))]
self.pt_list_cam.sort(key=lambda x: os.path.getsize('./models/detect/' + x)) # Sort by file size
self.model_box_cam.clear()
self.model_box_cam.addItems(self.pt_list_cam)
self.show_status("Current page: image or video detection page, Mode: Detect")
def button_pose(self):
self.task = 'Pose'
self.yolo_predict.task = self.task
self.yolo_predict_cam.task = self.task
self.yolo_predict.new_model_name = "./models/pose/%s" % self.select_model
self.yolo_predict_cam.new_model_name = "./models/pose/%s" % self.select_model_cam
if self.PageIndex != 0:
self.PageIndex = 0
self.content.setCurrentIndex(0)
self.src_home_button.setEnabled(True)
self.src_file_button.setEnabled(True)
self.src_img_button.setEnabled(True)
self.src_cam_button.setEnabled(True)
self.src_rtsp_button.setEnabled(True)
self.settings_button.clicked.connect(lambda: UIFuncitons.settingBox(self, True)) # Top right settings button
# Load model directory
self.pt_list = os.listdir('./models/pose/')
self.pt_list = [file for file in self.pt_list if file.endswith(('.pt', 'onnx', 'engine'))]
self.pt_list.sort(key=lambda x: os.path.getsize('./models/pose/' + x)) # Sort by file size
self.model_box.clear()
self.model_box.addItems(self.pt_list)
self.yolo_predict.new_model_name = "./models/pose/%s" % self.select_model
self.yolo_predict_cam.new_model_name = "./models/pose/%s" % self.select_model_cam
# Load camera model directory
self.pt_list_cam = os.listdir('./models/pose/')
self.pt_list_cam = [file for file in self.pt_list_cam if file.endswith(('.pt', 'onnx', 'engine'))]
self.pt_list_cam.sort(key=lambda x: os.path.getsize('./models/pose/' + x)) # Sort by file size
self.model_box_cam.clear()
self.model_box_cam.addItems(self.pt_list_cam)
self.show_status("Current page: image or video detection page, Mode: Pose")
def button_segment(self):
self.task = 'Segment'
self.yolo_predict.task = self.task
self.yolo_predict_cam.task = self.task
self.yolo_predict.new_model_name = "./models/segment/%s" % self.select_model
self.yolo_predict_cam.new_model_name = "./models/segment/%s" % self.select_model_cam
if self.PageIndex != 0:
self.PageIndex = 0
self.content.setCurrentIndex(0)
self.src_home_button.setEnabled(True)
self.src_file_button.setEnabled(True)
self.src_img_button.setEnabled(True)
self.src_cam_button.setEnabled(True)
self.src_rtsp_button.setEnabled(True)
self.settings_button.clicked.connect(lambda: UIFuncitons.settingBox(self, True)) # Top right settings button
# Load model directory
self.pt_list = os.listdir('./models/segment/')
self.pt_list = [file for file in self.pt_list if file.endswith(('.pt', 'onnx', 'engine'))]
self.pt_list.sort(key=lambda x: os.path.getsize('./models/segment/' + x)) # Sort by file size
self.model_box.clear()
self.model_box.addItems(self.pt_list)
self.yolo_predict.new_model_name = "./models/segment/%s" % self.select_model
self.yolo_predict_cam.new_model_name = "./models/segment/%s" % self.select_model_cam
# Load camera model directory
self.pt_list_cam = os.listdir('./models/segment/')
self.pt_list_cam = [file for file in self.pt_list_cam if file.endswith(('.pt', 'onnx', 'engine'))]
self.pt_list_cam.sort(key=lambda x: os.path.getsize('./models/segment/' + x)) # Sort by file size
self.model_box_cam.clear()
self.model_box_cam.addItems(self.pt_list_cam)
self.show_status("Current page: image or video detection page, Mode: Segment")
def button_track(self):
self.task = 'Track'
self.yolo_predict.task = self.task
self.yolo_predict_cam.task = self.task
self.yolo_predict.new_model_name = "./models/track/%s" % self.select_model
self.yolo_predict_cam.new_model_name = "./models/track/%s" % self.select_model_cam
if self.PageIndex != 0:
self.PageIndex = 0
self.content.setCurrentIndex(0)
self.src_home_button.setEnabled(True)
self.src_file_button.setEnabled(True)
self.src_img_button.setEnabled(True)
self.src_cam_button.setEnabled(True)
self.src_rtsp_button.setEnabled(True)
self.settings_button.clicked.connect(lambda: UIFuncitons.settingBox(self, True)) # Top right settings button
# Load model directory
self.pt_list = os.listdir('./models/track/')
self.pt_list = [file for file in self.pt_list if file.endswith(('.pt', 'onnx', 'engine'))]
self.pt_list.sort(key=lambda x: os.path.getsize('./models/track/' + x)) # Sort by file size
self.model_box.clear()
self.model_box.addItems(self.pt_list)
self.yolo_predict.new_model_name = "./models/track/%s" % self.select_model
self.yolo_predict_cam.new_model_name = "./models/track/%s" % self.select_model_cam
# Load camera model directory
self.pt_list_cam = os.listdir('./models/track/')
self.pt_list_cam = [file for file in self.pt_list_cam if file.endswith(('.pt', 'onnx', 'engine'))]
self.pt_list_cam.sort(key=lambda x: os.path.getsize('./models/track/' + x)) # Sort by file size
self.model_box_cam.clear()
self.model_box_cam.addItems(self.pt_list_cam)
self.show_status("Current page: image or video detection page, Mode: Track")
####################################image or video####################################
# Open local file
def open_src_file(self):
if self.task == 'Classify':
self.show_status("Current page: image or video detection page, Mode: Classify")
if self.task == 'Detect':
self.show_status("Current page: image or video detection page, Mode: Detect")
if self.task == 'Pose':
self.show_status("Current page: image or video detection page, Mode: Pose")
if self.task == 'Segment':
self.show_status("Current page: image or video detection page, Mode: Segment")
if self.task == 'Track':
self.show_status("Current page: image or video detection page, Mode: Track")
# Terminate cam thread to save resources
if self.yolo_thread_cam.isRunning():
self.yolo_thread_cam.quit()
self.cam_stop()
if self.PageIndex != 0:
self.PageIndex = 0
self.content.setCurrentIndex(0)
self.settings_button.clicked.connect(lambda: UIFuncitons.settingBox(self, True)) # Top right settings button
# Set the configuration file path
config_file = 'config/fold.json'
# Read the configuration file content
config = json.load(open(config_file, 'r', encoding='utf-8'))
# Get the last opened folder path
open_fold = config['open_fold']
# Use the current working directory if the last opened folder does not exist
if not os.path.exists(open_fold):
open_fold = os.getcwd()
FolderPath = QFileDialog.getExistingDirectory(self, 'Select your Folder', open_fold)
# If the user selects a file
if FolderPath:
FileFormat = [".jpg", ".png", ".jpeg", ".bmp", ".dib", ".jpe", ".jp2"]
Foldername = [(FolderPath + "/" + filename) for filename in os.listdir(FolderPath) for jpgname in FileFormat
if jpgname in filename]
if Foldername:
# Set the selected file path as the source for yolo_predict
self.yolo_predict.source = Foldername
# Display the folder load status
self.show_status('Load folder: {}'.format(os.path.dirname(FolderPath)))
# Update the last opened folder path in the configuration file
config['open_fold'] = os.path.dirname(FolderPath)
# Write the updated configuration file back to the file
config_json = json.dumps(config, ensure_ascii=False, indent=2)
with open(config_file, 'w', encoding='utf-8') as f:
f.write(config_json)
# Stop detection
self.stop()
else:
self.show_status('There are no pictures in the folder...')
# Open local file
def open_src_img(self):
if self.task == 'Classify':
self.show_status("Current page: image or video detection page, Mode: Classify")
if self.task == 'Detect':
self.show_status("Current page: image or video detection page, Mode: Detect")
if self.task == 'Pose':
self.show_status("Current page: image or video detection page, Mode: Pose")
if self.task == 'Segment':
self.show_status("Current page: image or video detection page, Mode: Segment")
if self.task == 'Track':
self.show_status("Current page: image or video detection page, Mode: Track")
# Terminate cam thread to save resources
if self.yolo_thread_cam.isRunning():
self.yolo_thread_cam.quit()
self.cam_stop()
if self.PageIndex != 0:
self.PageIndex = 0
self.content.setCurrentIndex(0)
self.settings_button.clicked.connect(lambda: UIFuncitons.settingBox(self, True)) # Top right settings button
# Set the configuration file path
config_file = 'config/fold.json'
# Read the configuration file content
config = json.load(open(config_file, 'r', encoding='utf-8'))
# Get the last opened folder path
open_fold = config['open_fold']
# Use the current working directory if the last opened folder does not exist
if not os.path.exists(open_fold):
open_fold = os.getcwd()
# Allow the user to select a picture or video file through a file dialog
if self.task == 'Track':
name, _ = QFileDialog.getOpenFileName(self, 'Video', open_fold, "Pic File(*.mp4 *.mkv *.avi *.flv)")
else:
name, _ = QFileDialog.getOpenFileName(self, 'Video/image', open_fold, "Pic File(*.mp4 *.mkv *.avi *.flv *.jpg *.png *.heic)")
# If the user selects a file
if name:
# Set the selected file path as the source for yolo_predict
self.yolo_predict.source = name
# Display the file load status
self.show_status('Load file: {}'.format(os.path.basename(name)))
# Update the last opened folder path in the configuration file
config['open_fold'] = os.path.dirname(name)
# Write the updated configuration file back to the file
config_json = json.dumps(config, ensure_ascii=False, indent=2)
with open(config_file, 'w', encoding='utf-8') as f:
f.write(config_json)
# Stop detection
self.stop()
# Display original image and detection result in main window
@staticmethod
def show_image(img_src, label, flag):
try:
if flag == "path":
img_src = cv2.imdecode(np.fromfile(img_src, dtype=np.uint8), -1)
# Get the height, width, and number of channels of the original image
ih, iw, _ = img_src.shape
# Get the width and height of the label
w = label.geometry().width()
h = label.geometry().height()
# Maintain the original data ratio
if iw / w > ih / h:
scal = w / iw
nw = w
nh = int(scal * ih)
img_src_ = cv2.resize(img_src, (nw, nh))
else:
scal = h / ih
nw = int(scal * iw)
nh = h
img_src_ = cv2.resize(img_src, (nw, nh))
# Convert the image to RGB format
frame = cv2.cvtColor(img_src_, cv2.COLOR_BGR2RGB)
# Convert the image data to a QPixmap object
img = QImage(frame.data, frame.shape[1], frame.shape[0], frame.shape[2] * frame.shape[1],
QImage.Format_RGB888)
# Display the image on the label
label.setPixmap(QPixmap.fromImage(img))
except Exception as e:
# Handle exceptions and print error messages
print(repr(e))
# Control start/pause of detection
def run_or_continue(self):
# Check if the source of YOLO prediction is empty
if self.yolo_predict.source == '':
self.show_status('Before starting detection, please select an image or video source...')
self.run_button.setChecked(False)
else:
# Set the stop flag of YOLO prediction to False
self.yolo_predict.stop_dtc = False
# If the start button is checked
if self.run_button.isChecked():
self.run_button.setChecked(True) # Activate button
self.save_txt_button.setEnabled(False) # Disable saving after detection starts
self.save_res_button.setEnabled(False)
self.show_status('Detecting...')
self.yolo_predict.continue_dtc = True # Control YOLO pause
if not self.yolo_thread.isRunning():
self.yolo_thread.start()
self.main2yolo_begin_sgl.emit()
# If the start button is not checked, it means pause detection
else:
self.yolo_predict.continue_dtc = False
self.show_status("Detection paused...")
self.run_button.setChecked(False) # Stop button
# Save test result button -- image/video
def is_save_res(self):
if self.save_res_button.checkState() == Qt.CheckState.Unchecked:
# Show message, indicating that image results will not be saved
self.show_status('NOTE: Image results will not be saved')
# Set the flag for saving results in the YOLO instance to False
self.yolo_predict.save_res = False
elif self.save_res_button.checkState() == Qt.CheckState.Checked:
# Show message, indicating that image results will be saved
self.show_status('NOTE: Image results will be saved')
# Set the flag for saving results in the YOLO instance to True
self.yolo_predict.save_res = True
# Save test result button -- label (txt)
def is_save_txt(self):
if self.save_txt_button.checkState() == Qt.CheckState.Unchecked:
# Show message, indicating that label results will not be saved
self.show_status('NOTE: Label results will not be saved')
# Set the flag for saving labels in the YOLO instance to False
self.yolo_predict.save_txt = False
elif self.save_txt_button.checkState() == Qt.CheckState.Checked:
# Show message, indicating that label results will be saved
self.show_status('NOTE: Label results will be saved')
# Set the flag for saving labels in the YOLO instance to True
self.yolo_predict.save_txt = True
# Terminate button and related state handling
def stop(self):
# If the YOLO thread is running, terminate the thread
if self.yolo_thread.isRunning():
self.yolo_thread.quit() # Terminate thread
# Set the termination flag of the YOLO instance to True
self.yolo_predict.stop_dtc = True
# Restore the status of the start button
self.run_button.setChecked(False)
self.save_res_button.setEnabled(True)
self.save_txt_button.setEnabled(True)
# Clear the image in the prediction result display area
self.pre_video.clear()
# Clear the image in the detection result display area
self.res_video.clear()
# Set the value of the progress bar to 0
self.progress_bar.setValue(0)
# Reset the class number, target number, and fps labels
self.Class_num.setText('--')
self.Target_num.setText('--')
self.fps_label.setText('--')
# Change detection parameters
def change_val(self, x, flag):
if flag == 'iou_spinbox':
# If the value of the iou_spinbox changes, change the value of the iou_slider
self.iou_slider.setValue(int(x * 100))
elif flag == 'iou_slider':
# If the value of the iou_slider changes, change the value of the iou_spinbox
self.iou_spinbox.setValue(x / 100)
# Show message, indicating IOU threshold change
self.show_status('IOU Threshold: %s' % str(x / 100))
# Set the IOU threshold of the YOLO instance
self.yolo_predict.iou_thres = x / 100
elif flag == 'conf_spinbox':
# If the value of the conf_spinbox changes, change the value of the conf_slider
self.conf_slider.setValue(int(x * 100))
elif flag == 'conf_slider':
# If the value of the conf_slider changes, change the value of the conf_spinbox
self.conf_spinbox.setValue(x / 100)
# Show message, indicating Confidence threshold change
self.show_status('Conf Threshold: %s' % str(x / 100))
# Set the Confidence threshold of the YOLO instance
self.yolo_predict.conf_thres = x / 100
elif flag == 'speed_spinbox':
# If the value of the speed_spinbox changes, change the value of the speed_slider
self.speed_slider.setValue(x)
elif flag == 'speed_slider':
# If the value of the speed_slider changes, change the value of the speed_spinbox
self.speed_spinbox.setValue(x)
# Show message, indicating delay time change
self.show_status('Delay: %s ms' % str(x))
# Set the delay time threshold of the YOLO instance
self.yolo_predict.speed_thres = x # milliseconds
# Change model
def change_model(self, x):
# Get the currently selected model name
self.select_model = self.model_box.currentText()
# Set the new model name of the YOLO instance
if self.task == 'Classify':
self.yolo_predict.new_model_name = "./models/classify/%s" % self.select_model
elif self.task == 'Detect':
self.yolo_predict.new_model_name = "./models/detect/%s" % self.select_model
elif self.task == 'Pose':
self.yolo_predict.new_model_name = "./models/pose/%s" % self.select_model
elif self.task == 'Segment':
self.yolo_predict.new_model_name = "./models/segment/%s" % self.select_model
elif self.task == 'Track':
self.yolo_predict.new_model_name = "./models/track/%s" % self.select_model
# Show message, indicating model has been changed
self.show_status('Change Model: %s' % self.select_model)
# Display the new model name on the interface
self.Model_name.setText(self.select_model)
####################################image or video####################################
####################################camera####################################
def cam_button(self):
self.yolo_predict_cam.source = 0
self.show_status('Current page: Webcam detection page')
# Terminate image or video thread to save resources
if self.yolo_thread.isRunning() or self.yolo_thread_cam.isRunning():
self.yolo_thread.quit()
self.yolo_thread_cam.quit()
self.stop()
self.cam_stop()
if self.PageIndex != 2:
self.PageIndex = 2
self.content.setCurrentIndex(2)
self.settings_button.clicked.connect(lambda: UIFuncitons.cam_settingBox(self, True)) # Top right settings button
# Control cam start/pause detection
def cam_run_or_continue(self):
if self.yolo_predict_cam.source == '':
self.show_status('Camera not detected')
self.run_button_cam.setChecked(False)
else:
# Set the stop flag for YOLO prediction to False
self.yolo_predict_cam.stop_dtc = False
# If the start button is checked
if self.run_button_cam.isChecked():
self.run_button_cam.setChecked(True) # Start button
self.save_txt_button_cam.setEnabled(False) # Disable save after detection starts
self.save_res_button_cam.setEnabled(False)
self.show_status('Detection in progress...')
self.yolo_predict_cam.continue_dtc = True # Control whether YOLO is paused
if not self.yolo_thread_cam.isRunning():
self.yolo_thread_cam.start()
self.main2yolo_begin_sgl.emit()
# If the start button is not checked, it means pause detection
else:
self.yolo_predict_cam.continue_dtc = False
self.show_status("Detection paused...")
self.run_button_cam.setChecked(False) # Stop button
# Display original image and detection results in the main cam window
@staticmethod
def cam_show_image(img_src, label, instance=None):
try:
# Get the height, width, and channels of the original image
ih, iw, _ = img_src.shape
# Get the width and height of the label
w = label.geometry().width()
h = label.geometry().height()
# Maintain the original data ratio
if iw / w > ih / h:
scal = w / iw
nw = w
nh = int(scal * ih)
img_src_ = cv2.resize(img_src, (nw, nh))
else:
scal = h / ih
nw = int(scal * iw)
nh = h
img_src_ = cv2.resize(img_src, (nw, nh))
# Convert the image to RGB format
frame = cv2.cvtColor(img_src_, cv2.COLOR_BGR2RGB)
# Convert the image data to a QPixmap object
img = QImage(frame.data, frame.shape[1], frame.shape[0], frame.shape[2] * frame.shape[1],
QImage.Format_RGB888)
# Display the image on the label
label.setPixmap(QPixmap.fromImage(img))
except Exception as e:
# Handle exceptions, print error messages
traceback.print_exc()
print(f"Error: {e}")
if instance is not None:
instance.show_status('%s' % e)
# Change detection parameters
def cam_change_val(self, c, flag):
if flag == 'iou_spinbox_cam':
# If the value of iou_spinbox changes, change the value of iou_slider
self.iou_slider_cam.setValue(int(c * 100))
elif flag == 'iou_slider_cam':
# If the value of iou_slider changes, change the value of iou_spinbox
self.iou_spinbox_cam.setValue(c / 100)
# Display message indicating IOU threshold change
self.show_status('IOU Threshold: %s' % str(c / 100))
# Set the IOU threshold for the YOLO instance
self.yolo_predict_cam.iou_thres = c / 100
elif flag == 'conf_spinbox_cam':
# If the value of conf_spinbox changes, change the value of conf_slider
self.conf_slider_cam.setValue(int(c * 100))
elif flag == 'conf_slider_cam':
# If the value of conf_slider changes, change the value of conf_spinbox
self.conf_spinbox_cam.setValue(c / 100)
# Display message indicating confidence threshold change
self.show_status('Conf Threshold: %s' % str(c / 100))
# Set the confidence threshold for the YOLO instance
self.yolo_predict_cam.conf_thres = c / 100
elif flag == 'speed_spinbox_cam':
# If the value of speed_spinbox changes, change the value of speed_slider
self.speed_slider_cam.setValue(c)
elif flag == 'speed_slider_cam':
# If the value of speed_slider changes, change the value of speed_spinbox
self.speed_spinbox_cam.setValue(c)
# Display message indicating delay time change
self.show_status('Delay: %s ms' % str(c))
# Set the delay time threshold for the YOLO instance
self.yolo_predict_cam.speed_thres = c # milliseconds
# Change model
def cam_change_model(self, c):
# Get the currently selected model name
self.select_model_cam = self.model_box_cam.currentText()
# Set the new model name for the YOLO instance
if self.task == 'Classify':
self.yolo_predict_cam.new_model_name = "./models/classify/%s" % self.select_model_cam
elif self.task == 'Detect':
self.yolo_predict_cam.new_model_name = "./models/detect/%s" % self.select_model_cam
elif self.task == 'Pose':
self.yolo_predict_cam.new_model_name = "./models/pose/%s" % self.select_model_cam
elif self.task == 'Segment':
self.yolo_predict_cam.new_model_name = "./models/segment/%s" % self.select_model_cam
elif self.task == 'Track':
self.yolo_predict_cam.new_model_name = "./models/track/%s" % self.select_model_cam
# Display message indicating the model has changed
self.show_status('Change Model:%s' % self.select_model_cam)
# Display the new model name on the interface
self.Model_name_cam.setText(self.select_model_cam)
# Save test result button -- image/video
def cam_is_save_res(self):
if self.save_res_button_cam.checkState() == Qt.CheckState.Unchecked:
# Display message, indicating that webcam results will not be saved
self.show_status('NOTE: Webcam results will not be saved')
# Set the flag for saving results in the YOLO instance to False
self.yolo_thread_cam.save_res = False
elif self.save_res_button_cam.checkState() == Qt.CheckState.Checked:
# Display message, indicating that webcam results will be saved
self.show_status('NOTE: Webcam results will be saved')
# Set the flag for saving results in the YOLO instance to True
self.yolo_thread_cam.save_res = True
# Save test result button -- label (txt)
def cam_is_save_txt(self):
if self.save_txt_button_cam.checkState() == Qt.CheckState.Unchecked:
# Display message, indicating that label results will not be saved
self.show_status('NOTE: Label results will not be saved')
# Set the flag for saving labels in the YOLO instance to False
self.yolo_thread_cam.save_txt_cam = False
elif self.save_txt_button_cam.checkState() == Qt.CheckState.Checked:
# Display message, indicating that label results will be saved
self.show_status('NOTE: Label results will be saved')
# Set the flag for saving labels in the YOLO instance to True
self.yolo_thread_cam.save_txt_cam = True
# Stop cam button and related state processing
def cam_stop(self):
# If the YOLO thread is running, terminate the thread
if self.yolo_thread_cam.isRunning():
self.yolo_thread_cam.quit() # Terminate thread
# Set the termination flag in the YOLO instance to True
self.yolo_predict_cam.stop_dtc = True
# Restore the status of the run button
self.run_button_cam.setChecked(False)
# Enable save button permissions
if self.task == 'Classify':
self.save_res_button_cam.setEnabled(False)
self.save_txt_button_cam.setEnabled(False)
else:
self.save_res_button_cam.setEnabled(True)
self.save_txt_button_cam.setEnabled(True)
# Clear the predicted result display area image
self.pre_cam.clear()
# Clear the detection result display area image
self.res_cam.clear()
# Reset the progress bar value
# self.progress_bar.setValue(0)
# Reset the class number, target number, and fps labels
self.Class_num_cam.setText('--')
self.Target_num_cam.setText('--')
self.fps_label_cam.setText('--')
####################################camera####################################
####################################rtsp####################################
# RTSP input address
def rtsp_button(self):
# Terminate image or video thread to save resources
if self.yolo_thread.isRunning() or self.yolo_thread_cam.isRunning():
self.yolo_thread.quit() # Terminate thread
self.yolo_thread_cam.quit()
self.stop()
self.cam_stop()
self.content.setCurrentIndex(2)
self.show_status('Current page: RTSP detection page')
self.rtsp_window = Window()
config_file = 'config/ip.json'
if not os.path.exists(config_file):
ip = "rtsp://admin:[email protected]:555"
new_config = {"ip": ip}
new_json = json.dumps(new_config, ensure_ascii=False, indent=2)
with open(config_file, 'w', encoding='utf-8') as f:
f.write(new_json)
else:
config = json.load(open(config_file, 'r', encoding='utf-8'))
ip = config['ip']
self.rtsp_window.rtspEdit.setText(ip)
self.rtsp_window.show()
self.rtsp_window.rtspButton.clicked.connect(lambda: self.load_rtsp(self.rtsp_window.rtspEdit.text()))
self.settings_button.clicked.connect(lambda: UIFuncitons.cam_settingBox(self, True)) # Top right settings button
# Load network source
def load_rtsp(self, ip):
try:
self.stop()
MessageBox(
self.close_button, title='NOTE', text='Loading RTSP...', time=1000, auto=True).exec()
self.yolo_predict_cam.source = ip
new_config = {"ip": ip}
new_json = json.dumps(new_config, ensure_ascii=False, indent=2)
with open('config/ip.json', 'w', encoding='utf-8') as f:
f.write(new_json)
self.show_status('Loaded RTSP: {}'.format(ip))
self.rtsp_window.close()
except Exception as e:
self.show_status('%s' % e)
####################################rtsp####################################
####################################common####################################
# Display information in the bottom status bar
def show_status(self, msg):
self.status_bar.setText(msg)
def handle_page_0():
if msg == 'Detection completed!':
self.save_res_button.setEnabled(True)
self.save_txt_button.setEnabled(True)
self.run_button.setChecked(False)
if self.yolo_thread.isRunning():
self.yolo_thread.quit()
elif msg == 'Detection terminated!':
self.save_res_button.setEnabled(True)
self.save_txt_button.setEnabled(True)
self.run_button.setChecked(False)
self.progress_bar.setValue(0)
if self.yolo_thread.isRunning():
self.yolo_thread.quit()
self.pre_video.clear()
self.res_video.clear()
self.Class_num.setText('--')
self.Target_num.setText('--')
self.fps_label.setText('--')
def handle_page_2():
if msg == 'Detection terminated!':
self.save_res_button_cam.setEnabled(True)
self.save_txt_button_cam.setEnabled(True)
self.run_button_cam.setChecked(False)
self.progress_bar_cam.setValue(0)
if self.yolo_thread_cam.isRunning():
self.yolo_thread_cam.quit()
self.pre_cam.clear()
self.res_cam.clear()
self.Class_num_cam.setText('--')
self.Target_num_cam.setText('--')
self.fps_label_cam.setText('--')
if self.PageIndex == 0:
handle_page_0()
elif self.PageIndex == 2:
handle_page_2()
# Monitor model file changes in a loop
def ModelBoxRefre(self):
# Get all model files in the model folder
if self.task == 'Classify':
pt_list = os.listdir('./models/classify')
pt_list = [file for file in pt_list if file.endswith(('.pt', 'onnx', 'engine'))]
pt_list.sort(key=lambda x: os.path.getsize('./models/classify/' + x))
# If the model file list changes, update the model dropdown content
if pt_list != self.pt_list:
self.pt_list = pt_list
self.model_box.clear()
self.model_box.addItems(self.pt_list)
self.pt_list_cam = pt_list
self.model_box_cam.clear()
self.model_box_cam.addItems(self.pt_list_cam)
# Repeat the same process for other tasks ('Detect', 'Pose', 'Segment', 'Track')
# Get the mouse position (for dragging the window by holding the title bar)
def mousePressEvent(self, event):
p = event.globalPosition()
globalPos = p.toPoint()
self.dragPos = globalPos
# Optimize adjustments when resizing the window (for resizing by dragging the bottom right corner)
def resizeEvent(self, event):
# Update the resize grip
UIFuncitons.resize_grips(self)
# Configuration initialization
def load_config(self):
config_file = 'config/setting.json'
# If the configuration file does not exist, create it and write default settings
if not os.path.exists(config_file):
iou = 0.26
conf = 0.33
rate = 10
save_res = 0
save_txt = 0
save_res_cam = 0
save_txt_cam = 0
new_config = {"iou": iou,
"conf": conf,
"rate": rate,
"save_res": save_res,