我们利用CARLA 的Python API可以简便快捷的在CARLA server上进行操作,例如加载地图;加载车辆,行人;控制车辆,行人的运动轨迹以及速度;加入传感器等。
我们利用一个例子来去理解Python API的基本操作。我们将让一辆车在地图上行走,并在车上安装摄像机传感器,观察摄像机视角中的图形信息。
第一步:
我们需要在代码中载入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
我们需要查看本机系统的python版本号是否与下载下来的egg文件名上的是否一致,不一致的话会出错。比如我本机python版本号为3.79
我下载的CARLA0.9.8版本的egg文件名与我的python相匹配:
第二步:
开创我们的世界,建造我们的车车
在CARLA中所有的对象都存在于“world”这个对象里,在这个对象里,我们可以用“actor”来创建车辆,行人等,并利用“blueprint”设置其性质
#与server建立起连接
client = carla.Client('localhost', 2000)
#设置超时时间
client.set_timeout(2.0)
#建立我们的世界
world = client.get_world()
#建立我们的蓝图
blueprint_library = world.get_blueprint_library()
#利用蓝图里的博物馆找到奥迪轿车的原型图
audi = blueprint_library.filter('audi')[0]
#为我们的Audi车涂上艳丽的车漆
if bp.has_attribute('color'):
color = audi.get_attribute('color').recommended_values[0]
audi.set_attribute('color', color)
#在地图上找到一个随机可放车的地方
spawn_point = random.choice(world.get_map().get_spawn_points())
#把车放在这里
vehicle = world.spawn_actor(audi, spawn_point)
#顺便让我的车不断加速向前
vehicle.apply_control(carla.VehicleControl(throttle=1.0, steer=0.0))
第三步:
在车子上安装摄像头,在摄像头的视角来看我们的世界
#在蓝图图书馆里找到摄像头的原型
camera= blueprint_library.find('sensor.camera.rgb')
#咱们在原型上赋予它咱们想要的性质
camera.set_attribute('image_size_x', '640')
camera.set_attribute('image_size_y', '480')
camera.set_attribute('fov', '110')
#我们接着设置摄像头的相对于车车的位置,切记是相对位置哦
spawn_point = carla.Transform(carla.Location(x=2.4, z=0.5))
#我们把摄像头安在车子上
sensor = world.spawn_actor(camera, spawn_point, attach_to=vehicle)
#接着我们就开始监听摄像头,如果摄像头这边传来data,我们就用process_img函数来处理
sensor.listen(lambda data: process_img(data))
#process_img 函数如下
def process_img(image):
i = np.array(image.raw_data)
i2 = i.reshape((640, 480, 4))
i3 = i2[:, :, :3]
cv2.imshow("", i3) # show it.
cv2.waitKey(1)
return i3/255.0 # normalize
加餐:如果我们想观看实时的摄像头视角的影像,我们需要改变我们观察者的视角
while True:
spectator = world.get_spectator()
transform = vehicle.get_transform()
spectator.set_transform(carla.Transform(
transform.location + carla.Location(x=3, z=0.8), carla.Rotation()))
time.sleep(0.01)



