在这篇博客中,我们将介绍如何使用YOLOv5实现车辆识别。YOLO(You Only Look Once)是一种流行的实时目标检测算法,YOLOv5是其最新版本,性能得到了显著提高。我们将使用Python编写代码,为您展示如何实现实时车辆检测。
源码:www.hedaoapp.com/goods/goods…
一、安装必要库
首先,我们需要安装YOLOv5所需的依赖库。确保您的系统已经安装了Python,然后运行以下命令:
pip install torch torchvision opencv-python
接下来,我们需要克隆YOLOv5的官方仓库,并安装所需的依赖:
git clone https://github.com/ultralytics/yolov5
cd yolov5
pip install -r requirements.txt
二、下载预训练模型
我们将使用在COCO数据集上预训练的YOLOv5模型。这里我们选择YOLOv5s,因为它较小,适用于实时检测。您可以在YOLOv5的发布页面找到其他版本的预训练模型。运行以下命令下载YOLOv5s模型:
wget https://github.com/ultralytics/yolov5/releases/download/v5.0/yolov5s.pt
三、编写车辆识别代码
我们首先导入所需的库:
import cv2
import torch
from yolov5.utils.general import non_max_suppression
接下来,我们定义一个函数来加载模型:
def load_model(weights_path, device):
model = torch.hub.load('ultralytics/yolov5', 'custom', path_or_model=weights_path)
model.to(device)
model.eval()
return model
现在,我们将创建一个函数来处理模型的输出:
def process_detections(detections, conf_thres):
car_detections = []
for det in detections:
if det[5] == 2: # 2对应于COCO数据集中的“汽车”类别
if det[4] >= conf_thres:
car_detections.append(det[:4].cpu().numpy().astype(int))
return car_detections
接下来,我们定义一个函数用于在图像上绘制检测结果:
def draw_detections(image, detections, color=(0, 255, 0), thickness=2):
for det in detections:
x1, y1, x2, y2 = det
cv2.rectangle(image, (x1, y1), (x2, y2), color, thickness)
return image
最后,我们编写主程序,从摄像头捕获视频流并进行实时车辆检测:
def main():
device = torch.device("cuda if torch.cuda.is_available() else "cpu") weights_path = "yolov5s.pt" conf_thres = 0.5
model = load_model(weights_path, device)
cap = cv2.VideoCapture(0) # 使用摄像头
while True:
ret, frame = cap.read()
if not ret:
break
# 将图像转换为模型输入格式
img = torch.from_numpy(frame).permute(2, 0, 1).float() / 255.0
img = img.unsqueeze(0).to(device)
# 进行目标检测
with torch.no_grad():
pred = model(img)[0]
pred = non_max_suppression(pred, conf_thres)
# 提取车辆检测结果
detections = process_detections(pred[0], conf_thres)
# 在图像上绘制检测结果
frame = draw_detections(frame, detections)
# 显示结果
cv2.imshow("Car Detection", frame)
# 按'q'键退出
if cv2.waitKey(1) & 0xFF == ord("q"):
break
cap.release()
cv2.destroyAllWindows()
if name == "main":
main()
现在,您可以运行此代码进行实时车辆检测。摄像头将捕获视频流,YOLOv5将识别图像中的车辆,并用矩形框标注出来。
YOLOv5还可以识别其他类型的目标,您可以根据需要调整代码。此外,可以尝试使用其他版本的预训练模型(如YOLOv5m或YOLOv5l)以获得更高的准确性,但可能会降低实时性能。
总之,YOLOv5是一个强大且实用的目标检测算法,非常适用于实时车辆识别。通过使用Python和YOLOv5,您可以轻松地开发自己