Nalyd1002

segmentation

May 7th, 2023
30
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 5.46 KB | None | 0 0
  1. import open3d as o3d
  2. import open3d.core as o3c
  3. import numpy as np
  4. import matplotlib.pyplot as plt
  5. import pybullet as p
  6. import pybullet_data
  7. import time
  8.  
  9. from sklearn.neighbors import NearestNeighbors
  10. import plotly.express as px
  11.  
  12. # Initialize the physics simulation
  13. physicsClient = p.connect(p.GUI)
  14. p.setAdditionalSearchPath(pybullet_data.getDataPath())
  15. p.setGravity(0, 0, -9.81)
  16.  
  17. # Load the objects into the simulation
  18. planeId = p.loadURDF("plane.urdf")
  19. sphereId = p.loadURDF("sphere_small.urdf", [0, 1, 0.01])
  20. sphereId2 = p.loadURDF("sphere_small.urdf", [0.5, 1, 0.01])
  21. #robotId = p.loadURDF("r2d2.urdf", [0.5,0.5,0.5],useFixedBase=True)
  22. cubeId = p.loadURDF("cube_small.urdf", [0, 0.5, 0.01])
  23. cubeId2 = p.loadURDF("cube_small.urdf", [0, 0.9, 0.01])
  24.  
  25. while True:
  26. # Get the image from the camera
  27. camera_pos = [0, 1, 2]
  28. viewMatrix = p.computeViewMatrix(
  29. cameraEyePosition=camera_pos,
  30. cameraTargetPosition=[0, 1, 0],
  31. cameraUpVector=[0, 1, 0])
  32.  
  33. # Set the intrinsic parameters of the camera
  34. fov = 60
  35. aspect = 320.0 / 240.0
  36. near = 0.01
  37. far = 100
  38.  
  39. # Get the image from the camera
  40. width, height, rgbImg, depthImg, segImg = p.getCameraImage(width=320, height=240, viewMatrix=viewMatrix,
  41. projectionMatrix=p.computeProjectionMatrixFOV(fov,
  42. aspect,
  43. near, far))
  44. # Convert the depth image to a point cloud
  45. points = np.zeros((height * width, 3))
  46. for y in range(height):
  47. for x in range(width):
  48. depth = depthImg[y, x]
  49. if depth != 0:
  50. points[y * width + x, 0] = (x - 160) * depth / 160.0
  51. points[y * width + x, 1] = (y - 120) * depth / 120.0
  52. points[y * width + x, 2] = depth
  53.  
  54. # Create Open3D point cloud object
  55. pcd = o3d.geometry.PointCloud()
  56. pcd.points = o3d.utility.Vector3dVector(points)
  57.  
  58.  
  59. """# Compute the distance graph
  60. neigh = NearestNeighbors(n_neighbors=5)
  61. nbrs = neigh.fit(pcd.points)
  62. distances, indices = nbrs.kneighbors(pcd.points)
  63. distances = np.sort(distances, axis=0)
  64. distances = distances[:, 1]
  65.  
  66. # Plot the distance graph
  67. plt.plot(distances)
  68. plt.xlabel('Data point index')
  69. plt.ylabel('Distance to the nearest neighbor')
  70. plt.show()"""
  71. # Preprocess the data
  72. #pcd_filtered = pcd.voxel_down_sample(voxel_size=0.021)
  73.  
  74. # Apply segmentation algorithm
  75. labels = pcd.cluster_dbscan(eps=0.0103655, min_points=9)
  76.  
  77. # Assign random colors to each segment
  78. num_segments = len(set(labels))
  79. print("Number of segments")
  80. print(num_segments)
  81. colors = [[1, 0, 0], [0, 1, 0], [0, 0, 1], [1, 1, 0], [1, 0, 1], [0, 1, 1]]
  82. color_array = [colors[label % num_segments] for label in np.asarray(labels).flatten()]
  83. pcd.colors = o3d.utility.Vector3dVector(color_array)
  84. o3d.visualization.draw_geometries([pcd])
  85.  
  86.  
  87. """"# Segment the point cloud into different regions using ECE algorithm
  88. ece = pcd.cluster_dbscan(eps=1, min_points=5)
  89. max_label = np.max(ece)
  90. print('max label')
  91. print(max_label)
  92. for i in range(max_label + 1):
  93. indices = np.where(ece == i)[0]
  94. segment = pcd.select_by_index(indices)
  95. labels = np.array(segment.cluster_dbscan(eps=1, min_points=5))
  96. print("ok")
  97. print(f"Number of clusters in segment {i}: {len(set(labels))}")
  98. """
  99. """"# Assign random colors to each segment
  100. num_segments = len(set(labels))
  101. print("Number of segments")
  102. print(num_segments)
  103. colors = [[1, 0, 0], [0, 1, 0], [0, 0, 1], [1, 1, 0], [1, 0, 1], [0, 1, 1]]
  104. color_array = [colors[label % num_segments] for label in np.asarray(labels).flatten()]
  105. pcd_filtered.colors = o3d.utility.Vector3dVector(color_array)
  106. o3d.visualization.draw_geometries([pcd_filtered])"""
  107. # Assign random colors to each segment
  108. """num_segments = len(set(labels))
  109. print("num seg")
  110. print(num_segments)
  111. colors = [[1, 0, 0], [0, 1, 0], [0, 0, 1], [1, 1, 0], [1, 0, 1], [0, 1, 1]]
  112. color_array = [colors[label % num_segments] for label in np.asarray(labels).flatten()]
  113.  
  114. # Assign a random color to each point
  115. pcd_filtered.colors = o3d.utility.Vector3dVector(np.random.rand(len(points), 3))
  116. o3d.visualization.draw_geometries([pcd_filtered])"""
  117.  
  118. # Extract object positions and orientations
  119. """for label in set(labels):
  120. if label == -1:
  121. continue
  122. points = pcd.select_down_sample(np.where(labels == label)[0])
  123. centroid = np.mean(points.points, axis=0)
  124. print(f"Object {label}: position={centroid}, orientation={points.get_oriented_bounding_box().get_rotation_matrix()}")"""
  125.  
  126. # Extract object positions and orientations
  127. for label in set(labels):
  128. print("enter1")
  129. print(set(labels))
  130. if label == -1:
  131. print("enter2")
  132. continue
  133. print("enter3")
  134. #for i in range(len(points)):
  135. #print(points[i])
  136. points = pcd.points[labels == label]
  137. print('points')
  138. print(points)
  139. cluster_center = np.mean(points, axis=0)
  140. # Print centroid coordinates
  141. print(
  142. f"Object {label}: position={cluster_center}")
  143.  
  144.  
  145.  
Advertisement
Add Comment
Please, Sign In to add comment