PCL庫學習(7)_關於如何給聚類得到的點雲上顏色(以歐式聚類爲例)

直接上代碼:

        pcl::PointCloud<pcl::PointXYZ>::Ptr add_cloud(new pcl::PointCloud<pcl::PointXYZ>);
pcl::search::KdTree<pcl::PointXYZ>::Ptr tree(new pcl::search::KdTree<pcl::PointXYZ>);//建立樹結構
tree->setInputCloud(cloud);
std::vector<pcl::PointIndices> cluster_indices;//被分割出來的點雲團,(標號隊列)
pcl::EuclideanClusterExtraction<pcl::PointXYZ> ec;//創建歐式聚類對象
ec.setClusterTolerance(ui.lineEdit_ClusterTolerance->text().toDouble());//設置近鄰搜索的搜索半徑(單位爲m)
ec.setMinClusterSize(ui.lineEdit_ClusterMinsize->text().toInt());//設置一個聚類需要的最小點數目
ec.setMaxClusterSize(ui.lineEdit_ClusterMaxsize->text().toInt());//設置一個聚類需要的最大點數目
ec.setSearchMethod(tree);//設置點雲搜索機制
ec.setInputCloud(cloud);
ec.extract(cluster_indices);//從點雲中提取聚類,並將點雲團保存在cluster_indices中
//迭代訪問點雲索引cluster_indices,直至分割出所有聚類
typedef std::vector<pcl::PointCloud<pcl::PointXYZ>::Ptr>  cloudptrlist;//所有類別點雲的向量
cloudptrlist ptrlist;
int j = 0;//定義變量j用於存儲點雲聚類名稱
for (std::vector<pcl::PointIndices>::const_iterator it = cluster_indices.begin(); it != cluster_indices.end(); it++)
{
pcl::PointCloud<pcl::PointXYZ>::Ptr cloud_cluster(new pcl::PointCloud<pcl::PointXYZ>);//存放當前的點雲聚類
for (std::vector<int>::const_iterator pit = it->indices.begin(); pit != it->indices.end(); pit++)
{
cloud_cluster->points.push_back(cloud->points[*pit]);//將當前點雲聚類中的點雲索引存放到cloud_cluster中
}
cloud_cluster->width = cloud_cluster->points.size();
cloud_cluster->height = 1;
cloud_cluster->is_dense = true;
//保存點雲文件
std::stringstream ss;
ss << "cloud_cluster_D" << j << ".pcd";//保存每一個聚類
pcl::PCDWriter writer;
writer.write<pcl::PointXYZ>(ss.str(), *cloud_cluster, false);
ptrlist.push_back(cloud_cluster);//關鍵的一句,所有的點雲聚類都放到數組向量中去
j++;
}
//隨機上色,注意區分點雲的ID
for (int i = 0; i < ptrlist.size(); i++)
{
double r = 256 * rand() / (RAND_MAX + 1.0f);
double g = 256 * rand() / (RAND_MAX + 1.0f);
double b = 256 * rand() / (RAND_MAX + 1.0f);
pcl::visualization::PointCloudColorHandlerCustom<pcl::PointXYZ> ::Ptr handler_tempt(new pcl::visualization::PointCloudColorHandlerCustom<pcl::PointXYZ>(r, g, b));
handler_tempt->setInputCloud(ptrlist[i]);
std::ostringstream oss;
oss << i;//不同的點雲,賦予不同的ID
viewer->addPointCloud(ptrlist[i], *handler_tempt, "cluster" + oss.str());
viewer->setPointCloudRenderingProperties(pcl::visualization::PCL_VISUALIZER_POINT_SIZE, 2, "cluster" + oss.str());
}


 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章