Open3D将聚类结果显示或者保存

将聚类结果按大小排序,并取出最大的4个结果 

import time
import open3d as o3d;
import numpy as np;
import matplotlib.pyplot as plt

#坐标
mesh_coord_frame = o3d.geometry.TriangleMesh.create_coordinate_frame(size=355, origin=[0, 0, 0])
#mesh_coord_frame = mesh_coord_frame.translate((0.16, 0.15, 0)) 


#加载点云数据
ply = o3d.io.read_point_cloud("source/Foam1.ply") 

# downply = ply.voxel_down_sample(voxel_size=0.103)
# o3d.visualization.draw_geometries([ downply],window_name="downply") 

#去除无效部分
plane_model, inliers = ply.segment_plane(distance_threshold=1.6,
                                         ransac_n=3,
                                         num_iterations=1000)

[a, b, c, d] = plane_model
print(f"Plane equation: {a:.2f}x + {b:.2f}y + {c:.2f}z + {d:.2f} = 0")

inlier_cloud = ply.select_by_index(inliers) 

pcd = ply.select_by_index(inliers, invert=True) 
o3d.visualization.draw_geometries([ inlier_cloud],window_name="3D海绵点云无效数据") 
o3d.visualization.draw_geometries([ pcd],window_name="3D海绵点云有效数据") 
 
# 使用聚类算法
with o3d.utility.VerbosityContextManager(o3d.utility.VerbosityLevel.Debug) as cm:
    labels = np.array(pcd.cluster_dbscan(eps=3.3, min_points=1, print_progress=True))

print(labels)
# 求点云的聚类数量
max_label = labels.max()
print(f"point cloud has {max_label + 1} clusters")
# 可视化
colors = plt.get_cmap("tab20")(labels / (max_label if max_label > 0 else 1))
colors[labels < 0] = 0
pcd.colors = o3d.utility.Vector3dVector(colors[:, :3])
o3d.visualization.draw_geometries([ pcd,mesh_coord_frame],window_name="3D海绵聚类") 


# Get the unique labels
unique_labels = np.unique(labels)

# Create a dictionary to store the cluster sizes
cluster_sizes = {}
for label in unique_labels:
    cluster_sizes[label] = np.count_nonzero(labels == label)

# Sort the dictionary by cluster size 排序取出最大的四个聚类结果
sorted_cluster_sizes = dict(
    sorted(cluster_sizes.items(), key=lambda item: item[1], reverse=True)[:4]
)

# Save the clustering results for each cluster in sorted order
for label, size in sorted_cluster_sizes.items():
    cluster_pcd = pcd.select_by_index(np.where(labels == label)[0])
    o3d.visualization.draw_geometries([ cluster_pcd,mesh_coord_frame],window_name="3D海绵聚类结果{}".format(size)) 
    # o3d.io.write_point_cloud(
    #     "path/to/clustered_point_cloud_{}.pcd".format(label), cluster_pcd
    # )

    # # Save the clustering results for each cluster in a specific format
    # o3d.io.write_point_cloud_ply(
    #     "path/to/clustered_point_cloud_{}.ply".format(label), cluster_pcd
    # )


 


 



 
 

 
 

聚类结果

Open3D将聚类结果显示或者保存_第1张图片

最大的面积 结果

Open3D将聚类结果显示或者保存_第2张图片

第二大面积结果

Open3D将聚类结果显示或者保存_第3张图片

你可能感兴趣的:(机器视觉,#,Open3D,python,聚类,数据挖掘,机器学习)