Valentina-Zhang commited on
Commit
d82ae7a
·
verified ·
1 Parent(s): 71d1da5

Upload align_scannetpp.py

Browse files
Files changed (1) hide show
  1. align_scannetpp.py +227 -0
align_scannetpp.py ADDED
@@ -0,0 +1,227 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import open3d as o3d
2
+ import numpy as np
3
+ import os
4
+
5
+ def align_scene_to_z_up(pcd, save_pcd_path=None, save_transform_path=None, visualize=False, fit_ground=True):
6
+ """
7
+ 将点云扫描转换为Z轴向上对齐,并尝试将墙壁对齐到X-Y平面
8
+
9
+ 参数:
10
+ points (np.ndarray): (N, 3) 点云数据
11
+ visualize (bool): 是否可视化结果
12
+
13
+ 返回:
14
+ aligned_points (np.ndarray): 对齐后的点云
15
+ transform_matrix (np.ndarray): 应用的4x4变换矩阵
16
+ """
17
+ points = np.asarray(pcd.points)
18
+ centroid = np.mean(points, axis=0)
19
+ distance_threshold = 0.02 # 动态距离阈值
20
+ R_ground = np.eye(3) # Initialize ground rotation matrix
21
+ if fit_ground:
22
+ plane_model, ground_inliers = pcd.segment_plane(
23
+ distance_threshold=distance_threshold,
24
+ ransac_n=3,
25
+ num_iterations=1000
26
+ )
27
+ [a, b, c, d] = plane_model
28
+ ground_normal = np.array([a, b, c])
29
+ # print('ground_normal:', ground_normal)
30
+ # 可视化地面点云
31
+ ground_cloud = pcd.select_by_index(ground_inliers)
32
+ ground_cloud.paint_uniform_color([1, 0, 0]) # 红色表示地面
33
+ if visualize:
34
+ o3d.visualization.draw_geometries([ground_cloud])
35
+
36
+ # 3. 计算旋转矩阵使地面法向量对齐到Z轴
37
+ z_axis = np.array([0, 0, 1])
38
+ ground_normal = ground_normal / np.linalg.norm(ground_normal)
39
+
40
+ # 计算旋转轴和角度
41
+ rotation_axis = np.cross(ground_normal, z_axis)
42
+ if np.linalg.norm(rotation_axis) < 1e-6:
43
+ rotation_axis = np.array([0, 1, 0]) # 避免零向量
44
+ else:
45
+ rotation_axis = rotation_axis / np.linalg.norm(rotation_axis)
46
+
47
+ cos_theta = np.dot(ground_normal, z_axis)
48
+ angle = np.arccos(np.clip(cos_theta, -1.0, 1.0))
49
+
50
+ # 使用罗德里格斯公式计算旋转矩阵
51
+ K = np.array([
52
+ [0, -rotation_axis[2], rotation_axis[1]],
53
+ [rotation_axis[2], 0, -rotation_axis[0]],
54
+ [-rotation_axis[1], rotation_axis[0], 0]
55
+ ])
56
+ R_ground = np.eye(3) + np.sin(angle) * K + (1 - np.cos(angle)) * (K @ K)
57
+
58
+ # [Alternate] concise method
59
+ # from scipy.spatial.transform import Rotation as R
60
+ # R_ground = R.from_rotvec(rotation_axis * angle).as_matrix()
61
+
62
+ # 4. 应用地面旋转
63
+ centered_points = points - centroid
64
+ ground_rotated = (R_ground @ centered_points.T).T
65
+
66
+ # 5. 检测墙壁平面(垂直平面)
67
+ all_indices = np.arange(len(points))
68
+ non_ground_indices = np.setdiff1d(all_indices, ground_inliers)
69
+ non_ground_points = ground_rotated[non_ground_indices]
70
+
71
+ # 创建临时点云用于墙壁检测
72
+ temp_pcd = o3d.geometry.PointCloud()
73
+ temp_pcd.points = o3d.utility.Vector3dVector(non_ground_points)
74
+ remaining_pcd = temp_pcd
75
+ else:
76
+ # already z up
77
+ remaining_pcd = pcd
78
+
79
+ wall_planes = []
80
+ wall_directions = []
81
+ max_points = 0
82
+ best_direction = None
83
+ R_walls = np.eye(3)
84
+ # 检测多个墙壁平面
85
+ for _ in range(6):
86
+ if len(remaining_pcd.points) < 100:
87
+ break
88
+
89
+ plane_model, inliers = remaining_pcd.segment_plane(
90
+ distance_threshold=distance_threshold,
91
+ ransac_n=3,
92
+ num_iterations=1000
93
+ )
94
+
95
+ wall_cloud = remaining_pcd.select_by_index(inliers)
96
+ wall_cloud.paint_uniform_color([1, 0, 0]) # 红色表示地面
97
+ if visualize:
98
+ o3d.visualization.draw_geometries([wall_cloud])
99
+
100
+ [a, b, c, d] = plane_model
101
+ normal = np.array([a, b, c])
102
+
103
+ # 检查是否为垂直平面(法向量的Z分量接近0)
104
+ if abs(normal[2]) < 0.1 and np.linalg.norm(normal[:2]) > 0.5:
105
+ # 提取水平方向
106
+ horizontal_dir = normal[:2] / np.linalg.norm(normal[:2])
107
+ wall_directions = horizontal_dir
108
+ # print('wall direction',normal)
109
+ if max_points < len(inliers):
110
+ max_points = len(inliers)
111
+ # print(max_points)
112
+ best_direction = wall_directions
113
+ # 计算最佳方向的旋转角度
114
+ angle = np.arctan2(best_direction[1], best_direction[0])
115
+
116
+ # 创建最终的旋转矩阵
117
+ R_walls = np.array([
118
+ [np.cos(-angle), -np.sin(-angle), 0],
119
+ [np.sin(-angle), np.cos(-angle), 0],
120
+ [0, 0, 1]
121
+ ])
122
+
123
+ remaining_pcd = remaining_pcd.select_by_index(inliers, invert=True)
124
+
125
+
126
+ # 8. 创建变换矩阵(旋转 + 平移)
127
+ if fit_ground:
128
+ # Compose the transformations: first ground rotation, then wall rotation
129
+ combined_rotation = R_walls @ R_ground
130
+ transform_matrix = np.eye(4)
131
+ transform_matrix[:3, :3] = combined_rotation
132
+ transform_matrix[:3, 3] = -combined_rotation @ centroid
133
+ else:
134
+ # Only wall rotation
135
+ transform_matrix = np.eye(4)
136
+ transform_matrix[:3, :3] = R_walls
137
+ transform_matrix[:3, 3] = -R_walls @ centroid # 平移使中心到原点
138
+
139
+ # 9. 应用变换
140
+ aligned_points = (transform_matrix[:3, :3] @ points.T + transform_matrix[:3, 3:4]).T
141
+
142
+ # 10. 创建对齐后的点云
143
+ aligned_pcd = o3d.geometry.PointCloud()
144
+ aligned_pcd.points = o3d.utility.Vector3dVector(aligned_points)
145
+
146
+ if pcd.colors:
147
+ aligned_pcd.colors = pcd.colors
148
+
149
+ # 11. 保存结果
150
+ if save_pcd_path:
151
+ o3d.io.write_point_cloud(save_pcd_path, aligned_pcd)
152
+
153
+ if save_transform_path:
154
+ np.savetxt(save_transform_path, transform_matrix, fmt='%.8f')
155
+
156
+
157
+
158
+ return aligned_pcd, transform_matrix
159
+
160
+ """创建4x4变换矩阵"""
161
+ transform = np.eye(4)
162
+ transform[:3, :3] = rotation_matrix
163
+ return transform
164
+
165
+ def visualize_alignment(pcd_orig, pcd_aligned):
166
+ """可视化原始点云和对齐后的点云"""
167
+ pcd_orig.paint_uniform_color([1, 0, 0]) # 红色为原始点云
168
+ pcd_aligned.paint_uniform_color([0, 1, 0]) # 绿色为对齐后点云
169
+
170
+ # 创建坐标系
171
+ coord_frame = o3d.geometry.TriangleMesh.create_coordinate_frame(size=1.0)
172
+
173
+ o3d.visualization.draw_geometries([pcd_orig, pcd_aligned, coord_frame])
174
+
175
+
176
+
177
+ npy_dir = '/media/vivo/vivo/Datasets/ScanNetpp/ScanNetpp_preprocessed/train/'
178
+ scene_names = os.listdir(npy_dir)
179
+
180
+ for scene_name in scene_names:
181
+ if scene_name.endswith('.zip'):
182
+ continue
183
+
184
+ print(scene_name)
185
+
186
+ scene_dir = os.path.join(npy_dir, scene_name)
187
+
188
+ npy_path = os.path.join(scene_dir, 'coord.npy')
189
+ points = np.load(npy_path) # (N, 3) 或 (N, 6)
190
+
191
+ # 创建点云对象
192
+ pcd = o3d.geometry.PointCloud()
193
+ pcd.points = o3d.utility.Vector3dVector(points[:, :3])
194
+
195
+ if points.shape[1] == 6:
196
+ pcd.colors = o3d.utility.Vector3dVector(points[:, 3:6]) # 如果包含 RGB
197
+
198
+
199
+ # 执行对齐
200
+ transformed_pcd, transform = align_scene_to_z_up(
201
+ pcd,
202
+ # save_transform_path=os.path.join(scene_dir, "transform.txt"),
203
+ visualize=False,
204
+ fit_ground=False
205
+ )
206
+
207
+ aligned_points = np.asarray(transformed_pcd.points)
208
+
209
+ # scale point cloud
210
+ # min_z = np.min(aligned_points[:, 2])
211
+ # max_z = np.max(aligned_points[:, 2])
212
+ # height = max_z - min_z
213
+ # print(f"Original height: {height}")
214
+ # estimated_height = 2.5
215
+ # scale = estimated_height / height
216
+ # print(f"Scale factor: {scale}")
217
+
218
+ # aligned_points_scaled = aligned_points * scale
219
+
220
+ transformed_pcd.points = o3d.utility.Vector3dVector(aligned_points)
221
+
222
+ # 保存为对齐后的 PLY 文件
223
+ # aligned_ply_path = os.path.join(scene_dir, scene_name + ".ply")
224
+ # o3d.io.write_point_cloud(aligned_ply_path, transformed_pcd)
225
+
226
+ # 也可以保存为对齐后的 npy
227
+ np.save(os.path.join(scene_dir, "coord_align.npy"), aligned_points)