ROS(机器人操作系统)快速入门指南#
本指南介绍如何将 Ultralytics YOLO 与 ROS1(rospy)或 ROS2(rclpy)集成,以便对 RGB 图像、深度图像和点云执行实时目标检测和分割。
跳转至设置 YOLO 与 ROS,然后处理RGB 图像、深度图像或点云。
什么是 ROS?#
机器人操作系统(ROS)是一个开源框架,广泛用于机器人研究和工业领域。ROS 提供一系列库和工具,帮助开发者构建机器人应用。ROS 专为适配各种机器人平台而设计,是一种灵活且强大的机器人开发工具。若要快速了解 ROS,请观看 Open Robotics 制作的三分钟ROS 介绍视频。
ROS 的主要特性#
-
模块化架构:ROS 采用模块化架构,开发者可以通过组合称为节点的小型可复用组件来构建复杂系统。每个节点通常执行特定功能,节点之间通过话题或服务传递消息进行通信。
-
通信中间件:ROS 提供了可靠的通信基础设施,支持进程间通信和分布式计算。它通过用于数据流(话题)的发布-订阅模型,以及用于服务调用的请求-应答模型来实现这些功能。
-
硬件抽象:ROS 在硬件之上提供了一层抽象,使开发者能够编写与设备无关的代码。因此,同一份代码可以用于不同的硬件配置,从而更容易进行集成和实验。
-
工具与实用程序:ROS 提供丰富的可视化、调试和仿真工具。例如,RViz 用于可视化传感器数据和机器人状态信息,而 Gazebo 提供了强大的仿真环境,可用于测试算法和机器人设计。
-
丰富的生态系统:ROS 生态系统规模庞大且持续发展,为导航、操控、感知等各种机器人应用提供了大量软件包。社区积极参与这些软件包的开发和维护。
ROS 版本的演进
自 2007 年开发以来,ROS 经历了多个版本的演进,并分为 ROS 1 和 ROS 2。以下现有示例使用 ROS1 Noetic;使用 ROS2一节中的精简适配器展示了当前 ROS2 版本对应的 rclpy 接口。
ROS 1 与 ROS 2#
ROS 1 为机器人开发提供了坚实的基础,而 ROS 2 通过以下方式弥补了它的不足:
- 实时性能:增强了对实时系统和确定性行为的支持。
- 安全性:增强了安全功能,确保在各种环境中安全可靠地运行。
- 可扩展性:更好地支持多机器人系统和大规模部署。
- 跨平台支持:扩展了与 Linux 以外各种操作系统的兼容性,包括 Windows 和 macOS。
- 灵活通信:使用 DDS 实现更灵活、高效的进程间通信。
ROS 消息与话题#
在 ROS 中,节点之间通过消息和话题进行通信。消息是一种数据结构,用于定义节点之间交换的信息;话题则是一个命名通道,消息通过该通道发送和接收。节点可以向话题发布消息,也可以订阅话题中的消息,从而彼此通信。这种发布-订阅模型支持异步通信,并使节点彼此解耦。在机器人系统中,每个传感器或执行器通常都会向话题发布数据,其他节点随后可以使用这些数据进行处理或控制。本指南将重点介绍 Image、Depth 和 PointCloud 消息以及相机话题。
使用 ROS 设置 Ultralytics YOLO#
ROS1 示例使用此 ROS 环境进行了测试,该环境是 ROSbot ROS 仓库的一个分支。在 ROS2 中,YOLO 和 NumPy 处理流程相同;不同之处仅在于节点生命周期和消息转换。
安装依赖项#
除了 ROS 环境,你还需要安装以下依赖项:
-
ROS NumPy 软件包:这是在 ROS Image 消息与 NumPy 数组之间快速转换所必需的。
pip install ros_numpy -
Ultralytics 软件包:
pip install ultralytics
使用 ROS2#
ROS2 使用 rclpy 替代 rospy,并使用 cv_bridge 进行 ros_numpy 图像转换。以下节点是下方 RGB 检测流程的完整 ROS2 对应实现;请只实例化一次模型,并在各个回调中重复使用。
import cv_bridge
import rclpy
from rclpy.node import Node
from rclpy.qos import qos_profile_sensor_data
from sensor_msgs.msg import Image
from ultralytics import YOLO
class UltralyticsNode(Node):
"""Run YOLO detection on ROS2 image messages."""
def __init__(self):
"""Initialize the ROS2 node, model, and image interfaces."""
super().__init__("ultralytics")
self.bridge = cv_bridge.CvBridge()
self.model = YOLO("yolo26m.pt")
self.publisher = self.create_publisher(Image, "/ultralytics/detection/image", 5)
self.create_subscription(Image, "/camera/color/image_raw", self.callback, qos_profile_sensor_data)
def callback(self, message):
"""Publish the annotated camera frame."""
image = self.bridge.imgmsg_to_cv2(message, desired_encoding="bgr8")
annotated = self.model(image)[0].plot(show=False)
self.publisher.publish(self.bridge.cv2_to_imgmsg(annotated, encoding="bgr8"))
def main(args=None):
"""Start the ROS2 node."""
rclpy.init(args=args)
node = UltralyticsNode()
rclpy.spin(node)
node.destroy_node()
rclpy.shutdown()
if __name__ == "__main__":
main()对于深度图像,请重复使用下方的深度处理代码,只替换消息获取和转换部分:
self.create_subscription(Image, "/camera/color/image_raw", self.rgb_callback, qos_profile_sensor_data)
self.create_subscription(Image, "/camera/depth/image_raw", self.depth_callback, qos_profile_sensor_data)
def rgb_callback(self, message):
self.rgb_image = self.bridge.imgmsg_to_cv2(message, desired_encoding="bgr8")
def depth_callback(self, message):
depth_image = self.bridge.imgmsg_to_cv2(message, desired_encoding="passthrough")
# 应用下方深度示例中的 NumPy 掩码和距离计算。对于点云,ROS2 提供 sensor_msgs_py.point_cloud2;将有序点云转换一次,然后重复使用下方的 NumPy 分割和 3D 映射代码:
from sensor_msgs_py import point_cloud2
points = point_cloud2.read_points_numpy(message, field_names=("x", "y", "z", "rgb"))
points = points.reshape(message.height, message.width, 4)在 ROS 中使用 Ultralytics 和 sensor_msgs/Image#
sensor_msgs/Image 消息类型常用于 ROS 中表示图像数据。它包含编码、高度、宽度和像素数据等字段,适合传输由相机或其他传感器采集的图像。图像消息广泛应用于机器人任务,例如视觉感知、目标检测和导航。
图像分步使用指南#
以下代码片段演示如何在 ROS 中使用 Ultralytics YOLO 软件包。在此示例中,我们订阅一个相机话题,使用 YOLO 处理接收到的图像,并将检测到的目标发布到用于检测和分割的新话题。
首先,导入所需的库并实例化两个模型:一个用于分割,另一个用于检测。初始化一个 ROS 节点(名称为 ultralytics),以便与 ROS 主节点通信。为确保连接稳定,我们会短暂暂停,让节点有足够时间建立连接,然后再继续。
import time
import rospy
from ultralytics import YOLO
detection_model = YOLO("yolo26m.pt")
segmentation_model = YOLO("yolo26m-seg.pt")
rospy.init_node("ultralytics")
time.sleep(1)初始化两个 ROS 话题:一个用于检测,另一个用于分割。这些话题用于发布带注释的图像,方便后续处理。节点之间通过 sensor_msgs/Image 消息进行通信。
from sensor_msgs.msg import Image
det_image_pub = rospy.Publisher("/ultralytics/detection/image", Image, queue_size=5)
seg_image_pub = rospy.Publisher("/ultralytics/segmentation/image", Image, queue_size=5)最后,创建一个订阅器,监听 /camera/color/image_raw 话题上的消息,并为每条新消息调用一个回调函数。此回调函数接收 sensor_msgs/Image 类型的消息,使用 ros_numpy 将其转换为 NumPy 数组,使用之前实例化的 YOLO 模型处理图像,为图像添加注释,然后将图像分别发布回相应话题:检测结果发布到 /ultralytics/detection/image,分割结果发布到 /ultralytics/segmentation/image。
import ros_numpy
def callback(data):
"""Callback function to process image and publish annotated images."""
array = ros_numpy.numpify(data)
if det_image_pub.get_num_connections():
det_result = detection_model(array)
det_annotated = det_result[0].plot(show=False)
det_image_pub.publish(ros_numpy.msgify(Image, det_annotated, encoding="rgb8"))
if seg_image_pub.get_num_connections():
seg_result = segmentation_model(array)
seg_annotated = seg_result[0].plot(show=False)
seg_image_pub.publish(ros_numpy.msgify(Image, seg_annotated, encoding="rgb8"))
rospy.Subscriber("/camera/color/image_raw", Image, callback)
while True:
rospy.spin()完整代码
import time
import ros_numpy
import rospy
from sensor_msgs.msg import Image
from ultralytics import YOLO
detection_model = YOLO("yolo26m.pt")
segmentation_model = YOLO("yolo26m-seg.pt")
rospy.init_node("ultralytics")
time.sleep(1)
det_image_pub = rospy.Publisher("/ultralytics/detection/image", Image, queue_size=5)
seg_image_pub = rospy.Publisher("/ultralytics/segmentation/image", Image, queue_size=5)
def callback(data):
"""Callback function to process image and publish annotated images."""
array = ros_numpy.numpify(data)
if det_image_pub.get_num_connections():
det_result = detection_model(array)
det_annotated = det_result[0].plot(show=False)
det_image_pub.publish(ros_numpy.msgify(Image, det_annotated, encoding="rgb8"))
if seg_image_pub.get_num_connections():
seg_result = segmentation_model(array)
seg_annotated = seg_result[0].plot(show=False)
seg_image_pub.publish(ros_numpy.msgify(Image, seg_annotated, encoding="rgb8"))
rospy.Subscriber("/camera/color/image_raw", Image, callback)
while True:
rospy.spin()调试
由于系统具有分布式特性,调试 ROS(机器人操作系统)节点可能颇具挑战。以下工具可以帮助你完成调试:
rostopic echo <TOPIC-NAME>:此命令可让你查看特定话题上发布的消息,帮助你检查数据流。rostopic list:使用此命令列出 ROS 系统中所有可用的话题,了解当前活动数据流的概况。rqt_graph:此可视化工具会显示节点之间的通信图,帮助你了解节点如何相互连接和交互。- 对于更复杂的可视化需求,例如 3D 表示,你可以使用 RViz。RViz(ROS 可视化)是一款强大的 ROS 3D 可视化工具。它可以让你实时查看机器人及其环境的状态。使用 RViz,你可以查看传感器数据(例如
sensor_msgs/Image)、机器人模型状态以及各种其他类型的信息,从而更轻松地调试和了解机器人系统的行为。
使用 std_msgs/String 发布检测到的类别#
ROS 标准消息还包括 std_msgs/String 消息。在许多应用中,无需重新发布整张带注释的图像;只需发布机器人视野中出现的类别即可。以下示例演示如何使用 std_msgs/String 消息,将检测到的类别重新发布到 /ultralytics/detection/classes 话题。这些消息更轻量,只提供必要的信息,因此适用于各种应用。
示例用例#
想象一台配有相机和目标检测模型的仓库机器人。机器人无需通过网络发送大型的带注释图像,而是可以将检测到的类别列表作为 std_msgs/String 消息发布。例如,当机器人检测到“箱子”、“托盘”和“叉车”等目标时,它会将这些类别发布到 /ultralytics/detection/classes 话题。中央监控系统可以使用这些信息实时跟踪库存、优化机器人的路径规划以避开障碍物,或触发特定操作,例如拾取检测到的箱子。这种方法可以减少通信所需的带宽,并将重点放在传输关键数据上。
字符串分步使用指南#
此示例演示如何在 ROS 中使用 Ultralytics YOLO 软件包。在此示例中,我们订阅一个相机话题,使用 YOLO 处理接收到的图像,并使用 std_msgs/String 消息将检测到的目标发布到新话题 /ultralytics/detection/classes。ros_numpy 软件包用于将 ROS Image 消息转换为 NumPy 数组,以便使用 YOLO 进行处理。
import time
import ros_numpy
import rospy
from sensor_msgs.msg import Image
from std_msgs.msg import String
from ultralytics import YOLO
detection_model = YOLO("yolo26m.pt")
rospy.init_node("ultralytics")
time.sleep(1)
classes_pub = rospy.Publisher("/ultralytics/detection/classes", String, queue_size=5)
def callback(data):
"""Callback function to process image and publish detected classes."""
array = ros_numpy.numpify(data)
if classes_pub.get_num_connections():
det_result = detection_model(array)
classes = det_result[0].boxes.cls.cpu().numpy().astype(int)
names = [det_result[0].names[i] for i in classes]
classes_pub.publish(String(data=str(names)))
rospy.Subscriber("/camera/color/image_raw", Image, callback)
while True:
rospy.spin()在 ROS 中使用 Ultralytics 处理深度图像#
除了 RGB 图像,ROS 还支持深度图像,可提供目标与相机之间的距离信息。深度图像对于避障、3D 映射和定位等机器人应用至关重要。
深度图像中的每个像素都表示相机到某个目标的距离。与捕捉颜色的 RGB 图像不同,深度图像捕捉的是空间信息,使机器人能够感知环境的 3D 结构。
可以使用各种传感器获取深度图像:
- 双目相机:使用两个相机根据图像视差计算深度。
- 飞行时间(ToF)相机:测量光线从目标反射返回所需的时间。
- 结构光传感器:投射图案,并测量图案在表面上的变形。
将 YOLO 用于深度图像#
在 ROS 中,深度图像由 sensor_msgs/Image 消息类型表示,其中包含编码、高度、宽度和像素数据等字段。深度图像的编码字段通常使用类似“16UC1”的格式,表示每个像素是一个 16 位无符号整数,每个值代表到目标的距离。深度图像通常与 RGB 图像结合使用,以提供更全面的环境视图。
使用 YOLO 可以提取并结合 RGB 图像和深度图像中的信息。例如,YOLO 可以检测 RGB 图像中的目标,然后利用检测结果在深度图像中定位对应区域。这样就能提取检测目标的精确深度信息,增强机器人对周围环境 3D 结构的理解能力。
处理深度图像时,务必确保 RGB 图像和深度图像正确对齐。像 Intel RealSense 系列这样的 RGB-D 相机可以提供同步的 RGB 图像和深度图像,从而更容易结合两个来源的信息。如果使用独立的 RGB 相机和深度相机,则必须对它们进行校准,以确保准确对齐。
深度图像分步使用指南#
在此示例中,我们使用 YOLO 分割图像,并将提取的掩码应用于深度图像,以分割其中的目标。这样就能确定目标中每个像素到相机焦点中心的距离。获取这些距离信息后,我们可以计算相机与场景中特定目标之间的距离。首先,导入所需的库、创建 ROS 节点,并实例化一个分割模型和一个 ROS 话题。
import time
import rospy
from std_msgs.msg import String
from ultralytics import YOLO
rospy.init_node("ultralytics")
time.sleep(1)
segmentation_model = YOLO("yolo26m-seg.pt")
classes_pub = rospy.Publisher("/ultralytics/detection/distance", String, queue_size=5)接下来,定义一个回调函数来处理接收到的深度图像消息。该函数会等待深度图像和 RGB 图像消息,将它们转换为 NumPy 数组,并对 RGB 图像应用分割模型。随后,它会提取每个检测目标的分割掩码,并使用深度图像计算目标与相机之间的平均距离。大多数传感器都有一个最大距离,称为截断距离;超过该距离的值会表示为 inf(np.inf)。处理之前,务必过滤掉这些空值,并将其设为 0。最后,将检测到的目标及其平均距离发布到 /ultralytics/detection/distance 话题。
import numpy as np
import ros_numpy
from sensor_msgs.msg import Image
def callback(data):
"""Callback function to process depth image and RGB image."""
image = rospy.wait_for_message("/camera/color/image_raw", Image)
image = ros_numpy.numpify(image)
depth = ros_numpy.numpify(data)
result = segmentation_model(image, retina_masks=True) # masks at the original image resolution
all_objects = []
for index, cls in enumerate(result[0].boxes.cls):
class_index = int(cls.cpu().numpy())
name = result[0].names[class_index]
mask = result[0].masks.data.cpu().numpy()[index, :, :].astype(int)
obj = depth[mask == 1]
obj = obj[~np.isnan(obj)]
avg_distance = np.mean(obj) if len(obj) else np.inf
all_objects.append(f"{name}: {avg_distance:.2f}m")
classes_pub.publish(String(data=str(all_objects)))
rospy.Subscriber("/camera/depth/image_raw", Image, callback)
while True:
rospy.spin()完整代码
import time
import numpy as np
import ros_numpy
import rospy
from sensor_msgs.msg import Image
from std_msgs.msg import String
from ultralytics import YOLO
rospy.init_node("ultralytics")
time.sleep(1)
segmentation_model = YOLO("yolo26m-seg.pt")
classes_pub = rospy.Publisher("/ultralytics/detection/distance", String, queue_size=5)
def callback(data):
"""Callback function to process depth image and RGB image."""
image = rospy.wait_for_message("/camera/color/image_raw", Image)
image = ros_numpy.numpify(image)
depth = ros_numpy.numpify(data)
result = segmentation_model(image, retina_masks=True) # masks at the original image resolution
all_objects = []
for index, cls in enumerate(result[0].boxes.cls):
class_index = int(cls.cpu().numpy())
name = result[0].names[class_index]
mask = result[0].masks.data.cpu().numpy()[index, :, :].astype(int)
obj = depth[mask == 1]
obj = obj[~np.isnan(obj)]
avg_distance = np.mean(obj) if len(obj) else np.inf
all_objects.append(f"{name}: {avg_distance:.2f}m")
classes_pub.publish(String(data=str(all_objects)))
rospy.Subscriber("/camera/depth/image_raw", Image, callback)
while True:
rospy.spin()在 ROS 中使用 Ultralytics 和 sensor_msgs/PointCloud2#
sensor_msgs/PointCloud2 消息类型是一种用于在 ROS 中表示 3D 点云数据的数据结构。这种消息类型是机器人应用的重要组成部分,可支持 3D 映射、目标识别和定位等任务。
点云是在三维坐标系中定义的一组数据点。这些数据点表示通过 3D 扫描技术捕获的目标或场景外表面。点云中的每个点都有 X、Y 和 Z 坐标,对应其空间位置,还可能包含颜色和强度等其他信息。
处理 sensor_msgs/PointCloud2 时,必须考虑获取点云数据的传感器参考坐标系。点云最初是在传感器的参考坐标系中采集的。你可以通过监听 /tf_static 话题来确定该参考坐标系。不过,根据具体应用需求,你可能需要将点云转换到另一个参考坐标系。可以使用 tf2_ros 软件包完成此转换,该软件包提供了管理坐标系以及在坐标系之间转换数据的工具。
可以使用各种传感器获取点云:
- 激光雷达(光探测与测距):利用激光脉冲测量目标距离并创建高精度的 3D 地图。
- 深度相机:捕捉每个像素的深度信息,以便对场景进行 3D 重建。
- 双目相机:利用两个或更多相机,通过三角测量获取深度信息。
- 结构光扫描仪:将已知图案投射到表面上,并测量图案的变形以计算深度。
将 YOLO 用于点云#
要将 YOLO 与 sensor_msgs/PointCloud2 类型的消息集成,我们可以采用与处理深度图类似的方法。利用点云中包含的颜色信息,我们可以提取 2D 图像,使用 YOLO 对该图像进行分割,然后将生成的掩码应用于 3D 点,从而分离出关注的 3D 目标。
对于点云处理,我们建议使用 Open3D(pip install open3d),这是一个易于使用的 Python 库。Open3D 提供了强大的工具,可用于管理点云数据结构、进行可视化以及无缝执行复杂操作。该库可以大大简化处理流程,并增强我们结合基于 YOLO 的分割来操作和分析点云的能力。
点云分步使用指南#
导入所需的库,并实例化用于分割的 YOLO 模型。
import time
import rospy
from ultralytics import YOLO
rospy.init_node("ultralytics")
time.sleep(1)
segmentation_model = YOLO("yolo26m-seg.pt")创建一个函数 pointcloud2_to_array,将 sensor_msgs/PointCloud2 消息转换为两个 NumPy 数组。sensor_msgs/PointCloud2 消息包含 n 个点,这些点依据采集图像的 width 和 height 生成。例如,480 x 640 图像将包含 307,200 个点。每个点都包含三个空间坐标(xyz)以及对应的颜色(RGB 格式)。它们可以视为两个独立的信息通道。
该函数以原始相机分辨率格式(width x height)返回 xyz 坐标和 RGB 值。大多数传感器都有一个最大距离,称为截断距离;超过该距离的值会表示为 inf(np.inf)。处理之前,务必过滤掉这些空值,并将其设为 0。
import numpy as np
import ros_numpy
def pointcloud2_to_array(pointcloud2: PointCloud2) -> tuple:
"""Convert a ROS PointCloud2 message to a numpy array.
Args:
pointcloud2 (PointCloud2): the PointCloud2 message
Returns:
(tuple): tuple containing (xyz, rgb)
"""
pc_array = ros_numpy.point_cloud2.pointcloud2_to_array(pointcloud2)
split = ros_numpy.point_cloud2.split_rgb_field(pc_array)
rgb = np.stack([split["b"], split["g"], split["r"]], axis=2)
xyz = ros_numpy.point_cloud2.get_xyz_points(pc_array, remove_nans=False)
xyz = np.array(xyz).reshape((pointcloud2.height, pointcloud2.width, 3))
nan_rows = np.isnan(xyz).all(axis=2)
xyz[nan_rows] = [0, 0, 0]
rgb[nan_rows] = [0, 0, 0]
return xyz, rgb接下来,订阅 /camera/depth/points 话题以接收点云消息,并使用 pointcloud2_to_array 函数将 sensor_msgs/PointCloud2 消息转换为包含 XYZ 坐标和 RGB 值的 NumPy 数组。使用 YOLO 模型处理 RGB 图像,以提取分割后的目标。对于每个检测到的目标,提取分割掩码,并将其应用于 RGB 图像和 XYZ 坐标,从而分离出 3D 空间中的目标。
处理掩码很简单,因为掩码由二进制值组成,其中 1 表示目标存在,0 表示目标不存在。应用掩码时,只需将原始通道与掩码相乘。此操作可以有效地从图像中分离出关注的目标。最后,创建一个 Open3D 点云对象,并在 3D 空间中可视化分割后的目标及其对应颜色。
import sys
import open3d as o3d
ros_cloud = rospy.wait_for_message("/camera/depth/points", PointCloud2)
xyz, rgb = pointcloud2_to_array(ros_cloud)
result = segmentation_model(rgb, retina_masks=True) # 原始图像分辨率下的掩码
if not len(result[0].boxes.cls):
print("No objects detected")
sys.exit()
classes = result[0].boxes.cls.cpu().numpy().astype(int)
for index, class_id in enumerate(classes):
mask = result[0].masks.data.cpu().numpy()[index, :, :].astype(int)
mask_expanded = np.stack([mask, mask, mask], axis=2)
obj_rgb = rgb * mask_expanded
obj_xyz = xyz * mask_expanded
pcd = o3d.geometry.PointCloud()
pcd.points = o3d.utility.Vector3dVector(obj_xyz.reshape((ros_cloud.height * ros_cloud.width, 3)))
pcd.colors = o3d.utility.Vector3dVector(obj_rgb.reshape((ros_cloud.height * ros_cloud.width, 3)) / 255)
o3d.visualization.draw_geometries([pcd])完整代码
import sys
import time
import numpy as np
import open3d as o3d
import ros_numpy
import rospy
from sensor_msgs.msg import PointCloud2
from ultralytics import YOLO
rospy.init_node("ultralytics")
time.sleep(1)
segmentation_model = YOLO("yolo26m-seg.pt")
def pointcloud2_to_array(pointcloud2: PointCloud2) -> tuple:
"""Convert a ROS PointCloud2 message to a numpy array.
Args:
pointcloud2 (PointCloud2): the PointCloud2 message
Returns:
(tuple): tuple containing (xyz, rgb)
"""
pc_array = ros_numpy.point_cloud2.pointcloud2_to_array(pointcloud2)
split = ros_numpy.point_cloud2.split_rgb_field(pc_array)
rgb = np.stack([split["b"], split["g"], split["r"]], axis=2)
xyz = ros_numpy.point_cloud2.get_xyz_points(pc_array, remove_nans=False)
xyz = np.array(xyz).reshape((pointcloud2.height, pointcloud2.width, 3))
nan_rows = np.isnan(xyz).all(axis=2)
xyz[nan_rows] = [0, 0, 0]
rgb[nan_rows] = [0, 0, 0]
return xyz, rgb
ros_cloud = rospy.wait_for_message("/camera/depth/points", PointCloud2)
xyz, rgb = pointcloud2_to_array(ros_cloud)
result = segmentation_model(rgb, retina_masks=True) # 原始图像分辨率下的掩码
if not len(result[0].boxes.cls):
print("No objects detected")
sys.exit()
classes = result[0].boxes.cls.cpu().numpy().astype(int)
for index, class_id in enumerate(classes):
mask = result[0].masks.data.cpu().numpy()[index, :, :].astype(int)
mask_expanded = np.stack([mask, mask, mask], axis=2)
obj_rgb = rgb * mask_expanded
obj_xyz = xyz * mask_expanded
pcd = o3d.geometry.PointCloud()
pcd.points = o3d.utility.Vector3dVector(obj_xyz.reshape((ros_cloud.height * ros_cloud.width, 3)))
pcd.colors = o3d.utility.Vector3dVector(obj_rgb.reshape((ros_cloud.height * ros_cloud.width, 3)) / 255)
o3d.visualization.draw_geometries([pcd])
结论#
将 Ultralytics YOLO 集成到 ROS 后,你的机器人就能对 RGB 图像、深度图像和点云进行目标检测和分割,将原始传感器数据流转化为可用于行动的感知结果。接下来,你可以探索预测模式以了解更多推理选项,也可以按照计算机视觉项目的步骤,将机器人应用从原型推进到生产环境。
常见问题#
机器人操作系统(ROS)是一个在机器人领域广泛使用的开源框架,可帮助开发者创建可靠的机器人应用。它提供了一系列用于构建机器人系统并与之交互的库和工具,让复杂应用的开发更加轻松。ROS 支持节点之间通过话题或服务传递消息进行通信。
将 Ultralytics YOLO 与 ROS 集成,需要设置 ROS 环境并使用 YOLO 处理传感器数据。首先,安装所需的依赖项,例如
ros_numpy和 Ultralytics YOLO:pip install ros_numpy ultralytics接下来,创建一个 ROS 节点并订阅图像话题,以处理接收到的数据并进行目标检测。以下是一个最简示例:
import ros_numpy import rospy from sensor_msgs.msg import Image from ultralytics import YOLO detection_model = YOLO("yolo26m.pt") rospy.init_node("ultralytics") det_image_pub = rospy.Publisher("/ultralytics/detection/image", Image, queue_size=5) def callback(data): array = ros_numpy.numpify(data) det_result = detection_model(array) det_annotated = det_result[0].plot(show=False) det_image_pub.publish(ros_numpy.msgify(Image, det_annotated, encoding="rgb8")) rospy.Subscriber("/camera/color/image_raw", Image, callback) rospy.spin()要在 ROS 中使用 YOLO 可视化 3D 点云:
- 将
sensor_msgs/PointCloud2消息转换为 NumPy 数组。 - 使用 YOLO 分割 RGB 图像。
- 将分割掩码应用于点云。
以下是使用 Open3D 进行可视化的示例:
import sys import numpy as np import open3d as o3d import ros_numpy import rospy from sensor_msgs.msg import PointCloud2 from ultralytics import YOLO rospy.init_node("ultralytics") segmentation_model = YOLO("yolo26m-seg.pt") def pointcloud2_to_array(pointcloud2): pc_array = ros_numpy.point_cloud2.pointcloud2_to_array(pointcloud2) split = ros_numpy.point_cloud2.split_rgb_field(pc_array) rgb = np.stack([split["b"], split["g"], split["r"]], axis=2) xyz = ros_numpy.point_cloud2.get_xyz_points(pc_array, remove_nans=False) xyz = np.array(xyz).reshape((pointcloud2.height, pointcloud2.width, 3)) return xyz, rgb ros_cloud = rospy.wait_for_message("/camera/depth/points", PointCloud2) xyz, rgb = pointcloud2_to_array(ros_cloud) result = segmentation_model(rgb, retina_masks=True) # 原始图像分辨率下的掩码 if not len(result[0].boxes.cls): print("No objects detected") sys.exit() classes = result[0].boxes.cls.cpu().numpy().astype(int) for index, class_id in enumerate(classes): mask = result[0].masks.data.cpu().numpy()[index, :, :].astype(int) mask_expanded = np.stack([mask, mask, mask], axis=2) obj_rgb = rgb * mask_expanded obj_xyz = xyz * mask_expanded pcd = o3d.geometry.PointCloud() pcd.points = o3d.utility.Vector3dVector(obj_xyz.reshape((-1, 3))) pcd.colors = o3d.utility.Vector3dVector(obj_rgb.reshape((-1, 3)) / 255) o3d.visualization.draw_geometries([pcd])这种方法可以 3D 可视化分割后的目标,适用于机器人应用中的导航和操作等任务。
- 将