Carla自动驾驶仿真九:车辆变道路径规划

2024-03-03 01:28

本文主要是介绍Carla自动驾驶仿真九:车辆变道路径规划,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

文章目录

  • 前言
  • 一、关键函数
  • 二、完整代码
  • 效果


前言

本文介绍一种在carla中比较简单的变道路径规划方法,主要核心是调用carla的GlobalRoutePlanner模块和PID控制模块实现变道,大体的框架如下图所示。

在这里插入图片描述

在这里插入图片描述


一、关键函数

1、get_spawn_point(),该函数根据指定road和lane获得waypoint(这里之所以这么用是为了选择一条比较长的直路)。具体用法可以参考上篇文章:Carla自动驾驶仿真八:两种查找CARLA地图坐标点的方法

def get_spawn_point(self,target_road_id,target_lane_id):#每隔5m生成1个waypointwaypoints = self.map.generate_waypoints(5.0)# 遍历路点for waypoint in waypoints:if waypoint.road_id == target_road_id:lane_id = waypoint.lane_id# 检查是否已经找到了特定车道ID的路点if lane_id == target_lane_id:location = waypoint.transform.locationlocation.z = 1ego_spawn_point = carla.Transform(location, waypoint.transform.rotation)breakreturn ego_spawn_point

2、should_cut_in(),用于主车和目标车的相对距离判断,当目标车超越自车一定距离时,开始给cut_in_flag置Ture,并在下一步骤规划变道路径和执行变道操作。

 def should_cut_in(self,npc_vehicle, ego_vehicle, dis_to_cut=5):location1 = npc_vehicle.get_transform().locationlocation2 = ego_vehicle.get_transform().locationrel_x = location1.x - location2.xrel_y = location1.y - location2.ydistance = math.sqrt(rel_x * rel_x + rel_y * rel_y)print("relative dis",distance)#rel_x 大于等于0,说明目标车在前方if rel_x >= 0:distance = distanceelse:distance = -distanceif distance >= dis_to_cut:print("The conditions for changing lanes are met.")cut_in_flag = Trueelse:cut_in_flag = Falsereturn cut_in_flag

3、cal_target_route(),函数中调用了Carla的GlobalRoutePlanner模块,能根据起点和终点自动生成车辆行驶的路径(重点),我这里的变道起点是两车相对距离达到(阈值)时目标车的当前位置,而终点就是左侧车道前方target_dis米。将起点和终点代入到route = grp.trace_route(current_location, target_location)就能获取到规划路径route

在这里插入图片描述

 def cal_target_route(self,vehicle=None,lanechange="left",target_dis=20):#实例化道路规划模块grp = GlobalRoutePlanner(self.map, 2)#获取npc车辆当前所在的waypointcurrent_location = vehicle.get_transform().locationcurrent_waypoint = self.map.get_waypoint(current_location)#选择变道方向if "left" in lanechange:target_org_waypoint = current_waypoint.get_left_lane()elif "right" in lanechange:target_org_waypoint = current_waypoint.get_right_lane()#获取终点的位置target_location = target_org_waypoint.next(target_dis)[0].transform.location#根据起点和重点生成规划路径route = grp.trace_route(current_location, target_location)return route

4、speed_con_by_pid(),通过PID控制车辆的达到目标速度,pid是通过实例化Carla的PIDLongitudinalController实现。由于pid.run_step()只返回油门的控制,需要增加刹车的逻辑。

 control_signal = pid.run_step(target_speed=target_speed, debug=False)throttle = max(min(control_signal, 1.0), 0.0)  # 确保油门值在0到1之间brake = 0.0  # 根据需要设置刹车值if control_signal < 0:throttle = 0.0brake = abs(control_signal)  # 假设控制器输出的负值可以用来刹车vehilce.apply_control(carla.VehicleControl(throttle=throttle, brake=brake))

5、PID = VehiclePIDController()是carla的pid横纵向控制模块,通过设置目标速度和目标终点来实现轨迹控制control = PID.run_step(target_speed, target_waypoint),PID参数我随便调了一组,有兴趣的可以深入调一下。


二、完整代码

