这一节将介绍如何在Carla 模拟器中生成一辆车vehicle,同时使用自动驾驶模式,让其在地图中跑。
所搭建的仿真环境是python3.7+Carla0.9.8+Win10
1.首先import 各种依赖
import glob
import os
import sys
import time
import random
import time
import numpy as np
import cv2
2.按照官网的例子配置系统路径,配置好后import carla
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
3.增加一个client(client的概念可参考 Carla核心概念),并且连接到world中
#create client
client = carla.Client('localhost', 2000)
client.set_timeout(2.0)
#world connection
world = client.get_world()
4.生成一辆Tesla model3,在这里是利用filter函数从blueprint中过滤,并且在terminal中打印信息
#get blueprint libarary
blueprint_library = world.get_blueprint_library()
#Choose a vehicle blueprint which name is model3 and select the first one
bp = blueprint_library.filter("model3")[0]
print(bp)
5.从地图中随机生成一个点,作为vehicle的初始位置,使用spawn_actor 函数 在地图中从天而降一辆vehicle,并且开启自动驾驶模式
vehicle = world.spawn_actor(bp,spawn_point)
#control the vehicle
vehicle.set_autopilot(enabled=True)
6.vehicle 作为一个actor(actor的概念可参考 Carla核心概念),最好将其放入list中存储,方便之后的销毁。
actor_list = []
actor_list.append(vehicle)
7.销毁actor的代码为
for actor in actor_list:
actor.destroy()
8.至此生成vehicle的完整代码如下所示,同时保存该文件为example.py
import glob
import os
import sys
import time
import random
import time
import numpy as np
import cv2
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
actor_list = []
try:
#create client
client = carla.Client('localhost', 2000)
client.set_timeout(2.0)
#world connection
world = client.get_world()
#get blueprint libarary
blueprint_library = world.get_blueprint_library()
#Choose a vehicle blueprint which name is model3 and select the first one
bp = blueprint_library.filter("model3")[0]
print(bp)
#Returns a list of recommended spawning points and random choice one from it
spawn_point = random.choice(world.get_map().get_spawn_points())
#spawn vehicle to the world by spawn_actor method
vehicle = world.spawn_actor(bp,spawn_point)
#control the vehicle
vehicle.set_autopilot(enabled=True)
# vehicle.apply_control(carla.VehicleControl(throttle=0.1,steer=0.0))
#add vehicle to the actor list
actor_list.append(vehicle)
time.sleep(50)
finally:
for actor in actor_list:
actor.destroy()
print("All cleaned up!")
9.运行CarlaUE4.exe(位于WindowsNoEditor\文件夹下),调整视野使得能看到全部地图
10.,打开终端运行example.py (注意terminal的路径应该是你存放py文件的位置) python example.py
仔细寻找你在车降落在哪里。
在terminal中会打印如下信息,至此可以看到车辆在地图中自动行驶,大概50秒后消失。
下一节,将介绍如何添加一个摄像头到vehicle上,并将获取的图片显示出来。