EuclideanClusterExtraction

std::vector<pcl::PointCloud<pcl::PointXYZ>> EuclideanClustering(const pcl::PointCloud<pcl::PointXYZ> &cloud,double cluster_tolerance = 0.1,int min_cluster_size = 100){
  std::vector<pcl::PointCloud<pcl::PointXYZ>> clusters;
	pcl::search::KdTree<pcl::PointXYZ>::Ptr tree (new pcl::search::KdTree<pcl::PointXYZ>);
	tree->setInputCloud(cloud.makeShared());
	std::vector<pcl::PointIndices> cluster_indices;//クラスタリング後のインデックスが格納されるベクトル
	pcl::EuclideanClusterExtraction<pcl::PointXYZ> ece;

	ece.setClusterTolerance(cluster_tolerance);//距離の閾値を設定
	ece.setMinClusterSize(min_cluster_size);//各クラスタのメンバの最小数を設定
	ece.setMaxClusterSize(cloud.points.size());//各クラスタのメンバの最大数を設定
	ece.setSearchMethod(tree);//探索方法設定
	ece.setInputCloud(cloud.makeShared());
	// クラスタリング
	ece.extract(cluster_indices);

	std::cout << "cluster_indices.size() = " << cluster_indices.size() << std::endl;

  //クラスタごとに分割
	pcl::ExtractIndices<pcl::PointXYZ> ei;
	ei.setInputCloud(cloud.makeShared());
	ei.setNegative(false);
	for(size_t i=0;i<cluster_indices.size();i++){
		//extract
		pcl::PointCloud<pcl::PointXYZ>::Ptr tmp_clustered_points (new pcl::PointCloud<pcl::PointXYZ>);
		pcl::PointIndices::Ptr tmp_clustered_indices (new pcl::PointIndices);
		*tmp_clustered_indices = cluster_indices[i];
		ei.setIndices(tmp_clustered_indices);
		ei.filter(*tmp_clustered_points);
		//input
		clusters.push_back(*tmp_clustered_points);
	}
  return clusters;
}

使い方


const double CLUSTER_TOLERANCE = 0.55;
const double MIN_CLUSTER_SIZE = 5;
std::vector<pcl::PointCloud<pcl::PointXYZ>> clusters=EuclideanClustering(cloud,CLUSTER_TOLERANCE,MIN_CLUSTER_SIZE);

参考サイト

【PCL,ROS】ユークリッドクラスタリング(EuclideanClusterExtraction) : LiLaBoC