@[TOC]PCL中点云分割模块的学习
学习背景
参考书籍:《点云库PCL从入门到精通》以及官方代码PCL官方代码链接,,PCL版本为1.10.0,CMake版本为3.16,可用点云下载地址
学习内容
如何使用已知系数的 SAC_Models 从点云中提取参数模型,例如平面或球面模型。
源代码及所用函数
源代码
#include <iostream>
#include <pcl/point_types.h>
#include <pcl/filters/model_outlier_removal.h>
int main ()
{
pcl::PointCloud<pcl::PointXYZ>::Ptr cloud (new pcl::PointCloud<pcl::PointXYZ>);
pcl::PointCloud<pcl::PointXYZ>::Ptr cloud_sphere_filtered (new pcl::PointCloud<pcl::PointXYZ>);
/*******************************************生成点云数据***************************************/
std::size_t noise_size = 5;
std::size_t sphere_data_size = 10;
cloud->width = noise_size + sphere_data_size;
cloud->height = 1;
cloud->points.resize (cloud->width * cloud->height);
// 增加噪音
for (std::size_t i = 0; i < noise_size; ++i)
{
(*cloud)[i].x = 1024 * rand () / (RAND_MAX + 1.0f);
(*cloud)[i].y = 1024 * rand () / (RAND_MAX + 1.0f);
(*cloud)[i].z = 1024 * rand () / (RAND_MAX + 1.0f);
}
// 增加球体
double rand_x1 = 1;
double rand_x2 = 1;
for (std::size_t i = noise_size; i < (noise_size + sphere_data_size); ++i)
{
while (pow (rand_x1, 2) + pow (rand_x2, 2) >= 1)
{
rand_x1 = (rand () % 100) / (50.0f) - 1;
rand_x2 = (rand () % 100) / (50.0f) - 1;
}
double pre_calc = sqrt (1 - pow (rand_x1, 2) - pow (rand_x2, 2));
(*cloud)[i].x = 2 * rand_x1 * pre_calc;
(*cloud)[i].y = 2 * rand_x2 * pre_calc;
(*cloud)[i].z = 1 - 2 * (pow (rand_x1, 2) + pow (rand_x2, 2));
rand_x1 = 1;
rand_x2 = 1;
}
std::cerr << "滤波前点云: " << std::endl;
for (const auto& point: *cloud)
std::cout << " " << point.x << " " << point.y << " " << point.z << std::endl;
/**********************************************过滤球************************************/
// 该球体的模型参数:
// position.x: 0, position.y: 0, position.z:0, radius: 1
pcl::ModelCoefficients sphere_coeff;
sphere_coeff.values.resize (4);
sphere_coeff.values[0] = 0;
sphere_coeff.values[1] = 0;
sphere_coeff.values[2] = 0;
sphere_coeff.values[3] = 1;
pcl::ModelOutlierRemoval<pcl::PointXYZ> sphere_filter;
sphere_filter.setModelCoefficients (sphere_coeff);
sphere_filter.setThreshold (0.05);
sphere_filter.setModelType (pcl::SACMODEL_SPHERE);
sphere_filter.setInputCloud (cloud);
sphere_filter.filter (*cloud_sphere_filtered);
std::cerr << "Sphere after filtering: " << std::endl;
for (const auto& point: *cloud_sphere_filtered)
std::cout << " " << point.x << " " << point.y << " " << point.z << std::endl;
return (0);
}
CMakeLists.txt
cmake_minimum_required(VERSION 3.16 FATAL_ERROR)#指定CMake的最低版本要求为3.16
project(project)#设置项目名称
find_package(PCL 1.10 REQUIRED)#查找PCL库,要求版本为1.10或更高。
include_directories(${PCL_INCLUDE_DIRS})#将PCL库的头文件目录添加到包含路径中
link_directories(${PCL_LIBRARY_DIRS})#将PCL库的库文件目录添加到链接器搜索路径中。
add_definitions(${PCL_DEFINITIONS})#添加PCL库的编译器定义
add_executable (model_outlier_removal model_outlier_removal.cpp)
target_link_libraries (model_outlier_removal ${PCL_LIBRARIES})#将PCL库链接到可执行文件目标。