#include <pcl/visualization/pcl_visualizer.h>
#include <pcl/types.h>
#include <pcl/io/pcd_io.h>
#include <pcl/io/ply_io.h>
#include <pcl/point_cloud.h>
//读取txt点云文件
void CreateCloudFromTxt(const std::string& file_path, pcl::PointCloud<pcl::PointXYZ>::Ptr cloud)
{
std::ifstream file(file_path.c_str());
std::string line;
pcl::PointXYZ point;
while (getline(file, line)) {
std::stringstream ss(line);
ss >> point.x;
ss >> point.y;
ss >> point.z;
cloud->push_back(point);
}
file.close();
}
//加载点云数据
void loadPointCloud(const std::string& fileName, pcl::PointCloud<pcl::PointXYZ>::Ptr cloud){
std::string suffix_str = fileName.substr(fileName.find_last_of('.') + 1);//获取文件后缀名
if(suffix_str.compare("pcd") == 0){ //pcd点云文件
if (pcl::io::loadPCDFile<pcl::PointXYZ>(fileName, *cloud) == -1) //* load the pcd file
{
std::cout <<"Couldn't read file \n";
return;
}
}
else if(suffix_str.compare("ply") == 0){ //ply点云文件
if (pcl::io::loadPLYFile<pcl::PointXYZ>(fileName, *cloud) == -1) //* load the ply file
{
std::cout <<"Couldn't read file \n";
return;
}
}
else if(suffix_str.compare("txt") == 0){ //txt点云文件
CreateCloudFromTxt(fileName, cloud);
}
else{
std::cout << "点云文件格式错误" << std::endl;
}
}
int main(int argc, char *argv[])
{
//读取点云数据
//创建2个PointCloud<pcl::PointXYZ> boost共享指针并进行实例化
pcl::PointCloud<pcl::PointXYZ>::Ptr cloud(new pcl::PointCloud<pcl::PointXYZ>);
pcl::PointCloud<pcl::PointXYZ>::Ptr cloud2(new pcl::PointCloud<pcl::PointXYZ>);
std::string fileName = "xxx/model.pcd";
//读取点云数据
loadPointCloud(fileName, cloud);
//可视化点云数据
//创建一个pcl::visualization::PCLVisualizer的boost::shared_ptr智能共享指针
boost::shared_ptr<pcl::visualization::PCLVisualizer> viewer;
//实例化viewer, 并给标题设置名称“3D Viewer”
viewer.reset(new pcl::visualization::PCLVisualizer ("3D Viewer"));
//创建左右两个视角
int leftPort(0);
int rightPort(0);
viewer->createViewPort(0.0, 0.0, 0.5, 1.0, leftPort); //4个参数分别是X轴的最小值,最大值,Y轴的最小值,最大值,取值0-1,left是标识
viewer->setBackgroundColor (0,0.3,0.4, leftPort);//设置视口的背景颜色
viewer->addPointCloud(cloud, "PointCloud_1");
viewer->createViewPort(0.5, 0.0, 1.0, 1.0, rightPort);
viewer->setBackgroundColor (0.3, 0.3, 0.3, rightPort);
viewer->addPointCloud(cloud, "PointCloud_2");
//不同的点云设置不同的大小
viewer->setPointCloudRenderingProperties (pcl::visualization::PCL_VISUALIZER_POINT_SIZE, 1, "PointCloud_1");
// viewer->setPointCloudRenderingProperties (pcl::visualization::PCL_VISUALIZER_POINT_SIZE, 3, "PointCloud_2");
// 阻塞式
viewer->spin();
}
可视化结果: