Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
21 changes: 21 additions & 0 deletions src/Yolov3_Autonomous_Vehicle_Object_Detection/LICENSE
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
MIT License

Copyright (c) 2026 Autonomous Vehicle Project Team

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
132 changes: 59 additions & 73 deletions src/Yolov3_Autonomous_Vehicle_Object_Detection/README.md
Original file line number Diff line number Diff line change
@@ -1,87 +1,73 @@
# Autonomous Vehicle Object Detection and Trajectory Planning
> 基于 YOLOv3 与 CARLA 模拟器的自动驾驶感知与决策系统 (v1.0.0 Release)

## 项目简介
本项目是一个基于自动驾驶场景的毕业设计项目。主要目的是利用 **YOLOv3** 目标检测算法与 **CARLA** 自动驾驶模拟器相结合,实现车辆对周围环境的感知(目标检测)以及基于环境反馈的轨迹规划。
![Python](https://img.shields.io/badge/Python-3.7%2B-blue)
![CARLA](https://img.shields.io/badge/CARLA-0.9.11-green)
![License](https://img.shields.io/badge/License-MIT-yellow)

通过模拟器获取实时传感器数据,利用深度学习模型识别路面障碍物(行人、车辆、交通标志等),并根据检测结果调整车辆的行驶轨迹,从而实现基础的自动驾驶避障功能。
## 📖 项目简介
本项目是一个基于自动驾驶场景的毕业设计/课程作业。核心目标是利用深度学习算法 (**YOLOv3**) 对 **CARLA** 模拟器中的交通环境进行实时感知,并基于视觉反馈实现基础的**自动紧急制动 (AEB)** 决策。

## 🚀 快速运行 (Quick Start)
确保 CARLA 模拟器已在后台运行,然后执行:
```bash
python main.py
```
系统通过 Python API 与 CARLA 服务器通信,经由 OpenCV DNN 模块进行推理,最终在可视化界面中展示检测结果与车辆控制状态。

## 核心目标
* [x] 搭建项目基础框架与环境依赖
* [ ] 实现 CARLA 模拟器环境的自动连接与车辆生成
* [ ] 集成 YOLOv3 算法进行实时目标检测
* [ ] 实现基于检测结果的简单轨迹规划(如紧急制动、自动避障)
* [ ] 使用 TensorBoard 监控系统推理性能与控制参数
## 🌟 核心功能
* **实时目标检测**: 识别行人、车辆、交通标志等 80 类目标。
* **自动避障决策 (AEB)**: 当检测到前方有碰撞风险时,自动触发紧急刹车。
* **安全走廊可视化**: 实时绘制驾驶辅助线,直观展示算法判定范围。
* **双模态控制**: 支持在“自动驾驶模式”与“紧急接管模式”间自动切换。
* **性能监控**: 集成 TensorBoard,实时记录 FPS 与置信度曲线。
* **灵活部署**: 支持命令行参数配置 IP、端口及无头模式(Headless)。

## 技术栈
* **开发语言**: Python 3.7+
* **模拟器**: CARLA Simulator (0.9.11)
* **深度学习框架**: PyTorch / OpenCV
* **目标检测**: YOLOv3 (Darknet weights)
* **可视化**: TensorBoard, Pygame
## 📂 项目结构
```text
Project_Root/
├── assets/ # 演示素材
├── config/ # 全局配置
├── models/ # 模型仓库 (YOLOv3)
├── utils/ # 工具模块
│ ├── carla_client.py # CARLA 客户端
│ ├── planner.py # AEB 决策规划
│ ├── logger.py # 日志记录
│ └── visualization.py # 可视化绘图
├── main.py # 程序主入口
├── requirements.txt # 依赖清单
└── LICENSE # 开源许可证
```

## 项目目录结构
为了确保代码的可维护性与模块化,本项目采用了以下结构:
## 🚀 快速开始 (Quick Start)

```text
Yolov3_Autonomous_Vehicle_Object_Detection/
├── assets/ # 存放项目演示图片、视频及文档
├── config/ # 存放系统配置参数 (如端口、模型阈值等)
│ ├── __init__.py
│ └── config.py # 全局配置文件
├── models/ # 存放 YOLOv3 权重文件与配置文件
│ ├── __init__.py
│ ├── coco.names # COCO数据集类别标签
│ └── yolo_detector.py # [新增] YOLO目标检测器封装类
├── utils/ # 存放通用的图像处理、坐标转换等工具函数
│ └── __init__.py
├── download_weights.py # 模型权重自动下载脚本
├── main.py # 项目主程序入口 (待开发)
├── requirements.txt # 项目依赖列表
└── README.md # 项目说明文档
### 1. 环境准备
```bash
pip install -r requirements.txt
python download_weights.py
```

## 环境安装与配置说明
1. **安装依赖库**:
建议在虚拟环境中运行以下命令安装必要的 Python 包:
```bash
pip install -r requirements.txt
```
### 2. 基础运行
确保 CARLA 模拟器已启动,然后运行:
```bash
python main.py
```

2. **下载模型权重 (重要)**:
本项目使用预训练的 YOLOv3 模型。由于权重文件体积较大(>200MB),不直接包含在仓库中。
请运行以下脚本自动下载 `yolov3.weights` 和 `yolov3.cfg` 到 `models/` 目录:
```bash
python download_weights.py
```
### 3. 高级用法 (CLI)
本项目支持命令行参数,适用于不同测试场景:

3. **配置 CARLA**:
请确保本地已下载并安装 [CARLA 0.9.11](https://github.com/carla-simulator/carla/releases/tag/0.9.11)。运行项目前需先启动 CARLA 服务端。
如果你的 CARLA 运行在非默认端口,请修改 `config/config.py` 中的 `CARLA_PORT` 参数。
* **连接远程服务器**:
```bash
python main.py --host 192.168.1.X --port 2000
```

## 进度追踪 (Development Plan)
1. [x] **2026-03-01**: 初始化项目结构,建立核心目录。
2. [x] **2026-03-02**: 编写全局配置模块 `config.py`。
3. [x] **2026-03-02**: 添加 COCO 类别标签,编写模型权重自动下载脚本。
4. [x] **2026-03-03**: 定义 YOLO 检测器类并实现模型加载逻辑 (OpenCV DNN)。
5. [x] **2026-03-03**: 实现图像预处理与前向推理 (Forward Inference)。
6. [x] **2026-03-03**: 实现检测结果后处理 (NMS) 与坐标还原。
7. [x] **2026-03-03**: 编写 CARLA 客户端连接与车辆生成逻辑。
8. [x] **2026-03-03**: 实现传感器数据采集 (RGB Camera) 与图像格式转换。
9. [x] **2026-03-04**: 整合 YOLOv3 与 CARLA,实现主程序循环与实时画面展示。
10. [x] **2026-03-04**: 优化可视化效果 (独立模块)。
11. [x] **2026-03-04**: 编写自动紧急制动 (AEB) 的决策逻辑。
12. [x] **2026-03-05**: 整合感知与控制模块,实现基于视觉的自动避障功能。
13. [x] **2026-03-05**: 集成 TensorBoard 性能监控模块。
14. [x] **2026-03-06**: 代码重构:提取全局配置参数与添加类型注解。
15. [ ] 增加异常捕获与日志增强。
...
* **后台无界面模式 (Headless)**:
用于在服务器上长时间挂机测试,不显示 OpenCV 窗口:
```bash
python main.py --no-render
```

### 4. 性能监控
```bash
tensorboard --logdir=runs
```

---
*注:本项目仍处于积极开发阶段,后续将持续更新功能模块。*
```
## 📅 开发日志
* **v1.0.0 (2026-03)**: 正式发布。集成 CLI 参数支持、安全走廊可视化与 AEB 完整逻辑。
* **v0.9.0**: 完成 TensorBoard 监控与全局配置重构。
* **v0.5.0**: 完成 YOLOv3 与 CARLA 的核心联调。
56 changes: 37 additions & 19 deletions src/Yolov3_Autonomous_Vehicle_Object_Detection/main.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,19 +3,36 @@
import queue
import numpy as np
import carla
import argparse # [新增] 引入命令行参数解析库

from config import config
from utils.carla_client import CarlaClient
from models.yolo_detector import YOLODetector
# [新增] 引入新的绘图函数
from utils.visualization import draw_results, draw_safe_zone
from utils.planner import SimplePlanner
from utils.logger import PerformanceLogger


# [新增] 参数解析函数
def parse_arguments():
parser = argparse.ArgumentParser(description="Autonomous Vehicle Object Detection System")

parser.add_argument("--host", default=config.CARLA_HOST, help="CARLA Host IP")
parser.add_argument("--port", type=int, default=config.CARLA_PORT, help="CARLA Port")
parser.add_argument("--no-render", action="store_true", help="Disable OpenCV rendering window (Headless mode)")

return parser.parse_args()


def main():
# 1. 初始化模块
# 1. 解析命令行参数
args = parse_arguments()

print("[Main] 初始化模块...")
# 打印运行模式
if args.no_render:
print("[INFO] 运行模式: Headless (无窗口渲染)")

detector = YOLODetector(
cfg_path=config.YOLO_CONFIG_PATH,
weights_path=config.YOLO_WEIGHTS_PATH,
Expand All @@ -27,7 +44,9 @@ def main():

planner = SimplePlanner()
logger = PerformanceLogger(log_dir=config.LOG_DIR)
client = CarlaClient()

# [Mod] 使用命令行参数初始化客户端
client = CarlaClient(host=args.host, port=args.port)

if not client.connect():
return
Expand Down Expand Up @@ -63,23 +82,20 @@ def main():
fps = 1 / (time.time() - start_time)
logger.log_step(fps, len(results))

# --- 可视化 ---
# 1. 先画安全走廊 (蓝色辅助线)
frame = draw_safe_zone(frame)

# 2. 再画检测框
frame = draw_results(frame, results, detector.classes)
# --- 可视化 (根据 --no-render 参数决定是否显示) ---
if not args.no_render:
frame = draw_safe_zone(frame)
frame = draw_results(frame, results, detector.classes)

# 3. 画 FPS 和警告
cv2.putText(frame, f"FPS: {fps:.2f}", (10, 30), cv2.FONT_HERSHEY_SIMPLEX, 1, (0, 0, 255), 2)
if is_brake:
cv2.putText(frame, "EMERGENCY BRAKING!", (150, 300), cv2.FONT_HERSHEY_SIMPLEX, 1.5, (0, 0, 255), 4)
cv2.putText(frame, warning_msg, (180, 350), cv2.FONT_HERSHEY_SIMPLEX, 0.8, (0, 0, 255), 2)

cv2.imshow("CARLA Object Detection", frame)
cv2.putText(frame, f"FPS: {fps:.2f}", (10, 30), cv2.FONT_HERSHEY_SIMPLEX, 1, (0, 0, 255), 2)
if is_brake:
cv2.putText(frame, "EMERGENCY BRAKING!", (150, 300), cv2.FONT_HERSHEY_SIMPLEX, 1.5, (0, 0, 255),
4)
cv2.putText(frame, warning_msg, (180, 350), cv2.FONT_HERSHEY_SIMPLEX, 0.8, (0, 0, 255), 2)

if cv2.waitKey(1) & 0xFF == ord('q'):
break
cv2.imshow("CARLA Object Detection", frame)
if cv2.waitKey(1) & 0xFF == ord('q'):
break

except queue.Empty:
continue
Expand All @@ -91,7 +107,9 @@ def main():
print("[Main] 正在清理资源...")
client.destroy_actors()
logger.close()
cv2.destroyAllWindows()
# 只有创建了窗口才需要销毁
if not args.no_render:
cv2.destroyAllWindows()
print("[Main] 程序已退出")


Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -20,9 +20,11 @@ class CarlaClient:
CARLA 模拟器客户端封装类
"""

def __init__(self):
self.host = config.CARLA_HOST
self.port = config.CARLA_PORT
# [Mod] 修改 __init__ 方法,允许覆盖 host 和 port
def __init__(self, host=None, port=None):
# 如果传入了参数就用传入的,否则用 config 里的默认值
self.host = host if host else config.CARLA_HOST
self.port = port if port else config.CARLA_PORT
self.timeout = config.CARLA_TIMEOUT

self.client = None
Expand Down Expand Up @@ -50,7 +52,6 @@ def spawn_vehicle(self):
print("[ERROR] 世界未加载,请先连接!")
return None

# [Refactor] 使用配置文件中的车型
model_name = config.VEHICLE_MODEL
bp = self.blueprint_library.find(model_name)

Expand All @@ -74,7 +75,6 @@ def setup_camera(self):
camera_bp.set_attribute('image_size_y', str(config.CAMERA_HEIGHT))
camera_bp.set_attribute('fov', str(config.CAMERA_FOV))

# [Refactor] 使用配置文件中的安装位置
spawn_point = carla.Transform(carla.Location(x=config.CAMERA_POS_X, z=config.CAMERA_POS_Z))

self.camera = self.world.spawn_actor(camera_bp, spawn_point, attach_to=self.vehicle)
Expand Down