From 0f9b297caf24ef2c747f3c8beef4940231dab8d3 Mon Sep 17 00:00:00 2001 From: lj2302 Date: Thu, 18 Dec 2025 19:16:01 +0800 Subject: [PATCH 01/24] 1 --- src/autonomous_car/README.md | 1 + src/car_control/README.md | 205 ------------------ src/car_control/main.py | 408 ----------------------------------- 3 files changed, 1 insertion(+), 613 deletions(-) create mode 100644 src/autonomous_car/README.md delete mode 100644 src/car_control/README.md delete mode 100644 src/car_control/main.py diff --git a/src/autonomous_car/README.md b/src/autonomous_car/README.md new file mode 100644 index 0000000000..8c27ba2124 --- /dev/null +++ b/src/autonomous_car/README.md @@ -0,0 +1 @@ +无人车 \ No newline at end of file diff --git a/src/car_control/README.md b/src/car_control/README.md deleted file mode 100644 index 3973b3231a..0000000000 --- a/src/car_control/README.md +++ /dev/null @@ -1,205 +0,0 @@ -# 人车模拟 -# CARLA 全局路径规划节点 - -实现基于 CARLA 模拟器的车辆全局路径规划功能,支持从车辆自身位置(通过里程计输入)到地图中随机目标点的路径生成,并通过 ROS 2 话题可视化规划结果,模拟用户预订行程后车辆的全局路径规划过程。 - - -## 功能概述 -该节点是 CARLA 自动驾驶仿真系统中的核心模块之一,主要功能包括: -- **CARLA 交互**:建立与 CARLA 服务器的连接,获取地图数据和可导航的生成点(目标点候选) -- **路径规划服务**:提供 ROS 2 服务 `plan_to_random_goal`,接收起始点里程计信息,生成到随机目标点的全局路径 -- **路径可视化**:通过 `visualization_marker` 话题发布路径标记,在 RViz 中以绿色线条直观展示规划结果 -- **鲁棒性保障**:包含路径有效性校验(确保路径长度满足需求)、异常捕获和错误日志输出,避免无限循环或崩溃 - - -## 环境配置 -### 基础环境 -| 类别 | 要求 | 说明 | -|------------|-------------------------------|---------------------------------------| -| 操作系统 | Ubuntu 20.04 LTS | 兼容 ROS 2 Foxy 版本,是 CARLA 推荐系统 | -| ROS 版本 | ROS 2 Foxy Fitzroy | 需确保环境变量无 ROS 1 冲突 | -| Python 版本| Python 3.8 | 匹配 ROS 2 Foxy 依赖及 CARLA 0.9.15 要求 | -| CARLA 版本 | CARLA 0.9.15 | 需与代码中客户端连接逻辑兼容 | - -### 依赖安装 -1. **ROS 2 Foxy 安装** - 参考 [ROS 2 官方文档](https://docs.ros.org/en/foxy/Installation/Ubuntu-Install-Debians.html) 完成基础安装,确保 `ros-foxy-nav-msgs`、`ros-foxy-visualization-msgs` 等依赖已安装: - ```bash - sudo apt update && sudo apt install -y ros-foxy-nav-msgs ros-foxy-visualization-msgs ros-foxy-geometry-msgs - ``` - -2. **CARLA Python 客户端** - 从 [CARLA 官网](https://carla.org/2023/07/11/release-0.9.15/) 下载对应版本的 CARLA 压缩包,解压后将 `PythonAPI/carla/dist/carla-0.9.15-py3.8-linux-x86_64.egg` 添加到 Python 路径: - ```bash - export PYTHONPATH=$PYTHONPATH:/path/to/your/carla/PythonAPI/carla/dist/carla-0.9.15-py3.8-linux-x86_64.egg - ``` - -3. **其他 Python 依赖** - 安装路径计算和坐标转换所需依赖: - ```bash - pip install tf-transformations # 用于欧拉角转四元数 - ``` - -4. **编译工具** - 安装 ROS 2 编译工具 `colcon`: - ```bash - sudo apt install -y python3-colcon-common-extensions - ``` - - -## 快速开始 -### 1. 工作空间准备 -假设你的 ROS 2 工作空间为 `carla_ws`,将该节点所在的功能包 `carla_global_planner` 放入 `src` 目录: -```bash -mkdir -p ~/carla_ws/src -cd ~/carla_ws/src -# 克隆或复制 carla_global_planner 功能包到此处 -``` - -### 2. 编译节点 -在工作空间根目录执行编译命令,确保无编译错误: -```bash -cd ~/carla_ws -# 激活 ROS 2 环境 -source /opt/ros/foxy/setup.bash -# 编译功能包(仅编译指定包可加快速度) -colcon build --packages-select carla_global_planner -``` - -### 3. 启动流程 -#### 步骤 1:启动 CARLA 服务器 -打开新终端,进入 CARLA 安装目录,启动无渲染模式(节省资源): -```bash -cd ~/carla/CARLA_0.9.15 # 替换为你的 CARLA 实际路径 -# 低画质+无渲染启动(适合后台运行) -./CarlaUE4.sh -quality-level=Low -RenderOffScreen -``` -- 若需可视化 CARLA 场景,可去掉 `-RenderOffScreen` 参数 - -#### 步骤 2:启动全局规划节点 -打开新终端,激活工作空间环境并启动节点: -```bash -cd ~/carla_ws -# 激活 ROS 2 环境和工作空间环境 -source /opt/ros/foxy/setup.bash -source install/setup.bash -# 启动节点 -ros2 run carla_global_planner carla_global_planner_node -``` -- 节点启动成功后,会输出日志 `CARLA全局路径规划服务已启动` -- 若脚本卡住无报错,说明节点正常运行(等待服务请求);若报错 "CARLA客户端初始化失败",需检查 CARLA 服务器是否已启动,或连接地址/端口是否正确 - -#### 步骤 3:调用路径规划服务 -打开新终端,通过 `ros2 service call` 命令测试服务(需替换 `start` 参数为实际里程计数据): -```bash -# 激活环境 -source /opt/ros/foxy/setup.bash -source ~/carla_ws/install/setup.bash -# 调用服务(示例:起始点为(0,0,0),姿态为默认) -ros2 service call /plan_to_random_goal carla_global_planner/srv/PlanGlobalPath "{start: {header: {frame_id: 'map'}, pose: {pose: {position: {x: 0.0, y: 0.0, z: 0.0}, orientation: {x: 0.0, y: 0.0, z: 0.0, w: 1.0}}}}}" -``` -- 服务调用成功后,节点会输出路径信息(如 `成功规划路径,包含XX个路点`) - -#### 步骤 4:可视化路径 -打开新终端,启动 RViz 查看路径: -```bash -source /opt/ros/foxy/setup.bash -rviz2 -``` -在 RViz 中配置: -1. 设置 `Fixed Frame` 为 `map` -2. 添加 `Marker` 显示项,设置 `Topic` 为 `/visualization_marker` -3. 路径会以绿色线条显示在场景中 - - -## 核心接口说明 -### 1. ROS 2 服务 -| 服务名称 | 服务类型 | 功能描述 | -|------------------------|-----------------------------------|-------------------------------------------| -| `/plan_to_random_goal` | `carla_global_planner/srv/PlanGlobalPath` | 输入起始点里程计信息,返回全局路径(`nav_msgs/Path`) | - -#### 服务请求(Request) -```msg -# 起始点里程计信息 -nav_msgs/Odometry start -``` - -#### 服务响应(Response) -```msg -# 规划后的全局路径 -nav_msgs/Path path -``` - -### 2. ROS 2 话题 -| 话题名称 | 消息类型 | 功能描述 | -|------------------------|-----------------------------------|-------------------------------------------| -| `/visualization_marker`| `visualization_msgs/Marker` | 发布路径可视化标记(绿色 LINE_STRIP 类型) | - - -## 常见问题排查 -1. **节点启动报错 "CARLA客户端初始化失败"** - - 检查 CARLA 服务器是否已启动:`ps aux | grep CarlaUE4` - - 确认 CARLA 服务器地址/端口与代码一致(默认 `localhost:2000`) - - 检查 Python 路径中是否正确添加了 CARLA 的 `egg` 文件 - -2. **服务调用后无路径生成** - - 检查 CARLA 地图是否加载完成(服务器启动后需等待地图加载,约10-20秒) - - 若提示 "未找到可用的生成点",需更换 CARLA 地图(如 `Town01`): - ```bash - # 在 CARLA 服务器终端中输入(需安装 CARLA 附加地图) - ./CarlaUE4.sh -quality-level=Low -RenderOffScreen -map Town01 - ``` - -3. **RViz 中看不到路径** - - 确认 `Fixed Frame` 已设置为 `map` - - 检查 `Marker` 话题是否正确订阅,且消息是否有更新(`ros2 topic echo /visualization_marker`) - - 检查路径点的坐标是否在 RViz 可视范围内(可通过 "Reset View" 重置视角) - -4. **编译报错 "找不到 carla_global_planner/srv/PlanGlobalPath"** - - 确认 `srv` 目录下已定义 `PlanGlobalPath.srv` 文件,且 `CMakeLists.txt`/`package.xml` 已正确配置服务依赖 - - -## 代码结构说明 -``` -carla_global_planner/ -├── src/ -│ └── carla_global_planner_node.py # 核心节点代码 -├── srv/ -│ └── PlanGlobalPath.srv # 路径规划服务定义 -├── utilities/ -│ └── planner.py # 路径计算工具(compute_route_waypoints 函数) -├── CMakeLists.txt # 编译配置 -└── package.xml # 依赖和包信息配置 -``` -核心节点代码关键函数: -- `_initialize_carla_client()`:初始化 CARLA 客户端和地图 -- `plan_path_cb()`:服务回调函数,处理路径规划请求 -- `_get_valid_route()`:生成满足长度要求的有效路径 -- `_build_path_message()`:将 CARLA 路径转换为 ROS 2 Path 消息 -- `_visualize_path()`:发布路径可视化标记 - - -## 贡献指南 -1. **代码规范** - - 遵循 [PEP 8 Python 代码风格](https://peps.pythonlang.cn/pep-0008/) - - 新增功能需添加对应的注释和文档字符串 - - 关键逻辑变更需同步更新 README.md - -2. **功能扩展建议** - - 支持自定义目标点(而非仅随机目标点) - - 增加路径规划算法选择(如 A*、RRT*) - - 添加路径平滑处理,优化车辆行驶轨迹 - - 增加单元测试(基于 `pytest` 和 `ros2 test`) - -3. **提交流程** - 准备提交代码前,请确保: - 1. 代码无编译错误和运行时异常 - 2. 新增功能包含对应的测试用例 - 3. 文档(如 README.md)已同步更新 - - -## 参考资料 -1. [CARLA 官方文档](https://carla.readthedocs.io/en/0.9.15/) - 了解 CARLA Python API 和地图数据结构 -2. [ROS 2 Foxy 官方文档](https://docs.ros.org/en/foxy/) - 学习 ROS 2 服务、话题和节点开发 -3. [nav_msgs/Path 消息定义](https://docs.ros.org/en/foxy/api/nav_msgs/html/msg/Path.html) - 路径消息格式说明 -4. [visualization_msgs/Marker 消息定义](https://docs.ros.org/en/foxy/api/visualization_msgs/html/msg/Marker.html) - 可视化标记格式说明 \ No newline at end of file diff --git a/src/car_control/main.py b/src/car_control/main.py deleted file mode 100644 index 7d01b8d6f7..0000000000 --- a/src/car_control/main.py +++ /dev/null @@ -1,408 +0,0 @@ -#!/usr/bin/env python3 -""" -CARLA全局路径规划节点 - 增强版 -提供从起始点到随机目标点的路径规划服务,并将规划结果通过ROS消息发布和可视化 -新增功能: -- 路径长度估算 -- 连接状态监控 -- 改进的错误处理 -- 性能统计 -- 配置参数化 -""" - -import rclpy -from rclpy.node import Node -from nav_msgs.msg import Path -from geometry_msgs.msg import PoseStamped, Point -from visualization_msgs.msg import Marker, MarkerArray -from carla_global_planner.srv import PlanGlobalPath -from utilities.planner import compute_route_waypoints - -import carla -import random -import time # 新增:用于性能统计 -import math # 新增:用于距离计算 -from tf_transformations import quaternion_from_euler - - -class GlobalPlannerNode(Node): - """全局路径规划节点类 - 增强版""" - - def __init__(self): - super().__init__('carla_global_planner_node') - - # 新增:配置参数定义 - self.declare_parameters( - namespace='', - parameters=[ - ('carla_host', 'localhost'), # CARLA服务器地址 - ('carla_port', 2000), # CARLA服务器端口 - ('carla_timeout', 5.0), # CARLA客户端超时时间 - ('min_waypoints', 50), # 最小路点数量 - ('max_planning_attempts', 10), # 最大规划尝试次数 - ('waypoint_resolution', 1.0), # 路点分辨率 - ('path_line_width', 0.6), # 路径可视化线宽 - ('enable_performance_stats', True), # 是否启用性能统计 - ('publish_goal_marker', True), # 是否发布目标点标记 - ] - ) - - # 新增:性能统计变量 - self.planning_count = 0 - self.total_planning_time = 0.0 - self.last_planning_time = 0.0 - - # 初始化CARLA客户端和世界对象 - self.client = None - self.world = None - self.map = None - self.carla_connected = False # 新增:连接状态标志 - self._initialize_carla_client() - - # 初始化ROS发布器和服务 - self.marker_pub = self.create_publisher( - Marker, 'visualization_marker', 10) - - # 新增:发布标记数组(用于同时显示路径和目标点) - self.marker_array_pub = self.create_publisher( - MarkerArray, 'visualization_marker_array', 10) - - self.srv = self.create_service( - PlanGlobalPath, 'plan_to_random_goal', self.plan_path_cb) - - # 新增:定时器用于连接状态检查 - self.connection_check_timer = self.create_timer( - 5.0, self._check_carla_connection) - - # 新增:定时器用于性能统计输出 - if self.get_parameter('enable_performance_stats').value: - self.stats_timer = self.create_timer( - 30.0, self._publish_performance_stats) - - self.get_logger().info("CARLA全局路径规划服务已启动 [增强版]") - - def _initialize_carla_client(self): - """初始化CARLA客户端连接 - 增强版错误处理""" - host = self.get_parameter('carla_host').value - port = self.get_parameter('carla_port').value - timeout = self.get_parameter('carla_timeout').value - - try: - self.client = carla.Client(host, port) - self.client.set_timeout(timeout) - - # 新增:测试连接 - version = self.client.get_server_version() - self.world = self.client.get_world() - self.map = self.world.get_map() - - self.carla_connected = True # 新增:设置连接状态 - self.get_logger().info( - f"成功连接到CARLA服务器 {host}:{port} " - f"(版本: {version})" - ) - - except Exception as e: - self.carla_connected = False # 新增:设置连接状态 - self.get_logger().error(f"CARLA客户端初始化失败: {str(e)}") - # 不再抛出异常,允许节点继续运行但处于降级模式 - self.get_logger().warn("节点将在降级模式下运行,等待CARLA连接恢复") - - def _check_carla_connection(self): - """新增:定期检查CARLA连接状态""" - if not self.carla_connected: - self.get_logger().info("尝试重新连接CARLA...") - self._initialize_carla_client() - else: - try: - # 测试连接是否仍然有效 - _ = self.world.get_weather() - except Exception as e: - self.get_logger().warning(f"CARLA连接丢失: {str(e)}") - self.carla_connected = False - - def _publish_performance_stats(self): - """新增:发布性能统计信息""" - if self.planning_count > 0: - avg_time = self.total_planning_time / self.planning_count - self.get_logger().info( - f"路径规划性能统计 - " - f"总次数: {self.planning_count}, " - f"平均用时: {avg_time:.3f}s, " - f"上次用时: {self.last_planning_time:.3f}s" - ) - - def plan_path_cb(self, request, response): - """ - 路径规划服务回调函数 - 增强版 - 接收起始点,规划到随机目标点的路径并返回 - 新增性能统计和更好的错误处理 - """ - start_time = time.time() # 新增:开始计时 - - # 新增:检查CARLA连接状态 - if not self.carla_connected or not self.map: - self.get_logger().error("CARLA连接未建立或地图未初始化,无法规划路径") - response.success = False # 假设服务定义中有success字段 - return response - - try: - # 将ROS坐标转换为CARLA坐标 - start_location = self._ros_to_carla_location(request.start) - start_wp = self.map.get_waypoint(start_location) - - if not start_wp: # 新增:检查起始路点有效性 - self.get_logger().error("无法在起始位置找到有效的路点") - return response - - # 规划足够长的路径 - min_waypoints = self.get_parameter('min_waypoints').value - max_attempts = self.get_parameter('max_planning_attempts').value - - route, goal_wp = self._get_valid_route(start_wp, min_waypoints, max_attempts) - if not route: - self.get_logger().error("无法生成有效的路径") - return response - - # 新增:计算路径总长度 - total_distance = self._calculate_path_distance(route) - - # 构建路径消息并可视化 - path_msg = self._build_path_message(route) - self._visualize_path_and_goal(path_msg, goal_wp) # 修改:同时可视化路径和目标点 - - response.path = path_msg - - # 新增:更新性能统计 - planning_time = time.time() - start_time - self.last_planning_time = planning_time - self.total_planning_time += planning_time - self.planning_count += 1 - - self.get_logger().info( - f"成功规划路径 - " - f"路点数: {len(route)}, " - f"总距离: {total_distance:.2f}m, " - f"用时: {planning_time:.3f}s" - ) - return response - - except Exception as e: - self.get_logger().error(f"路径规划过程中发生错误: {str(e)}") - return response - - def _ros_to_carla_location(self, odom_msg): - """将ROS里程计消息中的位置转换为CARLA坐标""" - return carla.Location( - x=odom_msg.pose.pose.position.x, - y=-odom_msg.pose.pose.position.y, # CARLA与ROS的Y轴方向相反 - z=odom_msg.pose.pose.position.z - ) - - def _get_valid_route(self, start_wp, min_waypoints=50, max_attempts=10): - """ - 获取有效的路径 - 增强版 - 返回路径和目标路点元组 - 尝试多次生成路径,直到满足最小路点数量要求或达到最大尝试次数 - """ - best_route = None - best_goal = None - best_length = 0 - - for attempt in range(max_attempts): - # 选择随机可行的目标点 - spawn_points = self.map.get_spawn_points() - if not spawn_points: - self.get_logger().warning("未找到可用的生成点") - continue # 修改:继续尝试而不是返回None - - goal_transform = random.choice(spawn_points) - goal_wp = self.map.get_waypoint(goal_transform.location) - - # 新增:确保目标点与起始点不同 - distance_to_goal = start_wp.transform.location.distance(goal_wp.transform.location) - if distance_to_goal < 10.0: # 如果距离太近,跳过此次尝试 - continue - - # 计算路径 - self.get_logger().debug( # 修改:改为debug级别以减少日志噪音 - f"路径规划尝试 {attempt + 1}/{max_attempts}: " - f"从({start_wp.transform.location.x:.2f}, {start_wp.transform.location.y:.2f}) " - f"到({goal_wp.transform.location.x:.2f}, {goal_wp.transform.location.y:.2f}) " - f"直线距离: {distance_to_goal:.2f}m" - ) - - resolution = self.get_parameter('waypoint_resolution').value - route = compute_route_waypoints( - self.map, start_wp, goal_wp, resolution=resolution) - - # 新增:保存最佳路径(最长的) - if len(route) > best_length: - best_route = route - best_goal = goal_wp - best_length = len(route) - - if len(route) >= min_waypoints: - return route, goal_wp # 找到满足要求的路径,直接返回 - - # 返回最佳路径(即使不满足最小长度要求) - if best_route: - self.get_logger().warning( - f"达到最大尝试次数({max_attempts}),返回最长路径 " - f"(长度: {best_length}, 要求: {min_waypoints})" - ) - return best_route, best_goal - - return None, None - - def _calculate_path_distance(self, route): - """新增:计算路径总长度""" - if len(route) < 2: - return 0.0 - - total_distance = 0.0 - for i in range(len(route) - 1): - current_wp = route[i][0] - next_wp = route[i + 1][0] - - # 计算两个路点之间的欧几里得距离 - dx = next_wp.transform.location.x - current_wp.transform.location.x - dy = next_wp.transform.location.y - current_wp.transform.location.y - dz = next_wp.transform.location.z - current_wp.transform.location.z - - distance = math.sqrt(dx * dx + dy * dy + dz * dz) - total_distance += distance - - return total_distance - - def _build_path_message(self, route): - """将CARLA路径转换为ROS Path消息""" - path_msg = Path() - path_msg.header.frame_id = 'map' - path_msg.header.stamp = self.get_clock().now().to_msg() - - for waypoint, _ in route: - pose = PoseStamped() - pose.header = path_msg.header - - # 设置位置(转换Y轴方向) - pose.pose.position.x = waypoint.transform.location.x - pose.pose.position.y = -waypoint.transform.location.y - pose.pose.position.z = waypoint.transform.location.z - - # 转换旋转角度为四元数 - yaw_rad = waypoint.transform.rotation.yaw * (3.1415 / 180.0) - q = quaternion_from_euler(0, 0, -yaw_rad) - pose.pose.orientation.x = q[0] - pose.pose.orientation.y = q[1] - pose.pose.orientation.z = q[2] - pose.pose.orientation.w = q[3] - - path_msg.poses.append(pose) - - return path_msg - - def _visualize_path_and_goal(self, path_msg, goal_wp): - """修改:可视化路径和目标点""" - # 原有的单独路径可视化保持不变 - self._visualize_path(path_msg) - - # 新增:如果启用了目标点标记,则发布目标点 - if self.get_parameter('publish_goal_marker').value and goal_wp: - self._visualize_goal_point(path_msg.header, goal_wp) - - def _visualize_path(self, path_msg): - """可视化路径,先删除旧标记再发布新标记""" - # 删除旧标记 - delete_marker = self._create_path_marker( - path_msg.header, action=Marker.DELETE) - self.marker_pub.publish(delete_marker) - - # 发布新标记 - line_width = self.get_parameter('path_line_width').value - new_marker = self._create_path_marker( - path_msg.header, - action=Marker.ADD, - points=[pose.pose.position for pose in path_msg.poses], - line_width=line_width - ) - self.marker_pub.publish(new_marker) - - def _visualize_goal_point(self, header, goal_wp): - """新增:可视化目标点""" - goal_marker = Marker() - goal_marker.header = header - goal_marker.ns = "carla_goal" - goal_marker.id = 1 # 不同的ID避免与路径标记冲突 - goal_marker.type = Marker.SPHERE - goal_marker.action = Marker.ADD - - # 设置目标点位置 - goal_marker.pose.position.x = goal_wp.transform.location.x - goal_marker.pose.position.y = -goal_wp.transform.location.y - goal_marker.pose.position.z = goal_wp.transform.location.z + 1.0 # 稍微提高以便可见 - - # 设置目标点外观(红色球体) - goal_marker.scale.x = 2.0 - goal_marker.scale.y = 2.0 - goal_marker.scale.z = 2.0 - goal_marker.color.a = 0.8 - goal_marker.color.r = 1.0 # 红色 - goal_marker.color.g = 0.0 - goal_marker.color.b = 0.0 - - self.marker_pub.publish(goal_marker) - - def _create_path_marker(self, header, action=Marker.ADD, points=None, line_width=0.6): - """创建路径可视化标记 - 增强版""" - marker = Marker() - marker.header = header - marker.ns = "carla_path" - marker.id = 0 - marker.type = Marker.LINE_STRIP - marker.action = action - - # 视觉外观设置 - marker.scale.x = line_width # 修改:使用参数化线宽 - marker.color.a = 1.0 # 透明度 - marker.color.r = 0.0 - marker.color.g = 1.0 # 绿色 - marker.color.b = 0.0 - - # 新增:设置生存时间,自动清理旧标记 - marker.lifetime.sec = 60 # 60秒后自动删除 - - # 添加点集(仅用于ADD动作) - if points and action == Marker.ADD: - marker.points = points - - return marker - - def __del__(self): - """新增:析构函数,用于清理资源""" - if hasattr(self, 'connection_check_timer'): - self.connection_check_timer.cancel() - if hasattr(self, 'stats_timer'): - self.stats_timer.cancel() - - -def main(args=None): - """主函数""" - rclpy.init(args=args) - - try: - node = GlobalPlannerNode() - rclpy.spin(node) - except KeyboardInterrupt: - print("接收到中断信号,正在关闭节点...") - except Exception as e: - print(f"节点运行失败: {str(e)}") - finally: - try: - rclpy.shutdown() - except Exception: - pass # 忽略关闭时的异常 - - -if __name__ == '__main__': - main() \ No newline at end of file From 5808e4835ce78dee14ec0b587c010857aff49588 Mon Sep 17 00:00:00 2001 From: lj2302 Date: Thu, 18 Dec 2025 19:51:06 +0800 Subject: [PATCH 02/24] 1 --- src/autonomous_car/README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/autonomous_car/README.md b/src/autonomous_car/README.md index 8c27ba2124..9b8b22ed90 100644 --- a/src/autonomous_car/README.md +++ b/src/autonomous_car/README.md @@ -1 +1 @@ -无人车 \ No newline at end of file +无人车 \ No newline at end of file From 541c0634e8796ee265256b9ebb26be74a6159943 Mon Sep 17 00:00:00 2001 From: lj2302 Date: Fri, 19 Dec 2025 13:59:26 +0800 Subject: [PATCH 03/24] =?UTF-8?q?=E6=97=A0=E4=BA=BA=E8=BD=A6=E5=8A=A8?= =?UTF-8?q?=E6=80=81=E9=9A=9C=E7=A2=8D=E7=89=A9=E9=81=BF=E9=9A=9C=E7=AE=97?= =?UTF-8?q?=E6=B3=95?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .idea/.gitignore | 3 +++ .idea/inspectionProfiles/profiles_settings.xml | 6 ++++++ .idea/misc.xml | 7 +++++++ .idea/modules.xml | 8 ++++++++ .idea/nn2.iml | 14 ++++++++++++++ .idea/vcs.xml | 6 ++++++ src/autonomous_car/README.md | 2 +- 7 files changed, 45 insertions(+), 1 deletion(-) create mode 100644 .idea/.gitignore create mode 100644 .idea/inspectionProfiles/profiles_settings.xml create mode 100644 .idea/misc.xml create mode 100644 .idea/modules.xml create mode 100644 .idea/nn2.iml create mode 100644 .idea/vcs.xml diff --git a/.idea/.gitignore b/.idea/.gitignore new file mode 100644 index 0000000000..359bb5307e --- /dev/null +++ b/.idea/.gitignore @@ -0,0 +1,3 @@ +# 默认忽略的文件 +/shelf/ +/workspace.xml diff --git a/.idea/inspectionProfiles/profiles_settings.xml b/.idea/inspectionProfiles/profiles_settings.xml new file mode 100644 index 0000000000..105ce2da2d --- /dev/null +++ b/.idea/inspectionProfiles/profiles_settings.xml @@ -0,0 +1,6 @@ + + + + \ No newline at end of file diff --git a/.idea/misc.xml b/.idea/misc.xml new file mode 100644 index 0000000000..98630f92cd --- /dev/null +++ b/.idea/misc.xml @@ -0,0 +1,7 @@ + + + + + + \ No newline at end of file diff --git a/.idea/modules.xml b/.idea/modules.xml new file mode 100644 index 0000000000..5fdb6d5018 --- /dev/null +++ b/.idea/modules.xml @@ -0,0 +1,8 @@ + + + + + + + + \ No newline at end of file diff --git a/.idea/nn2.iml b/.idea/nn2.iml new file mode 100644 index 0000000000..9e0ace9109 --- /dev/null +++ b/.idea/nn2.iml @@ -0,0 +1,14 @@ + + + + + + + + + + + + \ No newline at end of file diff --git a/.idea/vcs.xml b/.idea/vcs.xml new file mode 100644 index 0000000000..35eb1ddfbb --- /dev/null +++ b/.idea/vcs.xml @@ -0,0 +1,6 @@ + + + + + + \ No newline at end of file diff --git a/src/autonomous_car/README.md b/src/autonomous_car/README.md index 9b8b22ed90..472de539d2 100644 --- a/src/autonomous_car/README.md +++ b/src/autonomous_car/README.md @@ -1 +1 @@ -无人车 \ No newline at end of file +无人车 无人车动态障碍物避障算法 无人车动态障碍物避障的核心目标是:在实时感知环境中移动障碍物(行人和车辆)的基础上,快速规划出无碰撞、平滑且符合运动学约束的安全路径 \ No newline at end of file From 426fe49a62da04dad7ca8cec4dc9a7875aae0281 Mon Sep 17 00:00:00 2001 From: lj2302 Date: Fri, 19 Dec 2025 15:02:43 +0800 Subject: [PATCH 04/24] =?UTF-8?q?=E6=8F=90=E4=BA=A4=E9=80=89=E9=A2=98?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/autonomous_car/README.md | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/src/autonomous_car/README.md b/src/autonomous_car/README.md index 472de539d2..a93adc2a1c 100644 --- a/src/autonomous_car/README.md +++ b/src/autonomous_car/README.md @@ -1 +1,2 @@ -无人车 无人车动态障碍物避障算法 无人车动态障碍物避障的核心目标是:在实时感知环境中移动障碍物(行人和车辆)的基础上,快速规划出无碰撞、平滑且符合运动学约束的安全路径 \ No newline at end of file +无人车 无人车动态障碍物避障算法 无人车动态障碍物避障的核心目标是:在实时感知环境中移动障碍物(行人和车辆)的基础上,快速规划出无碰撞、平滑且符合运动学约束的安全路径 +环境:python3.13 \ No newline at end of file From 3cabf9eae58d0c3cf0f9db4ced22cabc2af5ffd6 Mon Sep 17 00:00:00 2001 From: lj2302 Date: Fri, 19 Dec 2025 15:45:27 +0800 Subject: [PATCH 05/24] =?UTF-8?q?=E5=88=A0=E9=99=A4=E5=A4=9A=E4=BD=99?= =?UTF-8?q?=E7=9A=84.idea=E6=96=87=E4=BB=B6=EF=BC=8C=E6=9B=B4=E6=94=B9?= =?UTF-8?q?=E9=A1=B9=E7=9B=AE=E5=90=8D?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .idea/.gitignore | 3 --- .idea/inspectionProfiles/profiles_settings.xml | 6 ------ .idea/misc.xml | 7 ------- .idea/modules.xml | 8 -------- .idea/nn2.iml | 14 -------------- .idea/vcs.xml | 6 ------ .../README.md | 0 7 files changed, 44 deletions(-) delete mode 100644 .idea/.gitignore delete mode 100644 .idea/inspectionProfiles/profiles_settings.xml delete mode 100644 .idea/misc.xml delete mode 100644 .idea/modules.xml delete mode 100644 .idea/nn2.iml delete mode 100644 .idea/vcs.xml rename src/{autonomous_car => Car_Perception_Automatic_Sensing}/README.md (100%) diff --git a/.idea/.gitignore b/.idea/.gitignore deleted file mode 100644 index 359bb5307e..0000000000 --- a/.idea/.gitignore +++ /dev/null @@ -1,3 +0,0 @@ -# 默认忽略的文件 -/shelf/ -/workspace.xml diff --git a/.idea/inspectionProfiles/profiles_settings.xml b/.idea/inspectionProfiles/profiles_settings.xml deleted file mode 100644 index 105ce2da2d..0000000000 --- a/.idea/inspectionProfiles/profiles_settings.xml +++ /dev/null @@ -1,6 +0,0 @@ - - - - \ No newline at end of file diff --git a/.idea/misc.xml b/.idea/misc.xml deleted file mode 100644 index 98630f92cd..0000000000 --- a/.idea/misc.xml +++ /dev/null @@ -1,7 +0,0 @@ - - - - - - \ No newline at end of file diff --git a/.idea/modules.xml b/.idea/modules.xml deleted file mode 100644 index 5fdb6d5018..0000000000 --- a/.idea/modules.xml +++ /dev/null @@ -1,8 +0,0 @@ - - - - - - - - \ No newline at end of file diff --git a/.idea/nn2.iml b/.idea/nn2.iml deleted file mode 100644 index 9e0ace9109..0000000000 --- a/.idea/nn2.iml +++ /dev/null @@ -1,14 +0,0 @@ - - - - - - - - - - - - \ No newline at end of file diff --git a/.idea/vcs.xml b/.idea/vcs.xml deleted file mode 100644 index 35eb1ddfbb..0000000000 --- a/.idea/vcs.xml +++ /dev/null @@ -1,6 +0,0 @@ - - - - - - \ No newline at end of file diff --git a/src/autonomous_car/README.md b/src/Car_Perception_Automatic_Sensing/README.md similarity index 100% rename from src/autonomous_car/README.md rename to src/Car_Perception_Automatic_Sensing/README.md From 5a2c700a0ebe31552c10e98a49a34ebf7749b84d Mon Sep 17 00:00:00 2001 From: lj2302 Date: Fri, 19 Dec 2025 17:08:23 +0800 Subject: [PATCH 06/24] =?UTF-8?q?=E5=88=9B=E5=BB=BA=20requirements.txt?= =?UTF-8?q?=EF=BC=8C=E5=88=97=E5=87=BA=E4=BE=9D=E8=B5=96=E5=BA=93=EF=BC=88?= =?UTF-8?q?numpy=E3=80=81torch=E3=80=81opencv=20=E7=AD=89=EF=BC=89?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/Car_Perception_Automatic_Sensing/requirements.txt.py | 0 1 file changed, 0 insertions(+), 0 deletions(-) create mode 100644 src/Car_Perception_Automatic_Sensing/requirements.txt.py diff --git a/src/Car_Perception_Automatic_Sensing/requirements.txt.py b/src/Car_Perception_Automatic_Sensing/requirements.txt.py new file mode 100644 index 0000000000..e69de29bb2 From 0f21da35d6d6235632f540f1a7073e57abf7c468 Mon Sep 17 00:00:00 2001 From: lj2302 Date: Fri, 19 Dec 2025 20:46:57 +0800 Subject: [PATCH 07/24] [env] add requirements.txt for dependencies --- .../requirements.txt | 35 +++++++++++++++++++ .../requirements.txt.py | 0 2 files changed, 35 insertions(+) create mode 100644 src/Car_Perception_Automatic_Sensing/requirements.txt delete mode 100644 src/Car_Perception_Automatic_Sensing/requirements.txt.py diff --git a/src/Car_Perception_Automatic_Sensing/requirements.txt b/src/Car_Perception_Automatic_Sensing/requirements.txt new file mode 100644 index 0000000000..b047471555 --- /dev/null +++ b/src/Car_Perception_Automatic_Sensing/requirements.txt @@ -0,0 +1,35 @@ +# 基础数值计算 +numpy>=1.24.0 +pandas>=2.0.0 + +# 深度学习框架 +torch>=2.0.0 +torchvision>=0.15.0 +torchaudio>=2.0.0 + +# 计算机视觉 +opencv-python>=4.8.0 +Pillow>=10.0.0 + +# 数据处理/增强 +albumentations>=1.3.0 +scikit-image>=0.21.0 + +# 可视化 +matplotlib>=3.7.0 +seaborn>=0.12.0 +cv2-imshow-enhanced>=0.1.0 + +# 工具类 +tqdm>=4.65.0 # 进度条 +argparse>=1.4.0 # 命令行参数解析 +pyyaml>=6.0 # 配置文件解析 +pytest>=7.4.0 # 单元测试 + +# 可选:ONNX 模型导出/推理 +onnx>=1.14.0 +onnxruntime>=1.15.0 + +# 可选:CUDA 加速(根据本地环境调整) +# torch==2.0.0+cu118 +# torchvision==0.15.1+cu118 \ No newline at end of file diff --git a/src/Car_Perception_Automatic_Sensing/requirements.txt.py b/src/Car_Perception_Automatic_Sensing/requirements.txt.py deleted file mode 100644 index e69de29bb2..0000000000 From 253c3857d81be21904086c6728fe70649022a143 Mon Sep 17 00:00:00 2001 From: lj2302 Date: Fri, 19 Dec 2025 20:54:37 +0800 Subject: [PATCH 08/24] [env] add requirements.txt for dependencies --- src/Car_Perception_Automatic_Sensing/requirements.txt | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/src/Car_Perception_Automatic_Sensing/requirements.txt b/src/Car_Perception_Automatic_Sensing/requirements.txt index b047471555..03124bb21d 100644 --- a/src/Car_Perception_Automatic_Sensing/requirements.txt +++ b/src/Car_Perception_Automatic_Sensing/requirements.txt @@ -1,4 +1,6 @@ # 基础数值计算 +@" +# 基础数值计算 numpy>=1.24.0 pandas>=2.0.0 @@ -32,4 +34,5 @@ onnxruntime>=1.15.0 # 可选:CUDA 加速(根据本地环境调整) # torch==2.0.0+cu118 -# torchvision==0.15.1+cu118 \ No newline at end of file +# torchvision==0.15.1+cu118 +"@ | Out-File -FilePath requirements.txt -Encoding utf8 \ No newline at end of file From 25a85dbe32080581052db3657ede5d81878f6842 Mon Sep 17 00:00:00 2001 From: lj2302 Date: Fri, 19 Dec 2025 21:24:33 +0800 Subject: [PATCH 09/24] [data] create data_loader.py skeleton --- .../data_loader.py | 77 +++++++++++++++++++ 1 file changed, 77 insertions(+) create mode 100644 src/Car_Perception_Automatic_Sensing/data_loader.py diff --git a/src/Car_Perception_Automatic_Sensing/data_loader.py b/src/Car_Perception_Automatic_Sensing/data_loader.py new file mode 100644 index 0000000000..28d852eb07 --- /dev/null +++ b/src/Car_Perception_Automatic_Sensing/data_loader.py @@ -0,0 +1,77 @@ +@" +""" +数据加载器模块 +负责自动驾驶感知任务的数据集加载、数据预处理分发等功能 +支持图像类数据集(如KITTI、COCO自动驾驶子集)的加载 +""" + +import os +import numpy as np +import torch +from torch.utils.data import Dataset, DataLoader + + +class AutoDriveDataset(Dataset): + """ + 自动驾驶感知数据集基类 + 所有自定义数据集需继承此类并实现抽象方法 + """ + def __init__(self, data_root: str, split: str = "train", transform=None): + """ + 初始化数据集 + :param data_root: 数据集根目录路径 + :param split: 数据集划分(train/val/test) + :param transform: 数据增强/预处理变换 + """ + self.data_root = data_root + self.split = split + self.transform = transform + self.sample_list = [] # 存储样本路径/索引的列表 + + # 后续将实现:加载样本列表 + self._load_sample_list() + + def _load_sample_list(self): + """ + 加载数据集样本列表(抽象方法,需子类实现) + """ + raise NotImplementedError("子类必须实现 _load_sample_list 方法") + + def __len__(self): + """ + 返回数据集样本总数 + """ + return len(self.sample_list) + + def __getitem__(self, idx: int): + """ + 根据索引获取单个样本(抽象方法,需子类实现) + :param idx: 样本索引 + :return: 处理后的图像和标注数据 + """ + raise NotImplementedError("子类必须实现 __getitem__ 方法") + + +def build_dataloader(dataset: Dataset, batch_size: int, shuffle: bool = True, num_workers: int = 4): + """ + 构建数据加载器 + :param dataset: 实例化的 Dataset 对象 + :param batch_size: 批次大小 + :param shuffle: 是否打乱样本顺序 + :param num_workers: 数据加载进程数 + :return: DataLoader 对象 + """ + dataloader = DataLoader( + dataset=dataset, + batch_size=batch_size, + shuffle=shuffle, + num_workers=num_workers, + pin_memory=True # 加速GPU数据传输 + ) + return dataloader + + +if __name__ == "__main__": + # 测试代码框架(后续可完善) + pass +"@ | Out-File -FilePath data_loader.py -Encoding utf8 \ No newline at end of file From 5aba4cc643f6cba011fa69d37b4341b05d1cdb43 Mon Sep 17 00:00:00 2001 From: lj2302 Date: Fri, 19 Dec 2025 23:16:40 +0800 Subject: [PATCH 10/24] [data] create data_loader.py skeleton --- src/Car_Perception_Automatic_Sensing/data_loader.py | 6 +----- 1 file changed, 1 insertion(+), 5 deletions(-) diff --git a/src/Car_Perception_Automatic_Sensing/data_loader.py b/src/Car_Perception_Automatic_Sensing/data_loader.py index 28d852eb07..eba4500e65 100644 --- a/src/Car_Perception_Automatic_Sensing/data_loader.py +++ b/src/Car_Perception_Automatic_Sensing/data_loader.py @@ -1,11 +1,8 @@ -@" """ 数据加载器模块 负责自动驾驶感知任务的数据集加载、数据预处理分发等功能 支持图像类数据集(如KITTI、COCO自动驾驶子集)的加载 """ - -import os import numpy as np import torch from torch.utils.data import Dataset, DataLoader @@ -73,5 +70,4 @@ def build_dataloader(dataset: Dataset, batch_size: int, shuffle: bool = True, nu if __name__ == "__main__": # 测试代码框架(后续可完善) - pass -"@ | Out-File -FilePath data_loader.py -Encoding utf8 \ No newline at end of file + pass \ No newline at end of file From b81022425926f64e1826c7129ade18f76d6cfb0e Mon Sep 17 00:00:00 2001 From: lj2302 Date: Sat, 20 Dec 2025 18:02:14 +0800 Subject: [PATCH 11/24] [data] implement image loading function --- qodana.yaml | 41 +++++++++++++++++++ .../data_loader.py | 22 ++++++++++ 2 files changed, 63 insertions(+) create mode 100644 qodana.yaml diff --git a/qodana.yaml b/qodana.yaml new file mode 100644 index 0000000000..38e12241aa --- /dev/null +++ b/qodana.yaml @@ -0,0 +1,41 @@ +#-------------------------------------------------------------------------------# +# Qodana analysis is configured by qodana.yaml file # +# https://www.jetbrains.com/help/qodana/qodana-yaml.html # +#-------------------------------------------------------------------------------# +version: "1.0" + +#Specify inspection profile for code analysis +profile: + name: qodana.starter + +#Enable inspections +#include: +# - name: + +#Disable inspections +#exclude: +# - name: +# paths: +# - + +#Execute shell command before Qodana execution (Applied in CI/CD pipeline) +#bootstrap: sh ./prepare-qodana.sh + +#Install IDE plugins before Qodana execution (Applied in CI/CD pipeline) +#plugins: +# - id: #(plugin id can be found at https://plugins.jetbrains.com) + +# Quality gate. Will fail the CI/CD pipeline if any condition is not met +# severityThresholds - configures maximum thresholds for different problem severities +# testCoverageThresholds - configures minimum code coverage on a whole project and newly added code +# Code Coverage is available in Ultimate and Ultimate Plus plans +#failureConditions: +# severityThresholds: +# any: 15 +# critical: 5 +# testCoverageThresholds: +# fresh: 70 +# total: 50 + +#Specify Qodana linter for analysis (Applied in CI/CD pipeline) +linter: jetbrains/qodana-:2025.2 diff --git a/src/Car_Perception_Automatic_Sensing/data_loader.py b/src/Car_Perception_Automatic_Sensing/data_loader.py index eba4500e65..4fa49039e5 100644 --- a/src/Car_Perception_Automatic_Sensing/data_loader.py +++ b/src/Car_Perception_Automatic_Sensing/data_loader.py @@ -3,7 +3,10 @@ 负责自动驾驶感知任务的数据集加载、数据预处理分发等功能 支持图像类数据集(如KITTI、COCO自动驾驶子集)的加载 """ + +import os import numpy as np +import cv2 # 新增:导入opencv用于图像读取 import torch from torch.utils.data import Dataset, DataLoader @@ -34,6 +37,25 @@ def _load_sample_list(self): """ raise NotImplementedError("子类必须实现 _load_sample_list 方法") + def _load_image(self, img_path: str) -> np.ndarray: + """ + 封装图像读取函数 + :param img_path: 图像文件路径 + :return: 读取后的RGB格式图像(np.ndarray) + """ + # 检查图像路径是否存在 + if not os.path.exists(img_path): + raise FileNotFoundError(f"图像文件不存在:{img_path}") + + # 读取图像(cv2默认读取为BGR格式) + img = cv2.imread(img_path) + if img is None: + raise ValueError(f"无法读取图像文件:{img_path}(可能是文件损坏或格式不支持)") + + # 转换为RGB格式(符合大多数深度学习框架的输入要求) + img_rgb = cv2.cvtColor(img, cv2.COLOR_BGR2RGB) + return img_rgb + def __len__(self): """ 返回数据集样本总数 From ff12afc62d0006f86fb7b1458678567ce5e54097 Mon Sep 17 00:00:00 2001 From: lj2302 Date: Sat, 20 Dec 2025 21:01:38 +0800 Subject: [PATCH 12/24] [data] implement image loading function --- src/Car_Perception_Automatic_Sensing/{ => data}/data_loader.py | 0 1 file changed, 0 insertions(+), 0 deletions(-) rename src/Car_Perception_Automatic_Sensing/{ => data}/data_loader.py (100%) diff --git a/src/Car_Perception_Automatic_Sensing/data_loader.py b/src/Car_Perception_Automatic_Sensing/data/data_loader.py similarity index 100% rename from src/Car_Perception_Automatic_Sensing/data_loader.py rename to src/Car_Perception_Automatic_Sensing/data/data_loader.py From f0351647bf2f213ff37b054a5103d578c360fd13 Mon Sep 17 00:00:00 2001 From: lj2302 Date: Sun, 21 Dec 2025 13:27:34 +0800 Subject: [PATCH 13/24] [data] implement image loading function --- src/Car_Perception_Automatic_Sensing/{data => }/data_loader.py | 1 - 1 file changed, 1 deletion(-) rename src/Car_Perception_Automatic_Sensing/{data => }/data_loader.py (98%) diff --git a/src/Car_Perception_Automatic_Sensing/data/data_loader.py b/src/Car_Perception_Automatic_Sensing/data_loader.py similarity index 98% rename from src/Car_Perception_Automatic_Sensing/data/data_loader.py rename to src/Car_Perception_Automatic_Sensing/data_loader.py index eba4500e65..bbb739b579 100644 --- a/src/Car_Perception_Automatic_Sensing/data/data_loader.py +++ b/src/Car_Perception_Automatic_Sensing/data_loader.py @@ -10,7 +10,6 @@ class AutoDriveDataset(Dataset): """ - 自动驾驶感知数据集基类 所有自定义数据集需继承此类并实现抽象方法 """ def __init__(self, data_root: str, split: str = "train", transform=None): From 26d2d285c5b7f4e01f13549f312ecc5e7e1f672a Mon Sep 17 00:00:00 2001 From: lj2302 Date: Sun, 21 Dec 2025 14:32:51 +0800 Subject: [PATCH 14/24] [data] implement image loading function --- src/Car_Perception_Automatic_Sensing/{ => data}/data_loader.py | 0 1 file changed, 0 insertions(+), 0 deletions(-) rename src/Car_Perception_Automatic_Sensing/{ => data}/data_loader.py (100%) diff --git a/src/Car_Perception_Automatic_Sensing/data_loader.py b/src/Car_Perception_Automatic_Sensing/data/data_loader.py similarity index 100% rename from src/Car_Perception_Automatic_Sensing/data_loader.py rename to src/Car_Perception_Automatic_Sensing/data/data_loader.py From 0253ecd183b48c9bafeba9b926a8c658d58377e6 Mon Sep 17 00:00:00 2001 From: lj2302 Date: Sun, 21 Dec 2025 22:50:43 +0800 Subject: [PATCH 15/24] [data] create data module with dataset base class and image loading function --- src/Car_Perception_Automatic_Sensing/data.py | 0 .../data/data_loader.py | 72 ------------------- .../data_loader.py | 0 3 files changed, 72 deletions(-) create mode 100644 src/Car_Perception_Automatic_Sensing/data.py delete mode 100644 src/Car_Perception_Automatic_Sensing/data/data_loader.py create mode 100644 src/Car_Perception_Automatic_Sensing/data_loader.py diff --git a/src/Car_Perception_Automatic_Sensing/data.py b/src/Car_Perception_Automatic_Sensing/data.py new file mode 100644 index 0000000000..e69de29bb2 diff --git a/src/Car_Perception_Automatic_Sensing/data/data_loader.py b/src/Car_Perception_Automatic_Sensing/data/data_loader.py deleted file mode 100644 index bbb739b579..0000000000 --- a/src/Car_Perception_Automatic_Sensing/data/data_loader.py +++ /dev/null @@ -1,72 +0,0 @@ -""" -数据加载器模块 -负责自动驾驶感知任务的数据集加载、数据预处理分发等功能 -支持图像类数据集(如KITTI、COCO自动驾驶子集)的加载 -""" -import numpy as np -import torch -from torch.utils.data import Dataset, DataLoader - - -class AutoDriveDataset(Dataset): - """ - 所有自定义数据集需继承此类并实现抽象方法 - """ - def __init__(self, data_root: str, split: str = "train", transform=None): - """ - 初始化数据集 - :param data_root: 数据集根目录路径 - :param split: 数据集划分(train/val/test) - :param transform: 数据增强/预处理变换 - """ - self.data_root = data_root - self.split = split - self.transform = transform - self.sample_list = [] # 存储样本路径/索引的列表 - - # 后续将实现:加载样本列表 - self._load_sample_list() - - def _load_sample_list(self): - """ - 加载数据集样本列表(抽象方法,需子类实现) - """ - raise NotImplementedError("子类必须实现 _load_sample_list 方法") - - def __len__(self): - """ - 返回数据集样本总数 - """ - return len(self.sample_list) - - def __getitem__(self, idx: int): - """ - 根据索引获取单个样本(抽象方法,需子类实现) - :param idx: 样本索引 - :return: 处理后的图像和标注数据 - """ - raise NotImplementedError("子类必须实现 __getitem__ 方法") - - -def build_dataloader(dataset: Dataset, batch_size: int, shuffle: bool = True, num_workers: int = 4): - """ - 构建数据加载器 - :param dataset: 实例化的 Dataset 对象 - :param batch_size: 批次大小 - :param shuffle: 是否打乱样本顺序 - :param num_workers: 数据加载进程数 - :return: DataLoader 对象 - """ - dataloader = DataLoader( - dataset=dataset, - batch_size=batch_size, - shuffle=shuffle, - num_workers=num_workers, - pin_memory=True # 加速GPU数据传输 - ) - return dataloader - - -if __name__ == "__main__": - # 测试代码框架(后续可完善) - pass \ No newline at end of file diff --git a/src/Car_Perception_Automatic_Sensing/data_loader.py b/src/Car_Perception_Automatic_Sensing/data_loader.py new file mode 100644 index 0000000000..e69de29bb2 From ce8b2654de0741fef58936e611f31a020613e406 Mon Sep 17 00:00:00 2001 From: lj2302 Date: Sun, 21 Dec 2025 22:55:10 +0800 Subject: [PATCH 16/24] [data] create data module with dataset base class and image loading function --- src/Car_Perception_Automatic_Sensing/data.py | 15 +++ .../data_loader.py | 96 +++++++++++++++++++ 2 files changed, 111 insertions(+) diff --git a/src/Car_Perception_Automatic_Sensing/data.py b/src/Car_Perception_Automatic_Sensing/data.py index e69de29bb2..6d2fd3587d 100644 --- a/src/Car_Perception_Automatic_Sensing/data.py +++ b/src/Car_Perception_Automatic_Sensing/data.py @@ -0,0 +1,15 @@ +""" +数据模块(data) +负责自动驾驶感知任务的数据集加载、图像预处理、数据增强等功能 +支持KITTI、Waymo、COCO等自动驾驶数据集 +""" + +# 导出核心类和函数 +from .data_loader import AutoDriveDataset, build_dataloader +from .preprocess_utils import load_image_rgb + +__all__ = [ + "AutoDriveDataset", + "build_dataloader", + "load_image_rgb" +] \ No newline at end of file diff --git a/src/Car_Perception_Automatic_Sensing/data_loader.py b/src/Car_Perception_Automatic_Sensing/data_loader.py index e69de29bb2..5ed9a7620b 100644 --- a/src/Car_Perception_Automatic_Sensing/data_loader.py +++ b/src/Car_Perception_Automatic_Sensing/data_loader.py @@ -0,0 +1,96 @@ +""" +数据加载器模块 +负责自动驾驶感知任务的数据集加载、数据预处理分发等功能 +支持图像类数据集(如KITTI、COCO自动驾驶子集)的加载 +""" + +import os +import numpy as np +import cv2 # 新增:导入opencv用于图像读取 +import torch +from torch.utils.data import Dataset, DataLoader + + +class AutoDriveDataset(Dataset): + """ + 自动驾驶感知数据集基类 + 所有自定义数据集需继承此类并实现抽象方法 + """ + + def __init__(self, data_root: str, split: str = "train", transform=None): + """ + 初始化数据集 + :param data_root: 数据集根目录路径 + :param split: 数据集划分(train/val/test) + :param transform: 数据增强/预处理变换 + """ + self.data_root = data_root + self.split = split + self.transform = transform + self.sample_list = [] # 存储样本路径/索引的列表 + + # 后续将实现:加载样本列表 + self._load_sample_list() + + def _load_sample_list(self): + """ + 加载数据集样本列表(抽象方法,需子类实现) + """ + raise NotImplementedError("子类必须实现 _load_sample_list 方法") + + def _load_image(self, img_path: str) -> np.ndarray: + """ + 封装图像读取函数 + :param img_path: 图像文件路径 + :return: 读取后的RGB格式图像(np.ndarray) + """ + # 检查图像路径是否存在 + if not os.path.exists(img_path): + raise FileNotFoundError(f"图像文件不存在:{img_path}") + + # 读取图像(cv2默认读取为BGR格式) + img = cv2.imread(img_path) + if img is None: + raise ValueError(f"无法读取图像文件:{img_path}(可能是文件损坏或格式不支持)") + + # 转换为RGB格式(符合大多数深度学习框架的输入要求) + img_rgb = cv2.cvtColor(img, cv2.COLOR_BGR2RGB) + return img_rgb + + def __len__(self): + """ + 返回数据集样本总数 + """ + return len(self.sample_list) + + def __getitem__(self, idx: int): + """ + 根据索引获取单个样本(抽象方法,需子类实现) + :param idx: 样本索引 + :return: 处理后的图像和标注数据 + """ + raise NotImplementedError("子类必须实现 __getitem__ 方法") + + +def build_dataloader(dataset: Dataset, batch_size: int, shuffle: bool = True, num_workers: int = 4): + """ + 构建数据加载器 + :param dataset: 实例化的 Dataset 对象 + :param batch_size: 批次大小 + :param shuffle: 是否打乱样本顺序 + :param num_workers: 数据加载进程数 + :return: DataLoader 对象 + """ + dataloader = DataLoader( + dataset=dataset, + batch_size=batch_size, + shuffle=shuffle, + num_workers=num_workers, + pin_memory=True # 加速GPU数据传输 + ) + return dataloader + + +if __name__ == "__main__": + # 测试代码框架(后续可完善) + pass \ No newline at end of file From 717d3f8bd9b18b29ddafa5d612034b0bbd200b10 Mon Sep 17 00:00:00 2001 From: lj2302 Date: Mon, 22 Dec 2025 09:48:18 +0800 Subject: [PATCH 17/24] [data] implement image loading function --- data/__init__.py | 0 .../data_loader.py | 0 src/Car_Perception_Automatic_Sensing/data.py | 15 --------------- 3 files changed, 15 deletions(-) create mode 100644 data/__init__.py rename {src/Car_Perception_Automatic_Sensing => data}/data_loader.py (100%) delete mode 100644 src/Car_Perception_Automatic_Sensing/data.py diff --git a/data/__init__.py b/data/__init__.py new file mode 100644 index 0000000000..e69de29bb2 diff --git a/src/Car_Perception_Automatic_Sensing/data_loader.py b/data/data_loader.py similarity index 100% rename from src/Car_Perception_Automatic_Sensing/data_loader.py rename to data/data_loader.py diff --git a/src/Car_Perception_Automatic_Sensing/data.py b/src/Car_Perception_Automatic_Sensing/data.py deleted file mode 100644 index 6d2fd3587d..0000000000 --- a/src/Car_Perception_Automatic_Sensing/data.py +++ /dev/null @@ -1,15 +0,0 @@ -""" -数据模块(data) -负责自动驾驶感知任务的数据集加载、图像预处理、数据增强等功能 -支持KITTI、Waymo、COCO等自动驾驶数据集 -""" - -# 导出核心类和函数 -from .data_loader import AutoDriveDataset, build_dataloader -from .preprocess_utils import load_image_rgb - -__all__ = [ - "AutoDriveDataset", - "build_dataloader", - "load_image_rgb" -] \ No newline at end of file From 21be098a3d5af759749011ed0e2263b24f37cfea Mon Sep 17 00:00:00 2001 From: lj2302 Date: Mon, 22 Dec 2025 10:57:28 +0800 Subject: [PATCH 18/24] [data] implement image loading function --- .../data/__init__.py | 0 .../data}/data_loader.py | 21 ------------------- src/__init__.py | 0 3 files changed, 21 deletions(-) create mode 100644 src/Car_Perception_Automatic_Sensing/data/__init__.py rename {data => src/Car_Perception_Automatic_Sensing/data}/data_loader.py (73%) create mode 100644 src/__init__.py diff --git a/src/Car_Perception_Automatic_Sensing/data/__init__.py b/src/Car_Perception_Automatic_Sensing/data/__init__.py new file mode 100644 index 0000000000..e69de29bb2 diff --git a/data/data_loader.py b/src/Car_Perception_Automatic_Sensing/data/data_loader.py similarity index 73% rename from data/data_loader.py rename to src/Car_Perception_Automatic_Sensing/data/data_loader.py index 5ed9a7620b..8f420fed6e 100644 --- a/data/data_loader.py +++ b/src/Car_Perception_Automatic_Sensing/data/data_loader.py @@ -6,7 +6,6 @@ import os import numpy as np -import cv2 # 新增:导入opencv用于图像读取 import torch from torch.utils.data import Dataset, DataLoader @@ -16,7 +15,6 @@ class AutoDriveDataset(Dataset): 自动驾驶感知数据集基类 所有自定义数据集需继承此类并实现抽象方法 """ - def __init__(self, data_root: str, split: str = "train", transform=None): """ 初始化数据集 @@ -38,25 +36,6 @@ def _load_sample_list(self): """ raise NotImplementedError("子类必须实现 _load_sample_list 方法") - def _load_image(self, img_path: str) -> np.ndarray: - """ - 封装图像读取函数 - :param img_path: 图像文件路径 - :return: 读取后的RGB格式图像(np.ndarray) - """ - # 检查图像路径是否存在 - if not os.path.exists(img_path): - raise FileNotFoundError(f"图像文件不存在:{img_path}") - - # 读取图像(cv2默认读取为BGR格式) - img = cv2.imread(img_path) - if img is None: - raise ValueError(f"无法读取图像文件:{img_path}(可能是文件损坏或格式不支持)") - - # 转换为RGB格式(符合大多数深度学习框架的输入要求) - img_rgb = cv2.cvtColor(img, cv2.COLOR_BGR2RGB) - return img_rgb - def __len__(self): """ 返回数据集样本总数 diff --git a/src/__init__.py b/src/__init__.py new file mode 100644 index 0000000000..e69de29bb2 From 78f834a351ba96c9ac6a4cc09a377a23a5aeacd2 Mon Sep 17 00:00:00 2001 From: lj2302 Date: Mon, 22 Dec 2025 19:47:29 +0800 Subject: [PATCH 19/24] [data] create data/ directory and data_loader.py skeleton --- .../data/__init__.py | 0 .../data/data_loader.py | 85 ++++++++----------- 2 files changed, 34 insertions(+), 51 deletions(-) delete mode 100644 src/Car_Perception_Automatic_Sensing/data/__init__.py diff --git a/src/Car_Perception_Automatic_Sensing/data/__init__.py b/src/Car_Perception_Automatic_Sensing/data/__init__.py deleted file mode 100644 index e69de29bb2..0000000000 diff --git a/src/Car_Perception_Automatic_Sensing/data/data_loader.py b/src/Car_Perception_Automatic_Sensing/data/data_loader.py index 8f420fed6e..c3b550c992 100644 --- a/src/Car_Perception_Automatic_Sensing/data/data_loader.py +++ b/src/Car_Perception_Automatic_Sensing/data/data_loader.py @@ -1,75 +1,58 @@ """ -数据加载器模块 -负责自动驾驶感知任务的数据集加载、数据预处理分发等功能 -支持图像类数据集(如KITTI、COCO自动驾驶子集)的加载 +数据加载器核心模块 +支持自动驾驶数据集的加载、样本管理与批次分发 """ - import os import numpy as np import torch from torch.utils.data import Dataset, DataLoader +from typing import Optional, List class AutoDriveDataset(Dataset): - """ - 自动驾驶感知数据集基类 - 所有自定义数据集需继承此类并实现抽象方法 - """ - def __init__(self, data_root: str, split: str = "train", transform=None): - """ - 初始化数据集 - :param data_root: 数据集根目录路径 - :param split: 数据集划分(train/val/test) - :param transform: 数据增强/预处理变换 - """ - self.data_root = data_root + """自动驾驶感知数据集基类(所有自定义数据集需继承此类)""" + def __init__(self, data_root: str, split: str = "train", transform: Optional[object] = None): + self.data_root = os.path.abspath(data_root) self.split = split self.transform = transform - self.sample_list = [] # 存储样本路径/索引的列表 - - # 后续将实现:加载样本列表 - self._load_sample_list() + self.sample_paths: List[str] = [] # 存储所有样本路径 + self._load_sample_paths() # 加载样本列表 - def _load_sample_list(self): - """ - 加载数据集样本列表(抽象方法,需子类实现) - """ - raise NotImplementedError("子类必须实现 _load_sample_list 方法") + def _load_sample_paths(self): + """加载样本路径(抽象方法,子类实现)""" + raise NotImplementedError("请在子类中实现 _load_sample_paths 方法") - def __len__(self): - """ - 返回数据集样本总数 - """ - return len(self.sample_list) + def __len__(self) -> int: + """返回样本总数""" + return len(self.sample_paths) def __getitem__(self, idx: int): - """ - 根据索引获取单个样本(抽象方法,需子类实现) - :param idx: 样本索引 - :return: 处理后的图像和标注数据 - """ - raise NotImplementedError("子类必须实现 __getitem__ 方法") - - -def build_dataloader(dataset: Dataset, batch_size: int, shuffle: bool = True, num_workers: int = 4): - """ - 构建数据加载器 - :param dataset: 实例化的 Dataset 对象 - :param batch_size: 批次大小 - :param shuffle: 是否打乱样本顺序 - :param num_workers: 数据加载进程数 - :return: DataLoader 对象 - """ - dataloader = DataLoader( + """获取单个样本(抽象方法,子类实现)""" + raise NotImplementedError("请在子类中实现 __getitem__ 方法") + + +def build_dataloader( + dataset: Dataset, + batch_size: int, + shuffle: bool = True, + num_workers: int = 4, + drop_last: bool = False +) -> DataLoader: + """构建PyTorch DataLoader(跨系统兼容)""" + # Windows系统默认关闭多进程 + if os.name == "nt": + num_workers = 0 + + return DataLoader( dataset=dataset, batch_size=batch_size, shuffle=shuffle, num_workers=num_workers, - pin_memory=True # 加速GPU数据传输 + pin_memory=True, + drop_last=drop_last ) - return dataloader if __name__ == "__main__": - # 测试代码框架(后续可完善) + # 框架测试 pass \ No newline at end of file From 5696af8b88b8fb2d5b66341b33df531c5fb4f1d4 Mon Sep 17 00:00:00 2001 From: lj2302 Date: Tue, 23 Dec 2025 17:17:06 +0800 Subject: [PATCH 20/24] =?UTF-8?q?=E4=BF=AE=E6=94=B9README.md=E6=96=87?= =?UTF-8?q?=E4=BB=B6?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../README.md | 31 +++++++++- .../data/data_loader.py | 58 ------------------- 2 files changed, 29 insertions(+), 60 deletions(-) delete mode 100644 src/Car_Perception_Automatic_Sensing/data/data_loader.py diff --git a/src/Car_Perception_Automatic_Sensing/README.md b/src/Car_Perception_Automatic_Sensing/README.md index a93adc2a1c..7b35be059e 100644 --- a/src/Car_Perception_Automatic_Sensing/README.md +++ b/src/Car_Perception_Automatic_Sensing/README.md @@ -1,2 +1,29 @@ -无人车 无人车动态障碍物避障算法 无人车动态障碍物避障的核心目标是:在实时感知环境中移动障碍物(行人和车辆)的基础上,快速规划出无碰撞、平滑且符合运动学约束的安全路径 -环境:python3.13 \ No newline at end of file +# Car_Perception_Automatic_Sensing +自动驾驶环境感知自动感知系统,支持车辆、行人、车道线等目标的检测与分割。 + +## 功能模块 +- 数据加载与预处理(支持 KITTI/Waymo 数据集) +- 深度学习模型搭建(CNN/Transformer 骨干网络) +- 模型训练与验证 +- 推理可视化与结果导出## +- 目录结构 +Car_Perception_Automatic_Sensing/ +- ├── data/ # 数据集目录 +- ├── model/ # 模型定义目录 +- ├── loss/ # 损失函数目录 +- ├── train/ # 训练脚本目录 +- ├── infer/ # 推理脚本目录 +- ├── utils/ # 工具类目录 +- ├── test/ # 测试用例目录 +- ├── requirements.txt # 依赖配置 +- └── README.md # 项目文档 + + +## 环境要求 +Python >= 3.8,PyTorch >= 2.0.0 + +## 快速开始 +1. 克隆仓库 +2. 安装依赖 +3. 准备数据集 +4. 运行训练脚本 \ No newline at end of file diff --git a/src/Car_Perception_Automatic_Sensing/data/data_loader.py b/src/Car_Perception_Automatic_Sensing/data/data_loader.py deleted file mode 100644 index c3b550c992..0000000000 --- a/src/Car_Perception_Automatic_Sensing/data/data_loader.py +++ /dev/null @@ -1,58 +0,0 @@ -""" -数据加载器核心模块 -支持自动驾驶数据集的加载、样本管理与批次分发 -""" -import os -import numpy as np -import torch -from torch.utils.data import Dataset, DataLoader -from typing import Optional, List - - -class AutoDriveDataset(Dataset): - """自动驾驶感知数据集基类(所有自定义数据集需继承此类)""" - def __init__(self, data_root: str, split: str = "train", transform: Optional[object] = None): - self.data_root = os.path.abspath(data_root) - self.split = split - self.transform = transform - self.sample_paths: List[str] = [] # 存储所有样本路径 - self._load_sample_paths() # 加载样本列表 - - def _load_sample_paths(self): - """加载样本路径(抽象方法,子类实现)""" - raise NotImplementedError("请在子类中实现 _load_sample_paths 方法") - - def __len__(self) -> int: - """返回样本总数""" - return len(self.sample_paths) - - def __getitem__(self, idx: int): - """获取单个样本(抽象方法,子类实现)""" - raise NotImplementedError("请在子类中实现 __getitem__ 方法") - - -def build_dataloader( - dataset: Dataset, - batch_size: int, - shuffle: bool = True, - num_workers: int = 4, - drop_last: bool = False -) -> DataLoader: - """构建PyTorch DataLoader(跨系统兼容)""" - # Windows系统默认关闭多进程 - if os.name == "nt": - num_workers = 0 - - return DataLoader( - dataset=dataset, - batch_size=batch_size, - shuffle=shuffle, - num_workers=num_workers, - pin_memory=True, - drop_last=drop_last - ) - - -if __name__ == "__main__": - # 框架测试 - pass \ No newline at end of file From 18618fe0c7b20f1fc95dbb6c04eda8fbd16f1f64 Mon Sep 17 00:00:00 2001 From: lj2302 Date: Tue, 23 Dec 2025 17:55:08 +0800 Subject: [PATCH 21/24] [data] create data/ directory and data/data_loader.py skeleton --- .../.gitignore | 30 ++++++++++ .../data/data_loader.py | 58 +++++++++++++++++++ 2 files changed, 88 insertions(+) create mode 100644 src/Car_Perception_Automatic_Sensing/.gitignore create mode 100644 src/Car_Perception_Automatic_Sensing/data/data_loader.py diff --git a/src/Car_Perception_Automatic_Sensing/.gitignore b/src/Car_Perception_Automatic_Sensing/.gitignore new file mode 100644 index 0000000000..f3285da82c --- /dev/null +++ b/src/Car_Perception_Automatic_Sensing/.gitignore @@ -0,0 +1,30 @@ +# Python 相关 +__pycache__/ +*.pyc +*.pyo +*.pyd +.venv/ +env/ +*.env + +# PyCharm 相关 +.idea/ +*.iml +*.iws +*.ipr +out/ + +# 项目无关目录/文件 +../../.idea/ + +# 数据与模型(后续会用到) +data/raw/ +data/kitti/ +*.npy +*.pth +train/checkpoints/ +infer/results/ + +# OS 相关 +.DS_Store +Thumbs.db \ No newline at end of file diff --git a/src/Car_Perception_Automatic_Sensing/data/data_loader.py b/src/Car_Perception_Automatic_Sensing/data/data_loader.py new file mode 100644 index 0000000000..13e62184d6 --- /dev/null +++ b/src/Car_Perception_Automatic_Sensing/data/data_loader.py @@ -0,0 +1,58 @@ +""" +数据加载器核心模块(data模块) +支持自动驾驶数据集的加载、样本管理与批次分发 +""" +import os +import numpy as np +import torch +from torch.utils.data import Dataset, DataLoader +from typing import Optional, List + + +class AutoDriveDataset(Dataset): + """自动驾驶感知数据集基类(所有自定义数据集需继承此类)""" + def __init__(self, data_root: str, split: str = "train", transform: Optional[object] = None): + self.data_root = os.path.abspath(data_root) # 绝对路径,提升兼容性 + self.split = split + self.transform = transform + self.sample_paths: List[str] = [] # 存储所有样本路径 + self._load_sample_paths() # 加载样本列表 + + def _load_sample_paths(self): + """加载样本路径(抽象方法,子类实现)""" + raise NotImplementedError("请在子类中实现 _load_sample_paths 方法") + + def __len__(self) -> int: + """返回样本总数""" + return len(self.sample_paths) + + def __getitem__(self, idx: int): + """获取单个样本(抽象方法,子类实现)""" + raise NotImplementedError("请在子类中实现 __getitem__ 方法") + + +def build_dataloader( + dataset: Dataset, + batch_size: int, + shuffle: bool = True, + num_workers: int = 4, + drop_last: bool = False +) -> DataLoader: + """构建PyTorch DataLoader(跨系统兼容)""" + # Windows系统默认关闭多进程(避免报错) + if os.name == "nt": + num_workers = 0 + + return DataLoader( + dataset=dataset, + batch_size=batch_size, + shuffle=shuffle, + num_workers=num_workers, + pin_memory=True, # 加速GPU数据传输 + drop_last=drop_last + ) + + +if __name__ == "__main__": + # 框架测试(空运行) + pass \ No newline at end of file From 603bcb6462c34bee00f2a2def4b57eb7f17d7997 Mon Sep 17 00:00:00 2001 From: lj2302 Date: Wed, 24 Dec 2025 19:24:54 +0800 Subject: [PATCH 22/24] =?UTF-8?q?=E4=BF=AE=E6=94=B9README.m=E6=96=87?= =?UTF-8?q?=E4=BB=B6?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../data/data_loader.py | 58 ------------------- 1 file changed, 58 deletions(-) delete mode 100644 src/Car_Perception_Automatic_Sensing/data/data_loader.py diff --git a/src/Car_Perception_Automatic_Sensing/data/data_loader.py b/src/Car_Perception_Automatic_Sensing/data/data_loader.py deleted file mode 100644 index 13e62184d6..0000000000 --- a/src/Car_Perception_Automatic_Sensing/data/data_loader.py +++ /dev/null @@ -1,58 +0,0 @@ -""" -数据加载器核心模块(data模块) -支持自动驾驶数据集的加载、样本管理与批次分发 -""" -import os -import numpy as np -import torch -from torch.utils.data import Dataset, DataLoader -from typing import Optional, List - - -class AutoDriveDataset(Dataset): - """自动驾驶感知数据集基类(所有自定义数据集需继承此类)""" - def __init__(self, data_root: str, split: str = "train", transform: Optional[object] = None): - self.data_root = os.path.abspath(data_root) # 绝对路径,提升兼容性 - self.split = split - self.transform = transform - self.sample_paths: List[str] = [] # 存储所有样本路径 - self._load_sample_paths() # 加载样本列表 - - def _load_sample_paths(self): - """加载样本路径(抽象方法,子类实现)""" - raise NotImplementedError("请在子类中实现 _load_sample_paths 方法") - - def __len__(self) -> int: - """返回样本总数""" - return len(self.sample_paths) - - def __getitem__(self, idx: int): - """获取单个样本(抽象方法,子类实现)""" - raise NotImplementedError("请在子类中实现 __getitem__ 方法") - - -def build_dataloader( - dataset: Dataset, - batch_size: int, - shuffle: bool = True, - num_workers: int = 4, - drop_last: bool = False -) -> DataLoader: - """构建PyTorch DataLoader(跨系统兼容)""" - # Windows系统默认关闭多进程(避免报错) - if os.name == "nt": - num_workers = 0 - - return DataLoader( - dataset=dataset, - batch_size=batch_size, - shuffle=shuffle, - num_workers=num_workers, - pin_memory=True, # 加速GPU数据传输 - drop_last=drop_last - ) - - -if __name__ == "__main__": - # 框架测试(空运行) - pass \ No newline at end of file From 180a8ab5c6a85f043d2ee0c919b37c7adf29cf6d Mon Sep 17 00:00:00 2001 From: lj2302 Date: Wed, 24 Dec 2025 19:31:45 +0800 Subject: [PATCH 23/24] =?UTF-8?q?=E4=BF=AE=E6=94=B9README.m=E6=96=87?= =?UTF-8?q?=E4=BB=B6?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/Car_Perception_Automatic_Sensing/README.md | 7 +++---- 1 file changed, 3 insertions(+), 4 deletions(-) diff --git a/src/Car_Perception_Automatic_Sensing/README.md b/src/Car_Perception_Automatic_Sensing/README.md index 7b35be059e..7602125d1c 100644 --- a/src/Car_Perception_Automatic_Sensing/README.md +++ b/src/Car_Perception_Automatic_Sensing/README.md @@ -8,9 +8,9 @@ - 推理可视化与结果导出## - 目录结构 Car_Perception_Automatic_Sensing/ -- ├── data/ # 数据集目录 -- ├── model/ # 模型定义目录 -- ├── loss/ # 损失函数目录 +- ├── data/ +- ├── model/ +- ├── loss/ - ├── train/ # 训练脚本目录 - ├── infer/ # 推理脚本目录 - ├── utils/ # 工具类目录 @@ -18,7 +18,6 @@ Car_Perception_Automatic_Sensing/ - ├── requirements.txt # 依赖配置 - └── README.md # 项目文档 - ## 环境要求 Python >= 3.8,PyTorch >= 2.0.0 From f9c5f7224765f16a7ca1d1a42f2c1f181fe08ced Mon Sep 17 00:00:00 2001 From: lj2302 Date: Thu, 25 Dec 2025 19:09:51 +0800 Subject: [PATCH 24/24] =?UTF-8?q?=E6=95=B0=E6=8D=AE=E6=A8=A1=E5=9D=97=20-?= =?UTF-8?q?=20=E5=AE=9E=E7=8E=B0=E5=9B=BE=E5=83=8F=E8=AF=BB=E5=8F=96?= =?UTF-8?q?=E5=8A=9F=E8=83=BD?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../data/__init__.py | 0 .../data/data_loader.py | 80 +++++++++++++++++++ .../data/preprocess.py | 40 ++++++++++ src/Car_Perception_Automatic_Sensing/main.py | 0 4 files changed, 120 insertions(+) create mode 100644 src/Car_Perception_Automatic_Sensing/data/__init__.py create mode 100644 src/Car_Perception_Automatic_Sensing/data/data_loader.py create mode 100644 src/Car_Perception_Automatic_Sensing/data/preprocess.py create mode 100644 src/Car_Perception_Automatic_Sensing/main.py diff --git a/src/Car_Perception_Automatic_Sensing/data/__init__.py b/src/Car_Perception_Automatic_Sensing/data/__init__.py new file mode 100644 index 0000000000..e69de29bb2 diff --git a/src/Car_Perception_Automatic_Sensing/data/data_loader.py b/src/Car_Perception_Automatic_Sensing/data/data_loader.py new file mode 100644 index 0000000000..f600a3e5e9 --- /dev/null +++ b/src/Car_Perception_Automatic_Sensing/data/data_loader.py @@ -0,0 +1,80 @@ +""" +数据加载器核心模块 +支持自动驾驶数据集的加载、样本管理与批次分发 +""" +import os +import numpy as np +import torch +from torch.utils.data import Dataset, DataLoader +from typing import Optional, List + + +class AutoDriveDataset(Dataset): + """自动驾驶感知数据集基类(所有自定义数据集需继承此类)""" + def __init__(self, data_root: str, split: str = "train", transform: Optional[object] = None): + self.data_root = os.path.abspath(data_root) + self.split = split + self.transform = transform + self.sample_paths: List[str] = [] # 存储所有样本路径 + self._load_sample_paths() # 加载样本列表 + + def _load_sample_paths(self): + """加载样本路径(抽象方法,子类实现)""" + raise NotImplementedError("请在子类中实现 _load_sample_paths 方法") + + def __len__(self) -> int: + """返回样本总数""" + return len(self.sample_paths) + + def __getitem__(self, idx: int): + """获取单个样本(抽象方法,子类实现)""" + raise NotImplementedError("请在子类中实现 __getitem__ 方法") + + +def build_dataloader( + dataset: Dataset, + batch_size: int, + shuffle: bool = True, + num_workers: int = 4, + drop_last: bool = False +) -> DataLoader: + """构建PyTorch DataLoader(跨系统兼容)""" + # Windows系统默认关闭多进程 + if os.name == "nt": + num_workers = 0 + + return DataLoader( + dataset=dataset, + batch_size=batch_size, + shuffle=shuffle, + num_workers=num_workers, + pin_memory=True, + drop_last=drop_last + ) + + +if __name__ == "__main__": + # 框架测试 + pass +# 新增导入 +import cv2 +from typing import Tuple + +# 在 AutoDriveDataset 类中新增方法 +def _load_image(self, img_rel_path: str) -> Tuple[np.ndarray, Tuple[int, int, int]]: + """ + 读取图像并转换为RGB格式 + :param img_rel_path: 图像相对路径(基于data_root) + :return: (RGB图像数组, 图像形状(h, w, c)) + """ + img_abs_path = os.path.join(self.data_root, img_rel_path) + # 路径校验 + if not os.path.exists(img_abs_path): + raise FileNotFoundError(f"图像不存在:{img_abs_path}") + # 读取图像(忽略透明通道) + img_bgr = cv2.imread(img_abs_path, cv2.IMREAD_COLOR) + if img_bgr is None: + raise ValueError(f"无法读取图像(损坏/格式不支持):{img_abs_path}") + # BGR转RGB + img_rgb = cv2.cvtColor(img_bgr, cv2.COLOR_BGR2RGB) + return img_rgb, img_rgb.shape \ No newline at end of file diff --git a/src/Car_Perception_Automatic_Sensing/data/preprocess.py b/src/Car_Perception_Automatic_Sensing/data/preprocess.py new file mode 100644 index 0000000000..7e3b4ab936 --- /dev/null +++ b/src/Car_Perception_Automatic_Sensing/data/preprocess.py @@ -0,0 +1,40 @@ +"""数据预处理工具:归一化、标准化""" +import numpy as np + + +def normalize_image(img: np.ndarray, target_range: tuple = (0, 1)) -> np.ndarray: + """ + 图像像素值归一化到指定范围 + :param img: 输入图像(np.ndarray, uint8/float32) + :param target_range: 目标范围,默认(0,1) + :return: 归一化后的图像(float32) + """ + img_float = img.astype(np.float32) + min_val = img_float.min() + max_val = img_float.max() + # 避免除零 + if max_val - min_val < 1e-6: + return np.zeros_like(img_float) + target_range[0] + # 归一化计算 + normalized = (img_float - min_val) / (max_val - min_val) + normalized = normalized * (target_range[1] - target_range[0]) + target_range[0] + return normalized + + +def standardize_image(img: np.ndarray, mean: list = None, std: list = None) -> np.ndarray: + """ + 图像标准化(减均值、除标准差) + :param img: 输入RGB图像(np.ndarray, (h,w,3)) + :param mean: 通道均值,默认ImageNet均值 + :param std: 通道标准差,默认ImageNet标准差 + :return: 标准化后的图像 + """ + if mean is None: + mean = [0.485, 0.456, 0.406] + if std is None: + std = [0.229, 0.224, 0.225] + + img_float = img.astype(np.float32) / 255.0 # 先归一化到0-1 + for i in range(3): + img_float[..., i] = (img_float[..., i] - mean[i]) / std[i] + return img_float \ No newline at end of file diff --git a/src/Car_Perception_Automatic_Sensing/main.py b/src/Car_Perception_Automatic_Sensing/main.py new file mode 100644 index 0000000000..e69de29bb2