SlekLi commited on
Commit
b22263c
·
verified ·
1 Parent(s): e6ab4cc

Upload try_merge.py

Browse files
Files changed (1) hide show
  1. try_merge.py +826 -0
try_merge.py ADDED
@@ -0,0 +1,826 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import numpy as np
2
+ import torch
3
+ from sklearn.cluster import AgglomerativeClustering
4
+ from plyfile import PlyData, PlyElement
5
+ import os
6
+ from pathlib import Path
7
+
8
+ # 评估指标库
9
+ from skimage.metrics import structural_similarity as ssim
10
+ from skimage.metrics import peak_signal_noise_ratio as psnr
11
+ import lpips
12
+ import cv2
13
+
14
+ class GaussianMerger:
15
+ """
16
+ 3DGS聚类Merge实现
17
+ 核心思路:
18
+ 1. 空间划分为带padding的cells
19
+ 2. 在每个cell内使用AgglomerativeClustering聚类
20
+ 3. 使用矩匹配合并高斯参数
21
+ 4. 只保留中心在no-padding区域的簇
22
+ """
23
+ def __init__(self, cell_size, padding_ratio=0.1, target_points_per_cluster=3):
24
+ """
25
+ Args:
26
+ cell_size: float, cell边长
27
+ padding_ratio: float, padding占边长的比例
28
+ target_points_per_cluster: int, 目标每簇点数(2-4)
29
+ """
30
+ self.cell_size = cell_size
31
+ self.padding_ratio = padding_ratio
32
+ self.padding_size = cell_size * padding_ratio
33
+ self.target_points_per_cluster = target_points_per_cluster
34
+
35
+ # 聚类特征权重
36
+ # 归一化位置(3维) + 不透明度(1维) + SH(48维,RGB三阶)
37
+ self.feature_weights = {
38
+ 'position': 1.0, # 空间位置权重
39
+ 'opacity': 1.0, # 不透明度权重
40
+ 'sh': 0.2, # SH系数权重(颜色特征)
41
+ }
42
+
43
+ def load_ply(self, ply_path):
44
+ """
45
+ 加载3DGS的.ply文件
46
+
47
+ 3DGS数据格式:
48
+ - xyz: 3个坐标
49
+ - opacity: 1个不透明度
50
+ - f_dc_0/1/2: DC分量(3维)
51
+ - f_rest_0~44: SH系数(45维,对应RGB各15个三阶SH系数)
52
+ - scale_0/1/2: 3个尺度
53
+ - rot_0/1/2/3: 四元数旋转(4维)
54
+
55
+ Returns:
56
+ dict: {
57
+ 'xyz': (N,3),
58
+ 'opacity': (N,1),
59
+ 'dc': (N,3), DC颜色分量
60
+ 'sh': (N,45), SH系数
61
+ 'scale': (N,3),
62
+ 'rotation': (N,4) 四元数 [w,x,y,z]
63
+ }
64
+ """
65
+ print(f"Loading 3DGS from {ply_path}...")
66
+ plydata = PlyData.read(ply_path)
67
+ vertices = plydata['vertex']
68
+
69
+ # 提取xyz坐标
70
+ xyz = np.stack([vertices['x'], vertices['y'], vertices['z']], axis=1)
71
+
72
+ # 提取不透明度
73
+ opacity = vertices['opacity'][:, np.newaxis]
74
+
75
+ # 提取DC分量
76
+ dc = np.stack([vertices['f_dc_0'], vertices['f_dc_1'], vertices['f_dc_2']], axis=1)
77
+
78
+ # 提取SH系数 (RGB三阶共45维)
79
+ sh_features = []
80
+ for i in range(45):
81
+ sh_features.append(vertices[f'f_rest_{i}'])
82
+ sh = np.stack(sh_features, axis=1)
83
+
84
+ # 提取scale
85
+ scale = np.stack([vertices['scale_0'], vertices['scale_1'], vertices['scale_2']], axis=1)
86
+
87
+ # 提取rotation (四元数)
88
+ rotation = np.stack([vertices['rot_0'], vertices['rot_1'],
89
+ vertices['rot_2'], vertices['rot_3']], axis=1)
90
+
91
+ print(f"Loaded {len(xyz)} Gaussians")
92
+ print(f"Scene bounds: {xyz.min(axis=0)} to {xyz.max(axis=0)}")
93
+
94
+ return {
95
+ 'xyz': xyz,
96
+ 'opacity': opacity,
97
+ 'dc': dc,
98
+ 'sh': sh,
99
+ 'scale': scale,
100
+ 'rotation': rotation
101
+ }
102
+
103
+ def save_ply(self, gaussians, output_path):
104
+ """
105
+ 保存merge后的高斯到.ply文件
106
+
107
+ Args:
108
+ gaussians: dict, merge后的高斯参数
109
+ output_path: str, 输出路径
110
+ """
111
+ print(f"Saving merged 3DGS to {output_path}...")
112
+
113
+ xyz = gaussians['xyz']
114
+ opacity = gaussians['opacity'].flatten()
115
+ dc = gaussians['dc']
116
+ sh = gaussians['sh']
117
+ scale = gaussians['scale']
118
+ rotation = gaussians['rotation']
119
+
120
+ n_points = len(xyz)
121
+
122
+ # 构建dtype
123
+ dtype_list = [
124
+ ('x', 'f4'), ('y', 'f4'), ('z', 'f4'),
125
+ ('opacity', 'f4'),
126
+ ('f_dc_0', 'f4'), ('f_dc_1', 'f4'), ('f_dc_2', 'f4'),
127
+ ]
128
+
129
+ # 添加SH系数
130
+ for i in range(45):
131
+ dtype_list.append((f'f_rest_{i}', 'f4'))
132
+
133
+ # 添加scale和rotation
134
+ dtype_list.extend([
135
+ ('scale_0', 'f4'), ('scale_1', 'f4'), ('scale_2', 'f4'),
136
+ ('rot_0', 'f4'), ('rot_1', 'f4'), ('rot_2', 'f4'), ('rot_3', 'f4')
137
+ ])
138
+
139
+ # 创建结构化数组
140
+ elements = np.empty(n_points, dtype=dtype_list)
141
+
142
+ # 填充数据
143
+ elements['x'] = xyz[:, 0]
144
+ elements['y'] = xyz[:, 1]
145
+ elements['z'] = xyz[:, 2]
146
+ elements['opacity'] = opacity
147
+ elements['f_dc_0'] = dc[:, 0]
148
+ elements['f_dc_1'] = dc[:, 1]
149
+ elements['f_dc_2'] = dc[:, 2]
150
+
151
+ for i in range(45):
152
+ elements[f'f_rest_{i}'] = sh[:, i]
153
+
154
+ elements['scale_0'] = scale[:, 0]
155
+ elements['scale_1'] = scale[:, 1]
156
+ elements['scale_2'] = scale[:, 2]
157
+ elements['rot_0'] = rotation[:, 0]
158
+ elements['rot_1'] = rotation[:, 1]
159
+ elements['rot_2'] = rotation[:, 2]
160
+ elements['rot_3'] = rotation[:, 3]
161
+
162
+ # 创建PlyElement
163
+ el = PlyElement.describe(elements, 'vertex')
164
+
165
+ # 写入文件
166
+ PlyData([el]).write(output_path)
167
+ print(f"Saved {n_points} merged Gaussians")
168
+
169
+ def partition_space(self, xyz):
170
+ """
171
+ 空间划分: 将场景划分为cell网格
172
+
173
+ 策略:
174
+ - 每个cell有padding区域用于聚类
175
+ - 但只保留中心在no-padding区域的簇
176
+
177
+ Args:
178
+ xyz: (N, 3) 点的位置
179
+ Returns:
180
+ cell_dict: {cell_id: [point_indices]} cell内的点索引(含padding)
181
+ cell_info: {cell_id: {'center', 'bounds_no_padding', 'bounds_with_padding'}}
182
+ """
183
+ print("Partitioning space into cells...")
184
+
185
+ # 计算场景边界(稍微扩大一点避免边界问题)
186
+ min_bound = xyz.min(axis=0) - self.padding_size
187
+ max_bound = xyz.max(axis=0) + self.padding_size
188
+
189
+ # 计算每个点所属的cell(基于no-padding边界)
190
+ cell_indices = np.floor((xyz - min_bound) / self.cell_size).astype(int)
191
+
192
+ # 获取所有唯一的cell
193
+ unique_cells = np.unique(cell_indices, axis=0)
194
+
195
+ cell_dict = {}
196
+ cell_info = {}
197
+
198
+ for cell_idx in unique_cells:
199
+ cell_id = tuple(cell_idx)
200
+
201
+ # Cell的no-padding边界
202
+ cell_min = min_bound + cell_idx * self.cell_size
203
+ cell_max = cell_min + self.cell_size
204
+
205
+ # Cell的with-padding边界
206
+ cell_min_padded = cell_min - self.padding_size
207
+ cell_max_padded = cell_max + self.padding_size
208
+
209
+ # 找到所有在padding范围内的点
210
+ mask = np.all((xyz >= cell_min_padded) & (xyz < cell_max_padded), axis=1)
211
+ point_indices = np.where(mask)[0]
212
+
213
+ if len(point_indices) > 0:
214
+ cell_dict[cell_id] = point_indices
215
+ cell_info[cell_id] = {
216
+ 'center': (cell_min + cell_max) / 2,
217
+ 'bounds_no_padding': (cell_min, cell_max),
218
+ 'bounds_with_padding': (cell_min_padded, cell_max_padded)
219
+ }
220
+
221
+ print(f"Created {len(cell_dict)} cells")
222
+ points_per_cell = [len(indices) for indices in cell_dict.values()]
223
+ print(f"Points per cell: min={min(points_per_cell)}, max={max(points_per_cell)}, avg={np.mean(points_per_cell):.1f}")
224
+
225
+ return cell_dict, cell_info
226
+
227
+ def compute_features_for_clustering(self, gaussians, point_indices, cell_bounds):
228
+ """
229
+ 计算聚类特征: 归一化位置(3) + 不透明度(1) + SH系数(48)
230
+
231
+ 注意:
232
+ - 位置需要在padding后的cell内归一化
233
+ - SH系数包含DC(3维)和高阶(45维),共48维
234
+ - 不同特征使用不同权重
235
+
236
+ Args:
237
+ gaussians: 完整的高斯数据
238
+ point_indices: 当前cell内的点索引
239
+ cell_bounds: (min_xyz, max_xyz) with padding
240
+ Returns:
241
+ features: (N, 52) 归一化后的特征向量
242
+ """
243
+ xyz = gaussians['xyz'][point_indices]
244
+ opacity = gaussians['opacity'][point_indices]
245
+ dc = gaussians['dc'][point_indices]
246
+ sh = gaussians['sh'][point_indices]
247
+
248
+ cell_min, cell_max = cell_bounds
249
+ cell_size_padded = cell_max - cell_min
250
+
251
+ # 归一化位置: (xyz - cell_min) / padded_cell_size
252
+ normalized_pos = (xyz - cell_min) / cell_size_padded
253
+
254
+ # 组合SH特征: DC + 高阶SH
255
+ sh_features = np.concatenate([dc, sh], axis=1) # (N, 48)
256
+
257
+ # 组合所有特征并加权
258
+ features = np.concatenate([
259
+ normalized_pos * self.feature_weights['position'], # (N, 3)
260
+ opacity * self.feature_weights['opacity'], # (N, 1)
261
+ sh_features * self.feature_weights['sh'] # (N, 48)
262
+ ], axis=1)
263
+
264
+ return features
265
+
266
+ def quaternion_to_rotation_matrix(self, q):
267
+ """
268
+ 四元数转旋转矩阵
269
+
270
+ Args:
271
+ q: (4,) [w, x, y, z] 或 (N, 4)
272
+ Returns:
273
+ R: (3, 3) 或 (N, 3, 3)
274
+ """
275
+ if q.ndim == 1:
276
+ w, x, y, z = q
277
+ R = np.array([
278
+ [1-2*(y**2+z**2), 2*(x*y-w*z), 2*(x*z+w*y)],
279
+ [2*(x*y+w*z), 1-2*(x**2+z**2), 2*(y*z-w*x)],
280
+ [2*(x*z-w*y), 2*(y*z+w*x), 1-2*(x**2+y**2)]
281
+ ])
282
+ return R
283
+ else:
284
+ # 批量处理
285
+ w, x, y, z = q[:, 0], q[:, 1], q[:, 2], q[:, 3]
286
+ R = np.zeros((len(q), 3, 3))
287
+ R[:, 0, 0] = 1 - 2*(y**2 + z**2)
288
+ R[:, 0, 1] = 2*(x*y - w*z)
289
+ R[:, 0, 2] = 2*(x*z + w*y)
290
+ R[:, 1, 0] = 2*(x*y + w*z)
291
+ R[:, 1, 1] = 1 - 2*(x**2 + z**2)
292
+ R[:, 1, 2] = 2*(y*z - w*x)
293
+ R[:, 2, 0] = 2*(x*z - w*y)
294
+ R[:, 2, 1] = 2*(y*z + w*x)
295
+ R[:, 2, 2] = 1 - 2*(x**2 + y**2)
296
+ return R
297
+
298
+ def compute_covariance(self, scale, rotation):
299
+ """
300
+ 计算协方差矩阵: Σ = R·S·S^T·R^T
301
+
302
+ Args:
303
+ scale: (N, 3) 三个轴的尺度
304
+ rotation: (N, 4) 四元数 [w,x,y,z]
305
+ Returns:
306
+ covariances: (N, 3, 3)
307
+ """
308
+ N = len(scale)
309
+ R = self.quaternion_to_rotation_matrix(rotation) # (N, 3, 3)
310
+
311
+ # S 是对角矩阵
312
+ S = np.zeros((N, 3, 3))
313
+ S[:, 0, 0] = scale[:, 0]
314
+ S[:, 1, 1] = scale[:, 1]
315
+ S[:, 2, 2] = scale[:, 2]
316
+
317
+ # Σ = R·S·S^T·R^T
318
+ covariances = np.einsum('nij,njk,nlk,nli->nil', R, S, S, R)
319
+
320
+ return covariances
321
+
322
+ def moment_matching(self, means, covariances, opacities, scales):
323
+ """
324
+ 矩匹配: 合并多个高斯分布
325
+
326
+ 公式:
327
+ - 权重: wi = opacity_i * volume_i
328
+ - 新均值: μ_new = Σ(wi * μi) / Σwi
329
+ - 新协方差: Σ_new = Σ(wi * (Σi + (μi-μ_new)(μi-μ_new)^T)) / Σwi
330
+ - 新不透明度: 质量守恒,Σ(opacity_i * volume_i) = opacity_new * volume_new
331
+
332
+ Args:
333
+ means: (K, 3) 各高斯均值
334
+ covariances: (K, 3, 3) 各高斯协方差矩阵
335
+ opacities: (K, 1) 不透明度
336
+ scales: (K, 3) 尺度
337
+ Returns:
338
+ new_mean: (3,)
339
+ new_covariance: (3, 3)
340
+ new_opacity: float
341
+ new_scale: (3,)
342
+ new_rotation: (4,) 四元数
343
+ """
344
+ # 计算权重 wi = opacity * scale_volume
345
+ scale_volumes = np.prod(scales, axis=1, keepdims=True) # (K, 1)
346
+ weights = opacities * scale_volumes # (K, 1)
347
+ total_weight = weights.sum()
348
+ weights_normalized = weights / total_weight # 归一化用于计算均值和协方差
349
+
350
+ # 计算加权均值
351
+ new_mean = np.sum(weights_normalized * means, axis=0) # (3,)
352
+
353
+ # 计算混合协方差
354
+ mean_diff = means - new_mean # (K, 3)
355
+ outer_products = np.einsum('ki,kj->kij', mean_diff, mean_diff) # (K, 3, 3)
356
+
357
+ new_covariance = np.sum(
358
+ weights_normalized[:, :, np.newaxis] * (covariances + outer_products),
359
+ axis=0
360
+ ) # (3, 3)
361
+
362
+ # 从协方差矩阵分解得到scale和rotation
363
+ # 特征值分解: Σ = V·Λ·V^T,其中V是旋转矩阵,Λ是特征值对角阵
364
+ eigenvalues, eigenvectors = np.linalg.eigh(new_covariance)
365
+
366
+ # scale = sqrt(eigenvalues)
367
+ new_scale = np.sqrt(np.abs(eigenvalues))
368
+ new_scale_volume = np.prod(new_scale)
369
+
370
+ # 质量守恒: Σ(opacity_i * volume_i) = opacity_new * volume_new
371
+ # opacity_new = Σ(opacity_i * volume_i) / volume_new
372
+ if new_scale_volume > 1e-10:
373
+ new_opacity = total_weight / new_scale_volume
374
+ new_opacity = np.clip(new_opacity, 0, 1) # 限制在[0,1]
375
+ else:
376
+ new_opacity = np.mean(opacities) # fallback
377
+
378
+ # rotation matrix = eigenvectors
379
+ R_new = eigenvectors
380
+
381
+ # 旋转矩阵转四元数
382
+ new_rotation = self.rotation_matrix_to_quaternion(R_new)
383
+
384
+ return new_mean, new_covariance, new_opacity, new_scale, new_rotation
385
+
386
+ def rotation_matrix_to_quaternion(self, R):
387
+ """
388
+ 旋转矩阵转四元数 [w, x, y, z]
389
+ 使用Shepperd方法,数值稳定
390
+ """
391
+ trace = np.trace(R)
392
+
393
+ if trace > 0:
394
+ s = 0.5 / np.sqrt(trace + 1.0)
395
+ w = 0.25 / s
396
+ x = (R[2, 1] - R[1, 2]) * s
397
+ y = (R[0, 2] - R[2, 0]) * s
398
+ z = (R[1, 0] - R[0, 1]) * s
399
+ elif R[0, 0] > R[1, 1] and R[0, 0] > R[2, 2]:
400
+ s = 2.0 * np.sqrt(1.0 + R[0, 0] - R[1, 1] - R[2, 2])
401
+ w = (R[2, 1] - R[1, 2]) / s
402
+ x = 0.25 * s
403
+ y = (R[0, 1] + R[1, 0]) / s
404
+ z = (R[0, 2] + R[2, 0]) / s
405
+ elif R[1, 1] > R[2, 2]:
406
+ s = 2.0 * np.sqrt(1.0 + R[1, 1] - R[0, 0] - R[2, 2])
407
+ w = (R[0, 2] - R[2, 0]) / s
408
+ x = (R[0, 1] + R[1, 0]) / s
409
+ y = 0.25 * s
410
+ z = (R[1, 2] + R[2, 1]) / s
411
+ else:
412
+ s = 2.0 * np.sqrt(1.0 + R[2, 2] - R[0, 0] - R[1, 1])
413
+ w = (R[1, 0] - R[0, 1]) / s
414
+ x = (R[0, 2] + R[2, 0]) / s
415
+ y = (R[1, 2] + R[2, 1]) / s
416
+ z = 0.25 * s
417
+
418
+ q = np.array([w, x, y, z])
419
+ q = q / np.linalg.norm(q) # 归一化
420
+ return q
421
+
422
+ def cluster_and_merge_cell(self, gaussians, point_indices, cell_info):
423
+ """
424
+ 在单个cell内进行聚类和merge
425
+
426
+ 流程:
427
+ 1. 提取padding区域内的所有点
428
+ 2. 计算聚类特征(归一化位置+不透明度+SH)
429
+ 3. 使用AgglomerativeClustering聚类
430
+ 4. 对每个簇使用矩匹配合并
431
+ 5. 只保留中心在no-padding区域的簇
432
+
433
+ Args:
434
+ gaussians: 完整的高斯数据dict
435
+ point_indices: 当前cell内的点索引 (包含padding区域)
436
+ cell_info: cell的边界信息
437
+ Returns:
438
+ merged_gaussians: dict, merge后的高斯参数
439
+ """
440
+ if len(point_indices) == 0:
441
+ return None
442
+
443
+ # 提取cell内的数据
444
+ xyz = gaussians['xyz'][point_indices]
445
+
446
+ # 计算聚类特征
447
+ cell_bounds = cell_info['bounds_with_padding']
448
+ features = self.compute_features_for_clustering(gaussians, point_indices, cell_bounds)
449
+
450
+ # 计算聚类数量: n_clusters = n_points // target_points_per_cluster
451
+ n_clusters = max(1, len(point_indices) // self.target_points_per_cluster)
452
+
453
+ # AgglomerativeClustering
454
+ clustering = AgglomerativeClustering(
455
+ n_clusters=n_clusters,
456
+ metric='euclidean',
457
+ linkage='ward'
458
+ )
459
+ labels = clustering.fit_predict(features)
460
+
461
+ # 对每个簇进行merge
462
+ merged_results = {
463
+ 'xyz': [],
464
+ 'opacity': [],
465
+ 'dc': [],
466
+ 'sh': [],
467
+ 'scale': [],
468
+ 'rotation': []
469
+ }
470
+
471
+ no_padding_min, no_padding_max = cell_info['bounds_no_padding']
472
+
473
+ for cluster_id in range(n_clusters):
474
+ cluster_mask = labels == cluster_id
475
+ cluster_point_indices = point_indices[cluster_mask]
476
+
477
+ if len(cluster_point_indices) == 0:
478
+ continue
479
+
480
+ # 提取簇内数据
481
+ cluster_xyz = gaussians['xyz'][cluster_point_indices]
482
+ cluster_opacity = gaussians['opacity'][cluster_point_indices]
483
+ cluster_dc = gaussians['dc'][cluster_point_indices]
484
+ cluster_sh = gaussians['sh'][cluster_point_indices]
485
+ cluster_scale = gaussians['scale'][cluster_point_indices]
486
+ cluster_rotation = gaussians['rotation'][cluster_point_indices]
487
+
488
+ # 计算协方差矩阵
489
+ cluster_covariances = self.compute_covariance(cluster_scale, cluster_rotation)
490
+
491
+ # 矩匹配合并位置和协方差
492
+ new_mean, new_cov, new_opacity, new_scale, new_rotation = self.moment_matching(
493
+ cluster_xyz, cluster_covariances, cluster_opacity, cluster_scale
494
+ )
495
+
496
+ # 只保留中心在no-padding区域的簇
497
+ if np.all(new_mean >= no_padding_min) and np.all(new_mean < no_padding_max):
498
+ # DC和SH使用加权平均
499
+ scale_volumes = np.prod(cluster_scale, axis=1, keepdims=True)
500
+ weights = cluster_opacity * scale_volumes
501
+ weights = weights / weights.sum()
502
+
503
+ new_dc = np.sum(weights * cluster_dc, axis=0)
504
+ new_sh = np.sum(weights * cluster_sh, axis=0)
505
+
506
+ # 添加到结果
507
+ merged_results['xyz'].append(new_mean)
508
+ merged_results['opacity'].append([new_opacity])
509
+ merged_results['dc'].append(new_dc)
510
+ merged_results['sh'].append(new_sh)
511
+ merged_results['scale'].append(new_scale)
512
+ merged_results['rotation'].append(new_rotation)
513
+
514
+ # 转换为numpy数组
515
+ if len(merged_results['xyz']) == 0:
516
+ return None
517
+
518
+ for key in merged_results:
519
+ merged_results[key] = np.array(merged_results[key])
520
+
521
+ return merged_results
522
+
523
+ def merge_all(self, gaussians):
524
+ """
525
+ 对所有cell进行聚类merge
526
+
527
+ Args:
528
+ gaussians: 原始高斯数据
529
+ Returns:
530
+ merged_gaussians: merge后的高斯数据
531
+ """
532
+ # 空间划分
533
+ cell_dict, cell_info = self.partition_space(gaussians['xyz'])
534
+
535
+ # 对每个cell进行处理
536
+ all_merged = {
537
+ 'xyz': [],
538
+ 'opacity': [],
539
+ 'dc': [],
540
+ 'sh': [],
541
+ 'scale': [],
542
+ 'rotation': []
543
+ }
544
+
545
+ total_cells = len(cell_dict)
546
+ for idx, (cell_id, point_indices) in enumerate(cell_dict.items()):
547
+ if (idx + 1) % 100 == 0:
548
+ print(f"Processing cell {idx+1}/{total_cells}...")
549
+
550
+ merged = self.cluster_and_merge_cell(gaussians, point_indices, cell_info[cell_id])
551
+
552
+ if merged is not None:
553
+ for key in all_merged:
554
+ all_merged[key].append(merged[key])
555
+
556
+ # 合并所有cell的结果
557
+ final_merged = {}
558
+ for key in all_merged:
559
+ final_merged[key] = np.concatenate(all_merged[key], axis=0)
560
+
561
+ print(f"\nMerge Statistics:")
562
+ print(f" Original points: {len(gaussians['xyz'])}")
563
+ print(f" Merged points: {len(final_merged['xyz'])}")
564
+ print(f" Compression ratio: {len(gaussians['xyz']) / len(final_merged['xyz']):.2f}x")
565
+
566
+ return final_merged
567
+
568
+
569
+ class ImageEvaluator:
570
+ """
571
+ 图像质量评估
572
+ 支持: PSNR, SSIM, LPIPS, NIQE, FID, MEt3R
573
+ """
574
+ def __init__(self, device='cuda' if torch.cuda.is_available() else 'cpu'):
575
+ self.device = device
576
+
577
+ # 初始化LPIPS模型
578
+ self.lpips_model = lpips.LPIPS(net='alex').to(device)
579
+
580
+ def load_image(self, image_path):
581
+ """
582
+ 加载图像,支持jpg和png
583
+ Returns:
584
+ img: (H, W, 3) numpy array, range [0, 1]
585
+ """
586
+ img = cv2.imread(image_path)
587
+ img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)
588
+ img = img.astype(np.float32) / 255.0
589
+ return img
590
+
591
+ def compute_psnr(self, img1, img2):
592
+ """
593
+ 计算PSNR
594
+ """
595
+ return psnr(img1, img2, data_range=1.0)
596
+
597
+ def compute_ssim(self, img1, img2):
598
+ """
599
+ 计算SSIM
600
+ """
601
+ return ssim(img1, img2, multichannel=True, data_range=1.0, channel_axis=2)
602
+
603
+ def compute_lpips(self, img1, img2):
604
+ """
605
+ 计算LPIPS (需要转换为tensor)
606
+ """
607
+ # 转换为tensor: (H,W,3) -> (1,3,H,W)
608
+ img1_t = torch.from_numpy(img1).permute(2, 0, 1).unsqueeze(0).to(self.device)
609
+ img2_t = torch.from_numpy(img2).permute(2, 0, 1).unsqueeze(0).to(self.device)
610
+
611
+ # LPIPS期望输入范围[-1, 1]
612
+ img1_t = img1_t * 2 - 1
613
+ img2_t = img2_t * 2 - 1
614
+
615
+ with torch.no_grad():
616
+ lpips_value = self.lpips_model(img1_t, img2_t).item()
617
+
618
+ return lpips_value
619
+
620
+ def compute_niqe(self, img):
621
+ """
622
+ 计算NIQE (无参考图像质量评估)
623
+ 注意: 需要安装piq库或使用opencv实现
624
+ 这里使用简化版本
625
+ """
626
+ try:
627
+ import piq
628
+ img_t = torch.from_numpy(img).permute(2, 0, 1).unsqueeze(0).to(self.device)
629
+ niqe_value = piq.niqe(img_t).item()
630
+ return niqe_value
631
+ except:
632
+ print("Warning: NIQE requires 'piq' library. Returning 0.")
633
+ return 0.0
634
+
635
+ def compute_fid(self, real_images, fake_images):
636
+ """
637
+ 计算FID (Frechet Inception Distance)
638
+ 需要多张图像,这里提供接口
639
+
640
+ Args:
641
+ real_images: list of image paths or numpy arrays
642
+ fake_images: list of image paths or numpy arrays
643
+ """
644
+ try:
645
+ from pytorch_fid import fid_score
646
+ # FID需要使用目录路径或特征统计
647
+ print("Warning: FID computation requires pytorch-fid library and image directories.")
648
+ print("Please use fid_score.calculate_fid_given_paths() separately.")
649
+ return 0.0
650
+ except:
651
+ print("Warning: FID computation not available. Install pytorch-fid.")
652
+ return 0.0
653
+
654
+ def compute_meter(self, img1, img2):
655
+ """
656
+ 计算MEt3R (需要MEt3R模型)
657
+ 这是一个学习型指标,需要预训练模型
658
+ """
659
+ print("Warning: MEt3R computation requires specific model weights.")
660
+ print("Please refer to MEt3R paper and implementation.")
661
+ return 0.0
662
+
663
+ def evaluate_image_pair(self, gt_path, rendered_path):
664
+ """
665
+ 评估一对图像
666
+
667
+ Args:
668
+ gt_path: 高分辨率ground truth图像路径
669
+ rendered_path: 渲染的图像路径
670
+ Returns:
671
+ dict: 包含所有评估指标
672
+ """
673
+ print(f"Evaluating: {rendered_path}")
674
+
675
+ # 加载图像
676
+ gt_img = self.load_image(gt_path)
677
+ rendered_img = self.load_image(rendered_path)
678
+
679
+ # 确保尺寸一致
680
+ if gt_img.shape != rendered_img.shape:
681
+ print(f"Warning: Image size mismatch. GT: {gt_img.shape}, Rendered: {rendered_img.shape}")
682
+ # 调整rendered_img到gt_img的大小
683
+ rendered_img = cv2.resize(rendered_img, (gt_img.shape[1], gt_img.shape[0]))
684
+
685
+ # 计算所有指标
686
+ metrics = {
687
+ 'PSNR': self.compute_psnr(gt_img, rendered_img),
688
+ 'SSIM': self.compute_ssim(gt_img, rendered_img),
689
+ 'LPIPS': self.compute_lpips(gt_img, rendered_img),
690
+ 'NIQE': self.compute_niqe(rendered_img), # 无参考指标
691
+ }
692
+
693
+ return metrics
694
+
695
+ def evaluate_multiple_views(self, gt_dir, rendered_dir):
696
+ """
697
+ 评估多个视角
698
+
699
+ Args:
700
+ gt_dir: ground truth图像目录
701
+ rendered_dir: 渲染图像目录
702
+ Returns:
703
+ dict: 平均指标
704
+ """
705
+ import glob
706
+
707
+ # 获取所有图像
708
+ gt_images = sorted(glob.glob(os.path.join(gt_dir, '*.jpg')) +
709
+ glob.glob(os.path.join(gt_dir, '*.png')))
710
+ rendered_images = sorted(glob.glob(os.path.join(rendered_dir, '*.jpg')) +
711
+ glob.glob(os.path.join(rendered_dir, '*.png')))
712
+
713
+ if len(gt_images) != len(rendered_images):
714
+ print(f"Warning: Number of images mismatch. GT: {len(gt_images)}, Rendered: {len(rendered_images)}")
715
+
716
+ all_metrics = []
717
+
718
+ for gt_path, rendered_path in zip(gt_images, rendered_images):
719
+ metrics = self.evaluate_image_pair(gt_path, rendered_path)
720
+ all_metrics.append(metrics)
721
+
722
+ # 计算平均值
723
+ avg_metrics = {}
724
+ for key in all_metrics[0].keys():
725
+ avg_metrics[key] = np.mean([m[key] for m in all_metrics])
726
+ avg_metrics[key + '_std'] = np.std([m[key] for m in all_metrics])
727
+
728
+ return avg_metrics, all_metrics
729
+
730
+
731
+ # ==================== 使用示例 ====================
732
+
733
+ def main():
734
+ """
735
+ 完整流程示例:
736
+ 1. 加载原始3DGS
737
+ 2. 执行聚类merge
738
+ 3. 保存merged模型
739
+ 4. 调用渲染(需要外部实现)
740
+ 5. 评估图像质量
741
+ """
742
+
743
+ # ============ Step 1: 配置参数 ============
744
+ config = {
745
+ 'original_ply': 'path/to/original_3dgs.ply',
746
+ 'merged_ply': 'path/to/merged_3dgs.ply',
747
+ 'gt_image_dir': 'path/to/high_res_images',
748
+ 'rendered_image_dir': 'path/to/rendered_images',
749
+ 'cell_size': 1.0, # 根据场景大小调整
750
+ 'padding_ratio': 0.1,
751
+ 'target_points_per_cluster': 3
752
+ }
753
+
754
+ # ============ Step 2: 执行Merge ============
755
+ print("="*50)
756
+ print("Step 1: Merging Gaussians")
757
+ print("="*50)
758
+
759
+ merger = GaussianMerger(
760
+ cell_size=config['cell_size'],
761
+ padding_ratio=config['padding_ratio'],
762
+ target_points_per_cluster=config['target_points_per_cluster']
763
+ )
764
+
765
+ # 加载原始3DGS
766
+ gaussians = merger.load_ply(config['original_ply'])
767
+
768
+ # 执行merge
769
+ merged_gaussians = merger.merge_all(gaussians)
770
+
771
+ # 保存结果
772
+ merger.save_ply(merged_gaussians, config['merged_ply'])
773
+
774
+ # ============ Step 3: 渲染 (需要外部实现) ============
775
+ print("\n" + "="*50)
776
+ print("Step 2: Rendering (Please implement separately)")
777
+ print("="*50)
778
+ print(f"Please use your 3DGS renderer to render images from:")
779
+ print(f" Model: {config['merged_ply']}")
780
+ print(f" Output to: {config['rendered_image_dir']}")
781
+ print("\nExample command (using gaussian-splatting):")
782
+ print(f" python render.py -m {config['merged_ply']} -s <scene_path>")
783
+
784
+ # ============ Step 4: 评估 ============
785
+ print("\n" + "="*50)
786
+ print("Step 3: Evaluating Image Quality")
787
+ print("="*50)
788
+
789
+ evaluator = ImageEvaluator()
790
+
791
+ # 评估多个视角
792
+ avg_metrics, all_metrics = evaluator.evaluate_multiple_views(
793
+ config['gt_image_dir'],
794
+ config['rendered_image_dir']
795
+ )
796
+
797
+ # 打印结果
798
+ print("\n" + "="*50)
799
+ print("Evaluation Results")
800
+ print("="*50)
801
+ for metric_name, value in avg_metrics.items():
802
+ if not metric_name.endswith('_std'):
803
+ std = avg_metrics.get(metric_name + '_std', 0)
804
+ print(f"{metric_name:10s}: {value:.4f} ± {std:.4f}")
805
+
806
+ # 保存详细结果
807
+ import json
808
+ results = {
809
+ 'config': config,
810
+ 'merge_stats': {
811
+ 'original_points': len(gaussians['xyz']),
812
+ 'merged_points': len(merged_gaussians['xyz']),
813
+ 'compression_ratio': len(gaussians['xyz']) / len(merged_gaussians['xyz'])
814
+ },
815
+ 'average_metrics': {k: float(v) for k, v in avg_metrics.items()},
816
+ 'per_view_metrics': [{k: float(v) for k, v in m.items()} for m in all_metrics]
817
+ }
818
+
819
+ with open('evaluation_results.json', 'w') as f:
820
+ json.dump(results, f, indent=2)
821
+
822
+ print(f"\nResults saved to: evaluation_results.json")
823
+
824
+
825
+ if __name__ == "__main__":
826
+ main()