测试用例
PythonAPI/examples/tutorial.py
这是一个基础传感器数据采集示例,演示如何:
- 在仿真中生成一辆主车并启用自动驾驶
- 为主车挂载一个深度摄像头(Depth Camera)
- 将摄像头捕获的图像自动保存到磁盘
- 动态调整车辆位置并批量生成 NPC 车辆
适用于数据集生成、传感器调试、自动化测试等场景。
保存的depth图如下:
🔑 主要模块解析
1.客户端连接与世界获取
client=carla.Client('localhost',2000)world=client.get_world()- 连接到远程 CARLA 服务器
- 获取当前仿真世界实例
✅ 这是所有 CARLA 脚本的起点。
2.主车生成与配置
bp=random.choice(blueprint_library.filter('vehicle'))ifbp.has_attribute('color'):color=random.choice(bp.get_attribute('color').recommended_values)bp.set_attribute('color',color)transform=random.choice(world.get_map().get_spawn_points())vehicle=world.spawn_actor(bp,transform)vehicle.set_autopilot(True)- 随机选择车辆模型(如 Tesla、Dodge 等)
- 随机设置车身颜色
- 在地图出生点生成车辆
- 启用自动驾驶(由 TrafficManager 控制)
💡 注意:车辆被加入
actor_list以确保后续销毁。
3.深度摄像头挂载与图像保存
camera_bp=blueprint_library.find('sensor.camera.depth')camera_transform=carla.Transform(carla.Location(x=1.5,z=2.4))camera=world.spawn_actor(camera_bp,camera_transform,attach_to=vehicle)cc=carla.ColorConverter.LogarithmicDepth camera.listen(lambdaimage:image.save_to_disk('_out/%06d.png'%image.frame,cc))- 创建深度摄像头,安装在车头前方(x=1.5m, z=2.4m)
- 使用对数深度着色器(
LogarithmicDepth),将深度值映射为灰度图像 - 注册回调函数:每帧图像自动保存为
_out/000001.png,_out/000002.png…
✅ 这是传感器数据自动采集的核心机制。
4.动态调整主车位置
location=vehicle.get_location()location.x+=40vehicle.set_location(location)- 将主车沿 X 轴向前移动 40 米
- 注意:此操作会瞬移车辆(不经过物理运动),常用于快速定位
⚠️ 此操作仅适用于测试,真实驾驶中应通过控制指令移动。
5.批量生成 NPC 车辆
transform.location+=carla.Location(x=40,y=-3.2)transform.rotation.yaw=-180.0for_inrange(10):transform.location.x+=8.0npc=world.try_spawn_actor(bp,transform)ifnpcisnotNone:npc.set_autopilot(True)- 在主车前方道路线性排列生成 10 辆 NPC 车
- 使用
try_spawn_actor()避免因碰撞导致崩溃 - 所有 NPC 启用自动驾驶,形成简单交通流
✅ 演示了可控的交通场景构建方法。
6.资源安全清理
finally:camera.destroy()client.apply_batch([carla.command.DestroyActor(x)forxinactor_list])- 使用
finally块确保无论是否异常,所有 Actor 都被销毁 - 采用批量销毁命令(
apply_batch)提高效率
✅ 这是 CARLA 脚本的最佳实践,防止仿真环境残留。
修改demo:添加观察者视角
原测试用例使用默认观察者视角,随着主车、NPC位置的变动,导致在默认视角看不到车辆;因此,我们就可以修改设置下观察者视角;
在 vehicle = world.spawn_actor(…) 之后添加:
spectator = world.get_spectator() vehicle_location = vehicle.get_transform().location spectator.set_transform(carla.Transform( vehicle_location + carla.Location(z=50), # 高空俯视 carla.Rotation(pitch=-90) # 垂直向下看 ))或更真实的跟随视角:
# 第三人称跟随 spectator.set_transform(carla.Transform(vehicle.get_transform().location+carla.Location(x=-10,z=5),vehicle.get_transform().rotation))✅ 总结
该脚本是 CARLA最基础但完整的数据采集范例,展示了:
- 如何生成并控制车辆
- 如何挂载传感器并保存数据
- 如何构建简单交通场景
- 如何安全管理仿真资源