[小程序系列] C++ PCL pcd与txt转换

[小程序系列] C++ PCL pcd与txt转换

    • 引言
    • 代码

引言

记录一下简单的点云txt文件的转换,用一个小程序实现。以pcd为例,利用stream实现即可。

代码

#include
#include
#include
#include 
#include 
#include 

void Txt2Cloud(pcl::PointCloud<pcl::PointXYZI>& cloud,const std::string & txt_path){
    char buffer[255];
    std::fstream out;
    out.open(txt_path, ios::in);
    while (!out.eof()){
        out.getline(buffer, 256, '\n');
        std::istringstream record(buffer);
        std::string data;
        std::vector<float> point_d;
        while (record >> data) {
            point_d.push_back(atof(data.c_str())); //将获取的数据存入vector中
        }
        if(point_d.size() !=4 ) break;
        
        pcl::PointXYZI pt;
        pt.x = point_d[0];
        pt.y = point_d[1];
        pt.z = point_d[2];
        pt.intensity = point_d[3];
        cloud.points.push_back(pt);
    }
    out.close();
    std::cout<<"cloud size: "<<cloud.points.size()<<std::endl;
    return;
}

void Cloud2Txt(const pcl::PointCloud<pcl::PointXYZI> & cloud,const std::string txt_path){
    std::fstream fs;
    fs.open(txt_path,std::fstream::out);
    for (size_t i = 0; i < cloud.points.size(); ++i){
        fs << cloud.points[i].x << "  "
            << cloud.points[i].y << "  "
            << cloud.points[i].z << "  "
            << cloud.points[i].intensity << "\n";
    }
    fs.close();
    return;
}

int main(int argc, char** argv){
	pcl::PointCloud<pcl::PointXYZI>::Ptr cloud(new pcl::PointCloud<pcl::PointXYZI>);
	if(pcl::io::loadPCDFile<pcl::PointXYZI>(argv[1], *cloud) == -1){
		PCL_ERROR("Couldn't read file *.pcd\n");
	    return(-1);
	}
    std::string txt_path = std::string (argv[2]);
    Cloud2Txt(*cloud,txt_path);
    pcl::PointCloud<pcl::PointXYZI> out_cloud;
    std::cout<<"save txt."<<std::endl;
    Txt2Cloud(out_cloud,txt_path);
    pcl::visualization::CloudViewer viewer("cloud viewer");
    viewer.showCloud(out_cloud.makeShared());
    while(!viewer.wasStopped()){}
	return 0;
}

你可能感兴趣的:(小程序系列,c++,开发语言,自动驾驶)