ROS2下编写package利用orbbec相机进行yolov8实时目标检测

news/2025/2/23 7:38:03

视频讲解

ROS2下编写package利用orbbec相机进行yolov8实时目标检测

在《ROS2下编写orbbec相机C++ package并Rviz显示》的基础上,继续添加对获取的图像使用YOLO进行目标检测

首先安装YOLO以及相关库

pip3 install ultralytics 

使用如下指令测试下yolo安装情况

yolo task=detect mode=predict model=yolov8n.pt source='https://ultralytics.com/images/bus.jpg'

成功会在当前位置下生成runs,如下图为检测加上标签的图片,确认yolo调用成功

接下来使用orbbec发布的图像,进行YOLO实时识别

编写yolo识别package

ros2 pkg create --build-type ament_python yolo_target_detection --dependencies rclpy sensor_msgs cv_bridge

指定依赖项 rclpy(ROS 2 Python 客户端库)、sensor_msgs(用于处理图像消息)和 cv_bridge(用于在 ROS 图像消息和 OpenCV 图像之间进行转换)

在src/yolo_target_detection/yolo_target_detection目录下创建一个 Python 脚本,例如yolo_target_detection.py,并添加以下代码:

import rclpy
from rclpy.node import Node
from sensor_msgs.msg import Image
from cv_bridge import CvBridge
import cv2
from ultralytics import YOLO
import numpy as np
from std_msgs.msg import Header
from sensor_msgs.msg import Image as ROSImage


class YoloTargetDetectionNode(Node):
    def __init__(self):
        super().__init__('yolo_target_detection_node')
        
        # Initialize the YOLOv8 model
        self.model = YOLO("yolov8n.pt")  # 选择你训练的模型
        self.bridge = CvBridge()

        # Create a subscriber for RGB image
        self.image_sub = self.create_subscription(
            Image,
            '/rgb_image',  # 修改为你订阅的topic
            self.image_callback,
            10
        )

        # Create a publisher for output image with bounding boxes
        self.obb_pub = self.create_publisher(
            ROSImage,
            '/obb_image',
            10
        )

    def image_callback(self, msg):
        try:
            # Convert ROS Image message to OpenCV image
            cv_image = self.bridge.imgmsg_to_cv2(msg, "bgr8")
        except Exception as e:
            self.get_logger().error(f"Error converting image: {e}")
            return

        # Perform object detection using YOLOv8
        results = self.model(cv_image)
        
        # YOLOv8 returns a list of results, each result is a Results object
        result = results[0]  # Get the first result (assuming single image inference)
        
        # Get bounding boxes, class IDs, and confidences
        boxes = result.boxes.xywh.cpu().numpy()  # Bounding boxes (x_center, y_center, width, height)
        confidences = result.boxes.conf.cpu().numpy()  # Confidence scores
        class_ids = result.boxes.cls.cpu().numpy()  # Class IDs
        labels = result.names  # Class names

        # Draw bounding boxes on the image
        for i, box in enumerate(boxes):
            x_center, y_center, width, height = box[:4]
            confidence = confidences[i]
            class_id = int(class_ids[i])  # Get the class ID
            label = labels[class_id]  # Get the class label
            
            # Convert center to top-left coordinates for cv2
            x1 = int((x_center - width / 2))
            y1 = int((y_center - height / 2))
            x2 = int((x_center + width / 2))
            y2 = int((y_center + height / 2))

            # Draw bounding box and label on the image
            cv2.rectangle(cv_image, (x1, y1), (x2, y2), (0, 255, 0), 2)
            cv2.putText(cv_image, f"{label} {confidence:.2f}", (x1, y1 - 10),
                        cv2.FONT_HERSHEY_SIMPLEX, 0.6, (255, 0, 0), 2)

        # Convert the image with bounding boxes back to ROS message
        try:
            obb_image_msg = self.bridge.cv2_to_imgmsg(cv_image, encoding="bgr8")
            obb_image_msg.header = Header()
            obb_image_msg.header.stamp = self.get_clock().now().to_msg()
            obb_image_msg.header.frame_id = "camera_frame"  # 根据你的相机frame进行调整
            
            # Publish the image with bounding boxes
            self.obb_pub.publish(obb_image_msg)
            self.get_logger().info("Published object-bound box image.")
        except Exception as e:
            self.get_logger().error(f"Error publishing image: {e}")

def main(args=None):
    rclpy.init(args=args)
    node = YoloTargetDetectionNode()

    try:
        rclpy.spin(node)
    except KeyboardInterrupt:
        pass
    finally:
        node.destroy_node()
        rclpy.shutdown()


if __name__ == '__main__':
    main()

打开src/yolo_target_detection/setup.py文件,添加以下内容:

[develop]
script_dir=$base/lib/yolo_target_detection
[install]
install_scripts=$base/lib/yolo_target_detection

在终端中执行以下命令构建和安装包:

colcon build --packages-select yolo_target_detection
source install/setup.bash
ros2 run yolo_target_detection yolo_target_detection

打开Rviz及Orbbec节点发布rgb_image消息即可,同时配置Rviz增加新的image显示,订阅消息为obb_image


http://www.niftyadmin.cn/n/5863176.html

相关文章

anaconda不显示jupyter了?

以前下载的anaconda显示jupyter,但是最近学习吴恩达的机器学习视频,需要用到jupyter,以前的jupyter运行不了,就重新下载了一个anaconda,发现新版的anaconda首页不显示jupyter了,在查找资料之后,…

请说明C#中的List是如何扩容的?

在 C# 中&#xff0c;List<T>是一个动态数组&#xff0c;它会根据需要自动调整其容量以容纳更多的元素。 目录 1 扩容条件与扩容算法规则 2 总结 1 扩容条件与扩容算法规则 当你创建一个新的List<T>实例时&#xff0c;如果没有指定初始容量&#xff0c;它会使…

小智机器人CMakeLists编译文件解析

编译完成后&#xff0c;成功烧录&#xff01; 这段代码是一个CMake脚本&#xff0c;用于配置和构建一个嵌入式项目&#xff0c;特别是针对ESP32系列芯片的项目。CMake是一个跨平台的构建系统&#xff0c;用于管理项目的编译过程。 set(SOURCES "audio_codecs/audio_code…

2025前端框架最新组件解析与实战技巧:Vue与React的革新之路

作者&#xff1a;飞天大河豚 引言 2025年的前端开发领域&#xff0c;Vue与React依然是开发者最青睐的框架。随着Vue 3的全面普及和React 18的持续优化&#xff0c;两大框架在组件化开发、性能优化、工程化支持等方面均有显著突破。本文将从最新组件特性、使用场景和编码技巧三…

【C语言】第六期——数组

目录 0 前言 1 声明数组 2 初始化数组 2.1 部分初始化 3 访问数组元素 4 修改数组元素 5 计算数组长度&#xff08;size of&#xff09; 5.1 应用&#xff1a;遍历数组 6 定义使用数组时常见的错误 7 选择排序和冒泡排序&#xff08;拓展&#xff09; 7.1 选择排序 …

ChromeDriver版本不匹配问题的解决

今天运行一个以前写的爬虫程序&#xff0c;遇到如下错误&#xff1a; selenium.common.exceptions.SessionNotCreatedException: Message: session not created: This version of ChromeDriver only supports Chrome version 121 Current browser version is 133.0.6943.98 w…

计算机毕业设计SpringBoot+Vue.js学生读书笔记共享(源码+LW文档+PPT+讲解+开题报告)

温馨提示&#xff1a;文末有 CSDN 平台官方提供的学长联系方式的名片&#xff01; 温馨提示&#xff1a;文末有 CSDN 平台官方提供的学长联系方式的名片&#xff01; 温馨提示&#xff1a;文末有 CSDN 平台官方提供的学长联系方式的名片&#xff01; 作者简介&#xff1a;Java领…

车载诊断数据库 --- AUTOSAR诊断文件DEXT简介

我是穿拖鞋的汉子,魔都中坚持长期主义的汽车电子工程师。 老规矩,分享一段喜欢的文字,避免自己成为高知识低文化的工程师: 简单,单纯,喜欢独处,独来独往,不易合同频过着接地气的生活,除了生存温饱问题之外,没有什么过多的欲望,表面看起来很高冷,内心热情,如果你身…