import carla
import time
import math
import sys#修改成自己的carla路径
sys.path.append(r'D:\CARLA_0.9.14\WindowsNoEditor\PythonAPI\carla')
from agents.navigation.global_route_planner import GlobalRoutePlanner
from agents.navigation.controller import VehiclePIDController,PIDLongitudinalController
from agents.tools.misc import draw_waypoints, distance_vehicle, vector, is_within_distance, get_speedclass CarlaWorld:def __init__(self):self.client = carla.Client('localhost', 2000)self.world = self.client.load_world('Town06')# self.world = self.client.get_world()self.map = self.world.get_map()# 开启同步模式settings = self.world.get_settings()settings.synchronous_mode = Truesettings.fixed_delta_seconds = 0.05def spawm_ego_by_point(self,ego_spawn_point):vehicle_bp = self.world.get_blueprint_library().filter('vehicle.tesla.*')[0]ego_vehicle = self.world.try_spawn_actor(vehicle_bp,ego_spawn_point)return ego_vehicledef spawn_npc_by_offset(self,ego_spawn_point,offset):vehicle_bp = self.world.get_blueprint_library().filter('vehicle.tesla.*')[0]# 计算新的生成点rotation = ego_spawn_point.rotationlocation = ego_spawn_point.locationlocation.x += offset.xlocation.y += offset.ylocation.z += offset.znpc_transform = carla.Transform(location, rotation)npc_vehicle = self.world.spawn_actor(vehicle_bp, npc_transform)return npc_vehicledef get_spawn_point(self,target_road_id,target_lane_id):#每隔5m生成1个waypointwaypoints = self.map.generate_waypoints(5.0)# 遍历路点for waypoint in waypoints:if waypoint.road_id == target_road_id:lane_id = waypoint.lane_id# 检查是否已经找到了特定车道ID的路点if lane_id == target_lane_id:location = waypoint.transform.locationlocation.z = 1ego_spawn_point = carla.Transform(location, waypoint.transform.rotation)breakreturn ego_spawn_pointdef cal_target_route(self,vehicle=None,lanechange="left",target_dis=20):#实例化道路规划模块grp = GlobalRoutePlanner(self.map, 2)#获取npc车辆当前所在的waypointcurrent_location = vehicle.get_transform().locationcurrent_waypoint = self.map.get_waypoint(current_location)#选择变道方向if "left" in lanechange:target_org_waypoint = current_waypoint.get_left_lane()elif "right" in lanechange:target_org_waypoint = current_waypoint.get_right_lane()#获取终点的位置target_location = target_org_waypoint.next(target_dis)[0].transform.location#根据起点和重点生成规划路径route = grp.trace_route(current_location, target_location)return routedef draw_target_line(self,waypoints):# 获取世界和调试助手debug = self.world.debug# 设置绘制参数life_time = 60.0  # 点和线将持续显示的时间(秒)color = carla.Color(255, 0, 0)thickness = 0.3  # 线的厚度for i in range(len(waypoints) - 1):debug.draw_line(waypoints[i][0].transform.location + carla.Location(z=0.5),waypoints[i + 1][0].transform.location + carla.Location(z=0.5),thickness=thickness,color=color,life_time=life_time)def draw_current_point(self,current_point):self.world.debug.draw_point(current_point,size=0.1, color=carla.Color(b=255), life_time=60)def speed_con_by_pid(self,vehilce=None,pid=None,target_speed=30):control_signal = pid.run_step(target_speed=target_speed, debug=False)throttle = max(min(control_signal, 1.0), 0.0)  # 确保油门值在0到1之间brake = 0.0  # 根据需要设置刹车值if control_signal < 0:throttle = 0.0brake = abs(control_signal)  # 假设控制器输出的负值可以用来刹车vehilce.apply_control(carla.VehicleControl(throttle=throttle, brake=brake))def set_spectator(self,vehicle):self.world.get_spectator().set_transform(carla.Transform(vehicle.get_transform().location +carla.Location(z=50), carla.Rotation(pitch=-90)))def should_cut_in(self,npc_vehicle, ego_vehicle, dis_to_cut=5):location1 = npc_vehicle.get_transform().locationlocation2 = ego_vehicle.get_transform().locationrel_x = location1.x - location2.xrel_y = location1.y - location2.ydistance = math.sqrt(rel_x * rel_x + rel_y * rel_y)print("relative dis",distance)if rel_x >= 0:distance = distanceelse:distance = -distanceif distance >= dis_to_cut:print("The conditions for changing lanes are met.")cut_in_flag = Trueelse:cut_in_flag = Falsereturn cut_in_flagif __name__ == '__main__':try:CARLA = CarlaWorld()#根据road_id和lane_id选择出生点start_point = CARLA.get_spawn_point(target_road_id=40, target_lane_id=-5)#生成自车ego_vehicle = CARLA.spawm_ego_by_point(start_point)#设置初始的观察者视角CARLA.set_spectator(ego_vehicle)#相对ego生成目标车relative_ego = carla.Location(x=-10, y=3.75, z=0)npc_vehicle = CARLA.spawn_npc_by_offset(start_point, relative_ego)# 设置ego自动巡航ego_vehicle.set_autopilot(True)#设置目标车初始速度的纵向控制PIDinitspd_pid = PIDLongitudinalController(npc_vehicle, K_P=1.0, K_I=0.1, K_D=0.05)#设置目标车的cut_in的横纵向控制PIDargs_lateral_dict = {'K_P': 0.8, 'K_D': 0.8, 'K_I': 0.70, 'dt': 1.0 / 10.0}args_long_dict = {'K_P': 1, 'K_D': 0.0, 'K_I': 0.75, 'dt': 1.0 / 10.0}PID = VehiclePIDController(npc_vehicle, args_lateral_dict, args_long_dict)waypoints = Nonewaypoint_index = 0need_cal_route = Truecut_in_flag = Falsearrive_target_point = Falsetarget_distance_threshold = 2.0  # 切换waypoint的距离start_sim_time = time.time()while not arrive_target_point:CARLA.world.tick()# 更新观察者的视野CARLA.set_spectator(ego_vehicle)#计算目标车的初始速度ego_speed = (ego_vehicle.get_velocity().x  * 3.6) #km/htarget_speed = ego_speed + 8 #目标车的目标速度#是否满足cut_in条件if cut_in_flag:if need_cal_route:#生成车侧车道前方30m的waypointwaypoints = CARLA.cal_target_route(npc_vehicle,lanechange= "left",target_dis=30)CARLA.draw_target_line(waypoints)need_cal_route = False# 如果已经计算了路线if waypoints is not None and waypoint_index < len(waypoints):# 获取当前目标路点target_waypoint = waypoints[waypoint_index][0]# 获取车辆当前位置transform = npc_vehicle.get_transform()#绘制当前运行的点CARLA.draw_current_point(transform.location)# 计算车辆与当前目标路点的距离distance_to_waypoint = distance_vehicle(target_waypoint, transform)# 如果车辆距离当前路点的距离小于阈值,则更新到下一个路点if distance_to_waypoint < target_distance_threshold:waypoint_index += 1  # 移动到下一个路点if waypoint_index >= len(waypoints):arrive_target_point = Trueprint("npc_vehicle had arrive target point.")break  # 如果没有更多的路点,退出循环else:# 计算控制命令control = PID.run_step(target_speed, target_waypoint)# 应用控制命令npc_vehicle.apply_control(control)else:#设置NPC的初始速度CARLA.speed_con_by_pid(npc_vehicle,initspd_pid,target_speed)#判断是否可以cut incut_in_flag = CARLA.should_cut_in(npc_vehicle,ego_vehicle,dis_to_cut=8)# 判断是否达到模拟时长if time.time() - start_sim_time > 60:print("Simulation ended due to time limit.")break#到达目的地停车npc_vehicle.apply_control(carla.VehicleControl(throttle=0, steer=0, brake=-0.5))print("Control the target car to brake.")time.sleep(10)except Exception as e:print(f"An error occurred: {e}")finally:# 清理资源print("Cleaning up the simulation...")if ego_vehicle is not None:ego_vehicle.destroy()if npc_vehicle is not None:npc_vehicle.destroy()settings = CARLA.world.get_settings()settings.synchronous_mode = False  # 禁用同步模式settings.fixed_delta_seconds = None

