该代码的作用是客户端连接carla服务端,将服务端里面车上rgb相机传感器数据和速度位置传给客户端,图片保存在…/outputs/output_basic_api目录下,速度实时打印在控制台上,可以修改一下程序打印在日志里
"""
In this script, we are going to learn how to spawn a vehicle on the road and make it autopilot.
At the same time, we will collect camera and lidar data from it.
"""
import carla
import os
import random
def main():
actor_list = []
sensor_list = []
try:
# First of all, we need to create the client that will send the requests, assume port is 2000
client=carla.Client(host='127.0.0.1', port=2000)
client.set_timeout(2.0)
# Retrieve the world that is currently running
world = client.get_world()
# world = client.load_world('Town02') # you can also retrive another world by specifically defining
blueprint_library = world.get_blueprint_library()
# Set weather for your world
# create the ego vehicle
ego_vehicle_bp = blueprint_library.find('vehicle.tesla.model3')
# black color
ego_vehicle_bp.set_attribute('color', '0, 0, 0')
# get a random valid occupation in the world
transform = random.choice(world.get_map().get_spawn_points())
# spawn the vehilce
ego_vehicle = world.spawn_actor(ego_vehicle_bp, transform)
# set the vehicle autopilot mode
ego_vehicle.set_autopilot(True)
# collect all actors to destroy when we quit the script
actor_list.append(ego_vehicle)
blueprint_library = world.get_blueprint_library()
#选择相机模型
camera_bp = blueprint_library.find("sensor.camera.rgb")
IM_WIDTH = 640
IM_HEIIGHT = 480
# set the attribute of camera
camera_bp.set_attribute("image_size_x", "{}".format(IM_WIDTH))
camera_bp.set_attribute("image_size_y", "{}".format(IM_HEIIGHT))
camera_bp.set_attribute("fov", "90")
camera_transform = carla.Transform(carla.Location(x=2.5, z=0.7))
camera = world.spawn_actor(camera_bp, camera_transform, attach_to=ego_vehicle)
output_path = '../outputs/output_basic_api'
if not os.path.exists(output_path):
os.makedirs(output_path)
# set the callback function
camera.listen(lambda image: image.save_to_disk(os.path.join(output_path, '%06d.png' % image.frame)))
sensor_list.append(camera)
# 获取所有车辆
actors = world.get_actors().filter('vehicle.*')
while True:
# set the sectator to follow the ego vehicle
spectator = world.get_spectator()
transform = ego_vehicle.get_transform()
spectator.set_transform(carla.Transform(transform.location + carla.Location(z=20),
carla.Rotation(pitch=-90)))
# 遍历每个车辆并获取位置和速度信息
for actor in actors:
location = actor.get_location()
velocity = actor.get_velocity()
print(f"车辆ID: {actor.id}")
print(f"位置: {location.x}, {location.y}, {location.z}")
print(f"速度: {velocity.x}, {velocity.y}, {velocity.z}")
print("---------------------")
finally:
print('destroying actors')
client.apply_batch([carla.command.DestroyActor(x) for x in actor_list])
for sensor in sensor_list:
sensor.destroy()
print('done.')
if __name__ == '__main__':
try:
main()
except KeyboardInterrupt:
print(' - Exited by user.')
参考:
https://www.ngui.cc/el/2651369.html?action=onClick
https://www.zhihu.com/column/c_1324712096148516864