ros2配合yolov8具体实现

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

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

自定义消息

int64 xmin
int64 ymin
int64 xmax
int64 ymax
float32 conf
string name

发布端代码

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()

订阅端代码

#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;
}
  • 10
    点赞
  • 15
    收藏
    觉得还不错? 一键收藏
  • 4
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 4
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值