Carla入门 (四)- 车辆跟随视角

本文介绍了如何在CARLA模拟器中使用Python和Pygame创建自驾车(Ego_vehicle)并配置旁观者相机(SpectatorCamera),实现车辆的自动驾驶和实时图像显示。作者展示了如何在游戏循环中处理控制、键入事件以及相机的切换和销毁。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

一、Ego_vehicle

通过blueprint获取所需的vehicle,在地图上获取随即生成点生成,并将其设置为自动驾驶模式。

import carla
import random
import pygame
import numpy as np

client = carla.Client('localhost', 2000)
world = client.get_world()

blueprint_library = world.get_blueprint_library()
vehicle_bp = = blueprint_library.filter('*vehicle*')
spawn_points = world.get_map().get_spawn_points()
ego_vehicle = world.spawn_actor(random.choice(vehicle_bp), random.choice(spawn_points))
ego_vehicle.set_autopilot(True)

二、Spectator Camera

  1. 获取camera蓝图
  2. 生成camera并绑定ego_vehicle
  3. 设置camera监听模式
camera_trans =carla.Transform(carla.Location(x=-5,z=3),carla.Rotation(pitch=-20))
camera_bp = world.get_blueprint_library().find('sensor.camera.rgb')
camera = world.spawn_actor(camera_bp, camera_trans, attach_to=ego_vehicle)

camera.listen(lambda image : pygame_callback(image,renderObject))

三、设置Pygame

class RenderObject(object):
    def __init__(self,width, height):
        init_img = np.random.randint(0,255,(height,width,3), dtype='uint8')
        self.surface = pygame.surfarray.make_surface(init_img.swapaxes(0,1))

def pygame_callback(data, obj):
    img = np.reshape(np.copy(data.raw_data),(data.height, data.width, 4))
    img = img[:, :, :3]
    img = img[:, :, ::-1]
    obj.surface = pygame.surfarray.make_surface(img.swapaxes(0,1))

image_w = camera_bp.get_attribute("image_size_x").as_int()
image_h = camera_bp.get_attribute("image_size_y").as_int()

renderObject = RenderObject(image_w, image_h)

pygame.init()
gameDisplay = pygame.display.set_mode((image_w,image_h),pygame.HWSURFACE | pygame.DOUBLEBUF)
gameDisplay.fill((0, 0, 0))
gameDisplay.blit(renderObject.surface, (0,0))
pygame.display.flip()

# Game loop
crashed = False

while not crashed:
    # Advance the simulation time
    world.tick()
    # Update the display
    gameDisplay.blit(renderObject.surface, (0,0))
    pygame.display.flip()
    # Process the current control state
    # controlObject.process_control()
    # Collect key press events
    for event in pygame.event.get():
        # If the window is closed, break the while loop
        if event.type == pygame.QUIT:
            crashed = True

        # Parse effect of key press event on control state
        # controlObject.parse_control(event)
        if event.type == pygame.KEYUP:
            # TAB key switches vehicle
            if event.key == pygame.K_TAB:
                ego_vehicle.set_autopilot(True)
                ego_vehicle = random.choice(vehicles)
                # Ensure vehicle is still alive (might have been destroyed)
                if ego_vehicle.is_alive:
                    # Stop and remove the camera
                    camera.stop()
                    camera.destroy()

                    # Spawn new camera and attach to new vehicle
                    # controlObject = ControlObject(ego_vehicle)
                    camera = world.spawn_actor(camera_bp, camera_init_trans, attach_to=ego_vehicle)
                    camera.listen(lambda image: pygame_callback(image, renderObject))

                    # Update PyGame window
                    gameDisplay.fill((0,0,0))               
                    gameDisplay.blit(renderObject.surface, (0,0))
                    pygame.display.flip()

# Stop camera and quit PyGame after exiting game loop
camera.stop()
pygame.quit()
### 安装CARLA模拟器 为了在Ubuntu 20.04上成功安装CARLA模拟器,需遵循特定步骤来确保兼容性和稳定性。由于CARLA ROS Bridge依赖于ROS2 Foxy版本,这进一步限定了操作系统为Ubuntu 20.04 (Focal Fossa)[^1]。 #### 下载CARLA 访问官方GitHub页面获取最新发布的CARLA版本[^4]: ```bash wget https://github.com/carla-simulator/carla/releases/download/0.9.14/CarlaUE4.sh chmod +x CarlaUE4.sh ``` 启动脚本前,请确认已满足所有必要的硬件需求和软件环境设置[^2]。 #### 安装依赖项 执行以下命令以准备系统环境: ```bash sudo apt update && sudo apt upgrade -y sudo apt install -y curl git build-essential libssl-dev ``` 对于图形处理单元的支持,特别是NVIDIA GPU用户应按照指南完成相应的驱动安装[^3]。 #### 启动CARLA服务器 通过终端导航至CARLA目录并运行启动文件: ```bash cd /path/to/CARLA_0.9.14 ./CarlaUE4.sh ``` 此时可以测试基本功能是否正常工作。 --- ### 配置CARLA-ROS-Bridge 鉴于CARLA与ROS之间的交互需求,接下来重点在于搭建`carla_ros_bridge`组件。 #### 设置ROS2环境 首先初始化ROS2 Foxy的工作空间,并构建源码包: ```bash mkdir -p ~/carla_ws/src cd ~/carla_ws/ source /opt/ros/foxy/setup.bash git clone https://github.com/carla-simulator/ros-bridge.git src/ros-bridge colcon build --symlink-install source install/local_setup.bash ``` 上述操作完成后,即完成了初步集成框架的建立。 #### 运行Bridge节点 利用RVIZ可视化工具展示来自CARLA的数据流,可参照如下指令开启相应进程: ```bash roslaunch carla_ros_bridge carla_ros_bridge.launch town:=Town01 host:=localhost port:=2000 timeout:=2 rosrun rviz rviz -d `rospack find carla_ros_bridge`/config/town01.rviz ``` 以上配置允许远程服务器作为CARLA的服务端而本地机器充当客户端角色,在此架构下实现高效数据交换及场景再现。
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值