这里订阅了的是Kinect for Xbox One或是华硕的Xtion Pro Live的topic:/camera/depth_registered/points,初学者务必要了解什么是depth_registered(配准)。这个topic是包含了利用相机内置的calibration参数来配准RGB图和深度图,也即它的像素点包含了颜色和深度信息。
1、编写源程序
下面给出源程序,源程序来源:http://blog.csdn.net/yaked/article/details/52584231,亲测可用,其他的都不太行!
#include <iostream>
#include <ros/ros.h>
#include <pcl/point_cloud.h>
#include <pcl_conversions/pcl_conversions.h>
#include <pcl/io/pcd_io.h>
#include <pcl/visualization/cloud_viewer.h>
#include <sensor_msgs/PointCloud2.h>
using std::cout;
using std::endl;
using std::stringstream;
using std::string;
using namespace pcl;
unsigned int filesNum = 0;
bool saveCloud(false);
boost::shared_ptr<visualization::CloudViewer> viewer;
void cloudCB(const sensor_msgs::PointCloud2& input)
{
pcl::PointCloud<pcl::PointXYZRGBA> cloud; // With color
pcl::fromROSMsg(input, cloud); // sensor_msgs::PointCloud2 ----> pcl::PointCloud<T>
if(! viewer->wasStopped()) viewer->showCloud(cloud.makeShared());
if(saveCloud)
{
stringstream stream;
stream << "inputCloud"<< filesNum<< ".pcd";
string filename = stream.str();
if(io::savePCDFile(filename, cloud, true) == 0)
{
filesNum++;
cout << filename<<" Saved."<<endl;
}
else PCL_ERROR("Problem saving %s.\n", filename.c_str());
saveCloud = false;
}
}
void
keyboardEventOccured(const visualization::KeyboardEvent& event, void* nothing)
{
if(event.getKeySym() == "space"&& event.keyDown())
saveCloud = true;
}
// Creates, initializes and returns a new viewer.
boost::shared_ptr<visualization::CloudViewer> createViewer()
{
boost::shared_ptr<visualization::CloudViewer> v(new visualization::CloudViewer("OpenNI viewer"));
v->registerKeyboardCallback(keyboardEventOccured);
return(v);
}
int main (int argc, char** argv)
{
ros::init(argc, argv, "pcl_write");
ros::NodeHandle nh;
cout<< "Press space to record point cloud to a file."<<endl;
viewer = createViewer();
ros::Subscriber pcl_sub = nh.subscribe("/camera/depth_registered/points", 1, cloudCB);
ros::Rate rate(30.0);
while (ros::ok() && ! viewer->wasStopped())
{
ros::spinOnce();
rate.sleep();
}
return 0;
}
2、在ubuntu终端启动Xtion pro live 驱动
3、用qt编译并运行节点
小便利:这里强烈建议初学者在qt下运行ros节点,主要是因为qt5.5.0以上版本已经可以安装ros插件,使得建立工作空间(catkin_ws)、包(package)、和节点(node)都可以不再在终端下用命令行进行,非常有助于帮助我们进行后续的编程及管理。
4、运行节点后结果显示
注意:按空格键会将当前的点云保存下来,保存到你所建立的package文件夹下。名字为inputcloud0.pcd,inputcloud1.pcd,...依次类推。
至此,ROS下订阅topic并保存Xtion深度点云图实现结束!