plane_fitting_ransac.hpp
Go to the documentation of this file.
1#pragma once
2
3#include <pcl/ModelCoefficients.h>
4#include <pcl/sample_consensus/method_types.h>
5#include <pcl/sample_consensus/model_types.h>
6#include <pcl/segmentation/sac_segmentation.h>
7
9
10// This header exposes more includes, but also the function template.
11
12namespace visionx::tools
13{
14
15 template <typename PointT, typename IndicesPtrT = pcl::IndicesPtr>
16 std::optional<PlaneFittingResult>
17 fitPlaneRansac(typename pcl::PointCloud<PointT>::Ptr cloud,
18 double distanceThreshold = 1.0,
19 const IndicesPtrT& indices = nullptr)
20 {
21 // Reference: http://pointclouds.org/documentation/tutorials/planar_segmentation.php
22
23 pcl::ModelCoefficients::Ptr coefficients(new pcl::ModelCoefficients);
24 pcl::PointIndices::Ptr inliers(new pcl::PointIndices);
25
26 // Create the segmentation object
27 pcl::SACSegmentation<PointT> seg;
28
29 // Optional
30 seg.setOptimizeCoefficients(true);
31
32 // Mandatory
33 seg.setModelType(pcl::SACMODEL_PLANE);
34 seg.setMethodType(pcl::SAC_RANSAC);
35 seg.setDistanceThreshold(distanceThreshold);
36
37 seg.setInputCloud(cloud);
38 if (indices)
39 {
40 seg.setIndices(indices);
41 }
42 seg.segment(*inliers, *coefficients);
43
44 if (inliers->indices.empty())
45 {
46 return std::nullopt;
47 }
48
49 float a = coefficients->values.at(0);
50 float b = coefficients->values.at(1);
51 float c = coefficients->values.at(2);
52 float d = coefficients->values.at(3);
53 Eigen::Hyperplane3f plane(Eigen::Vector3f(a, b, c), d);
54
55 // Assure plane normal points updwards.
56 if (plane.normal().dot(Eigen::Vector3f::UnitZ()) < 0)
57 {
58 plane = Eigen::Hyperplane3f(-plane.normal(), -plane.offset());
59 }
60
61 return PlaneFittingResult{inliers, plane};
62 }
63
64} // namespace visionx::tools
constexpr T c
Hyperplane< float, 3 > Hyperplane3f
Definition Elements.h:34
std::optional< PlaneFittingResult > fitPlaneRansac(typename pcl::PointCloud< PointT >::Ptr cloud, double distanceThreshold=1.0, const IndicesPtrT &indices=nullptr)