ROS2 单帧Pcd转多帧节点 录制Bag
在项目上有pcd转bag的需求,支持类模板适配,增加发布计时器
ros2 pkg create ros2pcl --build-type ament_cmake --dependencies rclcpp pcl_ros pcl_conversions sensor_msgscolcon build. install/setup.bashros2 run ros2pcl ros2pcl_test_sub + 你的pcd路径 ros2 bag record /point_cloud_topic
#include <iostream>
#include <memory>
#include <string>
#include <time.h>
#include "stdio.h"
#include "rclcpp/rclcpp.hpp"
#include "sensor_msgs/msg/point_cloud.hpp"
#include "pcl_conversions/pcl_conversions.h"#include <pcl/point_types.h>
#include <pcl/io/pcd_io.h>template<typename PointT>
class PointCloudShow: public rclcpp::Node {
public:PointCloudShow(const std::string & file_name): Node("point_cloud_show") {publisher_ = this->create_publisher<sensor_msgs::msg::PointCloud2>("point_cloud_topic", 10);typename pcl::PointCloud<PointT>::Ptr cloud(new pcl::PointCloud<PointT>);if (pcl::io::loadPCDFile<PointT>(file_name, *cloud) == -1) {PCL_ERROR("无法读取文件 %s\n", file_name.c_str());}time_t startTime,endTime,curTime,previous,play_time;play_time = 10;//设置你的播放时间time(&startTime);endTime = startTime + play_time;previous = startTime;while(curTime != endTime) {time(&curTime);if (curTime - previous > 0) {previous = curTime;std::cout<<"time last:"<<endTime - curTime<<" "<<std::endl; }sensor_msgs::msg::PointCloud2 cloud_msg;pcl::toROSMsg(*cloud, cloud_msg);cloud_msg.header.frame_id = "velo_link";publisher_->publish(cloud_msg);}}
private:rclcpp::Publisher<sensor_msgs::msg::PointCloud2>::SharedPtr publisher_;
};int main(int argc, char * argv[])
{if(argc<2){std::cerr << "请在节点后输入要显示的pcd文件地址!" << std::endl;return 1;}rclcpp::init(argc, argv);// PointCloudShow<pcl::PointXYZI>* node = new PointCloudShow<pcl::PointXYZI>(argv[1]);auto node = std::make_shared<PointCloudShow<pcl::PointXYZI>>(argv[1]);rclcpp::spin(node);rclcpp::shutdown();return 0;
}
CMaktLists.txt
cmake_minimum_required(VERSION 3.5)
project(ros2pcl)if(NOT CMAKE_C_STANDARD)set(CMAKE_C_STANDARD 99)
endif()if(NOT CMAKE_CXX_STANDARD)set(CMAKE_CXX_STANDARD 14)
endif()if(CMAKE_COMPILER_IS_GNUCXX OR CMAKE_CXX_COMPILER_ID MATCHES "Clang")add_compile_options(-Wall -Wextra -Wpedantic)
endif()find_package(ament_cmake REQUIRED)
find_package(rclcpp REQUIRED)
find_package(sensor_msgs REQUIRED)
find_package(PCL REQUIRED)if(BUILD_TESTING)find_package(ament_lint_auto REQUIRED)ament_lint_auto_find_test_dependencies()
endif()add_executable(ros2pcl_test_sub src/subscription_pcl.cpp
)
ament_target_dependencies(ros2pcl_test_sub rclcpp sensor_msgsPCL
)
link_directories(${PCL_LIBRARY_DIRS})
add_definitions(${PCL_DEFINITIONS})
target_link_libraries(ros2pcl_test_sub ${PCL_LIBRARIES})
install(TARGETSros2pcl_test_sub DESTINATION lib/${PROJECT_NAME})ament_package()
参考 【ROS2】ROS2环境下用RVIZ2进行点云的可视化_ros2 rviz-CSDN博客