-
Notifications
You must be signed in to change notification settings - Fork 597
/
yolov8.py
113 lines (67 loc) · 3.2 KB
/
yolov8.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
import torch
import numpy as np
import cv2
from time import time
from ultralytics import YOLO
from supervision.draw.color import ColorPalette
from supervision.tools.detections import Detections, BoxAnnotator
class ObjectDetection:
def __init__(self, capture_index):
self.capture_index = capture_index
self.device = 'cuda' if torch.cuda.is_available() else 'cpu'
print("Using Device: ", self.device)
self.model = self.load_model()
self.CLASS_NAMES_DICT = self.model.model.names
self.box_annotator = BoxAnnotator(color=ColorPalette(), thickness=3, text_thickness=3, text_scale=1.5)
def load_model(self):
model = YOLO("yolov8n.pt") # load a pretrained YOLOv8n model
model.fuse()
return model
def predict(self, frame):
results = self.model(frame)
return results
def plot_bboxes(self, results, frame):
xyxys = []
confidences = []
class_ids = []
# Extract detections for person class
for result in results[0]:
class_id = result.boxes.cls.cpu().numpy().astype(int)
if class_id == 0:
xyxys.append(result.boxes.xyxy.cpu().numpy())
confidences.append(result.boxes.conf.cpu().numpy())
class_ids.append(result.boxes.cls.cpu().numpy().astype(int))
# Setup detections for visualization
detections = Detections(
xyxy=results[0].boxes.xyxy.cpu().numpy(),
confidence=results[0].boxes.conf.cpu().numpy(),
class_id=results[0].boxes.cls.cpu().numpy().astype(int),
)
# Format custom labels
self.labels = [f"{self.CLASS_NAMES_DICT[class_id]} {confidence:0.2f}"
for _, confidence, class_id, tracker_id
in detections]
# Annotate and display frame
frame = self.box_annotator.annotate(frame=frame, detections=detections, labels=self.labels)
return frame
def __call__(self):
cap = cv2.VideoCapture(self.capture_index)
assert cap.isOpened()
cap.set(cv2.CAP_PROP_FRAME_WIDTH, 1280)
cap.set(cv2.CAP_PROP_FRAME_HEIGHT, 720)
while True:
start_time = time()
ret, frame = cap.read()
assert ret
results = self.predict(frame)
frame = self.plot_bboxes(results, frame)
end_time = time()
fps = 1/np.round(end_time - start_time, 2)
cv2.putText(frame, f'FPS: {int(fps)}', (20,70), cv2.FONT_HERSHEY_SIMPLEX, 1.5, (0,255,0), 2)
cv2.imshow('YOLOv8 Detection', frame)
if cv2.waitKey(5) & 0xFF == 27:
break
cap.release()
cv2.destroyAllWindows()
detector = ObjectDetection(capture_index=0)
detector()