diff --git a/src/lane_visualize/README.md b/src/lane_visualize/README.md index d3553309e5..d508e8703e 100644 --- a/src/lane_visualize/README.md +++ b/src/lane_visualize/README.md @@ -1,101 +1,38 @@ -# AutoPilot System: Lane & Object Detection +# AutoPilot System V3.0: Perception, Decision & Control -这是一个结合了**传统计算机视觉**与**深度学习**的自动驾驶辅助系统原型。它利用 OpenCV 进行高精度的车道线检测,并集成 YOLOv8 模型实现对车辆、行人等障碍物的实时识别。 +这是一个模拟 **ADAS (高级驾驶辅助系统)** 的完整原型项目。 +V3.0 版本不仅实现了对车道和车辆的**感知**,还加入了**决策逻辑**(碰撞预警)、**模拟控制**(虚拟方向盘)以及**黑匣子取证**功能。 ![Status](https://img.shields.io/badge/Status-Active-success) -![Python](https://img.shields.io/badge/Python-3.8%2B-blue) +![Version](https://img.shields.io/badge/Version-V3.0-blue) +![Python](https://img.shields.io/badge/Python-3.8%2B-yellow) -## ✨ 核心功能 +## ✨ V3.0 核心特性 -### 1. 🛣️ 车道线检测 (Lane Detection) -* **视觉管线**: 灰度化 -> 高斯模糊 -> Canny 边缘检测 -> 动态 ROI -> 霍夫变换。 -* **算法优化**: - * **智能平滑**: 使用 `deque` 历史队列消除车道线抖动。 - * **斜率过滤**: 自动剔除路面阴影和垂直路标干扰。 - * **可视化调参**: 提供 `tuner.py` 工具,实时寻找针对当前天气的最佳参数。 +### 1. 🧠 智能感知 (Perception) +* **车道保持**: 使用 OpenCV + 霍夫变换 + **EMA 平滑滤波**,稳定追踪车道线。 +* **目标检测**: 集成 **YOLOv8** 模型,实时识别车辆、行人、卡车等障碍物。 +* **跳帧优化**: 采用 "Skip-Frame" 策略,大幅降低 CPU 负载,实现流畅运行。 -### 2. 🚗 目标检测 (Object Detection) -* **深度学习**: 集成 **YOLOv8 (Nano)** 模型。 -* **识别对象**: 实时框出前方车辆 (Car)、卡车 (Truck)、巴士 (Bus) 和行人 (Person)。 -* **性能**: 针对 CPU 优化,轻量级推理。 +### 2. 🛡️ 决策与预警 (Decision Making) +* **FCW (前向碰撞预警)**: 实时计算前车距离(基于视觉占比),触发 **"BRAKE!"** 红色警报。 +* **LDW (车道偏离预警)**: 监测车辆中心与车道中心的偏差。 + +### 3. 🧭 模拟控制 (Control Simulation) +* **虚拟方向盘**: 屏幕下方通过 **Steering Dashboard** 实时显示转向角度。 +* **自动修正**: 根据车道曲率自动计算方向盘应转动的角度。 + +### 4. 📹 黑匣子取证 (Event Data Recorder) +* **自动抓拍**: 当系统判定有碰撞风险(出现 "BRAKE!")时,自动保存当前画面。 +* **证据留存**: 图片自动保存在 `events/` 目录下,文件名包含精确时间戳。 ## 🛠️ 环境准备 ### 1. 运行环境 -* Python 3.8+ (推荐 Python 3.13) -* 建议使用独立显卡 (GPU) 以获得更高帧率,但在 CPU 上也能运行 (FPS 5-10)。 +* Python 3.8+ +* 推荐配置: 具有独立显卡 (NVIDIA) 可获最佳性能,但在 CPU 环境下也能通过跳帧策略流畅运行。 ### 2. 安装依赖 -请确保安装了最新版本的依赖库(包含 ultralytics): -```bash -pip install -r requirements.txt - -``` - -## 🚀 使用指南 - -### 第一步:视觉参数调优 (可选但推荐) - -如果发现车道线检测不准(乱飞或消失),请先运行调参工具: - +本项目已移除沉重的 TensorFlow 依赖,仅需轻量级库: ```bash -python tuner.py sample.hevc - -``` - -* 按 `空格` 暂停,拖动滑动条调整 Canny 阈值和 ROI 区域。 -* 记下最佳参数,并填入 `main.py` 顶部的配置区。 - -### 第二步:启动自动驾驶系统 - -直接运行主程序,系统将同时加载车道检测器和 YOLO 模型: - -```bash -python main.py sample.hevc - -``` - -* **首次运行提示**: 程序会自动下载 `yolov8n.pt` 模型权重文件 (约 6MB),请保持网络连接。 - -## 📂 项目结构 - -```text -Project_Root/ -├── main.py # [入口] 主程序,协调车道与YOLO检测 -├── yolo_det.py # [模块] 封装 YOLOv8 目标检测逻辑 -├── tuner.py # [工具] 视觉参数调试器 -├── requirements.txt # 依赖清单 -├── README.md # 项目文档 -└── sample.hevc # 测试数据 - -``` - -## ⚠️ 常见问题 - -**Q1: 画面非常卡顿 (Low FPS)?** - -* **原因**: 深度学习模型在没有 GPU 加速的电脑上运行较慢。 -* **优化**: 可以在 `main.py` 中实现“跳帧机制”(例如每 3 帧跑一次 YOLO,中间帧沿用结果)。 - -**Q2: 报错 `ModuleNotFoundError: No module named 'ultralytics'`?** - -* **解决**: 请运行 `pip install -r requirements.txt` 确保库已安装。 - -## 🔮 路线图 (Roadmap) - -* [x] 基础 OpenCV 车道线检测 -* [x] 可视化参数调试工具 (`tuner.py`) -* [x] 帧间平滑与防抖算法 -* [x] 集成 YOLOv8 目标检测 (`yolo_det.py`) -* [ ] 性能优化:加入多线程或跳帧处理 -* [ ] 车辆距离估算 (基于检测框大小) -* [ ] 偏离预警系统 (LDW) - -## 📚 参考资料 - -* [Ultralytics YOLOv8 Docs](https://docs.ultralytics.com/) -* [OpenCV Computer Vision](https://opencv.org/) - -``` - -``` \ No newline at end of file +pip install -r requirements.txt \ No newline at end of file diff --git a/src/lane_visualize/main.py b/src/lane_visualize/main.py index 33510d82d5..00174fd56d 100644 --- a/src/lane_visualize/main.py +++ b/src/lane_visualize/main.py @@ -4,28 +4,46 @@ import time import os import math -from collections import deque +from collections import deque # 【新增】引入双端队列用于历史缓冲 from yolo_det import ObjectDetector # ================= 配置区 ================= -CANNY_LOW, CANNY_HIGH = 50, 150 +# --- 视觉参数 (新) --- +# Canny 边缘检测阈值 (在颜色过滤后应用,可以适当降低) +CANNY_LOW, CANNY_HIGH = 30, 100 +# ROI 区域设置 ROI_TOP, ROI_HEIGHT = 0.40, 0.60 + +# --- HLS 颜色阈值 (关键优化点) --- +# 白色掩码范围 (对亮度L要求高,对色相H和饱和度S要求低) +# 注意:OpenCV中 H范围是0-180, L和S是0-255 +WHITE_LOWER = np.array([0, 160, 0], dtype=np.uint8) +WHITE_UPPER = np.array([180, 255, 100], dtype=np.uint8) +# 黄色掩码范围 (H通常在15-35之间,S要够高) +YELLOW_LOWER = np.array([15, 80, 80], dtype=np.uint8) +YELLOW_UPPER = np.array([35, 255, 255], dtype=np.uint8) + +# --- 平滑参数 (新) --- +# 历史记录长度:越大越稳,但滞后感越强。8-12帧通常是不错的平衡点。 +HISTORY_LEN = 10 + +# --- 交互参数 --- SKIP_FRAMES = 3 # 跳帧数 WARNING_RATIO = 0.20 # 碰撞预警阈值 -STEER_SENSITIVITY = 1.5 # 转向灵敏度 (越大方向盘转得越快) +STEER_SENSITIVITY = 1.5 # 转向灵敏度 # ========================================== class EventLogger: - """黑匣子:负责记录危险事件""" + """黑匣子:负责记录危险事件 (保持 V3.0 功能不变)""" def __init__(self, save_dir="events"): self.save_dir = save_dir if not os.path.exists(save_dir): os.makedirs(save_dir) self.last_save_time = 0 - self.cooldown = 2.0 # 两次抓拍最小间隔(秒) + self.cooldown = 2.0 def log_danger(self, frame, obj_name): now = time.time() @@ -40,22 +58,41 @@ def log_danger(self, frame, obj_name): class LaneSystem: + """【重构】车道线系统:颜色过滤 + 加权拟合 + 历史平滑""" + def __init__(self): - self.left_fit_avg = None - self.right_fit_avg = None + # 使用双端队列存储最近 N 帧的拟合结果 (斜率, 截距) + self.left_history = deque(maxlen=HISTORY_LEN) + self.right_history = deque(maxlen=HISTORY_LEN) + # 存储最近一次稳定的检测结果,用于兜底 + self.last_stable_left = None + self.last_stable_right = None self.vertices = None + def color_filter(self, frame): + """【核心优化1】HLS颜色空间过滤,只提取白色和黄色""" + hls = cv2.cvtColor(frame, cv2.COLOR_BGR2HLS) + white_mask = cv2.inRange(hls, WHITE_LOWER, WHITE_UPPER) + yellow_mask = cv2.inRange(hls, YELLOW_LOWER, YELLOW_UPPER) + # 合并掩码 + combined_mask = cv2.bitwise_or(white_mask, yellow_mask) + # 轻微膨胀,连接断续的线段 + kernel = np.ones((3, 3), np.uint8) + combined_mask = cv2.dilate(combined_mask, kernel, iterations=1) + return combined_mask + def get_lane_info(self, frame): """返回: (lane_mask, deviation_percent, curvature_angle)""" if frame is None: return None, 0, 0 + h, w = frame.shape[:2] - # 1. 视觉处理 - gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY) - blur = cv2.GaussianBlur(gray, (5, 5), 0) - edges = cv2.Canny(blur, CANNY_LOW, CANNY_HIGH) + # 1. 视觉处理流程升级 + # 旧版: Gray -> Canny + # 新版: HLS Color Mask -> Canny (只在筛选出的颜色区域找边缘) + color_mask = self.color_filter(frame) + edges = cv2.Canny(color_mask, CANNY_LOW, CANNY_HIGH) - # 2. ROI - h, w = frame.shape[:2] + # 2. ROI (感兴趣区域) if self.vertices is None: top_w = w * ROI_TOP self.vertices = np.array([[ @@ -64,110 +101,129 @@ def get_lane_info(self, frame): (int(w * 0.5 + top_w / 2), int(h * ROI_HEIGHT)), (w, h) ]], dtype=np.int32) - mask = np.zeros_like(edges) cv2.fillPoly(mask, self.vertices, 255) roi = cv2.bitwise_and(edges, mask) - # 3. 霍夫变换 - lines = cv2.HoughLinesP(roi, 1, np.pi / 180, 20, minLineLength=20, maxLineGap=100) + # 3. 霍夫变换 (参数微调:提高最小长度要求,过滤噪点) + lines = cv2.HoughLinesP(roi, 1, np.pi / 180, threshold=20, minLineLength=30, maxLineGap=100) - # 4. 计算拟合线 - l_fit, r_fit = self.avg_lines(lines) - self.left_fit_avg = self.smooth(self.left_fit_avg, l_fit) - self.right_fit_avg = self.smooth(self.right_fit_avg, r_fit) + # 4. 【核心优化2】处理线段:分类、过滤、加权拟合 + curr_l_fit, curr_r_fit = self.process_lines(lines, h) - # 5. 计算绘制点 + # 5. 【核心优化3】历史缓冲平滑 + # 如果当前帧检测到了,加入历史队列 + if curr_l_fit is not None: self.left_history.append(curr_l_fit) + if curr_r_fit is not None: self.right_history.append(curr_r_fit) + + # 计算平滑后的结果(取历史平均值) + # 如果历史队列为空,尝试使用上一次的稳定值兜底 + smooth_left = np.mean(self.left_history, axis=0) if self.left_history else self.last_stable_left + smooth_right = np.mean(self.right_history, axis=0) if self.right_history else self.last_stable_right + + # 更新稳定兜底值 + if smooth_left is not None: self.last_stable_left = smooth_left + if smooth_right is not None: self.last_stable_right = smooth_right + + # 6. 计算绘制点 (使用平滑后的结果) y_min = int(h * ROI_HEIGHT) + 40 - l_pts = self.make_pts(self.left_fit_avg, y_min, h) - r_pts = self.make_pts(self.right_fit_avg, y_min, h) + # 只有当左右两条线都有稳定结果时才绘制 + l_pts = self.make_pts(smooth_left, y_min, h) if smooth_left is not None else None + r_pts = self.make_pts(smooth_right, y_min, h) if smooth_right is not None else None - # 6. 计算偏离度与转向角 + # 7. 计算偏离度与转向角 deviation = 0 angle = 0 + lane_layer = np.zeros_like(frame) + if l_pts and r_pts: + # 绘制绿色车道区域 + pts = np.array([l_pts[0], l_pts[1], r_pts[1], r_pts[0]], dtype=np.int32) + cv2.fillPoly(lane_layer, [pts], (0, 255, 0)) + + # 计算控制数据 lane_center = (l_pts[0][0] + r_pts[1][0]) / 2 screen_center = w / 2 - # 偏离度: +右偏, -左偏 deviation = (lane_center - screen_center) / w - # 简单估算弯道角度 (基于左右线斜率的平均值) - l_slope = self.left_fit_avg[0] - r_slope = self.right_fit_avg[0] - # 将斜率转换为角度 (这是一个近似值) - angle = math.degrees(math.atan((l_slope + r_slope) / 2)) - - # 7. 绘制 - lane_layer = np.zeros_like(frame) - if l_pts and r_pts: - pts = np.array([l_pts[0], l_pts[1], r_pts[1], r_pts[0]], dtype=np.int32) - cv2.fillPoly(lane_layer, [pts], (0, 255, 0)) + # 计算转向角:取左右斜率的平均值代表道路趋势 + l_slope = smooth_left[0] + r_slope = smooth_right[0] + avg_slope = (l_slope + r_slope) / 2 + # 转换为角度,取反以适配仪表盘显示习惯(负斜率=左转=正角度) + angle = -math.degrees(math.atan(avg_slope)) return lane_layer, deviation, angle - def avg_lines(self, lines): - lefts, rights = [], [] + def process_lines(self, lines, height): + """【核心优化2实现】加权拟合,长线段权重更大""" + left_lines, right_lines = [], [] + left_weights, right_weights = [], [] # 权重列表 + if lines is None: return None, None for line in lines: x1, y1, x2, y2 = line[0] - if x2 == x1: continue + if x2 == x1: continue # 防止垂直线除零 + slope = (y2 - y1) / (x2 - x1) intercept = y1 - slope * x1 - if abs(slope) < 0.3 or abs(slope) > 5: continue - if slope < 0: - lefts.append((slope, intercept)) - else: - rights.append((slope, intercept)) - return (np.mean(lefts, axis=0) if lefts else None, - np.mean(rights, axis=0) if rights else None) + length = np.sqrt((x2 - x1) ** 2 + (y2 - y1) ** 2) # 计算线段长度作为权重 + + # 过滤掉过于水平或垂直的噪点线段 + if abs(slope) < 0.3 or abs(slope) > 3.0: continue - def smooth(self, curr, new_val): - return curr * 0.8 + new_val * 0.2 if curr is not None and new_val is not None else new_val + # 简单的左右分类 + if slope < 0: # 左车道线通常斜率为负 + left_lines.append((slope, intercept)) + left_weights.append(length) + else: # 右车道线通常斜率为正 + right_lines.append((slope, intercept)) + right_weights.append(length) + + # 使用加权平均计算最终拟合线 + # 如果某侧没有检测到线,返回 None + left_fit = np.average(left_lines, axis=0, weights=left_weights) if left_lines else None + right_fit = np.average(right_lines, axis=0, weights=right_weights) if right_lines else None + + return left_fit, right_fit def make_pts(self, line, y1, y2): if line is None: return None s, i = line - if abs(s) < 1e-3: return None + # 防止斜率过小导致计算出的x坐标飞出天际 + if abs(s) < 1e-2: return None try: - return ((int((y1 - i) / s), y1), (int((y2 - i) / s), y2)) + x1 = int((y1 - i) / s) + x2 = int((y2 - i) / s) + # 增加边界检查,防止绘制错误 + if x1 < -2000 or x1 > 4000 or x2 < -2000 or x2 > 4000: return None + return ((x1, y1), (x2, y2)) except: return None def draw_dashboard(img, deviation, steer_angle, fps, status): - """绘制高科技仪表盘 (方向盘 + 数据)""" + """绘制高科技仪表盘 (保持 V3.0 功能不变)""" h, w = img.shape[:2] - # 1. 底部黑色面板 cv2.rectangle(img, (0, h - 80), (w, h), (0, 0, 0), -1) - - # 2. 虚拟方向盘 (Steering Wheel) + # 2. 虚拟方向盘 center = (w // 2, h - 40) radius = 30 - # 计算旋转后的终点 - # steer_angle 是基于路面斜率的,我们需要把它放大一点显示 - display_angle = steer_angle * 5 * STEER_SENSITIVITY - # 限制最大转角 + display_angle = steer_angle * 4 * STEER_SENSITIVITY # 调整了显示系数 display_angle = max(-90, min(90, display_angle)) - - rad = math.radians(display_angle - 90) # -90因为OpenCV里0度是3点钟方向 + rad = math.radians(display_angle - 90) end_x = int(center[0] + radius * math.cos(rad)) end_y = int(center[1] + radius * math.sin(rad)) - - # 画圆和指针 cv2.circle(img, center, radius, (200, 200, 200), 2) cv2.line(img, center, (end_x, end_y), (0, 0, 255), 3) cv2.putText(img, "STEER", (center[0] - 20, center[1] + 45), cv2.FONT_HERSHEY_SIMPLEX, 0.4, (255, 255, 255), 1) - # 3. 偏离指示条 - bar_width = 200 cv2.rectangle(img, (w // 2 - 100, h - 75), (w // 2 + 100, h - 70), (50, 50, 50), -1) - # 指示点 - marker_x = int(w // 2 + deviation * w) # 偏差值映射到像素 + marker_x = int(w // 2 + deviation * w) marker_x = max(w // 2 - 100, min(w // 2 + 100, marker_x)) color = (0, 255, 0) if abs(deviation) < 0.05 else (0, 0, 255) cv2.circle(img, (marker_x, h - 72), 6, color, -1) - # 4. 数据显示 cv2.putText(img, f"FPS: {fps:.1f}", (20, h - 20), cv2.FONT_HERSHEY_SIMPLEX, 0.6, (0, 255, 255), 1) cv2.putText(img, f"STATUS: {status}", (w - 150, h - 20), cv2.FONT_HERSHEY_SIMPLEX, 0.6, (200, 200, 200), 1) @@ -176,13 +232,16 @@ def draw_dashboard(img, deviation, steer_angle, fps, status): def main(): source = sys.argv[1] if len(sys.argv) > 1 else "sample.hevc" cap = cv2.VideoCapture(source) - if not cap.isOpened(): return + if not cap.isOpened(): + print(f"Error: Cannot open video source {source}") + return + # 初始化新的车道系统 lane_sys = LaneSystem() yolo_sys = ObjectDetector() logger = EventLogger() - print("🚀 AutoPilot V3.0: 启动虚拟控制与取证系统...") + print("🚀 AutoPilot V3.1 (Stable): 启动优化版控制系统...") frame_count = 0 current_dets = [] @@ -214,7 +273,6 @@ def main(): color = (0, 0, 255) is_danger = True danger_obj = det['class'] - # 画面中心大字警告 cv2.putText(display, "BRAKE!", (x1, y1 - 30), cv2.FONT_HERSHEY_SIMPLEX, 1, color, 3) cv2.rectangle(display, (x1, y1), (x2, y2), color, 2) @@ -222,12 +280,12 @@ def main(): # --- C. 黑匣子: 自动抓拍 --- if is_danger: - # 传入原始未画框的帧,还是画了框的?画了框的更直观 if logger.log_danger(display, danger_obj): cv2.putText(display, "SNAPSHOT SAVED", (w // 2 - 100, 50), cv2.FONT_HERSHEY_SIMPLEX, 0.8, (255, 255, 255), 2) - # --- D. 控制层: 车道与转向 --- + # --- D. 控制层: 优化的车道与转向 --- + # 这里调用的是新的 LaneSystem 逻辑 lane_layer, deviation, steer_angle = lane_sys.get_lane_info(frame) if lane_layer is not None: display = cv2.addWeighted(display, 1, lane_layer, 0.4, 0) @@ -237,7 +295,7 @@ def main(): status = "DANGER" if is_danger else "CRUISING" draw_dashboard(display, deviation, steer_angle, fps, status) - cv2.imshow('AutoPilot V3.0 - Control Dashboard', display) + cv2.imshow('AutoPilot V3.1 (Stable)', display) frame_count += 1 if cv2.waitKey(1) & 0xFF == ord('q'): break