1、配置工程的依赖选项
catkin_create_pkg chapter6_tutorials pcl_ros roscpp rospy sensor_msgs std_msgs
2、修改 CMakelist.txt 和 package.xml 文件
3、代码方案1
#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.
main (int argc, char **argv)
{
ros::init (argc, argv, "UandBdetect");
ros::NodeHandle nh;
ros::Publisher pcl_pub = nh.advertise<sensor_msgs::PointCloud2> ("pcl_output1", 1);
pcl::PointCloud<pcl::PointXYZ> cloud;
sensor_msgs::PointCloud2 output;
pcl::io::loadPCDFile ("/home/lucifr/code/voxel_grid/table_scene_lms400.pcd", cloud);
//Convert the cloud to ROS message
pcl::toROSMsg(cloud, output);
output.header.frame_id = "odom1";//this has been done in order to be able to visualize our PointCloud2 message on the RViz visualizer
ros::Rate loop_rate(1);
while (ros::ok())
{
pcl_pub.publish(output);
ros::spinOnce();
loop_rate.sleep();
}
return 0;
}
4、代码方案2
#include <ros/ros.h>
// PCL specific includes
#include <sensor_msgs/PointCloud2.h>
#include <pcl_conversions/pcl_conversions.h>
#include <pcl/point_cloud.h>
#include <pcl/point_types.h>
#include <iostream>
#include <pcl/io/pcd_io.h>
#include <pcl/point_types.h>
#include <pcl/filters/voxel_grid.h>
ros::Publisher pub;
sensor_msgs::PointCloud2 output;//声明的输出的点云的格式
int main (int argc, char** argv)
{
ros::init (argc, argv, "voxel_grid");//声明节点的名称
ros::NodeHandle nh;
//pcl::PCLPointCloud2::Ptr cloud (new pcl::PCLPointCloud2 ());
//pcl::PCLPointCloud2::Ptr cloud_filtered (new pcl::PCLPointCloud2 ());
pcl::PCLPointCloud2* cloud = new pcl::PCLPointCloud2; //原始的点云的数据格式
pcl::PCLPointCloud2ConstPtr cloudPtr(cloud);
pcl::PCLPointCloud2 cloud_filtered;//存储滤波后的数据格式
pub = nh.advertise<sensor_msgs::PointCloud2> ("out_put2", 1);
// Fill in the cloud data
pcl::PCDReader reader;
// Replace the path below with the path where you saved your file
reader.read ("/home/lucifr/code/voxel_grid/table_scene_lms400.pcd", *cloud); // Remember to download the file first!
std::cerr << "PointCloud before filtering: " << cloud->width * cloud->height
<< " data points (" << pcl::getFieldsList (*cloud) << ").";
// Create the filtering object
pcl::VoxelGrid<pcl::PCLPointCloud2> sor;
sor.setInputCloud (cloudPtr); //设置输入的滤波,将需要过滤的点云给滤波对象
sor.setLeafSize (0.1f, 0.1f, 0.1f); //值越大,采样越稀疏
sor.filter (cloud_filtered);
pcl_conversions::moveFromPCL(cloud_filtered, output);//第一个参数是输入,后面的是输出
output.header.frame_id = std::string("base1_link");
// Publish the data
ros::Rate loop_rate(1);
while (ros::ok())
{
pub.publish(output);
ros::spinOnce();
std::cout << "hha" << std::endl;
loop_rate.sleep();
}
//pub.publish (output);
//std::cout << "8" << std::endl;
ros::spin ();
return 0;
}
5、打开 rviz, add 点云对应的topic