环境:
Ubuntu16.04
ROS kinetic
C++
创建工作空间和功能包
cd Downloads/ROS
mkdir -p pcdreadshow_ws/src
cd src
catkin_init_workspace
catkin_create_pkg read_pcd pcl_conversions pcl_ros roscpp sensor_msgs
进入到功能包的src文件夹下面新建.cpp文件read_pcd.cpp
#include<ros/ros.h>
#include<pcl/point_cloud.h>
#include<pcl_conversions/pcl_conversions.h>
#include<sensor_msgs/PointCloud2.h>
#include<pcl/io/pcd_io.h>//which contains the required definitions to load and store point clouds to PCD and other file formats.
int main(int argc,char **argv){
ros::init(argc,argv,"UandBdetect");
ros::NodeHandle nh;
ros::Publisher pcl_pub=nh.advertise<sensor_msgs::PointCloud2> ("pcl_output",1);
pcl::PointCloud<pcl::PointXYZ> cloud;
sensor_msgs::PointCloud2 output;
pcl::io::loadPCDFile("/home/wyh/Downloads/ROS/pcdreadshow_ws/src/read_pcd/src/data/pcd/data_1/0000000001.pcd",cloud);//修改自己pcd文件所在路径
//Convert the cloud to ROS message
pcl::toROSMsg(cloud,output);
output.header.frame_id="odom";//this has been done in order to be able to visualize our PointCloud2 message on the RViz visualizer
//!!!这一步需要注意,是后面rviz的 fixed_frame !!!敲黑板,画重点。
ros::Rate loop_rate(1);
while (ros::ok())
{
/* code for loop body */
pcl_pub.publish(output);
ros::spinOnce();
loop_rate.sleep();
}
return 0;
}
将下面的编译规则写入功能包下面的CMAKE.list文件中
add_executable(read_pcd src/read_pcd.cpp)
target_link_libraries(read_pcd ${catkin_LIBRARIES})
回到工作空间路径下在终端中输入catkin_make进行编译.
分别依次打开多个终端分别输入下面的命令:
roscore
rosrun read_pcd read_pcd
rviz
打开rviz后add一个pointcloud2,topic话题选择pcl_outputm,然后FixedFrame填入odom即可看到图像。