效果

下述是变道规划简单的实现,轨迹跟踪效果比较一般,PID没有仔细调,紫色是车辆运行的点迹。

在这里插入图片描述
公众号:自动驾驶simulation

这篇关于Carla自动驾驶仿真九:车辆变道路径规划的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/768030

相关文章

Python使用Tenacity一行代码实现自动重试详解

《Python使用Tenacity一行代码实现自动重试详解》tenacity是一个专为Python设计的通用重试库,它的核心理念就是用简单、清晰的方式,为任何可能失败的操作添加重试能力,下面我们就来看... 目录一切始于一个简单的 API 调用Tenacity 入门:一行代码实现优雅重试精细控制:让重试按我

SQL Server跟踪自动统计信息更新实战指南

《SQLServer跟踪自动统计信息更新实战指南》本文详解SQLServer自动统计信息更新的跟踪方法,推荐使用扩展事件实时捕获更新操作及详细信息,同时结合系统视图快速检查统计信息状态,重点强调修... 目录SQL Server 如何跟踪自动统计信息更新:深入解析与实战指南 核心跟踪方法1️⃣ 利用系统目录

python设置环境变量路径实现过程

《python设置环境变量路径实现过程》本文介绍设置Python路径的多种方法:临时设置(Windows用`set`,Linux/macOS用`export`)、永久设置(系统属性或shell配置文件... 目录设置python路径的方法临时设置环境变量(适用于当前会话)永久设置环境变量(Windows系统

Spring Security 单点登录与自动登录机制的实现原理

《SpringSecurity单点登录与自动登录机制的实现原理》本文探讨SpringSecurity实现单点登录(SSO)与自动登录机制,涵盖JWT跨系统认证、RememberMe持久化Token... 目录一、核心概念解析1.1 单点登录(SSO)1.2 自动登录(Remember Me)二、代码分析三、

MyBatis-Plus 自动赋值实体字段最佳实践指南

《MyBatis-Plus自动赋值实体字段最佳实践指南》MyBatis-Plus通过@TableField注解与填充策略,实现时间戳、用户信息、逻辑删除等字段的自动填充,减少手动赋值,提升开发效率与... 目录1. MyBATis-Plus 自动赋值概述1.1 适用场景1.2 自动填充的原理1.3 填充策略

Spring Boot中的路径变量示例详解

《SpringBoot中的路径变量示例详解》SpringBoot中PathVariable通过@PathVariable注解实现URL参数与方法参数绑定,支持多参数接收、类型转换、可选参数、默认值及... 目录一. 基本用法与参数映射1.路径定义2.参数绑定&nhttp://www.chinasem.cnbs

SpringBoot+Docker+Graylog 如何让错误自动报警

《SpringBoot+Docker+Graylog如何让错误自动报警》SpringBoot默认使用SLF4J与Logback,支持多日志级别和配置方式,可输出到控制台、文件及远程服务器,集成ELK... 目录01 Spring Boot 默认日志框架解析02 Spring Boot 日志级别详解03 Sp

浏览器插件cursor实现自动注册、续杯的详细过程

《浏览器插件cursor实现自动注册、续杯的详细过程》Cursor简易注册助手脚本通过自动化邮箱填写和验证码获取流程,大大简化了Cursor的注册过程,它不仅提高了注册效率,还通过友好的用户界面和详细... 目录前言功能概述使用方法安装脚本使用流程邮箱输入页面验证码页面实战演示技术实现核心功能实现1. 随机

HTML5实现的移动端购物车自动结算功能示例代码

《HTML5实现的移动端购物车自动结算功能示例代码》本文介绍HTML5实现移动端购物车自动结算,通过WebStorage、事件监听、DOM操作等技术,确保实时更新与数据同步,优化性能及无障碍性,提升用... 目录1. 移动端购物车自动结算概述2. 数据存储与状态保存机制2.1 浏览器端的数据存储方式2.1.

一文详解MySQL如何设置自动备份任务

《一文详解MySQL如何设置自动备份任务》设置自动备份任务可以确保你的数据库定期备份,防止数据丢失,下面我们就来详细介绍一下如何使用Bash脚本和Cron任务在Linux系统上设置MySQL数据库的自... 目录1. 编写备份脚本1.1 创建并编辑备份脚本1.2 给予脚本执行权限2. 设置 Cron 任务2