作用:主要用于剔除离群点,或则测量误差导致的粗差点.
原理:对每一个点的邻域进行一个统计分析,计算它到所有临近点的平均距离。假设得到的结果是一个高斯分布,其形状是由均值和标准差决定,那么平均距离在标准范围(由全局距离平均值和方差定义)之外的点,可以被定义为离群点并从数据中去除。
代码展示
#include <iostream>
#include <pcl/point_types.h>
#include <pcl/point_cloud.h>
#include <pcl/io/pcd_io.h>
#include <pcl/visualization/pcl_visualizer.h>
#include <pcl/filters/statistical_outlier_removal.h>
using namespace std;
int main() {
pcl::PointCloud<pcl::PointXYZ>::Ptr cloud(new pcl::PointCloud<pcl::PointXYZ>);
pcl::PointCloud<pcl::PointXYZ>::Ptr cloud_filtered(new pcl::PointCloud<pcl::PointXYZ>);
//-------------------------------读取点云文件---------------------------------------------------
// 点云文件地址:https://github.com/PointCloudLibrary/data/blob/master/tutorials/table_scene_lms400.pcd
if (pcl::io::loadPCDFile("table_scene_lms400.pcd", *cloud) == -1)
{
cout << "COULD NOT READ FILE table_scene_lms400.pcd \n";
system("pause");
return (-1);
}
cout << "points size is:" << cloud->size() << endl;
// 定义滤波器
pcl::StatisticalOutlierRemoval<pcl::PointXYZ> sor;
sor.setInputCloud(cloud);
sor.setMeanK(50); //设置在进行统计时考虑查询点邻近点数
sor.setStddevMulThresh(1.0); //设置判断是否为离群点的阈值,如果一个点的距离超出平均距离一个标准差以上,则该点被标记为离群点,并将被移除。
sor.filter(*cloud_filtered);
//---------------------------------显示---------------------------------------------------------------------
pcl::visualization::PCLVisualizer viewer("3D viewer");
int v1(0);
viewer.createViewPort(0.0, 0.0, 0.5, 1.0, v1);//xmin, ymin, xmax, ymax,取值范围0-1
viewer.setBackgroundColor(0, 0, 0, v1);
pcl::visualization::PointCloudColorHandlerCustom<pcl::PointXYZ> green0(cloud, 0, 225, 0);
viewer.addPointCloud(cloud, green0, "cloud", v1);
int v2(0);
viewer.createViewPort(0.5, 0.0, 1.0, 1.0, v2);
viewer.setBackgroundColor(0.3, 0.3, 0.3, v2);
pcl::visualization::PointCloudColorHandlerCustom<pcl::PointXYZ> green1(cloud_filtered, 0, 225, 0);
viewer.addPointCloud(cloud_filtered, green1, "cloud_filtered", v2);
while (!viewer.wasStopped()) {
viewer.spinOnce(100);
}
system("pause");
return 0;
}
效果展示