yolov5如何实现目标检测跟踪
时间: 2023-11-16 09:52:11 浏览: 137
yolov5_目标检测
YOLOv5是一种基于深度学习的目标检测算法,它可以实现目标的检测和跟踪。下面是一个简单的示例,展示了如何使用YOLOv5实现目标检测和跟踪:
```python
import torch
import cv2
from yolov5.models import *
from yolov5.utils import *
# 加载YOLOv5模型
model = attempt_load('yolov5s.pt', map_location=torch.device('cpu')).autoshape()
# 加载预训练权重
weights = 'yolov5s.pt'
device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
model.load_state_dict(torch.load(weights, map_location=device)['model'])
# 设置模型为推理模式
model = model.to(device).eval()
# 加载类别名称
class_names = load_classes('coco.names')
# 初始化跟踪器
tracker = cv2.TrackerKCF_create()
# 打开摄像头
video = cv2.VideoCapture(0)
# 读取视频帧并进行目标检测和跟踪
while True:
ret, frame = video.read()
if not ret:
break
# 目标检测
img = torch.from_numpy(frame).to(device)
img = img.float() / 255.0
img = img.unsqueeze(0)
pred = model(img)[0]
# 跟踪目标
boxes = non_max_suppression(pred, conf_thres=0.3, iou_thres=0.45)
if len(boxes) > 0:
box = boxes[0]
x, y, w, h = int(box[0]), int(box[1]), int(box[2] - box[0]), int(box[3] - box[1])
tracker.init(frame, (x, y, w, h))
# 更新跟踪器
success, box = tracker.update(frame)
if success:
x, y, w, h = [int(v) for v in box]
cv2.rectangle(frame, (x, y), (x + w, y + h), (0, 255, 0), 2)
# 显示结果
cv2.imshow('Object Detection and Tracking', frame)
if cv2.waitKey(1) == ord('q'):
break
# 释放资源
video.release()
cv2.destroyAllWindows()
```
这段代码使用了YOLOv5模型进行目标检测,然后使用OpenCV中的`TrackerKCF_create()`函数进行目标跟踪。代码首先加载YOLOv5模型和预训练权重,然后初始化跟踪器并打开摄像头。在每个视频帧上,代码将图像输入到YOLOv5模型中进行目标检测,然后根据检测结果初始化或更新跟踪器的状态。最后,代码显示带有检测和跟踪结果的视频帧。
阅读全文