-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathyolo-detection-adv.py
More file actions
2214 lines (1801 loc) · 79.5 KB
/
yolo-detection-adv.py
File metadata and controls
2214 lines (1801 loc) · 79.5 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 sys
import os
import cv2
import numpy as np
import torch
import pandas as pd
import datetime
import json
from pathlib import Path
from PyQt6.QtWidgets import (
QApplication,
QMainWindow,
QPushButton,
QLabel,
QVBoxLayout,
QHBoxLayout,
QFileDialog,
QWidget,
QProgressBar,
QComboBox,
QSlider,
QGroupBox,
QTabWidget,
QSplitter,
QCheckBox,
QListWidget,
QListWidgetItem,
QDialog,
QLineEdit,
QGridLayout,
QSpinBox,
QDoubleSpinBox,
QTextEdit,
QScrollArea,
QMenu,
QToolBar,
QStatusBar,
QMessageBox,
QDockWidget,
QTableWidget,
QTableWidgetItem,
QHeaderView,
QRadioButton,
QButtonGroup,
)
from PyQt6.QtCore import Qt, QTimer, QThread, pyqtSignal, QSize, QUrl, QRect, QPoint
from PyQt6.QtGui import (
QImage,
QPixmap,
QFont,
QIcon,
QPalette,
QColor,
QPainter,
QPen,
QAction,
)
import matplotlib.pyplot as plt
from matplotlib.backends.backend_qtagg import FigureCanvasQTAgg
from matplotlib.figure import Figure
from ultralytics import YOLO
from datetime import timedelta
import seaborn as sns
import webbrowser
import tempfile
from reportlab.lib.pagesizes import letter
from reportlab.pdfgen import canvas
from reportlab.lib import colors
from reportlab.platypus import (
SimpleDocTemplate,
Table,
TableStyle,
Paragraph,
Image,
Spacer,
)
from reportlab.lib.styles import getSampleStyleSheet
class VideoPlayerWidget(QWidget):
def __init__(self, parent=None):
super().__init__(parent)
self.layout = QVBoxLayout(self)
# Video display
self.video_frame = QLabel()
self.video_frame.setAlignment(Qt.AlignmentFlag.AlignCenter)
self.video_frame.setStyleSheet("background-color: #1e1e1e; color: white;")
self.video_frame.setText("Load a video to begin analysis")
self.video_frame.setMinimumSize(640, 480)
# Controls layout
self.controls_layout = QHBoxLayout()
# Play/Pause button
self.play_btn = QPushButton()
self.play_btn.setIcon(QIcon.fromTheme("media-playback-start"))
self.play_btn.setFixedSize(40, 40)
self.play_btn.setToolTip("Play/Pause")
self.play_btn.clicked.connect(self.toggle_playback)
# Previous frame button
self.prev_frame_btn = QPushButton()
self.prev_frame_btn.setIcon(QIcon.fromTheme("media-skip-backward"))
self.prev_frame_btn.setFixedSize(40, 40)
self.prev_frame_btn.setToolTip("Previous Frame")
self.prev_frame_btn.clicked.connect(self.prev_frame)
# Next frame button
self.next_frame_btn = QPushButton()
self.next_frame_btn.setIcon(QIcon.fromTheme("media-skip-forward"))
self.next_frame_btn.setFixedSize(40, 40)
self.next_frame_btn.setToolTip("Next Frame")
self.next_frame_btn.clicked.connect(self.next_frame)
# Position slider
self.position_slider = QSlider(Qt.Orientation.Horizontal)
self.position_slider.setToolTip("Video Position")
self.position_slider.sliderMoved.connect(self.set_position)
# Current time / total time label
self.time_label = QLabel("00:00 / 00:00")
# Speed control
self.speed_combo = QComboBox()
self.speed_combo.addItems(["0.25x", "0.5x", "1.0x", "1.5x", "2.0x"])
self.speed_combo.setCurrentIndex(2) # Default to 1.0x
self.speed_combo.setToolTip("Playback Speed")
self.speed_combo.currentIndexChanged.connect(self.change_speed)
# Add widgets to controls layout
self.controls_layout.addWidget(self.prev_frame_btn)
self.controls_layout.addWidget(self.play_btn)
self.controls_layout.addWidget(self.next_frame_btn)
self.controls_layout.addWidget(self.position_slider)
self.controls_layout.addWidget(self.time_label)
self.controls_layout.addWidget(self.speed_combo)
# Add everything to the main layout
self.layout.addWidget(self.video_frame)
self.layout.addLayout(self.controls_layout)
# Playback variables
self.timer = QTimer(self)
self.timer.timeout.connect(self.update_frame)
self.cap = None
self.is_playing = False
self.current_frame_idx = 0
self.total_frames = 0
self.fps = 0
self.speed_factor = 1.0
# Enable/disable controls
self.set_controls_enabled(False)
def load_video(self, video_path):
if not video_path or not os.path.exists(video_path):
return False
# Open video file
self.cap = cv2.VideoCapture(video_path)
if not self.cap.isOpened():
QMessageBox.critical(self, "Error", "Could not open video file.")
return False
# Get video properties
self.total_frames = int(self.cap.get(cv2.CAP_PROP_FRAME_COUNT))
self.fps = self.cap.get(cv2.CAP_PROP_FPS)
self.position_slider.setRange(0, self.total_frames - 1)
self.current_frame_idx = 0
# Update duration label
duration = self.total_frames / self.fps
self.time_label.setText(f"00:00 / {timedelta(seconds=int(duration))}")
# Read first frame
ret, frame = self.cap.read()
if ret:
self.display_frame(frame)
# Enable controls
self.set_controls_enabled(True)
return True
def display_frame(self, frame, detections=None):
if frame is None:
return
# If we have detections, draw them
if detections is not None:
frame = self.draw_detections(frame.copy(), detections)
# Convert frame to QPixmap and display
h, w, ch = frame.shape
bytes_per_line = ch * w
# Convert to RGB for Qt
rgb_image = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)
qt_image = QImage(
rgb_image.data, w, h, bytes_per_line, QImage.Format.Format_RGB888
)
# Scale to fit the label while maintaining aspect ratio
pixmap = QPixmap.fromImage(qt_image)
# Get label size
label_size = self.video_frame.size()
scaled_pixmap = pixmap.scaled(label_size, Qt.AspectRatioMode.KeepAspectRatio)
self.video_frame.setPixmap(scaled_pixmap)
def draw_detections(self, frame, detections):
# If detections is a YOLOv8 result, use its plot function
if (
hasattr(detections, "__iter__")
and len(detections) > 0
and hasattr(detections[0], "plot")
):
annotated_frame = detections[0].plot()
return annotated_frame
# Otherwise, it might be our custom detection format
# Example: draw bounding boxes for people
if isinstance(detections, dict):
for det_type, instances in detections.items():
color = (0, 255, 0) # Green for falls
if det_type == "attacks":
color = (0, 0, 255) # Red for attacks
elif det_type == "accidents":
color = (255, 0, 0) # Blue for accidents
for instance in instances:
if isinstance(instance, tuple) and len(instance) >= 2:
# Expected format: (frame_num, details)
details = instance[1]
if "bbox" in details:
x1, y1, x2, y2 = details["bbox"]
cv2.rectangle(
frame, (int(x1), int(y1)), (int(x2), int(y2)), color, 2
)
cv2.putText(
frame,
det_type,
(int(x1), int(y1) - 10),
cv2.FONT_HERSHEY_SIMPLEX,
0.9,
color,
2,
)
return frame
def toggle_playback(self):
if not self.cap:
return
if self.is_playing:
self.timer.stop()
self.play_btn.setIcon(QIcon.fromTheme("media-playback-start"))
else:
interval = int(1000 / (self.fps * self.speed_factor))
self.timer.start(max(1, interval))
self.play_btn.setIcon(QIcon.fromTheme("media-playback-pause"))
self.is_playing = not self.is_playing
def update_frame(self):
if not self.cap:
return
# Check if we've reached the end
if self.current_frame_idx >= self.total_frames - 1:
self.timer.stop()
self.is_playing = False
self.play_btn.setIcon(QIcon.fromTheme("media-playback-start"))
return
# Increment frame index
self.current_frame_idx += 1
# Set position in video
self.cap.set(cv2.CAP_PROP_POS_FRAMES, self.current_frame_idx)
# Read frame
ret, frame = self.cap.read()
if ret:
# Update UI
self.display_frame(frame)
self.position_slider.setValue(self.current_frame_idx)
# Update time label
current_time = self.current_frame_idx / self.fps
total_time = self.total_frames / self.fps
self.time_label.setText(
f"{timedelta(seconds=int(current_time))} / {timedelta(seconds=int(total_time))}"
)
def next_frame(self):
if not self.cap or self.current_frame_idx >= self.total_frames - 1:
return
self.current_frame_idx += 1
self.cap.set(cv2.CAP_PROP_POS_FRAMES, self.current_frame_idx)
ret, frame = self.cap.read()
if ret:
self.display_frame(frame)
self.position_slider.setValue(self.current_frame_idx)
# Update time label
current_time = self.current_frame_idx / self.fps
total_time = self.total_frames / self.fps
self.time_label.setText(
f"{timedelta(seconds=int(current_time))} / {timedelta(seconds=int(total_time))}"
)
def prev_frame(self):
if not self.cap or self.current_frame_idx <= 0:
return
self.current_frame_idx -= 1
self.cap.set(cv2.CAP_PROP_POS_FRAMES, self.current_frame_idx)
ret, frame = self.cap.read()
if ret:
self.display_frame(frame)
self.position_slider.setValue(self.current_frame_idx)
# Update time label
current_time = self.current_frame_idx / self.fps
total_time = self.total_frames / self.fps
self.time_label.setText(
f"{timedelta(seconds=int(current_time))} / {timedelta(seconds=int(total_time))}"
)
def set_position(self, position):
if not self.cap:
return
self.current_frame_idx = position
self.cap.set(cv2.CAP_PROP_POS_FRAMES, position)
ret, frame = self.cap.read()
if ret:
self.display_frame(frame)
# Update time label
current_time = position / self.fps
total_time = self.total_frames / self.fps
self.time_label.setText(
f"{timedelta(seconds=int(current_time))} / {timedelta(seconds=int(total_time))}"
)
def change_speed(self, index):
speeds = [0.25, 0.5, 1.0, 1.5, 2.0]
self.speed_factor = speeds[index]
# Update timer interval if playing
if self.is_playing:
self.timer.stop()
interval = int(1000 / (self.fps * self.speed_factor))
self.timer.start(max(1, interval))
def set_controls_enabled(self, enabled):
self.play_btn.setEnabled(enabled)
self.prev_frame_btn.setEnabled(enabled)
self.next_frame_btn.setEnabled(enabled)
self.position_slider.setEnabled(enabled)
self.speed_combo.setEnabled(enabled)
def update_frame_with_detection(self, frame, detections):
self.display_frame(frame, detections)
class RegionOfInterestDialog(QDialog):
def __init__(self, frame, parent=None):
super().__init__(parent)
self.setWindowTitle("Select Region of Interest")
self.frame = frame
self.roi = None
self.drawing = False
self.start_point = QPoint()
self.end_point = QPoint()
# Set up UI
layout = QVBoxLayout()
self.instructions = QLabel(
"Click and drag to select a region of interest.\n"
"Press OK to confirm, or Cancel to use the entire frame."
)
layout.addWidget(self.instructions)
self.frame_label = QLabel()
self.frame_label.setMinimumSize(640, 480)
layout.addWidget(self.frame_label)
# Display initial frame
self.display_frame()
# Buttons
button_layout = QHBoxLayout()
self.reset_btn = QPushButton("Reset")
self.reset_btn.clicked.connect(self.reset_selection)
self.ok_button = QPushButton("OK")
self.ok_button.clicked.connect(self.accept)
self.ok_button.setEnabled(False)
self.cancel_button = QPushButton("Cancel")
self.cancel_button.clicked.connect(self.reject)
button_layout.addWidget(self.reset_btn)
button_layout.addWidget(self.ok_button)
button_layout.addWidget(self.cancel_button)
layout.addLayout(button_layout)
self.setLayout(layout)
def display_frame(self):
frame_copy = self.frame.copy()
# Draw current selection
if self.start_point and self.end_point:
x1, y1 = self.start_point.x(), self.start_point.y()
x2, y2 = self.end_point.x(), self.end_point.y()
cv2.rectangle(frame_copy, (x1, y1), (x2, y2), (0, 255, 0), 2)
# Convert frame to QPixmap
h, w, ch = frame_copy.shape
bytes_per_line = ch * w
rgb_image = cv2.cvtColor(frame_copy, cv2.COLOR_BGR2RGB)
qt_image = QImage(
rgb_image.data, w, h, bytes_per_line, QImage.Format.Format_RGB888
)
pixmap = QPixmap.fromImage(qt_image)
# Resize to fit label
label_size = self.frame_label.size()
scaled_pixmap = pixmap.scaled(label_size, Qt.AspectRatioMode.KeepAspectRatio)
self.frame_label.setPixmap(scaled_pixmap)
def mousePressEvent(self, event):
if event.button() == Qt.MouseButton.LeftButton:
# Get position relative to label
pos = self.frame_label.mapFromParent(event.pos())
if self.frame_label.rect().contains(pos):
self.drawing = True
# Adjust coordinates based on scaled image
pixmap = self.frame_label.pixmap()
pixmap_rect = QRect(
(self.frame_label.width() - pixmap.width()) // 2,
(self.frame_label.height() - pixmap.height()) // 2,
pixmap.width(),
pixmap.height(),
)
if pixmap_rect.contains(pos):
# Convert to original image coordinates
x_ratio = self.frame.shape[1] / pixmap.width()
y_ratio = self.frame.shape[0] / pixmap.height()
x = int((pos.x() - pixmap_rect.x()) * x_ratio)
y = int((pos.y() - pixmap_rect.y()) * y_ratio)
self.start_point = QPoint(x, y)
self.end_point = QPoint(x, y)
self.display_frame()
def mouseMoveEvent(self, event):
if self.drawing:
# Get position relative to label
pos = self.frame_label.mapFromParent(event.pos())
# Adjust coordinates based on scaled image
pixmap = self.frame_label.pixmap()
pixmap_rect = QRect(
(self.frame_label.width() - pixmap.width()) // 2,
(self.frame_label.height() - pixmap.height()) // 2,
pixmap.width(),
pixmap.height(),
)
if pixmap_rect.contains(pos):
# Convert to original image coordinates
x_ratio = self.frame.shape[1] / pixmap.width()
y_ratio = self.frame.shape[0] / pixmap.height()
x = int((pos.x() - pixmap_rect.x()) * x_ratio)
y = int((pos.y() - pixmap_rect.y()) * y_ratio)
self.end_point = QPoint(x, y)
self.display_frame()
def mouseReleaseEvent(self, event):
if event.button() == Qt.MouseButton.LeftButton and self.drawing:
self.drawing = False
# Normalize coordinates (ensure start is top-left, end is bottom-right)
x1 = min(self.start_point.x(), self.end_point.x())
y1 = min(self.start_point.y(), self.end_point.y())
x2 = max(self.start_point.x(), self.end_point.x())
y2 = max(self.start_point.y(), self.end_point.y())
self.start_point = QPoint(x1, y1)
self.end_point = QPoint(x2, y2)
# Store ROI
self.roi = (x1, y1, x2, y2)
# Enable OK button if we have a valid ROI
if x2 > x1 and y2 > y1:
self.ok_button.setEnabled(True)
self.display_frame()
def reset_selection(self):
self.start_point = QPoint()
self.end_point = QPoint()
self.roi = None
self.ok_button.setEnabled(False)
self.display_frame()
class CustomDetectionRuleDialog(QDialog):
def __init__(self, parent=None):
super().__init__(parent)
self.setWindowTitle("Custom Detection Rule")
self.setMinimumWidth(500)
layout = QVBoxLayout()
# Rule name
name_layout = QHBoxLayout()
name_layout.addWidget(QLabel("Rule Name:"))
self.name_edit = QLineEdit()
self.name_edit.setPlaceholderText("E.g., Crawling person")
name_layout.addWidget(self.name_edit)
layout.addLayout(name_layout)
# Rule type
type_group = QGroupBox("Detection Type")
type_layout = QVBoxLayout()
self.type_buttons = QButtonGroup(self)
self.fall_radio = QRadioButton("Fall")
self.attack_radio = QRadioButton("Attack")
self.accident_radio = QRadioButton("Accident")
self.custom_radio = QRadioButton("Custom")
self.type_buttons.addButton(self.fall_radio, 1)
self.type_buttons.addButton(self.attack_radio, 2)
self.type_buttons.addButton(self.accident_radio, 3)
self.type_buttons.addButton(self.custom_radio, 4)
self.fall_radio.setChecked(True)
type_layout.addWidget(self.fall_radio)
type_layout.addWidget(self.attack_radio)
type_layout.addWidget(self.accident_radio)
type_layout.addWidget(self.custom_radio)
type_group.setLayout(type_layout)
layout.addWidget(type_group)
# Detection parameters
params_group = QGroupBox("Detection Parameters")
params_layout = QGridLayout()
# Confidence threshold
params_layout.addWidget(QLabel("Confidence Threshold:"), 0, 0)
self.conf_threshold = QDoubleSpinBox()
self.conf_threshold.setRange(0.1, 1.0)
self.conf_threshold.setSingleStep(0.05)
self.conf_threshold.setValue(0.5)
params_layout.addWidget(self.conf_threshold, 0, 1)
# Time threshold
params_layout.addWidget(QLabel("Minimum Duration (frames):"), 1, 0)
self.time_threshold = QSpinBox()
self.time_threshold.setRange(1, 100)
self.time_threshold.setValue(5)
params_layout.addWidget(self.time_threshold, 1, 1)
# Person count
params_layout.addWidget(QLabel("Minimum People Count:"), 2, 0)
self.person_count = QSpinBox()
self.person_count.setRange(1, 10)
self.person_count.setValue(1)
params_layout.addWidget(self.person_count, 2, 1)
params_group.setLayout(params_layout)
layout.addWidget(params_group)
# Advanced conditions
advanced_group = QGroupBox("Advanced Conditions")
advanced_layout = QVBoxLayout()
advanced_layout.addWidget(QLabel("Custom Condition Logic:"))
self.condition_edit = QTextEdit()
self.condition_edit.setPlaceholderText(
"Example conditions:\n"
"- Head position < 0.4 * body height\n"
"- Distance between people < 100 pixels\n"
"- Person area decreased by > 40%"
)
self.condition_edit.setMaximumHeight(100)
advanced_layout.addWidget(self.condition_edit)
advanced_group.setLayout(advanced_layout)
layout.addWidget(advanced_group)
# Buttons
button_layout = QHBoxLayout()
self.save_btn = QPushButton("Save Rule")
self.save_btn.clicked.connect(self.accept)
self.cancel_btn = QPushButton("Cancel")
self.cancel_btn.clicked.connect(self.reject)
button_layout.addWidget(self.save_btn)
button_layout.addWidget(self.cancel_btn)
layout.addLayout(button_layout)
self.setLayout(layout)
def get_rule_data(self):
rule_type = "fall"
if self.attack_radio.isChecked():
rule_type = "attack"
elif self.accident_radio.isChecked():
rule_type = "accident"
elif self.custom_radio.isChecked():
rule_type = "custom"
return {
"name": self.name_edit.text(),
"type": rule_type,
"confidence_threshold": self.conf_threshold.value(),
"time_threshold": self.time_threshold.value(),
"person_count": self.person_count.value(),
"custom_conditions": self.condition_edit.toPlainText(),
}
class VideoProcessingThread(QThread):
update_frame = pyqtSignal(np.ndarray, list)
update_progress = pyqtSignal(int)
processing_finished = pyqtSignal(dict)
def __init__(
self, video_path, model, conf_threshold=0.5, roi=None, custom_rules=None
):
super().__init__()
self.video_path = video_path
self.model = model
self.conf_threshold = conf_threshold
self.roi = roi # Region of interest (x1, y1, x2, y2)
self.custom_rules = custom_rules or []
self.running = True
def run(self):
cap = cv2.VideoCapture(self.video_path)
total_frames = int(cap.get(cv2.CAP_PROP_FRAME_COUNT))
fps = cap.get(cv2.CAP_PROP_FPS)
incidents = {"falls": [], "attacks": [], "accidents": []}
# Add custom rule types if any
for rule in self.custom_rules:
if rule["type"] not in incidents and rule["type"] != "custom":
incidents[rule["type"]] = []
# Keep track of recent frames for temporal analysis
recent_frames = []
max_recent_frames = 10
# Tracks for people
tracks = {}
frame_count = 0
while self.running and cap.isOpened():
ret, frame = cap.read()
if not ret:
break
# Apply ROI if specified
if self.roi:
x1, y1, x2, y2 = self.roi
frame_roi = frame[y1:y2, x1:x2]
# Run YOLOv8 inference on ROI
results = self.model(frame_roi, verbose=False, conf=self.conf_threshold)
# Adjust bounding box coordinates back to original frame
if hasattr(results[0], "boxes") and len(results[0].boxes) > 0:
boxes = results[0].boxes.xyxy.cpu().numpy()
boxes[:, 0] += x1
boxes[:, 1] += y1
boxes[:, 2] += x1
boxes[:, 3] += y1
# Now we need to update the results with adjusted boxes...
# This is simplified - would need proper implementation
else:
# Run YOLOv8 inference on full frame
results = self.model(frame, verbose=False, conf=self.conf_threshold)
# Add current frame to recent frames list
if len(recent_frames) >= max_recent_frames:
recent_frames.pop(0)
recent_frames.append((frame, results))
# Process results to detect anomalies
detections = self.process_detections(
results, frame_count, fps, recent_frames, tracks
)
# Update tracks
self.update_tracks(results, frame_count, tracks)
# Update incidents dictionary
for key in incidents:
if key in detections and detections[key]:
# Add bounding box to detection
if hasattr(results[0], "boxes") and len(results[0].boxes) > 0:
for det in detections[key]:
# Match detection to a box
# Simplified - would need proper matching logic
box = results[0].boxes.xyxy[0].cpu().numpy()
detections[key][0]["bbox"] = box
incidents[key].append((frame_count, detections[key]))
# Apply any custom rules
for rule in self.custom_rules:
detections = self.apply_custom_rule(
rule, results, frame_count, fps, recent_frames, tracks
)
if detections:
rule_type = rule["type"]
if rule_type == "custom":
rule_type = rule["name"].lower().replace(" ", "_")
if rule_type not in incidents:
incidents[rule_type] = []
incidents[rule_type].append((frame_count, detections))
# Emit signals for UI updates
self.update_frame.emit(frame, results)
progress = int((frame_count / total_frames) * 100)
self.update_progress.emit(progress)
frame_count += 1
cap.release()
self.processing_finished.emit(incidents)
def update_tracks(self, results, frame_count, tracks):
# Simple tracking implementation
# In a real application, would use a more sophisticated tracker
if not hasattr(results[0], "boxes") or len(results[0].boxes) == 0:
return
boxes = results[0].boxes.xyxy.cpu().numpy()
# Match current detections to existing tracks
matched_tracks = set()
for i, box in enumerate(boxes):
best_match = None
best_iou = 0
for track_id, track_info in tracks.items():
last_box = track_info["boxes"][-1]
iou = self.calculate_iou(box, last_box)
if iou > 0.3 and iou > best_iou: # IOU threshold
best_match = track_id
best_iou = iou
if best_match is not None:
# Update existing track
tracks[best_match]["boxes"].append(box)
tracks[best_match]["frames"].append(frame_count)
matched_tracks.add(best_match)
else:
# Create new track
new_id = max(tracks.keys(), default=0) + 1
tracks[new_id] = {"boxes": [box], "frames": [frame_count]}
# Remove old tracks (not matched for several frames)
track_ids = list(tracks.keys())
for track_id in track_ids:
if track_id not in matched_tracks:
if (
frame_count - tracks[track_id]["frames"][-1] > 10
): # Remove after 10 frames of absence
del tracks[track_id]
def calculate_iou(self, box1, box2):
# Calculate intersection over union between two boxes
x1_1, y1_1, x2_1, y2_1 = box1
x1_2, y1_2, x2_2, y2_2 = box2
# Calculate intersection
x1_i = max(x1_1, x1_2)
y1_i = max(y1_1, y1_2)
x2_i = min(x2_1, x2_2)
y2_i = min(y2_1, y2_2)
# Check if boxes overlap
if x2_i < x1_i or y2_i < y1_i:
return 0.0
intersection = (x2_i - x1_i) * (y2_i - y1_i)
# Calculate areas
area1 = (x2_1 - x1_1) * (y2_1 - y1_1)
area2 = (x2_2 - x1_2) * (y2_2 - y1_2)
# Calculate IoU
union = area1 + area2 - intersection
iou = intersection / union
return iou
def process_detections(self, results, frame_count, fps, recent_frames, tracks):
# This is a simplified detection logic
# In a real application, you would implement more sophisticated algorithms
detections = {}
# Example: Analyze poses to detect falls
# This requires pose estimation from YOLOv8 pose model
if hasattr(results[0], "keypoints") and results[0].keypoints is not None:
poses = results[0].keypoints.data
for i, pose in enumerate(poses):
keypoints = pose.cpu().numpy()
if self.detect_fall(keypoints):
confidence = 0.8
detections["falls"] = [
{
"confidence": confidence,
"time": frame_count / fps,
"person_idx": i,
}
]
# Look for violent actions (simplified)
boxes = results[0].boxes if hasattr(results[0], "boxes") else None
if boxes is not None and len(boxes) >= 2: # Multiple people detected
if self.detect_attack(boxes):
detections["attacks"] = [{"confidence": 0.7, "time": frame_count / fps}]
# Detect accidents (simplified logic)
if len(recent_frames) >= 3:
if self.detect_accident(recent_frames, frame_count, fps):
detections["accidents"] = [
{"confidence": 0.6, "time": frame_count / fps}
]
return detections
def detect_fall(self, pose_keypoints):
# Fall detection logic
# Check if head keypoint is close to ground level
if len(pose_keypoints) >= 17: # COCO keypoints format
nose = pose_keypoints[0] # Nose keypoint
left_ankle = pose_keypoints[15] # Left ankle keypoint
right_ankle = pose_keypoints[16] # Right ankle keypoint
# Check if keypoints are valid (visible)
if nose[2] > 0.5 and (left_ankle[2] > 0.5 or right_ankle[2] > 0.5):
head_y = nose[1]
ankle_y = (
max(left_ankle[1], right_ankle[1])
if left_ankle[2] > 0.5 and right_ankle[2] > 0.5
else left_ankle[1] if left_ankle[2] > 0.5 else right_ankle[1]
)
# Check if head is close to ground level (near ankles)
if head_y > ankle_y * 0.8:
# Check body orientation (horizontal)
# Get shoulder keypoints
left_shoulder = pose_keypoints[5]
right_shoulder = pose_keypoints[6]
if left_shoulder[2] > 0.5 and right_shoulder[2] > 0.5:
shoulder_diff_y = abs(left_shoulder[1] - right_shoulder[1])
shoulder_diff_x = abs(left_shoulder[0] - right_shoulder[0])
# If shoulders are more horizontal than vertical
if shoulder_diff_y < shoulder_diff_x:
return True
return False
def detect_attack(self, boxes):
# Attack detection
if not hasattr(boxes, "xyxy") or len(boxes.xyxy) < 2:
return False
box_data = boxes.xyxy.cpu().numpy()
# Check for close proximity between people
for i in range(len(box_data)):
for j in range(i + 1, len(box_data)):
box1 = box_data[i]
box2 = box_data[j]
# Calculate centers
center1 = ((box1[0] + box1[2]) / 2, (box1[1] + box1[3]) / 2)
center2 = ((box2[0] + box2[2]) / 2, (box2[1] + box2[3]) / 2)
# Calculate distance between centers
distance = np.sqrt(
(center1[0] - center2[0]) ** 2 + (center1[1] - center2[1]) ** 2
)
# Calculate average box size for reference
avg_width = (box1[2] - box1[0] + box2[2] - box2[0]) / 2
# If people are very close (distance less than average width)
if distance < avg_width * 0.8:
return True
return False
def detect_accident(self, recent_frames, frame_count, fps):
# Simplified accident detection
# Looking for sudden movements or changes in position
if len(recent_frames) < 3:
return False
# Get current and previous frames
current_frame, current_results = recent_frames[-1]
prev_frame, prev_results = recent_frames[
-3
] # Skip one frame to see more pronounced changes
# Check if we have detections in both frames
if not hasattr(current_results[0], "boxes") or not hasattr(
prev_results[0], "boxes"
):
return False
current_boxes = (
current_results[0].boxes.xyxy.cpu().numpy()
if len(current_results[0].boxes) > 0
else []
)
prev_boxes = (
prev_results[0].boxes.xyxy.cpu().numpy()
if len(prev_results[0].boxes) > 0
else []
)
if len(current_boxes) == 0 or len(prev_boxes) == 0:
return False
# Calculate motion between frames
max_motion = 0
for i, curr_box in enumerate(current_boxes):
# Find closest box in previous frame
best_iou = 0
best_motion = 0
for prev_box in prev_boxes:
iou = self.calculate_iou(curr_box, prev_box)
if iou > 0.3: # Assume it's the same person if IoU > 0.3
# Calculate center points
curr_center = (
(curr_box[0] + curr_box[2]) / 2,
(curr_box[1] + curr_box[3]) / 2,
)
prev_center = (
(prev_box[0] + prev_box[2]) / 2,
(prev_box[1] + prev_box[3]) / 2,
)
# Calculate motion (displacement)
motion = np.sqrt(
(curr_center[0] - prev_center[0]) ** 2
+ (curr_center[1] - prev_center[1]) ** 2
)
if iou > best_iou:
best_iou = iou
best_motion = motion
if best_iou > 0 and best_motion > max_motion:
max_motion = best_motion
# Consider as accident if motion exceeds threshold
# This threshold would need tuning for real applications
motion_threshold = 50 # pixels