Webots环境下使用Supervisor控制器获取传送带子节点Kinect设备图像时出现AttributeError问题求助
解决Webots Supervisor获取传送带子节点Kinect图像的问题
首先得说清你报错的原因:conveyor_belt是Node类型对象,而getDevice()是Robot(包括Supervisor)类的专属方法——它只能获取当前控制器所属机器人节点上挂载的设备,没法直接在其他Node对象上调用,这就是抛出AttributeError的根源。
下面给你两种可行的解决办法,任选其一都能实现需求:
方法1:给Kinect Camera节点添加DEF,直接获取
这是最省心的方式,先在Webots场景编辑器里做一步操作:找到传送带子节点里的Kinect Color Camera,给它添加一个DEF属性(比如命名为CONVEYOR_KINECT_COLOR)。然后修改代码如下:
from controller import Camera, Supervisor robot = Supervisor() timestep = int(robot.getBasicTimeStep()) # 直接通过DEF获取Kinect的Camera节点 kinect_camera_node = robot.getFromDef("CONVEYOR_KINECT_COLOR") assert(kinect_camera_node is not None, "未找到Camera节点!") # 将Node转换为Camera设备对象 conveyor_kinectcolor = Camera(kinect_camera_node) # 启用图像采集,设置采样频率(约24帧/秒) conveyor_kinectcolor.enable(int(1000/24)) # 主循环中读取图像 while robot.step(timestep) != -1: image = conveyor_kinectcolor.getImage() if image: # 可获取图像尺寸或做后续处理 width = conveyor_kinectcolor.getWidth() height = conveyor_kinectcolor.getHeight() print(f"成功获取图像:{width}x{height}")
方法2:遍历传送带子节点定位Camera
如果不想修改场景中的DEF属性,也可以通过遍历传送带的子节点找到目标Kinect:
from controller import Camera, Supervisor robot = Supervisor() timestep = int(robot.getBasicTimeStep()) conveyor_belt = robot.getFromDef("CONVEYOR_BELT") assert(conveyor_belt is not None, "未找到传送带节点!") # 获取传送带的子节点列表 children_field = conveyor_belt.getField("children") conveyor_kinectcolor = None # 逐个检查子节点,找到目标Camera for i in range(children_field.getCount()): child_node = children_field.getMFNode(i) # 先判断节点类型是否为Camera if child_node.getTypeName() == "Camera": # 再通过名称筛选(对应场景中的"kinect color") if child_node.getName() == "kinect color": conveyor_kinectcolor = Camera(child_node) break assert(conveyor_kinectcolor is not None, "未找到Kinect彩色相机!") conveyor_kinectcolor.enable(int(1000/24)) # 主循环中读取图像 while robot.step(timestep) != -1: image = conveyor_kinectcolor.getImage() if image: width = conveyor_kinectcolor.getWidth() height = conveyor_kinectcolor.getHeight() print(f"图像尺寸:{width}x{height}")
关键注意点
- 一定要保留主循环里的
robot.step(timestep)!Webots的传感器数据完全依赖这个步骤函数更新,没有它你根本拿不到有效图像。 Supervisor虽然继承自Robot,但getDevice()只能获取自身节点的设备;其他节点的设备,必须先拿到对应的Device节点,再用对应的设备类(比如Camera)包装后才能操作。
内容的提问来源于stack exchange,提问作者meng han
相关产品推荐
相关产品推荐

