从训练到部署:如何将自定义数据集训练的YOLOv5模型集成到ROS机器人中

张开发
2026/5/17 15:42:24 15 分钟阅读
从训练到部署:如何将自定义数据集训练的YOLOv5模型集成到ROS机器人中
从训练到部署将YOLOv5模型无缝集成到ROS机器人的全流程指南当你在自己的数据集上完成了YOLOv5模型训练获得了那个经过反复调优的.pt权重文件时真正的挑战才刚刚开始——如何让这个模型在ROS机器人系统中活起来本文将带你走过从模型训练到ROS集成的完整路径解决那些鲜少被提及但至关重要的实践细节。1. 环境准备与功能包定制在开始之前确保你的开发环境满足以下基础要求Ubuntu 18.04/20.04推荐20.04以获得更好的Python3支持ROS Noetic对应Ubuntu 20.04或ROS Melodic对应Ubuntu 18.04Python 3.6建议使用3.8以获得最佳兼容性PyTorch 1.7与训练环境版本保持一致提示强烈建议使用conda创建独立Python环境避免与系统Python环境产生冲突。安装基础依赖conda create -n yolov5_ros python3.8 conda activate yolov5_ros pip install torch torchvision torchaudio获取并配置yolov5_ros功能包cd ~/catkin_ws/src git clone https://github.com/qq44642754a/Yolov5_ros.git cd Yolov5_ros/yolov5 pip install -r requirements.txt2. 模型转换与适配2.1 自定义模型集成将你训练好的模型权重如best.pt放入yolov5_ros/weights目录后需要进行以下关键修改模型加载路径配置 修改launch/yolo_v5.launch文件中的权重路径参数param nameweights_path value$(find yolov5_ros)/weights/best.pt /类别标签适配 在yolov5_ros/data目录下创建或修改custom.yaml确保类别名称与训练时一致names: [class1, class2, class3] # 替换为你的实际类别2.2 推理参数优化根据你的硬件条件和实时性需求调整detect.py中的关键参数参数推荐值说明img-size640输入图像尺寸与训练时保持一致conf-thres0.4置信度阈值可根据场景调整iou-thres0.45NMS的IOU阈值device0使用GPU (0)或CPU (cpu)max-det100单帧最大检测数量3. ROS接口深度配置3.1 图像话题适配修改launch/yolo_v5.launch中的图像订阅话题确保与你的相机驱动发布的话题一致param nameinput_image_topic value/camera/color/image_raw /3.2 检测结果发布功能包默认会发布以下话题/yolov5/detections检测结果边界框类别置信度/yolov5/visualization带检测框的可视化图像若要与其他ROS节点交互建议将检测结果转换为标准消息类型。以下是转换为vision_msgs/Detection2DArray的示例代码from vision_msgs.msg import Detection2D, Detection2DArray, ObjectHypothesisWithPose def convert_to_detection2d(bboxes, img_header): detections Detection2DArray() detections.header img_header for bbox in bboxes: detection Detection2D() detection.bbox.center.x (bbox[0] bbox[2]) / 2 detection.bbox.center.y (bbox[1] bbox[3]) / 2 detection.bbox.size_x bbox[2] - bbox[0] detection.bbox.size_y bbox[3] - bbox[1] hypothesis ObjectHypothesisWithPose() hypothesis.id int(bbox[5]) hypothesis.score bbox[4] detection.results.append(hypothesis) detections.detections.append(detection) return detections4. 性能优化与实时性提升4.1 推理加速技巧TensorRT加速 将PyTorch模型转换为TensorRT引擎可以显著提升推理速度from torch2trt import torch2trt model torch.hub.load(ultralytics/yolov5, custom, pathweights/best.pt) model.eval() x torch.ones((1, 3, 640, 640)).cuda() model_trt torch2trt(model, [x]) torch.save(model_trt.state_dict(), weights/best_trt.pt)半精度推理 在支持FP16的GPU上可以启用半精度计算model.half() # 转换为半精度4.2 资源占用监控使用rostopic hz监控处理帧率rostopic hz /yolov5/detections对于资源受限的平台可以通过cpulimit限制Python进程的CPU使用率cpulimit -l 80 -p $(pgrep -f python.*yolov5)5. 实际部署中的问题排查5.1 常见问题与解决方案问题现象可能原因解决方案检测结果为空类别不匹配检查data/下的yaml文件是否与训练时一致推理速度慢未使用GPU确保launch文件中device参数设置为0内存泄漏PyTorch缓存未清在代码中添加torch.cuda.empty_cache()图像不同步时间戳不匹配启用use_image_timestamp参数5.2 日志调试技巧在detect.py中增加调试输出import rospy rospy.loginfo(fDetection time: {t2 - t1:.3f}s) rospy.logdebug(fDetected {len(pred)} objects)设置ROS日志级别rosparam set /yolov5/log_level DEBUG6. 进阶集成方案6.1 与机器人导航栈集成将检测结果转换为costmap供导航栈避障使用from nav_msgs.msg import OccupancyGrid def create_obstacle_layer(detections, map_info): grid OccupancyGrid() grid.header map_info.header grid.info map_info # 将检测框转换为障碍物 for det in detections.detections: # 计算检测框在costmap中的位置 pass return grid6.2 多模型协同工作通过nodelet实现多个模型共享图像数据node pkgnodelet typenodelet nameyolov5_manager argsmanager/ node pkgnodelet typenodelet nameyolov5 argsload yolov5_ros/Yolov5Nodelet yolov5_manager param nameweights_path value$(find yolov5_ros)/weights/best.pt / /node在实际部署到TurtleBot3上时发现将检测框转换为激光扫描数据可以让机器人更自然地避开动态障碍物。具体做法是将检测框投影到激光扫描平面上生成虚拟的障碍点云。这种方案在人员跟随场景中表现尤为出色机器人能够平滑地绕行前方行人而不会出现急停或剧烈转向。

更多文章