How to publish a point cloud

In this example, we will see how to publish a point cloud data using the sensor_msgs/PointCloud2 message. The code will use PCL APIs for handling and creating the point cloud, and converting the PCL cloud data to PointCloud2 message type. You will get the example code pcl_publisher.cpp from the chapter_8_codes/pcl_ros_tutorial/src folder.

#include <ros/ros.h> 
 
// point cloud headers 
#include <pcl/point_cloud.h> 
//Header which contain PCL to ROS and ROS to PCL conversion functions 
#include <pcl_conversions/pcl_conversions.h> 
 
//sensor_msgs header for point cloud2 
#include <sensor_msgs/PointCloud2.h> 
 
main (int argc, char **argv) 
{ 
    ros::init (argc, argv, "pcl_create"); 
 
 
    ROS_INFO("Started PCL publishing node"); 
 
    ros::NodeHandle nh; 
 
//Creating publisher object for point cloud 
 
    ros::Publisher pcl_pub = nh.advertise<sensor_msgs::PointCloud2> ("pcl_output", 1); 
 
//Creating a cloud object 
    pcl::PointCloud<pcl::PointXYZ> cloud; 
 
//Creating a sensor_msg of point cloud 
 
    sensor_msgs::PointCloud2 output; 
 
    //Insert cloud data 
    cloud.width  = 50000; 
    cloud.height = 2; 
    cloud.points.resize(cloud.width * cloud.height); 
 
//Insert random points on the clouds 
 
    for (size_t i = 0; i < cloud.points.size (); ++i) 
    { 
        cloud.points[i].x = 512 * rand () / (RAND_MAX + 1.0f); 
        cloud.points[i].y = 512 * rand () / (RAND_MAX + 1.0f); 
        cloud.points[i].z = 512 * rand () / (RAND_MAX + 1.0f); 
    } 
 
    //Convert the cloud to ROS message 
    pcl::toROSMsg(cloud, output); 
    output.header.frame_id = "point_cloud"; 
 
    ros::Rate loop_rate(1); 
    while (ros::ok()) 
    { 
        //publishing point cloud data 
      pcl_pub.publish(output); 
        ros::spinOnce(); 
        loop_rate.sleep(); 
    } 
 
    return 0; 
} 

The creation of PCL cloud is done as follows:

//Creating a cloud object 
pcl::PointCloud<pcl::PointXYZ> cloud; 

After creating this cloud, we insert random points to the clouds. We convert the PCL cloud to a ROS message using the following function:

//Convert the cloud to ROS message 
pcl::toROSMsg(cloud, output);

After converting to ROS messages, we can simply publish the data on the topic /pcl_output.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.221.154.151