赞
踩
随着自动驾驶技术的发展,障碍物检测成为保障行车安全的重要一环。通过深度学习模型,尤其是YOLO(You Only Look Once)模型,可以高效、准确地检测道路上的障碍物,从而提高自动驾驶系统的安全性和可靠性。
安装 Python
访问 Python 官方网站 下载并安装最新版本的 Python。
安装 pip(Python 包管理工具)
通常 Python 自带 pip。如果没有,可以通过以下命令安装:
sudo apt-get install python3-pip # Ubuntu
brew install python # macOS
创建虚拟环境
python -m venv obstacle_env
source obstacle_env/bin/activate # Linux/macOS
obstacle_env\Scripts\activate # Windows
安装深度学习相关库
pip install torch torchvision torchaudio # 如果使用PyTorch
pip install tensorflow # 如果使用TensorFlow
pip install opencv-python
pip install matplotlib
pip install numpy
pip install Flask # 用于创建UI
dataset/
│
├── images/
│ ├── train/
│ ├── val/
│
└── labels/
├── train/
├── val/
使用 albumentations 库进行数据增强:
import albumentations as A
from albumentations.pytorch import ToTensorV2
import cv2
transform = A.Compose([
A.HorizontalFlip(p=0.5),
A.RandomBrightnessContrast(p=0.2),
A.Rotate(limit=15),
ToTensorV2()
])
image = cv2.imread('path_to_image')
transformed = transform(image=image)
transformed_image = transformed["image"]
git clone https://github.com/ultralytics/yolov5
cd yolov5
pip install -r requirements.txt
修改 data.yaml
文件以适配你的数据集:
train: ../dataset/images/train
val: ../dataset/images/val
nc: 3 # 类别数量
names: ['pedestrian', 'vehicle', 'obstacle'] # 类别名称
python train.py --img 640 --batch 16 --epochs 50 --data data.yaml --weights yolov5s.pt --cache
from yolov5.models.common import DetectMultiBackend
from yolov5.utils.datasets import LoadImages
from yolov5.utils.general import non_max_suppression, scale_coords
from yolov5.utils.plots import plot_one_box
import torch
model = DetectMultiBackend(weights='best.pt')
stride, names, pt, jit, onnx, engine = model.stride, model.names, model.pt, model.jit, model.onnx, model.engine
device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
dataset = LoadImages('path_to_image')
for path, img, im0s, vid_cap, s in dataset:
img = torch.from_numpy(img).to(device)
img = img.float()
img /= 255.0
if img.ndimension() == 3:
img = img.unsqueeze(0)
pred = model(img)
pred = non_max_suppression(pred, 0.25, 0.45, classes=None, agnostic=False)
for i, det in enumerate(pred):
if len(det):
det[:, :4] = scale_coords(img.shape[2:], det[:, :4], im0s.shape).round()
for *xyxy, conf, cls in reversed(det):
label = f'{names[int(cls)]} {conf:.2f}'
plot_one_box(xyxy, im0s, label=label, color=(255, 0, 0), line_thickness=2)
cv2.imshow('result', im0s)
cv2.waitKey(0)
from flask import Flask, request, render_template
import os
app = Flask(__name__)
UPLOAD_FOLDER = 'uploads'
os.makedirs(UPLOAD_FOLDER, exist_ok=True)
app.config['UPLOAD_FOLDER'] = UPLOAD_FOLDER
@app.route('/')
def index():
return render_template('index.html')
@app.route('/upload', methods=['POST'])
def upload_file():
if 'file' not in request.files:
return 'No file part'
file = request.files['file']
if file.filename == '':
return 'No selected file'
if file:
file_path = os.path.join(app.config['UPLOAD_FOLDER'], file.filename)
file.save(file_path)
# 调用检测函数并返回结果
result = detect_obstacles(file_path)
return result
def detect_obstacles(image_path):
# 在这里调用训练好的YOLO模型进行检测
pass
if __name__ == '__main__':
app.run(debug=True)
index.html
文件<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>障碍物检测系统</title>
</head>
<body>
<h1>障碍物检测系统</h1>
<form action="/upload" method="post" enctype="multipart/form-data">
<input type="file" name="file">
<input type="submit" value="上传并检测">
</form>
</body>
</html>
python app.py
访问 http://127.0.0.1:5000
查看效果。
创建 Dockerfile
文件:
FROM python:3.8-slim
WORKDIR /app
COPY . /app
RUN pip install -r requirements.txt
CMD ["python", "app.py"]
构建并运行 Docker 镜像:
docker build -t obstacle-detection .
docker run -p 5000:5000 obstacle-detection
声明:本文只是简单的项目思路,如有部署的想法,想要(UI界面+YOLOv8/v7/v6/v5代码+训练数据集+视频教学)的可以联系作者.
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。