-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathyolotest.py
69 lines (53 loc) · 1.79 KB
/
yolotest.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
from ultralytics import YOLO
import cv2
import numpy as np
# Load the YOLO model
model = YOLO('yolov8n.pt')
annotations = []
classes = []
def process_frame(frame):
global annotations
global classes
# Convert frame from BGR to RGB
frame_rgb = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)
# Perform object detection on the frame
results = model(frame_rgb, verbose=True)
print("Results:", results)
# Ensure that results is not empty
if results:
# Get the first result object
result = results[0]
annotations = result.boxes.xyxy.tolist()
classes = [model.names[int(i)] for i in result.boxes.cls]
# print("\n\n\n")
# print("ANNOTATIONS",annotations)
# print("\n\n\n")
# print("CLASSES",classes)
# print("\n\n\n")
# Get annotated image with bounding boxes
annotated_image = result.plot()
# Convert annotated image from numpy array to BGR format
annotated_image_bgr = cv2.cvtColor(np.array(annotated_image), cv2.COLOR_RGB2BGR)
# Display the frame with bounding boxes
cv2.imshow('YOLO Object Detection', annotated_image_bgr)
else:
# Display the original frame if no results found
cv2.imshow('YOLO Object Detection', frame)
annotations = {}
cap = cv2.VideoCapture(0)
while True:
# Capture frame from webcam
ret, frame = cap.read()
if not ret:
break
w = frame.shape[1]
h = frame.shape[0]
s = min(w, h)
# crop width to center s
frame = frame[(h-s)//2:(h+s)//2, (w-s)//2:(w+s)//2]
# resize to 512x512
frame = cv2.resize(frame, (512, 512))
# Convert frame to JPEG format
_, frame_data = cv2.imencode('.jpg', frame)
process_frame(frame)
cv2.destroyAllWindows()