yolov5 行人检测
时间: 2023-08-29 17:12:47 浏览: 56
YOLOv5是一种目标检测算法,可以用于检测图像中的行人。你可以使用YOLOv5预训练模型或者自己训练一个模型。以下是一个使用YOLOv5检测行人的简单示例:
1. 安装YOLOv5:可以从YOLOv5的官方GitHub仓库中获取源代码,然后按照官方文档的说明进行安装。
2. 下载行人检测预训练模型:YOLOv5提供了一些预训练模型,可以在官方GitHub仓库或者官网上进行下载。
3. 加载预训练模型:使用YOLOv5提供的API或者自己编写代码来加载预训练模型。
4. 进行行人检测:使用加载的模型对输入的图像进行行人检测,并输出检测结果。
下面是一个使用YOLOv5检测行人的Python示例代码:
```python
import torch
import cv2
import numpy as np
from models.experimental import attempt_load
from utils.general import non_max_suppression, scale_coords
from utils.torch_utils import select_device
# 加载预训练模型
weights = 'yolov5s.pt'
device = select_device('cpu')
model = attempt_load(weights, map_location=device)
model.eval()
# 定义类别名称
class_names = ['person']
# 加载图像
img = cv2.imread('test.jpg')
# 将图像转换为Tensor
img = torch.from_numpy(img.transpose(2, 0, 1)).float() / 255.0
img = img.unsqueeze(0)
# 将图像输入模型中进行检测
with torch.no_grad():
detections = model(img, augment=False)[0]
# 进行非极大值抑制
detections = non_max_suppression(detections, conf_thres=0.3, iou_thres=0.45)
# 输出检测结果
for detection in detections:
if detection is not None:
# 对坐标进行缩放
detection = scale_coords(img.shape[2:], detection[:, :4], img.shape[2:]).round()
# 遍历每个检测结果
for x1, y1, x2, y2, conf, cls in detection:
# 输出类别和置信度
print(f'Class: {class_names[int(cls)]}, Confidence: {conf.item()}')
# 画框
cv2.rectangle(img, (x1, y1), (x2, y2), (0, 255, 0), 2)
# 显示图像
cv2.imshow('Image', img.numpy()[0].transpose(1, 2, 0))
cv2.waitKey(0)
cv2.destroyAllWindows()
```
注意:上述代码仅是一个简单的示例,实际使用时需要根据具体情况进行修改和调整。