Jetson Nano之ROS入门 -- YOLO目标检测与定位

chatgpt/2023/9/27 16:30:48

文章目录

  • 前言
  • 一、yolo板端部署推理
  • 二、目标深度测距
  • 三、目标方位解算与导航点设定
    • 1、相机成像原理
    • 2、Python实现目标定位
  • 总结


前言

在这里插入图片描述

Darknet_ros是一个基于ROS(机器人操作系统)的开源深度学习框架,它使用YOLO算法进行目标检测和识别。YOLO算法是一种实时物体检测算法,它能够在单个前向传递中同时检测图像中的多个目标。

Darknet_ros将YOLO算法集成到ROS中,使得机器人可以实时地检测和识别周围环境中的物体。它提供了一些ROS节点和服务,可以在ROS系统中轻松使用YOLO算法进行目标检测和识别。同时,它还提供了一些示例程序,帮助用户快速了解如何在ROS中使用深度学习算法进行机器人视觉任务。

Darknet_ros的优点是速度快、准确度高,可以在实时应用中使用。它还可以在不同的机器人项目中使用,例如无人机、机器人车辆和机器人臂等。


一、yolo板端部署推理

首先确认CUDA,OpenCV,cuDNN已安装,可以用命令查看CUDA是否安装

ls -l /usr/local | grep cuda

查看opencv版本

opencv_version

接着从gitee上克隆darknet_ros源码下来

git clone https://gitee.com/bluesky_ryan/darknet_ros.git

按照如下指引下载权重文件,将下载的weights权重文件放在
darknet_ros/darknet_ros/yolo_network_config/weights

cd catkin_workspace/src/darknet_ros/darknet_ros/yolo_network_config/weights/COCO data set (Yolo v2):wget http://pjreddie.com/media/files/yolov2.weightswget http://pjreddie.com/media/files/yolov2-tiny.weightsVOC data set (Yolo v2):wget http://pjreddie.com/media/files/yolov2-voc.weightswget http://pjreddie.com/media/files/yolov2-tiny-voc.weightsYolo v3:wget http://pjreddie.com/media/files/yolov3.weightswget http://pjreddie.com/media/files/yolov3-voc.weights

使用jetson nano自带的opencv4.x编译会报错,需要安装opencv3.4.2版本,配置opencv cmake桥接目录

sudo vim /opt/ros/melodic/share/cv_bridge/cmake/cv_bridgeConfig.cmake 

在这里插入图片描述

接着cd到工作空间下,编译darknet_ros功能包

catkin_make -DCATKIN_WHITELIST_PACKAGES="darknet_ros"

配置launch文件图像输入的topic,可以打开摄像头节点后用rostopic命令查看

rostopic list

我的RGB图像发布的话题是/camera/rgb/image_raw,接着配置yolo网络参数,我用的是yolov2-tiny权重文件,检查一下ros.yaml文件也要配置成/camera/rgb/image_raw
在这里插入图片描述
打开终端,source一下工作空间下ros的环境变量

source /catkin_ws/devel/setup.bash

首先启动相机节点,需要有/camera/rgb/image_raw的话题输出,再运行darknet_ros 节点

roslaunch darknet_ros darknet_ros.launch

接着会弹出一个窗口,展示识别到的物体
在这里插入图片描述

二、目标深度测距

目标的深度测距的实现我们可以结合darknet_ros功能包,我这里用的是RGBD相机,型号是Astra_Pro,深度相机节点在启动后会输出深度图的话题

rostopic list/camera/depth/image_rect_raw

查看一下darknet_ros功能包的msg消息文件,下面是BoundingBoxes.msg消息文件

Header header
Header image_header
BoundingBox[] bounding_boxes

下面是BoundingBox.msg消息文件

float64 probability
int64 xmin
int64 ymin
int64 xmax
int64 ymax
int16 id
string Class

用rostopic info命令可以看到/darknet_ros/bounding_boxes话题的具体内容

