赞
踩
- from sklearn.cluster import DBSCAN
- import matplotlib.pyplot as plt
- from matplotlib.patches import Rectangle
- import open3d as o3d
- import numpy as np
-
- # Reading data
- inputPath = r'E:\迅雷下载\kitti-velodyne-viewer-matlab-main\training\velodyne\000020.bin'
- num = np.fromfile(inputPath, dtype='float32', count=-1, sep='', offset=0)
- new = np.asarray(num).reshape(-1, 4)
-
- # Assigning data to different variables
- X = num[0::4]
- Y = num[1::4]
- Z = num[2::4]
- W = num[3::4]
-
- # Creating point cloud
- xyz = np.zeros((np.size(X), 3))
- xyz[:, 0] = X
- xyz[:, 1] = Y
- xyz[:, 2] = Z
- pc = o3d.geometry.PointCloud()
- pc.points = o3d.utility.Vector3dVector(xyz)
-
- # Downsampling
- downpcd = pc.voxel_down_sample(voxel_size=0.4) # Adjust voxel size
-
- # Segmentation
- plane_model, inliers = downpcd.segment_plane(distance_threshold=1, ransac_n=3, num_iterations=1000) # Adjust distance_threshold
- [a, b, c, d] = plane_model
- print(f"Plane equation: {a:.2f}x + {b:.2f}y + {c:.2f}z + {d:.2f} = 0")
- inlier_cloud = downpcd.select_by_index(inliers)
- outlier_cloud = downpcd.select_by_index(inliers, invert=True)
-
- # Clustering using DBSCAN
- clustering = DBSCAN(eps=2, min_samples=10).fit(np.asarray(outlier_cloud.points))
- labels = clustering.labels_
-
- max_label = labels.max()
- print(f"point cloud has {max_label + 1} clusters")
-
- # Visualization with bounding boxes
- fig = plt.figure()
- ax = fig.add_subplot(111)
-
- car_cluster_labels = []
- for cluster_label in range(max_label + 1):
- cluster_points = np.asarray(outlier_cloud.points)[labels == cluster_label]
- if len(cluster_points) > 0:
- min_x, min_y, min_z = np.min(cluster_points, axis=0)
- max_x, max_y, max_z = np.max(cluster_points, axis=0)
- width = max_x - min_x
- height = max_y - min_y
- depth = max_z - min_z
-
- volume = width * height * depth
- # Assume a car's volume is between 2 and 10 m^3 and z range between -1.5 and -0.5
- if 2 < volume < 10 and -1.5 < min_z < -0.5:
- car_cluster_labels.append(cluster_label)
- rect = Rectangle((min_x, min_y), width, height, linewidth=1, edgecolor='r', facecolor='none')
- ax.add_patch(rect)
- ax.text(min_x + width / 2, min_y + height / 2, 'car', color='blue', ha='center', va='center')
- # Plot points with different colors for each cluster
- ax.scatter(cluster_points[:, 0], cluster_points[:, 1], s=5, label=f"Cluster {cluster_label} - Car" if cluster_label in car_cluster_labels else f"Cluster {cluster_label}")
- print(f"Found {len(car_cluster_labels)} car clusters")
- # Show the legend to differentiate clusters
- ax.legend()
- # Show the 2D plot with bounding boxes
- ax.set_aspect('equal', adjustable='box')
- plt.show()
- # Show the 3D point cloud with bounding boxes
- o3d.visualization.draw_geometries([outlier_cloud])

Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。