目的
在进行点云项目的时候用到了下采样,去除离群点等操作。所以把它俩写到了一起,最后加了个可视化方便查看。其中下采样是用的VoxelGrid滤波器,去除离群点使用了StatisticsOutlierRemoval滤波器。
代码
#include <iostream>
#include <pcl/io/pcd_io.h>
#include <pcl/point_types.h>
#include <pcl/filters/voxel_grid.h>
#include <pcl/filters/statistical_outlier_removal.h>
#include <pcl/visualization/cloud_viewer.h>
#include <pcl/visualization/pcl_visualizer.h>
int
main()
{
//----------------------- 下采样 --------------------------------------------------
pcl::PCLPointCloud2::Ptr cloud(new pcl::PCLPointCloud2()); //体素滤波的输入点云
pcl::PCLPointCloud2::Ptr cloud_filtered(new pcl::PCLPointCloud2()); //体素滤波的结果点云
pcl::PointCloud<pcl::PointXYZ>::Ptr cloud_filtered_z(new pcl::PointCloud<pcl::PointXYZ>); //提速滤波的转换格式后的点云
//读取点云
pcl::PCDReader reader;
reader.read("D:/ground_1.pcd",*cloud);
std::cerr << "下采样前: " << cloud->width * cloud->height
<< " data points (" << pcl::getFieldsList(*cloud) << ")." << std::endl;
//创建滤波器
pcl::VoxelGrid<pcl::PCLPointCloud2> sor_1;
sor_1.setInputCloud(cloud); //设置输入点云(要进行采样的点云)
sor_1.setLeafSize(0.01f, 0.01f, 0.01f); //设置叶子大小
sor_1.filter(*cloud_filtered); //得到采样后的点云
pcl::fromPCLPointCloud2(*cloud_filtered, *cloud_filtered_z);//转换格式(将pcl::PCLPointCloud2::Ptr 转换为 pcl::PointCloud<pcl::PointXYZ>::Ptr)
std::cerr << "下采样后: " << cloud_filtered->width * cloud_filtered->height
<< " data points (" << pcl::getFieldsList(*cloud_filtered) << ")." << std::endl;
cout << endl;
//----------------------- 去除离群点-----------------------------------------------
pcl::PointCloud<pcl::PointXYZ>::Ptr cloud_filtered_2(new pcl::PointCloud<pcl::PointXYZ>); //去除离群点的结果点云
std::cerr << "去除离群点之前: " << std::endl;
std::cerr << *cloud_filtered_z << std::endl;
//创建滤波器
pcl::StatisticalOutlierRemoval<pcl::PointXYZ> sor_2;
sor_2.setInputCloud(cloud_filtered_z);
sor_2.setMeanK(50);
sor_2.setStddevMulThresh(1.0);
sor_2.filter(*cloud_filtered_2);
std::cerr << "去除离群点之后: " << std::endl;
std::cerr << *cloud_filtered_2 << std::endl;
//----------------------- 可视化 -----------------------------------------------
boost::shared_ptr<pcl::visualization::PCLVisualizer> m_viewer; //窗口
//显示窗口初始化
m_viewer.reset(new pcl::visualization::PCLVisualizer("viewer", false));
m_viewer->setBackgroundColor(0, 0, 0);//设置背景颜色
m_viewer->initCameraParameters();
m_viewer->addCoordinateSystem();//添加红绿蓝坐标轴
m_viewer->createInteractor();
while (!m_viewer->wasStopped()) {
m_viewer->spinOnce(1);
if (!m_viewer->updatePointCloud(cloud_filtered_2->makeShared(), "cloud")) {//pointCloud_XYZRGBA是指针类型,不能用( . )运算符
m_viewer->addPointCloud(cloud_filtered_2->makeShared(), "cloud");
}
}
system("pause");
return (0);
}
说明
如果点云数量过多,计算时间会有些长。
结果