当前位置:   article > 正文

ros2配合yolov8具体实现

ros2配合yolov8具体实现

效果图
在这里插入图片描述

  1. 用yolov8实时检测物体,包括物体的类别,置信度和坐标
  2. 通过ros2发布出去

自定义消息

int64 xmin
int64 ymin
int64 xmax
int64 ymax
float32 conf
string name
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6

发布端代码

from ultralytics import YOLO
import cv2
import rclpy
from yolo_interfaces.msg import Msgyolo

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

    node = rclpy.create_node('yolo_pub')
    pub = node.create_publisher(Msgyolo, 'msgyolo', 10)

    model = YOLO("/home/galactic/yolo_ws/src/yolo_detection/resource/yolov8m.pt") 

    while rclpy.ok():
        results = model.predict(source=0, show=True, stream=True)

        for r in results:
            preds = r.boxes.xyxy.cpu().numpy().astype('uint32')

            for index, pred in enumerate(preds):
                cl = int(r.boxes.cls[index].item())
                # print('......', int(pred[0]), int(pred[1]), int(pred[2]), int(pred[3]))# 坐标位置
                # print('name = ', r.names[cl])# 分类名称
                # print('conf = ', r.boxes.conf[index])# 置信度
                msg = Msgyolo()
                msg.xmin = int(pred[0])
                msg.ymin = int(pred[1])
                msg.xmax = int(pred[2])
                msg.ymax = int(pred[3])
                msg.conf = float(r.boxes.conf[index])
                msg.name = r.names[cl]
                pub.publish(msg)

        rclpy.spin_once(node)

    rclpy.shutdown()
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36

订阅端代码

#include <rclcpp/rclcpp.hpp>
#include "yolo_interfaces/msg/msgyolo.hpp"

using namespace std::chrono_literals;

class YoloNode : public rclcpp::Node
{
public:
  explicit YoloNode() : Node("yolo_node") {
    subscriber_ = this->create_subscription<yolo_interfaces::msg::Msgyolo>(
      "msgyolo", 10, 
      std::bind(&YoloNode::topic_callback, this, std::placeholders::_1));
  }

private:
  void topic_callback(const yolo_interfaces::msg::Msgyolo::SharedPtr msg) const
  {
    RCLCPP_INFO(this->get_logger(), "目标的坐标信息为:name=%s,conf=%f,xmin=%d,ymin=%d,xmax=%d,ymax=%d",
        msg->name.c_str(), msg->conf, msg->xmin, msg->ymin, msg->xmax, msg->ymax);
  }

  rclcpp::Subscription<yolo_interfaces::msg::Msgyolo>::SharedPtr subscriber_;
};

int main(int argc, char * argv[])
{
  rclcpp::init(argc, argv);
  rclcpp::spin(std::make_shared<YoloNode>());
  rclcpp::shutdown();
  return 0;
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/blog/article/detail/51995
推荐阅读
相关标签
  

闽ICP备14008679号