-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathYOLO_Video.py
45 lines (37 loc) · 1.57 KB
/
YOLO_Video.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
from ultralytics import YOLO
import cv2
import math
def video_detection(path_x):
video_capture = path_x
# Create a Webcam Object
cap = cv2.VideoCapture(video_capture)
# frame_width = int(cap.get(3))
# frame_height = int(cap.get(4))
model = YOLO("YOLO-Weights/latestAccident.pt")
classnames = ['Accident']
while True:
success, img = cap.read()
results = model(img, stream=True)
for r in results:
boxes = r.boxes
for box in boxes:
x1, y1, x2, y2 = box.xyxy[0]
x1, y1, x2, y2 = int(x1), int(y1), int(x2), int(y2)
print(x1, y1, x2, y2)
conf = math.ceil((box.conf[0] * 100)) / 100
cls = int(box.cls[0])
try:
class_name = classnames[cls]
label = f'{class_name}{conf}'
t_size = cv2.getTextSize(label, 0, fontScale=1, thickness=2)[0]
print(t_size)
c2 = x1 + t_size[0], y1 - t_size[1] - 3
color = (85, 45, 255)
if conf > 0.5:
cv2.rectangle(img, (x1, y1), (x2, y2), color, 3)
cv2.rectangle(img, (x1, y1), c2, color, -1, cv2.LINE_AA) # filled
cv2.putText(img, label, (x1, y1 - 2), 0, 1, [255, 255, 255], thickness=1, lineType=cv2.LINE_AA)
except IndexError:
print(f"Invalid class index: {cls}")
yield img
cv2.destroyAllWindows()