rostopic info /darknet_ros/bounding_boxesType: darknet_ros_msgs/BoundingBoxesPublishers: * /darknet_ros (http://localhost:43545/)

这个话题就是我们需要的目标检测框的信息,将目标检测框输出到深度图我们就可以读取目标的深度

首先创建一个scripts文件夹,创建ObjectLocation.py文件

touch ObjectLocation.py

目标深度测距的代码思路首先导入rospy、cv2、numpy、darknet_ros_msgs等包,创建一个目标定位的类,实例化类的一些参数,订阅深度图话题并转化为深度矩阵,订阅目标检测框将坐标信息对齐到深度图中,按照3x3滑动窗口遍历检测框进行中值滤波,最后取中心深度作为目标的估计深度,并发布距离话题

#!/usr/bin/env python
#-*- coding: utf-8 -*-
import rospy
import cv2
from cv_bridge import CvBridge, CvBridgeError
from sensor_msgs.msg import Image
from darknet_ros_msgs.msg import BoundingBoxes 
import numpy as np
from scipy.ndimage import median_filter
import mathclass ObjectLocation:def __init__(self):self.bridge = CvBridge()self.depth_image = Noneself.bounding_boxes = Noneself.probability = 0self.Class = Noneself.distance = 0self.centerx = 0self.centery = 0self.x_h = 0self.y_h = 0self.w_h = 0cv2.destroyAllWindows()'''get depth distance from found object rect'''def depthDistanceFromCoordinate(self, data):try:self.depth_image = self.bridge.imgmsg_to_cv2(data, "passthrough")depth_array = np.array(self.depth_image, dtype=np.float32)filter_depth_array = np.zeros_like(depth_array)if self.bounding_boxes != None:for bounding_box in self.bounding_boxes:# bounding box coordinates # less than 0 and larger than width or heightxmin = 0 if bounding_box.xmin < 0 else bounding_box.xminxmax = bounding_box.xmax if bounding_box.xmax < len(depth_array[0]) else len(depth_array[0])ymin = 0 if bounding_box.ymin < 0 else bounding_box.yminymax = bounding_box.ymax if bounding_box.ymax < len(depth_array) else len(depth_array)dep_aver = 0filter_depth_array = median_filter(depth_array, size=(3, 3))dep_aver = filter_depth_array[int((ymin + ymax) / 2), int((xmin + xmax) / 2)]self.probability = bounding_box.probabilityself.Class = bounding_box.Classself.distance = dep_averself.centerx =  (xmin + xmax) / 2self.centery =  (ymin + ymax) / 2rospy.loginfo("Class=%s, Probability=%f, Distance=%f", self.Class, self.probability, self.distance)pub = rospy.Publisher('/darknet_ros/distance', self.distance, queue_size = 100)pub.publish(self.distance)except Exception as e:print(e)def bbox_callback(self, msg):self.bounding_boxes = msg.bounding_boxesif __name__ == '__main__':od = ObjectLocation()rospy.init_node('ObjectLocation', anonymous=True)rospy.Subscriber('/darknet_ros/bounding_boxes', BoundingBoxes, od.bbox_callback)rospy.Subscriber('/camera/depth/image_rect_raw', Image, od.depthDistanceFromCoordinate)rate = rospy.Rate(10)rate.sleep()rospy.spin()

三、目标方位解算与导航点设定

1、相机成像原理

我们需要根据相机内外参去解算目标的方位,相机内参外参原理参照下面链接,依据成像原理我们可以将在像素坐标系下的目标映射到相机坐标系
https://zhuanlan.zhihu.com/p/389653208

2、Python实现目标定位

运行标定相机的demo就可以得到相机的内参外参矩阵,我的是出厂就标定好的附带内参矩阵,放在
home/wheeltec/.ros/camera_info/camera.yaml 文件里,内参矩阵是相机出厂时就决定了的

image_width: 640
image_height: 480
camera_name: camera
camera_matrix:rows: 3cols: 3data: [ 581.88585,    0.     ,  314.2472 ,0.     ,  592.27138,  210.27091,0.     ,    0.     ,    1.     ]
camera_model: plumb_bob
distortion_model: plumb_bob
distortion_coefficients:rows: 1cols: 5data: [0.221666, -0.575455, -0.014215, 0.003895, 0.000000]
rectification_matrix:rows: 3cols: 3data: [ 1.,  0.,  0.,0.,  1.,  0.,0.,  0.,  1.]
projection_matrix:rows: 3cols: 4data: [ 591.88599,    0.     ,  315.96148,    0.     ,0.     ,  603.39893,  205.72873,    0.     ,0.     ,    0.     ,    1.     ,    0.     ]

相机的外参矩阵则要确定机器人坐标系下的相机位姿,才能将目标方位解算到机器人bse_link坐标系下。用Python程序设定导航目标点的主要通过ROS中名为"move_base"的动作服务器(Action Server),负责接收和处理导航目标,我们将导航目标点位姿信息解算好,发送到move_base节点即可。

在原有的ObjectLocation.py上导入actionlib、tf、move_base_msgs等包,使用矩阵求逆加内积来将像素坐标系下的目标位置映射到相机坐标系,再通过tf坐标变换映射到机器人坐标系,实例化导航目标点,将目标点位姿发送到move_base节点,等待动作服务器响应即可

#!/usr/bin/env python
#-*- coding: utf-8 -*-
import rospy
import cv2
from cv_bridge import CvBridge, CvBridgeError
from sensor_msgs.msg import Image
from darknet_ros_msgs.msg import  BoundingBoxes 
import numpy as np
from scipy.ndimage import median_filter
import actionlib
from move_base_msgs.msg import MoveBaseAction, MoveBaseGoal 
import tf.transformations as tr
import mathclass ObjectLocation:def __init__(self):self.bridge = CvBridge()self.depth_image = Noneself.bounding_boxes = Noneself.probability = 0self.Class = Noneself.distance = 0self.centerx = 0self.centery = 0self.x_h = 0self.y_h = 0self.w_h = 0cv2.destroyAllWindows()'''get depth distance from found object rect'''def depthDistanceFromCoordinate(self, data):try:self.depth_image = self.bridge.imgmsg_to_cv2(data, "passthrough")depth_array = np.array(self.depth_image, dtype=np.float32)filter_depth_array = np.zeros_like(depth_array)if self.bounding_boxes != None:for bounding_box in self.bounding_boxes:# bounding box coordinates # less than 0 and larger than width or heightxmin = 0 if bounding_box.xmin < 0 else bounding_box.xminxmax = bounding_box.xmax if bounding_box.xmax < len(depth_array[0]) else len(depth_array[0])ymin = 0 if bounding_box.ymin < 0 else bounding_box.yminymax = bounding_box.ymax if bounding_box.ymax < len(depth_array) else len(depth_array)dep_aver = 0filter_depth_array = median_filter(depth_array, size=(3, 3))dep_aver = filter_depth_array[int((ymin + ymax) / 2), int((xmin + xmax) / 2)]self.probability = bounding_box.probabilityself.Class = bounding_box.Classself.distance = dep_averself.centerx =  (xmin + xmax) / 2self.centery =  (ymin + ymax) / 2rospy.loginfo("Class=%s, Probability=%f, Distance=%f", self.Class, self.probability, self.distance)if self.Class == "pottedplant":fx = 581.88585fy = 592.27138cx = 314.2472cy = 210.27091K = np.array([[fx, 0., cx], [0., fy, cy], [0., 0., 1.]])point_pixel = np.array([self.centerx, self.centery, 1])point_camera = np.dot(np.linalg.inv(K), point_pixel) * self.distanceself.y_h = - point_camera[0] - 460self.x_h = point_camera[2] + 110orientation = tr.quaternion_from_euler(0, 0, math.atan2(self.y_h, self.x_h))self.w_h = orientation[3]rospy.loginfo("%s Goal location is x_h = %f, y_h = %f, w_h=%f", "pottedplant", self.x_h, self.y_h, self.w_h)self.movebase_callback()pub = rospy.Publisher('/darknet_ros/distance', self.distance, queue_size = 100)pub.publish(self.distance)except Exception as e:print(e)def movebase_callback(self):try:client = actionlib.SimpleActionClient('move_base', MoveBaseAction)client.wait_for_server()goal = MoveBaseGoal()goal.target_pose.header.frame_id = "base_link"goal.target_pose.pose.position.x = self.x_h * 4 / 5000goal.target_pose.pose.position.y = self.y_h * 4 / 5000goal.target_pose.pose.orientation.w = self.w_hclient.send_goal(goal)rospy.loginfo("move_base set goal success!")client.wait_for_result()except Exception as e:print("movebase_callback service failed")def bbox_callback(self, msg):self.bounding_boxes = msg.bounding_boxesif __name__ == '__main__':od = ObjectLocation()rospy.init_node('ObjectLocation', anonymous=True)rospy.Subscriber('/darknet_ros/bounding_boxes', BoundingBoxes, od.bbox_callback)rospy.Subscriber('/camera/depth/image_rect_raw', Image, od.depthDistanceFromCoordinate)rate = rospy.Rate(10)rate.sleep()rospy.spin()

下面是演示结果,其实还可以用其他滤波方法让深度估计更加精确,用重采样方法让方位估计更加精准
在这里插入图片描述


总结

darknet_ros软件包将ROS和YOLO很好的融合在一起,为机器人视觉任务开发提供了更多可能性。通过实时目标检测和识别,机器人能够感知和理解环境,实现人机交互,提高安全性,并在各种应用中发挥更智能和自主的作用。通过实时目标检测和识别,可以帮助机器人识别不同类型的物体,并根据目标物体的位置和特征来理解当前场景。这对于机器人在导航、路径规划和任务执行中具有重要意义。

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.exyb.cn/news/show-5313305.html

如若内容造成侵权/违法违规/事实不符,请联系郑州代理记账网进行投诉反馈,一经查实,立即删除!

相关文章

URL存储解锁数据管理的新思路,重新定义数据传输与共享(@vue/repl)

Thinking系列&#xff0c;旨在利用10分钟的时间传达一种可落地的编程思想。 近日&#xff0c;在了解 vue/repl 相关内容&#xff0c;其通过 URL 进行数据存储&#xff0c;感觉思路惊奇&#xff0c;打开了新方式。 首先&#xff0c;通过 URL 存储最大的便利是&#xff1a;无需服…

奇富科技联合哈银消金获《亚洲银行家》中国最佳信贷项目奖

7月28日&#xff0c;全球金融领域最具含金量的奖项之一《亚洲银行家》颁布2023年度奖项&#xff0c;奇富科技荣获“中国最佳信贷项目”殊荣。值得关注的是&#xff0c;该奖项由奇富科技与哈银消金联合获得&#xff0c;双方联合获奖&#xff0c;是主办方对奇富科技全面赋能金融机…

C++推理

YOLOv5 OpenCV DNN C导出的 ONNX 模型示例的推理&#xff1a; https://github.com/Hexmagic/ONNX-yolov5/blob/master/src/test.cpphttps://github.com/doleron/yolov5-opencv-cpp-python YOLOv5 OpenVINO C推理示例&#xff1a; GitHub - dacquaviva/yolov5-openvino-cpp-p…

性能测试必备监控技能linux篇

前言 如果性能测试的目标服务器是linux系统&#xff0c;在如何使用linux自带的命令来实现性能测试过程的监控分析呢&#xff1f; 对于日常性能测试来讲&#xff0c;在linux下或是类Unix系统&#xff0c;我们必须掌握以下常用的指标查看命令。 ps pstree top free vmstat …

学习笔记——压力测试案例,监控平台

测试案例 # 最简单的部署方式直接单机启动 nohup java -jar lesson-one-0.0.1-SNAPSHOT.jar > ./server.log 2>&1 &然后配置执行计划&#xff1a; 新建一个执行计划 配置请求路径 配置断言配置响应持续时间断言 然后配置一些查看结果的统计报表或者图形 然后我…

代码随想录算法训练营day55 392.判断子序列 115.不同的子序列

题目链接392.判断子序列 class Solution {public boolean isSubsequence(String s, String t) {int length1 s.length();int length2 t.length();int[][] dp new int[length11][length21];for(int i 1; i < length1; i){for(int j 1; j <length2; j){if(s.charAt(i…

Rust- 错误处理

Rust approaches error handling with the aim of being explicit about possible error conditions. It separates the concerns of “normal” return values and “error” return values by using a specific set of types for each concern. Rust’s primary tools for ex…

热度升温 SSOT上海国际智慧办公展览会精彩预告福利放送

上海国际智慧办公展览会&#xff08;SSOT&#xff09;是智慧办公及商用空间智能化解决方案及技术应用的专业平台&#xff0c;本届展会除了将“智联”智能行业&#xff0c;同时会以“智越”为题&#xff0c;与行业共建跨越行业界限之桥梁。 展会将融合应用智慧办公、智慧地产、智…
推荐文章