yolov8启用摄像头
时间: 2023-08-26 20:05:10 浏览: 138
要使用 YOLOv8 模型启用摄像头,您需要安装 OpenCV 库并编写一些 Python 代码。
以下是一个简单的 Python 代码示例,可用于使用 YOLOv8 模型从摄像头捕获视频并检测物体:
```python
import cv2
import numpy as np
import time
from yolov8 import YOLOv8
# Load YOLOv8 model
yolo = YOLOv8()
# Open camera
cap = cv2.VideoCapture(0)
while True:
# Capture frame-by-frame
ret, frame = cap.read()
if ret:
# Run object detection
start_time = time.time()
boxes, confidences, class_ids = yolo.detect(frame)
end_time = time.time()
print("Inference time: {:.2f} ms".format((end_time - start_time) * 1000))
# Draw boxes and labels on the frame
for i in range(len(boxes)):
x, y, w, h = boxes[i]
label = yolo.class_names[class_ids[i]]
cv2.rectangle(frame, (x, y), (x + w, y + h), (0, 255, 0), 2)
cv2.putText(frame, label, (x, y - 10), cv2.FONT_HERSHEY_SIMPLEX, 0.5, (0, 255, 0), 2)
# Display the resulting frame
cv2.imshow('frame', frame)
# Press 'q' to quit
if cv2.waitKey(1) & 0xFF == ord('q'):
break
# Release the capture
cap.release()
cv2.destroyAllWindows()
```
此代码使用 YOLOv8 模型从摄像头捕获视频并检测物体。在每个帧上运行对象检测时,它会绘制边框和标签,并在屏幕上显示帧。按 'q' 键退出。
阅读全文