yolov5调用usb摄像头
时间: 2023-10-16 14:09:49 浏览: 118
可以使用OpenCV库来调用USB摄像头,并将其输入到YOLOv5模型中进行目标检测。以下是一个简单的示例代码:
```python
import cv2
import torch
from models.experimental import attempt_load
from utils.general import non_max_suppression, scale_coords, plot_one_box
# 加载YOLOv5模型
model = attempt_load('yolov5s.pt', map_location=torch.device('cpu'))
# 打开USB摄像头
cap = cv2.VideoCapture(0)
while True:
# 读取一帧图像
ret, img = cap.read()
# 将图像转换为RGB格式
img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)
# 运行YOLOv5模型进行目标检测
results = model(img)
# 对检测结果进行后处理
results = non_max_suppression(results, conf_thres=0.5, iou_thres=0.5)
for result in results:
if result is not None:
# 缩放检测框坐标到原始图像尺寸
result[:, :4] = scale_coords(img.shape[1:], result[:, :4], img.shape[:2]).round()
# 绘制检测框和类别标签
for *xyxy, conf, cls in result:
label = f'{model.names[int(cls)]} {conf:.2f}'
plot_one_box(xyxy, img, label=label, color=(0, 255, 0))
# 显示结果图像
cv2.imshow('result', img)
# 按下q键退出循环
if cv2.waitKey(1) == ord('q'):
break
# 释放摄像头并关闭窗口
cap.release()
cv2.destroyAllWindows()
```
阅读全文