diff --git a/src/Autonomous_vehicle_navigation_using_deep_learning_master/README.md b/src/Autonomous_vehicle_navigation_using_deep_learning_master/README.md index f60838bd84..3a90822a45 100644 --- a/src/Autonomous_vehicle_navigation_using_deep_learning_master/README.md +++ b/src/Autonomous_vehicle_navigation_using_deep_learning_master/README.md @@ -1,17 +1,85 @@ -这是manayume的使用深度学习的自动驾驶汽车导航项目测试 -参考项目:https://github.com/varunpratap222/Autonomous-Vehicle-Navigation-Using-Deep-Learning.git -测试环境:使用ubuntu20.04版本,conda虚拟环境,python3.7版本,安装的软件包按照requirements.txt文件安装,使用Carla0.9.13版本进行模拟 +# Autonomous Vehicle Navigation Using Deep Learning +本项目基于深度学习实现自动驾驶汽车在CARLA仿真环境中的导航系统,支持自定义轨迹规划和行人动态模拟。 -启动流程 -## Run -1. Run Carla Server using: `./CarlaUE4.sh` -2. Run `config.py` file to load Town02 -3. Generate traffic either using `generate_traffic.py` or spawn pedestrians at random location along Trajectory 1 and 2 using the `pedestrians_1.py` and `pedestrians_2.py` script. Change the number of vehicles and pedestrians to spawn using `generate_traffic.py` by passing the corresponding arguments. -4. Select an existing trajectory (Trajectory 1, Trajectory 2, Trajectory 3, Trajectory 4) or set custom trajectory using the format given in `test_everything.py` arguments. -5. To find the initial and final locations of the custom trajectory, make use of `get_location.py` file and navigate the map using W,A,S,D, E, and Q keys. -6. Enter locations or select existing trajectories and run the `test_everything.py` file. +## 快速开始 +### 环境要求 +- **操作系统**: Ubuntu 20.04 +- **仿真环境**: CARLA 0.9.13 +- **Python**: 3.7 +- **包管理**: Conda虚拟环境 +### 安装步骤 +1. **安装依赖包**: +```bash +conda create -n carla-env python=3.7 +conda activate carla-env +pip install -r requirements.txt +``` +2. **启动CARLA仿真器**: +```bash +./CarlaUE4.sh +``` + +3. **运行主程序**: +```bash +python main.py +``` + +## 项目结构 + +``` +├── main.py # 主程序入口 +├── config.py # 配置文件 +├── get_location.py # 位置坐标获取工具 +├── test_braking.py # 刹车模型测试 +├── test_driving.py # 驾驶模型测试 +├── pedestrians_1.py # 行人生成器1 +├── pedestrians_2.py # 行人生成器2 +└── requirements.txt # 依赖包列表 +``` + +## 核心功能 + +### 1. 自定义轨迹规划 +使用 `get_location.py` 获取当前摄像头坐标,配置到 `config.py`: + +```python +TRAJECTORIES = { + "custom_trajectory": { + "start": [x, y, z, yaw], # 起点坐标和朝向 + "end": [x, y, z], # 终点坐标 + "description": "自定义轨迹 - 城镇道路" + } +} +``` + +### 2. 模型测试 +- **刹车测试**: `test_braking.py` - 验证紧急制动性能 +- **驾驶测试**: `test_driving.py` - 评估导航准确性 + +### 3. 行人模拟 +- `pedestrians_1.py` - 随机行人生成(模式1) +- `pedestrians_2.py` - 随机行人生成(模式2) +## 配置说明 + +### 关键配置文件 +`config.py` 包含所有可调整参数: +- 轨迹起点/终点坐标 +- 深度学习模型参数 +- 仿真环境设置 + +## 参考项目 +本项目参考自: [varunpratap222/Autonomous-Vehicle-Navigation-Using-Deep-Learning](https://github.com/varunpratap222/Autonomous-Vehicle-Navigation-Using-Deep-Learning.git) + +## 📝 注意事项 +1. 确保CARLA仿真器已正确启动 +2. 建议在独立的Conda环境中运行 +3. 行人模拟模块需要额外计算资源 + +--- + +**温馨提示**: 运行前请确认CARLA版本为0.9.13,Python版本为3.7,以避免兼容性问题。 \ No newline at end of file diff --git a/src/Autonomous_vehicle_navigation_using_deep_learning_master/generate_traffic.py b/src/Autonomous_vehicle_navigation_using_deep_learning_master/generate_traffic.py deleted file mode 100644 index e3717baf40..0000000000 --- a/src/Autonomous_vehicle_navigation_using_deep_learning_master/generate_traffic.py +++ /dev/null @@ -1,383 +0,0 @@ -#!/usr/bin/env python - -# Copyright (c) 2021 Computer Vision Center (CVC) at the Universitat Autonoma de -# Barcelona (UAB). -# -# This work is licensed under the terms of the MIT license. -# For a copy, see . - -"""Example script to generate traffic in the simulation""" - -import glob -import os -import sys -import time - -try: - sys.path.append(glob.glob('../carla/dist/carla-*%d.%d-%s.egg' % ( - sys.version_info.major, - sys.version_info.minor, - 'win-amd64' if os.name == 'nt' else 'linux-x86_64'))[0]) -except IndexError: - pass - -import carla - -from carla import VehicleLightState as vls - -import argparse -import logging -from numpy import random - -def get_actor_blueprints(world, filter, generation): - bps = world.get_blueprint_library().filter(filter) - - if generation.lower() == "all": - return bps - - # If the filter returns only one bp, we assume that this one needed - # and therefore, we ignore the generation - if len(bps) == 1: - return bps - - try: - int_generation = int(generation) - # Check if generation is in available generations - if int_generation in [1, 2]: - bps = [x for x in bps if int(x.get_attribute('generation')) == int_generation] - return bps - else: - print(" Warning! Actor Generation is not valid. No actor will be spawned.") - return [] - except: - print(" Warning! Actor Generation is not valid. No actor will be spawned.") - return [] - -def main(): - argparser = argparse.ArgumentParser( - description=__doc__) - argparser.add_argument( - '--host', - metavar='H', - default='127.0.0.1', - help='IP of the host server (default: 127.0.0.1)') - argparser.add_argument( - '-p', '--port', - metavar='P', - default=2000, - type=int, - help='TCP port to listen to (default: 2000)') - argparser.add_argument( - '-n', '--number-of-vehicles', - metavar='N', - default=35, - type=int, - help='Number of vehicles (default: 30)') - argparser.add_argument( - '-w', '--number-of-walkers', - metavar='W', - default=80, - type=int, - help='Number of walkers (default: 10)') - argparser.add_argument( - '--safe', - action='store_true', - help='Avoid spawning vehicles prone to accidents') - argparser.add_argument( - '--filterv', - metavar='PATTERN', - default='vehicle.*', - help='Filter vehicle model (default: "vehicle.*")') - argparser.add_argument( - '--generationv', - metavar='G', - default='1', - help='restrict to certain vehicle generation (values: "1","2","All" - default: "All")') - argparser.add_argument( - '--filterw', - metavar='PATTERN', - default='walker.pedestrian.*', - help='Filter pedestrian type (default: "walker.pedestrian.*")') - argparser.add_argument( - '--generationw', - metavar='G', - default='2', - help='restrict to certain pedestrian generation (values: "1","2","All" - default: "2")') - argparser.add_argument( - '--tm-port', - metavar='P', - default=8000, - type=int, - help='Port to communicate with TM (default: 8000)') - argparser.add_argument( - '--asynch', - action='store_true', - help='Activate asynchronous mode execution') - argparser.add_argument( - '--hybrid', - action='store_true', - help='Activate hybrid mode for Traffic Manager') - argparser.add_argument( - '-s', '--seed', - metavar='S', - type=int, - help='Set random device seed and deterministic mode for Traffic Manager') - argparser.add_argument( - '--seedw', - metavar='S', - default=0, - type=int, - help='Set the seed for pedestrians module') - argparser.add_argument( - '--car-lights-on', - action='store_true', - default=False, - help='Enable automatic car light management') - argparser.add_argument( - '--hero', - action='store_true', - default=False, - help='Set one of the vehicles as hero') - argparser.add_argument( - '--respawn', - action='store_true', - default=False, - help='Automatically respawn dormant vehicles (only in large maps)') - argparser.add_argument( - '--no-rendering', - action='store_true', - default=False, - help='Activate no rendering mode') - - args = argparser.parse_args() - - logging.basicConfig(format='%(levelname)s: %(message)s', level=logging.INFO) - - vehicles_list = [] - walkers_list = [] - all_id = [] - client = carla.Client(args.host, args.port) - client.set_timeout(10.0) - synchronous_master = False - random.seed(args.seed if args.seed is not None else int(time.time())) - - try: - world = client.get_world() - - traffic_manager = client.get_trafficmanager(args.tm_port) - traffic_manager.set_global_distance_to_leading_vehicle(2.5) - if args.respawn: - traffic_manager.set_respawn_dormant_vehicles(True) - if args.hybrid: - traffic_manager.set_hybrid_physics_mode(True) - traffic_manager.set_hybrid_physics_radius(70.0) - if args.seed is not None: - traffic_manager.set_random_device_seed(args.seed) - - settings = world.get_settings() - if not args.asynch: - traffic_manager.set_synchronous_mode(True) - if not settings.synchronous_mode: - synchronous_master = True - settings.synchronous_mode = True - settings.fixed_delta_seconds = 0.05 - else: - synchronous_master = False - else: - print("You are currently in asynchronous mode. If this is a traffic simulation, \ - you could experience some issues. If it's not working correctly, switch to synchronous \ - mode by using traffic_manager.set_synchronous_mode(True)") - - if args.no_rendering: - settings.no_rendering_mode = True - world.apply_settings(settings) - - blueprints = get_actor_blueprints(world, args.filterv, args.generationv) - blueprintsWalkers = get_actor_blueprints(world, args.filterw, args.generationw) - - - - if args.safe: - blueprints = [x for x in blueprints if int(x.get_attribute('number_of_wheels')) == 4] - blueprints = [x for x in blueprints if not x.id.endswith('microlino')] - blueprints = [x for x in blueprints if not x.id.endswith('carlacola')] - blueprints = [x for x in blueprints if not x.id.endswith('cybertruck')] - blueprints = [x for x in blueprints if not x.id.endswith('t2')] - blueprints = [x for x in blueprints if not x.id.endswith('sprinter')] - blueprints = [x for x in blueprints if not x.id.endswith('firetruck')] - blueprints = [x for x in blueprints if not x.id.endswith('ambulance')] - - blueprints = sorted(blueprints, key=lambda bp: bp.id) - - spawn_points = world.get_map().get_spawn_points() - number_of_spawn_points = len(spawn_points) - - if args.number_of_vehicles < number_of_spawn_points: - random.shuffle(spawn_points) - elif args.number_of_vehicles > number_of_spawn_points: - msg = 'requested %d vehicles, but could only find %d spawn points' - logging.warning(msg, args.number_of_vehicles, number_of_spawn_points) - args.number_of_vehicles = number_of_spawn_points - - # @todo cannot import these directly. - SpawnActor = carla.command.SpawnActor - SetAutopilot = carla.command.SetAutopilot - FutureActor = carla.command.FutureActor - - # -------------- - # Spawn vehicles - # -------------- - batch = [] - hero = args.hero - for n, transform in enumerate(spawn_points): - if n >= args.number_of_vehicles: - break - blueprint = random.choice(blueprints) - if blueprint.has_attribute('color'): - color = random.choice(blueprint.get_attribute('color').recommended_values) - blueprint.set_attribute('color', color) - if blueprint.has_attribute('driver_id'): - driver_id = random.choice(blueprint.get_attribute('driver_id').recommended_values) - blueprint.set_attribute('driver_id', driver_id) - if hero: - blueprint.set_attribute('role_name', 'hero') - hero = False - else: - blueprint.set_attribute('role_name', 'autopilot') - - # spawn the cars and set their autopilot and light state all together - batch.append(SpawnActor(blueprint, transform) - .then(SetAutopilot(FutureActor, True, traffic_manager.get_port()))) - - for response in client.apply_batch_sync(batch, synchronous_master): - if response.error: - logging.error(response.error) - else: - vehicles_list.append(response.actor_id) - - # Set automatic vehicle lights update if specified - if args.car_lights_on: - all_vehicle_actors = world.get_actors(vehicles_list) - for actor in all_vehicle_actors: - traffic_manager.update_vehicle_lights(actor, True) - - # ------------- - # Spawn Walkers - # ------------- - # some settings - percentagePedestriansRunning = 0.0 # how many pedestrians will run - percentagePedestriansCrossing = 0.0 # how many pedestrians will walk through the road - if args.seedw: - world.set_pedestrians_seed(args.seedw) - random.seed(args.seedw) - # 1. take all the random locations to spawn - spawn_points = [] - for i in range(args.number_of_walkers): - spawn_point = carla.Transform() - loc = world.get_random_location_from_navigation() - if (loc != None): - spawn_point.location = loc - spawn_points.append(spawn_point) - # 2. we spawn the walker object - batch = [] - walker_speed = [] - for spawn_point in spawn_points: - walker_bp = random.choice(blueprintsWalkers) - # set as not invincible - if walker_bp.has_attribute('is_invincible'): - walker_bp.set_attribute('is_invincible', 'false') - # set the max speed - if walker_bp.has_attribute('speed'): - if (random.random() > percentagePedestriansRunning): - # walking - walker_speed.append(walker_bp.get_attribute('speed').recommended_values[1]) - else: - # running - walker_speed.append(walker_bp.get_attribute('speed').recommended_values[2]) - else: - print("Walker has no speed") - walker_speed.append(0.0) - batch.append(SpawnActor(walker_bp, spawn_point)) - results = client.apply_batch_sync(batch, True) - walker_speed2 = [] - for i in range(len(results)): - if results[i].error: - logging.error(results[i].error) - else: - walkers_list.append({"id": results[i].actor_id}) - walker_speed2.append(walker_speed[i]) - walker_speed = walker_speed2 - # 3. we spawn the walker controller - batch = [] - walker_controller_bp = world.get_blueprint_library().find('controller.ai.walker') - for i in range(len(walkers_list)): - batch.append(SpawnActor(walker_controller_bp, carla.Transform(), walkers_list[i]["id"])) - results = client.apply_batch_sync(batch, True) - for i in range(len(results)): - if results[i].error: - logging.error(results[i].error) - else: - walkers_list[i]["con"] = results[i].actor_id - # 4. we put together the walkers and controllers id to get the objects from their id - for i in range(len(walkers_list)): - all_id.append(walkers_list[i]["con"]) - all_id.append(walkers_list[i]["id"]) - all_actors = world.get_actors(all_id) - - # wait for a tick to ensure client receives the last transform of the walkers we have just created - if args.asynch or not synchronous_master: - world.wait_for_tick() - else: - world.tick() - - # 5. initialize each controller and set target to walk to (list is [controler, actor, controller, actor ...]) - # set how many pedestrians can cross the road - world.set_pedestrians_cross_factor(percentagePedestriansCrossing) - for i in range(0, len(all_id), 2): - # start walker - all_actors[i].start() - # set walk to random point - all_actors[i].go_to_location(world.get_random_location_from_navigation()) - # max speed - all_actors[i].set_max_speed(float(walker_speed[int(i/2)])) - - print('spawned %d vehicles and %d walkers, press Ctrl+C to exit.' % (len(vehicles_list), len(walkers_list))) - - # Example of how to use Traffic Manager parameters - traffic_manager.global_percentage_speed_difference(30.0) - - while True: - if not args.asynch and synchronous_master: - world.tick() - else: - world.wait_for_tick() - - finally: - - if not args.asynch and synchronous_master: - settings = world.get_settings() - settings.synchronous_mode = False - settings.no_rendering_mode = False - settings.fixed_delta_seconds = None - world.apply_settings(settings) - - print('\ndestroying %d vehicles' % len(vehicles_list)) - client.apply_batch([carla.command.DestroyActor(x) for x in vehicles_list]) - - # stop walker controllers (list is [controller, actor, controller, actor ...]) - for i in range(0, len(all_id), 2): - all_actors[i].stop() - - print('\ndestroying %d walkers' % len(walkers_list)) - client.apply_batch([carla.command.DestroyActor(x) for x in all_id]) - - time.sleep(0.5) - -if __name__ == '__main__': - - try: - main() - except KeyboardInterrupt: - pass - finally: - print('\ndone.') diff --git a/src/Autonomous_vehicle_navigation_using_deep_learning_master/main.py b/src/Autonomous_vehicle_navigation_using_deep_learning_master/main.py index 104a8c1166..69975cea17 100644 --- a/src/Autonomous_vehicle_navigation_using_deep_learning_master/main.py +++ b/src/Autonomous_vehicle_navigation_using_deep_learning_master/main.py @@ -1,7 +1,6 @@ """ 主程序入口 - 协调所有模块 """ - import os os.environ['TF_CPP_MIN_LOG_LEVEL'] = '2' import time diff --git a/src/Autonomous_vehicle_navigation_using_deep_learning_master/test_everything.py b/src/Autonomous_vehicle_navigation_using_deep_learning_master/test_everything.py deleted file mode 100644 index 6518e316f5..0000000000 --- a/src/Autonomous_vehicle_navigation_using_deep_learning_master/test_everything.py +++ /dev/null @@ -1,302 +0,0 @@ -import os -os.environ['TF_CPP_MIN_LOG_LEVEL'] = '2' -import random -from collections import deque -import numpy as np -import cv2 -import time -import tensorflow as tf -from tensorflow.keras.models import load_model -from car_env import CarEnv, MEMORY_FRACTION -import carla -from carla import Transform, Location, Rotation - -# 轨迹定义 -trajectories = { - "custom_trajectory": { - "start": [-8.77956485748291,140.2951202392578,2.0014660358428955, 0], - "end": [74.17852020263672,-56.52183151245117,0.18172569572925568], - "description": "自定义轨迹" - } -} - -SELECTED_TRAJECTORY = "custom_trajectory" - -def get_selected_trajectory(): - """获取选定的轨迹""" - if SELECTED_TRAJECTORY in trajectories: - trajectory = trajectories[SELECTED_TRAJECTORY] - print(f"✅ 使用轨迹: {SELECTED_TRAJECTORY}") - print(f" 描述: {trajectory['description']}") - print(f" 起点: {trajectory['start']}") - print(f" 终点: {trajectory['end']}") - return trajectory - else: - print(f"❌ 轨迹 '{SELECTED_TRAJECTORY}' 不存在") - return None - -def safe_load_model(model_path): - """安全加载模型""" - try: - if not os.path.exists(model_path): - print(f"❌ 模型文件不存在: {model_path}") - return None - - model = load_model(model_path) - print(f"✅ 成功加载模型: {model_path}") - return model - - except Exception as e: - print(f"❌ 加载模型失败: {e}") - return None - -def setup_tensorflow(): - """设置 TensorFlow 配置""" - os.environ['TF_CPP_MIN_LOG_LEVEL'] = '2' - print(f"TensorFlow 版本: {tf.__version__}") - - # GPU 配置 - gpus = tf.config.list_physical_devices('GPU') - if gpus: - try: - for gpu in gpus: - tf.config.experimental.set_memory_growth(gpu, True) - print(f"✅ 找到 {len(gpus)} 个GPU,已启用内存增长") - except RuntimeError as e: - print(f"⚠️ GPU设置错误: {e}") - os.environ['CUDA_VISIBLE_DEVICES'] = '-1' - print("使用CPU运行") - else: - print("ℹ️ 未找到GPU,使用CPU运行") - -def set_spectator_to_vehicle(world, vehicle): - """设置观察者视角 - 车辆正后方跟随""" - try: - spectator = world.get_spectator() - transform = vehicle.get_transform() - - # 计算车辆后方的位置 - # 使用车辆的旋转来确定方向 - rotation = transform.rotation - yaw = np.radians(rotation.yaw) - - # 在车辆后方一定距离(例如8米),高度3米 - distance_behind = 8.0 - height = 3.0 - - # 计算后方位置(与车辆朝向相反的方向) - behind_x = transform.location.x - distance_behind * np.cos(yaw) - behind_y = transform.location.y - distance_behind * np.sin(yaw) - - # 设置观察者在车辆正后方,稍微高一点 - spectator.set_transform(Transform( - Location(x=behind_x, y=behind_y, z=transform.location.z + height), - Rotation(pitch=-15, yaw=rotation.yaw) # 与车辆相同的水平朝向 - )) - - except Exception as e: - print(f"⚠️ 设置视角时出错: {e}") - -def preprocess_state_for_prediction(state_data, model_type="braking"): - """预处理状态数据用于模型预测""" - try: - if model_type == "braking": - state_array = np.array(state_data[:2]) - else: - state_array = np.array(state_data[2:]) - - if len(state_array.shape) == 1: - state_array = state_array.reshape(1, -1) - - return state_array - except Exception as e: - print(f"状态预处理错误: {e}") - return np.array([[0, 0]]) - -def debug_vehicle_state(vehicle): - """调试车辆状态""" - if vehicle is None: - print("❌ 车辆为 None") - return - - try: - transform = vehicle.get_transform() - velocity = vehicle.get_velocity() - print(f"📍 车辆位置: ({transform.location.x:.2f}, {transform.location.y:.2f}, {transform.location.z:.2f})") - print(f"🧭 车辆朝向: {transform.rotation.yaw:.2f}°") - print(f"🚀 车辆速度: {np.sqrt(velocity.x**2 + velocity.y**2 + velocity.z**2):.2f} m/s") - except Exception as e: - print(f"❌ 获取车辆状态失败: {e}") - -def main(): - # 设置 TensorFlow - setup_tensorflow() - - # 获取选定的轨迹 - trajectory = get_selected_trajectory() - if trajectory is None: - print("❌ 无法获取轨迹,退出程序") - return - - start_location = trajectory["start"] - end_location = trajectory["end"] - - # 加载模型 - print("\n" + "="*50) - print("加载自动驾驶模型") - print("="*50) - - MODEL_PATH = "models/Braking___282.model" - MODEL_PATH2 = "models/Driving__6030.model" - - model = safe_load_model(MODEL_PATH) - model2 = safe_load_model(MODEL_PATH2) - - if model is None or model2 is None: - print("❌ 模型加载失败,退出程序") - return - - # 创建环境 - print("\n初始化CARLA环境...") - try: - env = CarEnv(start_location, end_location) - world = env.client.get_world() - - # 设置仿真设置 - settings = world.get_settings() - settings.synchronous_mode = False - settings.fixed_delta_seconds = 0.05 - world.apply_settings(settings) - - except Exception as e: - print(f"❌ 初始化环境失败: {e}") - return - - # 主循环 - fps_counter = deque(maxlen=60) - EPISODES = 2 - - for episode in range(EPISODES): - print(f'\n{"="*50}') - print(f'开始 Episode {episode + 1}/{EPISODES}') - print(f'{"="*50}') - - # 重置环境 - 这会生成车辆 - try: - print("重置环境...") - current_state = env.reset() - print(f"初始状态: {current_state}") - except Exception as e: - print(f"❌ 环境重置失败: {e}") - continue - - # 从环境中获取车辆 - ego_vehicle = env.vehicle - - if ego_vehicle is None: - print("❌ 环境中没有车辆,跳过此episode") - continue - - # 调试车辆状态 - debug_vehicle_state(ego_vehicle) - - # 设置观察者视角 - set_spectator_to_vehicle(world, ego_vehicle) - - done = False - step_count = 0 - max_steps = 1000 - - while not done and step_count < max_steps: - step_count += 1 - step_start = time.time() - - # 定期更新视角 - if step_count%5==0: - set_spectator_to_vehicle(world, ego_vehicle) - - # 动作预测 - action = 0 - try: - # 检查交通灯 - if hasattr(env, 'vehicle') and env.vehicle and env.vehicle.is_at_traffic_light(): - traffic_light = env.vehicle.get_traffic_light() - if traffic_light and traffic_light.get_state() == carla.TrafficLightState.Red: - print("🚦 红灯 - 停车") - action = 0 - else: - # 使用模型预测 - state_array = preprocess_state_for_prediction(current_state, "braking") - qs = model.predict(state_array, verbose=0)[0] - action = np.argmax(qs) - - if action == 1: # 安全时才使用驾驶模型 - state_array2 = preprocess_state_for_prediction(current_state, "driving") - qs2 = model2.predict(state_array2, verbose=0)[0] - action = np.argmax(qs2) + 1 - else: - # 正常情况下的决策 - state_array = preprocess_state_for_prediction(current_state, "braking") - qs = model.predict(state_array, verbose=0)[0] - action = np.argmax(qs) - - if action == 1: - state_array2 = preprocess_state_for_prediction(current_state, "driving") - qs2 = model2.predict(state_array2, verbose=0)[0] - action = np.argmax(qs2) + 1 - - except Exception as e: - print(f"❌ 预测错误: {e}") - action = 0 - - # 执行动作 - try: - new_state, reward, done, waypoint = env.step(action, current_state) - current_state = new_state - - # 显示额外信息 - if step_count % 10 == 0: - print(f"步骤 {step_count}, 奖励: {reward}, 完成: {done}") - - except Exception as e: - print(f"❌ 环境步骤错误: {e}") - done = True - - # 计算FPS - frame_time = time.time() - step_start - fps_counter.append(frame_time) - current_fps = len(fps_counter) / sum(fps_counter) if fps_counter else 0 - - # 显示动作名称 - action_names = ["刹车", "直行", "左转", "右转", "微左", "微右"] - action_name = action_names[action] if action < len(action_names) else str(action) - - print(f'Step: {step_count:>3d} | FPS: {current_fps:>4.1f} | Action: {action_name}') - - if done: - print(f"Episode {episode + 1} 完成,步数: {step_count}") - break - - if step_count >= max_steps: - print(f"Episode {episode + 1} 达到最大步数限制") - - # 等待一段时间再开始下一个episode - print(f"等待下一个episode...") - time.sleep(2.0) - - # 最终清理 - print("\n" + "="*50) - print("所有episodes完成!") - print("="*50) - - print("清理资源...") - try: - # 环境会在重置时自动清理车辆 - cv2.destroyAllWindows() - except: - pass - - print("程序结束") - -if __name__ == '__main__': - main() \ No newline at end of file