yolov8 调用摄像头
时间: 2023-10-26 22:05:48 浏览: 252
yolov5调用摄像头
5星 · 资源好评率100%
要使用YOLOv8调用摄像头,您需要安装所需的软件库和工具,并编写一些代码来实现这一功能。下面是一个示例代码段,展示了如何使用YOLOv8和OpenCV来实现摄像头检测:
```python
import cv2
from darknet import Darknet
# 加载YOLOv8模型
config_path = 'path_to_yolov8_config_file'
weights_path = 'path_to_yolov8_weights_file'
class_labels_path = 'path_to_class_labels_file'
net = Darknet(config_path)
net.load_weights(weights_path)
class_labels = net.load_class_names(class_labels_path)
# 打开摄像头
cap = cv2.VideoCapture(0)
while True:
ret, frame = cap.read()
# 调整图像尺寸并进行检测
resized_frame = cv2.resize(frame, (net.width, net.height))
detections = net.detect(resized_frame)
# 在图像上绘制边界框和类别标签
for detection in detections:
x, y, w, h, class_id, confidence = detection
label = class_labels[class_id]
cv2.rectangle(frame, (x, y), (x + w, y + h), (0, 255, 0), 2)
cv2.putText(frame, f'{label}: {confidence}', (x, y - 10), cv2.FONT_HERSHEY_SIMPLEX, 0.9, (0, 255, 0), 2)
# 显示结果
cv2.imshow('YOLOv8', frame)
# 按下q键退出循环
if cv2.waitKey(1) & 0xFF == ord('q'):
break
# 释放资源
cap.release()
cv2.destroyAllWindows()
```
请确保将 `path_to_yolov8_config_file` ,`path_to_yolov8_weights_file` 和 `path_to_class_labels_file` 替换为YOLOv8配置文件、权重文件和类别标签文件的路径。
阅读全文