基于yolo v5的汽车检测代码
时间: 2024-03-09 19:49:08 浏览: 59
以下是基于 YOLOv5 的汽车检测代码示例:
```python
import cv2
import torch
from models.experimental import attempt_load
from utils.general import non_max_suppression, scale_coords
from utils.torch_utils import select_device
# 加载模型
weights = 'path/to/weights.pt' # 模型权重文件路径
device = select_device('') # 自动选择最优设备
model = attempt_load(weights, map_location=device) # 加载模型
# 设置参数
img_size = 640 # 输入图像大小
conf_thres = 0.4 # 置信度阈值
iou_thres = 0.5 # NMS 阈值
# 打开摄像头
cap = cv2.VideoCapture(0)
while True:
# 读取图像
ret, img0 = cap.read()
# 图像预处理
img = cv2.resize(img0, (img_size, img_size))
img = img[:, :, ::-1].transpose(2, 0, 1) # BGR to RGB, to 3x416x416
img = np.ascontiguousarray(img)
# 推理
img = torch.from_numpy(img).to(device)
img = img.float() / 255.0
if img.ndimension() == 3:
img = img.unsqueeze(0)
pred = model(img)[0]
pred = non_max_suppression(pred, conf_thres, iou_thres)[0]
# 后处理
if pred is not None and len(pred) > 0:
pred[:, :4] = scale_coords(img.shape[2:], pred[:, :4], img0.shape).round()
for c in pred[:, -1].unique():
n = (pred[:, -1] == c).sum()
print(f'{n} {names[int(c)]}{"s" * (n > 1)},', end=' ')
for *xyxy, conf, cls in pred:
label = f'{names[int(cls)]} {conf:.2f}'
plot_one_box(xyxy, img0, label=label, color=colors[int(cls)], line_thickness=3)
# 显示图像
cv2.imshow('img', img0)
if cv2.waitKey(1) == ord('q'):
break
# 释放摄像头
cap.release()
cv2.destroyAllWindows()
```
需要注意的是,这只是一个示例代码,实际应用中需要根据具体情况进行修改。此外,还需要准备好模型权重文件、类别名称等相关资源。
阅读全文