SlekLi commited on
Commit
25169cb
·
verified ·
1 Parent(s): 2ee2169

Upload merge_finetine.py

Browse files
Files changed (1) hide show
  1. merge_finetine.py +657 -0
merge_finetine.py ADDED
@@ -0,0 +1,657 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import numpy as np
2
+ from plyfile import PlyData, PlyElement
3
+ from sklearn.cluster import AgglomerativeClustering
4
+ from sklearn.neighbors import NearestNeighbors
5
+ from scipy.spatial.transform import Rotation as R
6
+ from scipy.sparse import csr_matrix
7
+ from scipy.sparse.csgraph import connected_components
8
+ import os
9
+
10
+
11
+ # ============================================================
12
+ # 以下为原始 merge 相关函数(保持不变)
13
+ # ============================================================
14
+
15
+ def read_ply(ply_path):
16
+ """读取3DGS的.ply文件"""
17
+ plydata = PlyData.read(ply_path)
18
+ vertex = plydata['vertex']
19
+
20
+ positions = np.stack([vertex['x'], vertex['y'], vertex['z']], axis=1)
21
+ opacities = vertex['opacity'][:, np.newaxis]
22
+ scales = np.stack([vertex['scale_0'], vertex['scale_1'], vertex['scale_2']], axis=1)
23
+ rotations = np.stack([vertex['rot_0'], vertex['rot_1'], vertex['rot_2'], vertex['rot_3']], axis=1)
24
+ filter_3D = np.stack([vertex['filter_3D']], axis=1)
25
+ dc = np.stack([vertex['f_dc_0'], vertex['f_dc_1'], vertex['f_dc_2']], axis=1)
26
+
27
+ sh_keys = [key for key in vertex.data.dtype.names if key.startswith('f_rest_')]
28
+ if sh_keys:
29
+ sh_rest = np.stack([vertex[key] for key in sh_keys], axis=1)
30
+ else:
31
+ sh_rest = None
32
+
33
+ return {
34
+ 'positions': positions,
35
+ 'opacities': opacities,
36
+ 'scales': scales,
37
+ 'rotations': rotations,
38
+ 'dc': dc,
39
+ 'sh_rest': sh_rest,
40
+ 'plydata': plydata,
41
+ 'filter_3D': filter_3D
42
+ }
43
+
44
+
45
+ def quaternion_to_rotation_matrix(q):
46
+ try:
47
+ rot = R.from_quat(q)
48
+ except:
49
+ rot = R.from_quat([q[1], q[2], q[3], q[0]])
50
+ return rot.as_matrix()
51
+
52
+
53
+ def compute_covariance(rotation, scale_log):
54
+ R_mat = quaternion_to_rotation_matrix(rotation)
55
+ scale_actual = np.exp(scale_log)
56
+ S_mat = np.diag(scale_actual)
57
+ cov = R_mat @ S_mat @ S_mat.T @ R_mat.T
58
+ return cov
59
+
60
+
61
+ def covariance_to_rotation_scale(cov):
62
+ eigenvalues, eigenvectors = np.linalg.eigh(cov)
63
+ eigenvalues = np.maximum(eigenvalues, 1e-7)
64
+ scale = np.sqrt(eigenvalues)
65
+ if np.linalg.det(eigenvectors) < 0:
66
+ eigenvectors[:, 0] *= -1
67
+ rot = R.from_matrix(eigenvectors)
68
+ rotation = rot.as_quat() # [x,y,z,w]
69
+ return rotation, scale
70
+
71
+
72
+ def dc_to_rgb(dc):
73
+ C0 = 0.28209479177387814
74
+ rgb = dc * C0 + 0.5
75
+ return np.clip(rgb, 0, 1)
76
+
77
+
78
+ def rgb_to_dc(rgb):
79
+ C0 = 0.28209479177387814
80
+ dc = (rgb - 0.5) / C0
81
+ return dc
82
+
83
+
84
+ def build_octree(positions, max_points=5000):
85
+ cells = []
86
+
87
+ def subdivide(indices, bbox_min, bbox_max, depth=0):
88
+ if len(indices) <= max_points or depth > 10:
89
+ cells.append({'indices': indices, 'bbox_min': bbox_min, 'bbox_max': bbox_max})
90
+ return
91
+ center = (bbox_min + bbox_max) / 2
92
+ for i in range(8):
93
+ x_flag = i & 1
94
+ y_flag = (i >> 1) & 1
95
+ z_flag = (i >> 2) & 1
96
+ sub_min = np.array([
97
+ center[0] if x_flag else bbox_min[0],
98
+ center[1] if y_flag else bbox_min[1],
99
+ center[2] if z_flag else bbox_min[2]
100
+ ])
101
+ sub_max = np.array([
102
+ bbox_max[0] if x_flag else center[0],
103
+ bbox_max[1] if y_flag else center[1],
104
+ bbox_max[2] if z_flag else center[2]
105
+ ])
106
+ mask = np.all((positions[indices] >= sub_min) & (positions[indices] < sub_max), axis=1)
107
+ sub_indices = indices[mask]
108
+ if len(sub_indices) > 0:
109
+ subdivide(sub_indices, sub_min, sub_max, depth + 1)
110
+
111
+ bbox_min = positions.min(axis=0)
112
+ bbox_max = positions.max(axis=0)
113
+ subdivide(np.arange(len(positions)), bbox_min, bbox_max)
114
+ return cells
115
+
116
+
117
+ def build_knn_connectivity_graph(positions, k=10):
118
+ n_points = len(positions)
119
+ nbrs = NearestNeighbors(n_neighbors=min(k + 1, n_points), algorithm='kd_tree').fit(positions)
120
+ distances, indices = nbrs.kneighbors(positions)
121
+ row_indices, col_indices = [], []
122
+ for i in range(n_points):
123
+ for j in range(1, len(indices[i])):
124
+ neighbor_idx = indices[i][j]
125
+ row_indices.append(i);
126
+ col_indices.append(neighbor_idx)
127
+ row_indices.append(neighbor_idx);
128
+ col_indices.append(i)
129
+ data = np.ones(len(row_indices))
130
+ connectivity_matrix = csr_matrix((data, (row_indices, col_indices)), shape=(n_points, n_points))
131
+ return connectivity_matrix
132
+
133
+
134
+ def get_connected_clusters(labels, connectivity_matrix):
135
+ unique_labels = np.unique(labels)
136
+ refined_labels = labels.copy()
137
+ next_label = labels.max() + 1
138
+ for cluster_id in unique_labels:
139
+ cluster_mask = labels == cluster_id
140
+ cluster_indices = np.where(cluster_mask)[0]
141
+ if len(cluster_indices) <= 1:
142
+ continue
143
+ subgraph = connectivity_matrix[cluster_indices, :][:, cluster_indices]
144
+ n_components, component_labels = connected_components(subgraph, directed=False, return_labels=True)
145
+ if n_components > 1:
146
+ for comp_id in range(1, n_components):
147
+ comp_mask = component_labels == comp_id
148
+ comp_indices = cluster_indices[comp_mask]
149
+ refined_labels[comp_indices] = next_label
150
+ next_label += 1
151
+ return refined_labels
152
+
153
+
154
+ def cluster_and_merge_cell(data, cell_indices, bbox_min, bbox_max,
155
+ k_neighbors=5, spread_factor=0.01, aspect_ratio_threshold=5.0):
156
+ if len(cell_indices) < 4:
157
+ return None
158
+
159
+ n_clusters = max(1, len(cell_indices) // 2)
160
+ cell_positions = data['positions'][cell_indices]
161
+ cell_dc = data['dc'][cell_indices]
162
+ cell_opacities = data['opacities'][cell_indices]
163
+ cell_scales = data['scales'][cell_indices]
164
+ cell_rotations = data['rotations'][cell_indices]
165
+ cell_filter_3D = data['filter_3D'][cell_indices]
166
+
167
+ connectivity_matrix = build_knn_connectivity_graph(cell_positions, k=k_neighbors)
168
+
169
+ cell_size = np.maximum(bbox_max - bbox_min, 1e-6)
170
+ norm_positions = (cell_positions - bbox_min) / cell_size
171
+ rgb = dc_to_rgb(cell_dc)
172
+
173
+ features = np.concatenate([
174
+ norm_positions * np.sqrt(0.8),
175
+ rgb * np.sqrt(0.2)
176
+ ], axis=1)
177
+
178
+ clustering = AgglomerativeClustering(n_clusters=n_clusters, linkage='ward')
179
+ labels = clustering.fit_predict(features)
180
+ refined_labels = get_connected_clusters(labels, connectivity_matrix)
181
+ final_n_clusters = len(np.unique(refined_labels))
182
+ print(f" 原始簇数: {n_clusters}, 连通性约束后簇数: {final_n_clusters}")
183
+
184
+ merged_data = {
185
+ 'positions': [], 'opacities': [], 'scales': [], 'rotations': [],
186
+ 'dc': [], 'sh_rest': [] if data['sh_rest'] is not None else None,
187
+ 'filter_3D': []
188
+ }
189
+
190
+ for cluster_id in np.unique(refined_labels):
191
+ cluster_mask = refined_labels == cluster_id
192
+ cluster_indices_in_cell = np.where(cluster_mask)[0]
193
+ if len(cluster_indices_in_cell) == 0:
194
+ continue
195
+
196
+ scale_actual = np.exp(cell_scales[cluster_indices_in_cell])
197
+ approximate_volumes = np.prod(scale_actual, axis=1, keepdims=True)
198
+ actual_opacities = 1.0 / (1.0 + np.exp(-cell_opacities[cluster_indices_in_cell]))
199
+ weights = actual_opacities * approximate_volumes
200
+ weights_sum = weights.sum()
201
+ normalized_weights = weights / weights_sum
202
+
203
+ merged_position = (cell_positions[cluster_indices_in_cell] * normalized_weights).sum(axis=0)
204
+ merged_dc = (cell_dc[cluster_indices_in_cell] * normalized_weights).sum(axis=0)
205
+ merged_filter_3D = (cell_filter_3D[cluster_indices_in_cell] * normalized_weights).sum(axis=0)
206
+
207
+ if data['sh_rest'] is not None:
208
+ sh_rest_cell = data['sh_rest'][cell_indices]
209
+ merged_sh_rest = (sh_rest_cell[cluster_indices_in_cell] * normalized_weights).sum(axis=0)
210
+
211
+ covariances = []
212
+ for idx in cluster_indices_in_cell:
213
+ cov = compute_covariance(cell_rotations[idx], cell_scales[idx])
214
+ covariances.append(cov)
215
+ covariances = np.array(covariances)
216
+
217
+ merged_cov = np.zeros((3, 3))
218
+ for i, idx in enumerate(cluster_indices_in_cell):
219
+ diff = cell_positions[idx] - merged_position
220
+ outer = np.outer(diff, diff)
221
+ merged_cov += normalized_weights[i, 0] * (covariances[i] + spread_factor * outer)
222
+
223
+ merged_rotation, merged_scale = covariance_to_rotation_scale(merged_cov)
224
+
225
+ max_scale = merged_scale.max()
226
+ min_scale = merged_scale.min()
227
+ current_ratio = max_scale / (min_scale + 1e-8)
228
+ if current_ratio > aspect_ratio_threshold:
229
+ target_max = min_scale * aspect_ratio_threshold
230
+ merged_scale = np.clip(merged_scale, None, target_max)
231
+
232
+ merged_opacity_actual = (cell_opacities[cluster_indices_in_cell] * normalized_weights).sum(axis=0)
233
+ merged_opacity_actual = np.clip(merged_opacity_actual, 1e-5, 1.0 - 1e-5)
234
+ merged_opacity = np.log(merged_opacity_actual / (1.0 - merged_opacity_actual))
235
+
236
+ merged_data['positions'].append(merged_position)
237
+ merged_data['opacities'].append(merged_opacity)
238
+ merged_data['scales'].append(merged_scale)
239
+ merged_data['rotations'].append(merged_rotation)
240
+ merged_data['dc'].append(merged_dc)
241
+ if data['sh_rest'] is not None:
242
+ merged_data['sh_rest'].append(merged_sh_rest)
243
+ merged_data['filter_3D'].append(merged_filter_3D)
244
+
245
+ for key in merged_data:
246
+ if merged_data[key] is not None and len(merged_data[key]) > 0:
247
+ merged_data[key] = np.array(merged_data[key])
248
+
249
+ return merged_data
250
+
251
+
252
+ def validate_data(merged_data):
253
+ print("\n" + "=" * 60)
254
+ print("数据验证报告")
255
+ print("=" * 60)
256
+ total_points = len(merged_data['positions'])
257
+ print(f"\n总点数: {total_points}")
258
+
259
+ for name, key, ndim in [("位置 (positions)", 'positions', 'multi'),
260
+ ("不透明度 (opacities)", 'opacities', 'single'),
261
+ ("缩放 (scales)", 'scales', 'multi'),
262
+ ("旋转 (rotations)", 'rotations', 'multi'),
263
+ ("DC系数 (f_dc)", 'dc', 'multi')]:
264
+ arr = merged_data[key]
265
+ if ndim == 'multi':
266
+ nan_c = np.isnan(arr).any(axis=1).sum()
267
+ inf_c = np.isinf(arr).any(axis=1).sum()
268
+ else:
269
+ nan_c = np.isnan(arr).sum()
270
+ inf_c = np.isinf(arr).sum()
271
+ print(f"\n【{name}】 NaN: {nan_c} Inf: {inf_c}")
272
+
273
+ has_nan = (np.isnan(merged_data['positions']).any(axis=1) |
274
+ np.isnan(merged_data['opacities']).ravel() |
275
+ np.isnan(merged_data['scales']).any(axis=1) |
276
+ np.isnan(merged_data['rotations']).any(axis=1) |
277
+ np.isnan(merged_data['dc']).any(axis=1))
278
+ has_inf = (np.isinf(merged_data['positions']).any(axis=1) |
279
+ np.isinf(merged_data['opacities']).ravel() |
280
+ np.isinf(merged_data['scales']).any(axis=1) |
281
+ np.isinf(merged_data['rotations']).any(axis=1) |
282
+ np.isinf(merged_data['dc']).any(axis=1))
283
+ print(f"\n包含NaN的点: {has_nan.sum()} 包含Inf的点: {has_inf.sum()}")
284
+ print("=" * 60 + "\n")
285
+ return {'has_nan': has_nan.sum(), 'has_inf': has_inf.sum(), 'total': total_points}
286
+
287
+
288
+ def save_ply(merged_data, original_plydata, output_path):
289
+ n_points = len(merged_data['positions'])
290
+ dtype_list = [
291
+ ('x', 'f4'), ('y', 'f4'), ('z', 'f4'),
292
+ ('opacity', 'f4'),
293
+ ('scale_0', 'f4'), ('scale_1', 'f4'), ('scale_2', 'f4'),
294
+ ('rot_0', 'f4'), ('rot_1', 'f4'), ('rot_2', 'f4'), ('rot_3', 'f4'),
295
+ ('f_dc_0', 'f4'), ('f_dc_1', 'f4'), ('f_dc_2', 'f4'),
296
+ ]
297
+ if merged_data['sh_rest'] is not None:
298
+ n_sh_rest = merged_data['sh_rest'].shape[1]
299
+ for i in range(n_sh_rest):
300
+ dtype_list.append((f'f_rest_{i}', 'f4'))
301
+ if 'filter_3D' in merged_data and merged_data['filter_3D'] is not None:
302
+ dtype_list.append(('filter_3D', 'f4'))
303
+
304
+ vertex_data = np.empty(n_points, dtype=dtype_list)
305
+ vertex_data['x'] = merged_data['positions'][:, 0]
306
+ vertex_data['y'] = merged_data['positions'][:, 1]
307
+ vertex_data['z'] = merged_data['positions'][:, 2]
308
+ vertex_data['opacity'] = merged_data['opacities'].flatten()
309
+ vertex_data['scale_0'] = np.log(merged_data['scales'][:, 0])
310
+ vertex_data['scale_1'] = np.log(merged_data['scales'][:, 1])
311
+ vertex_data['scale_2'] = np.log(merged_data['scales'][:, 2])
312
+ vertex_data['rot_0'] = merged_data['rotations'][:, 0]
313
+ vertex_data['rot_1'] = merged_data['rotations'][:, 1]
314
+ vertex_data['rot_2'] = merged_data['rotations'][:, 2]
315
+ vertex_data['rot_3'] = merged_data['rotations'][:, 3]
316
+ vertex_data['f_dc_0'] = merged_data['dc'][:, 0]
317
+ vertex_data['f_dc_1'] = merged_data['dc'][:, 1]
318
+ vertex_data['f_dc_2'] = merged_data['dc'][:, 2]
319
+ if merged_data['sh_rest'] is not None:
320
+ for i in range(n_sh_rest):
321
+ vertex_data[f'f_rest_{i}'] = merged_data['sh_rest'][:, i]
322
+ if 'filter_3D' in merged_data and merged_data['filter_3D'] is not None:
323
+ vertex_data['filter_3D'] = merged_data['filter_3D'].flatten()
324
+
325
+ PlyElement.describe(vertex_data, 'vertex')
326
+ PlyData([PlyElement.describe(vertex_data, 'vertex')]).write(output_path)
327
+
328
+
329
+ # ============================================================
330
+ # 新增:Fine-tuning 阶段
331
+ # 冻结位置,用下采样图像优化其余参数 500 epoch
332
+ # ============================================================
333
+
334
+ def finetune_merged_gaussians(
335
+ merged_ply_path,
336
+ source_path,
337
+ output_ply_path,
338
+ sh_degree=3,
339
+ num_epochs=500,
340
+ lr_opacity=0.05,
341
+ lr_scaling=0.005,
342
+ lr_rotation=0.001,
343
+ lr_features_dc=0.0025,
344
+ lr_features_rest=0.000125,
345
+ white_background=False,
346
+ kernel_size=0.1,
347
+ gpu_id=0,
348
+ log_interval=50,
349
+ ):
350
+ """
351
+ 冻结高斯点的位置,用下采样训练图像对其余参数做fine-tuning。
352
+
353
+ 参数:
354
+ merged_ply_path : merge 输出的 PLY 文件路径
355
+ source_path : 下采样图像的 COLMAP 数据集根目录
356
+ (应包含 sparse/ 和 images/ ,images/ 里是你已下采样好的图像)
357
+ output_ply_path : fine-tuning 完成后保存的 PLY 路径
358
+ sh_degree : 球谐阶数,需与 merge 时一致
359
+ num_epochs : 优化轮数,默认 500
360
+ lr_* : 各参数学习率,与原版 3DGS 训练保持同量级
361
+ white_background: 背景颜色
362
+ kernel_size : 渲染时的 kernel size(与你的渲染脚本一致)
363
+ gpu_id : 使用的 GPU 编号
364
+ log_interval : 每隔多少 epoch 打印一次 loss
365
+ """
366
+ import torch
367
+ import torch.nn.functional as F
368
+ from scene import Scene
369
+ from gaussian_renderer import render, GaussianModel
370
+ from scene.dataset_readers import sceneLoadTypeCallbacks
371
+ from utils.camera_utils import loadCam
372
+ from utils.loss_utils import l1_loss, ssim
373
+
374
+ device = f'cuda:{gpu_id}'
375
+ torch.cuda.set_device(device)
376
+
377
+ bg_color = [1, 1, 1] if white_background else [0, 0, 0]
378
+ background = torch.tensor(bg_color, dtype=torch.float32, device=device)
379
+
380
+ # ---- 1. 加载 merge 后的高斯模型 ----
381
+ print("\n[Fine-tune] 加载 merge 后的高斯模型...")
382
+ gaussians = GaussianModel(sh_degree)
383
+ gaussians.load_ply(merged_ply_path)
384
+ print(f"[Fine-tune] 高斯点数: {gaussians.get_xyz.shape[0]}")
385
+
386
+ # ---- 2. 冻结位置,只保留其他参数的梯度 ----
387
+ # GaussianModel 内部用 _xyz / _features_dc / _features_rest /
388
+ # _scaling / _rotation / _opacity 存储(均为 nn.Parameter)
389
+ gaussians._xyz.requires_grad_(False)
390
+
391
+ # 构建优化器,只包含非位置参数
392
+ param_groups = [
393
+ {'params': [gaussians._features_dc], 'lr': lr_features_dc, 'name': 'f_dc'},
394
+ {'params': [gaussians._features_rest], 'lr': lr_features_rest, 'name': 'f_rest'},
395
+ {'params': [gaussians._opacity], 'lr': lr_opacity, 'name': 'opacity'},
396
+ {'params': [gaussians._scaling], 'lr': lr_scaling, 'name': 'scaling'},
397
+ {'params': [gaussians._rotation], 'lr': lr_rotation, 'name': 'rotation'},
398
+ ]
399
+ optimizer = torch.optim.Adam(param_groups, eps=1e-15)
400
+
401
+ # ---- 3. 读取下采样图像的相机列表 ----
402
+ print("[Fine-tune] 读取相机信息...")
403
+ if os.path.exists(os.path.join(source_path, "sparse")):
404
+ scene_info = sceneLoadTypeCallbacks["Colmap"](
405
+ source_path, "images", eval=False, resolution=1
406
+ )
407
+ elif os.path.exists(os.path.join(source_path, "transforms_train.json")):
408
+ scene_info = sceneLoadTypeCallbacks["Blender"](
409
+ source_path, white_background, eval=False, resolution=1
410
+ )
411
+ else:
412
+ raise ValueError(f"[Fine-tune] 无法识别数据集格式: {source_path}")
413
+
414
+ cam_infos = scene_info.train_cameras
415
+ print(f"[Fine-tune] 训练相机数量: {len(cam_infos)}")
416
+
417
+ # 预先把所有相机加载到内存(含 GT 图像)
418
+ class _LoadArgs:
419
+ resolution = 1
420
+ data_device = device
421
+
422
+ cameras = []
423
+ for i, ci in enumerate(cam_infos):
424
+ try:
425
+ cam = loadCam(_LoadArgs(), i, ci, 1.0, load_image=True)
426
+ cameras.append(cam)
427
+ except Exception as e:
428
+ print(f"[Fine-tune] 跳过相机 {i}: {e}")
429
+
430
+ if len(cameras) == 0:
431
+ raise RuntimeError("[Fine-tune] 没有可用的训练相机,请检查 source_path。")
432
+
433
+ # pipeline 设置(与你原有渲染脚本保持一致)
434
+ class _Pipeline:
435
+ convert_SHs_python = False
436
+ compute_cov3D_python = False
437
+ debug = False
438
+
439
+ pipeline = _Pipeline()
440
+
441
+ # ---- 4. Fine-tuning 主循环 ----
442
+ print(f"\n[Fine-tune] 开始优化,共 {num_epochs} epochs,{len(cameras)} 张图像...")
443
+ lambda_dssim = 0.2 # L1 + 0.2 * (1 - SSIM),与原版 3DGS 一致
444
+
445
+ import random
446
+ for epoch in range(1, num_epochs + 1):
447
+ # 每个 epoch 随机打乱相机顺序,逐张渲染并回传梯度
448
+ random.shuffle(cameras)
449
+ epoch_loss = 0.0
450
+
451
+ for cam in cameras:
452
+ optimizer.zero_grad()
453
+
454
+ # 渲染
455
+ render_pkg = render(cam, gaussians, pipeline, background, kernel_size=kernel_size)
456
+ rendered = render_pkg["render"] # (3, H, W)
457
+
458
+ # GT 图像:Camera 对象上的 original_image,已是 [0,1] float tensor
459
+ gt = cam.original_image.to(device) # (3, H, W)
460
+
461
+ # 确保尺寸一致(下采样图像与渲染尺寸应相同,以防万一做一次 resize)
462
+ if rendered.shape != gt.shape:
463
+ gt = F.interpolate(
464
+ gt.unsqueeze(0),
465
+ size=(rendered.shape[1], rendered.shape[2]),
466
+ mode='bilinear',
467
+ align_corners=False
468
+ ).squeeze(0)
469
+
470
+ # 损失:L1 + D-SSIM
471
+ Ll1 = l1_loss(rendered, gt)
472
+ loss = (1.0 - lambda_dssim) * Ll1 + lambda_dssim * (1.0 - ssim(rendered, gt))
473
+
474
+ loss.backward()
475
+ optimizer.step()
476
+ epoch_loss += loss.item()
477
+
478
+ if epoch % log_interval == 0 or epoch == 1:
479
+ avg_loss = epoch_loss / len(cameras)
480
+ print(f"[Fine-tune] Epoch {epoch:4d}/{num_epochs} avg_loss={avg_loss:.6f}")
481
+
482
+ # ---- 5. 保存 fine-tuned PLY ----
483
+ print(f"\n[Fine-tune] 优化完成,保存至 {output_ply_path} ...")
484
+ os.makedirs(os.path.dirname(os.path.abspath(output_ply_path)), exist_ok=True)
485
+ gaussians.save_ply(output_ply_path)
486
+ print("[Fine-tune] 保存完成。")
487
+
488
+
489
+ # ============================================================
490
+ # 主流程
491
+ # ============================================================
492
+
493
+ def merge_and_finetune(
494
+ ply_path,
495
+ output_path,
496
+ # merge 参数
497
+ k_neighbors=5,
498
+ spread_factor=0.0,
499
+ aspect_ratio_threshold=15.0,
500
+ # fine-tune 参数
501
+ do_finetune=True,
502
+ source_path=None,
503
+ finetuned_output_path=None,
504
+ sh_degree=3,
505
+ num_epochs=500,
506
+ lr_opacity=0.05,
507
+ lr_scaling=0.005,
508
+ lr_rotation=0.001,
509
+ lr_features_dc=0.0025,
510
+ lr_features_rest=0.000125,
511
+ white_background=False,
512
+ kernel_size=0.1,
513
+ gpu_id=0,
514
+ log_interval=50,
515
+ ):
516
+ """
517
+ 完整流程:merge -> (可选) fine-tune
518
+
519
+ 参数:
520
+ ply_path : 原始 3DGS PLY 文件
521
+ output_path : merge 后 PLY 的保存路径
522
+ do_finetune : 是否执行 fine-tuning 阶段
523
+ source_path : 下采样图像的 COLMAP 数据集目录(do_finetune=True 时必填)
524
+ finetuned_output_path : fine-tuning 后 PLY 的保存路径
525
+ (默认在 output_path 同目录下加 _finetuned 后缀)
526
+ """
527
+
528
+ # ---------- Step 1: Merge ----------
529
+ print("=" * 60)
530
+ print("Step 1: Merge 高斯点")
531
+ print("=" * 60)
532
+ print("读取PLY文件...")
533
+ data = read_ply(ply_path)
534
+ n_original = len(data['positions'])
535
+ print(f"原始高斯点数: {n_original}")
536
+
537
+ print("构建八叉树...")
538
+ cells = build_octree(data['positions'], max_points=5000)
539
+ print(f"划分为 {len(cells)} 个cells")
540
+
541
+ print("对每个cell进行聚类和合并...")
542
+ all_merged_data = {
543
+ 'positions': [], 'opacities': [], 'scales': [], 'rotations': [],
544
+ 'dc': [], 'sh_rest': [] if data['sh_rest'] is not None else None,
545
+ 'filter_3D': []
546
+ }
547
+
548
+ for i, cell in enumerate(cells):
549
+ if i % 100 == 0:
550
+ print(f"处理进度: {i}/{len(cells)}")
551
+ merged = cluster_and_merge_cell(
552
+ data, cell['indices'], cell['bbox_min'], cell['bbox_max'],
553
+ k_neighbors=k_neighbors,
554
+ spread_factor=spread_factor,
555
+ aspect_ratio_threshold=aspect_ratio_threshold
556
+ )
557
+ if merged is not None:
558
+ for key in all_merged_data:
559
+ if all_merged_data[key] is not None and len(merged[key]) > 0:
560
+ all_merged_data[key].append(merged[key])
561
+
562
+ print("合并所有cell的结果...")
563
+ final_data = {}
564
+ for key in all_merged_data:
565
+ if all_merged_data[key] is not None and len(all_merged_data[key]) > 0:
566
+ final_data[key] = np.concatenate(all_merged_data[key], axis=0)
567
+
568
+ n_merged = len(final_data['positions'])
569
+ print(f"合并后高斯点数: {n_merged}")
570
+ print(f"压缩率: {n_merged / n_original * 100:.2f}%")
571
+
572
+ validation_result = validate_data(final_data)
573
+ if validation_result['has_nan'] > 0 or validation_result['has_inf'] > 0:
574
+ print(f"\n⚠️ 警告: 发现 {validation_result['has_nan']} 个NaN和 "
575
+ f"{validation_result['has_inf']} 个Inf!")
576
+
577
+ print("保存 merge 后的PLY文件...")
578
+ os.makedirs(os.path.dirname(os.path.abspath(output_path)), exist_ok=True)
579
+ save_ply(final_data, data['plydata'], output_path)
580
+ print(f"Merge PLY 已保存到: {output_path}")
581
+
582
+ # ---------- Step 2: Fine-tune ----------
583
+ if not do_finetune:
584
+ print("\ndo_finetune=False,跳过 fine-tuning 阶段。")
585
+ return
586
+
587
+ if source_path is None:
588
+ raise ValueError("do_finetune=True 时必须提供 source_path(下采样图像的 COLMAP 目录)")
589
+
590
+ if finetuned_output_path is None:
591
+ base, ext = os.path.splitext(output_path)
592
+ finetuned_output_path = base + "_finetuned" + ext
593
+
594
+ print("\n" + "=" * 60)
595
+ print("Step 2: Fine-tune(冻结位置,优化其余参数)")
596
+ print("=" * 60)
597
+
598
+ finetune_merged_gaussians(
599
+ merged_ply_path=output_path,
600
+ source_path=source_path,
601
+ output_ply_path=finetuned_output_path,
602
+ sh_degree=sh_degree,
603
+ num_epochs=num_epochs,
604
+ lr_opacity=lr_opacity,
605
+ lr_scaling=lr_scaling,
606
+ lr_rotation=lr_rotation,
607
+ lr_features_dc=lr_features_dc,
608
+ lr_features_rest=lr_features_rest,
609
+ white_background=white_background,
610
+ kernel_size=kernel_size,
611
+ gpu_id=gpu_id,
612
+ log_interval=log_interval,
613
+ )
614
+
615
+ print("\n✅ 全流程完成!")
616
+ print(f" Merge PLY : {output_path}")
617
+ print(f" Fine-tuned PLY : {finetuned_output_path}")
618
+
619
+
620
+ # ============================================================
621
+ # 入口
622
+ # ============================================================
623
+
624
+ if __name__ == "__main__":
625
+ # ---------- 路径配置 ----------
626
+ input_ply = "merge/original_3dgs.ply"
627
+ merged_ply = "low_results/output_merged.ply"
628
+ finetuned_ply = "low_results/output_finetuned.ply"
629
+
630
+ # 你提供的下采样图像对应的 COLMAP 数据集目录
631
+ # 该目录下需有 sparse/ 和 images/(images/ 里存放下采样后的训练图像)
632
+ downsampled_source = "dataset/downsampled"
633
+
634
+ merge_and_finetune(
635
+ # merge 参数
636
+ ply_path=input_ply,
637
+ output_path=merged_ply,
638
+ k_neighbors=5,
639
+ spread_factor=0.0,
640
+ aspect_ratio_threshold=15.0,
641
+
642
+ # fine-tune 开关与参数
643
+ do_finetune=True,
644
+ source_path=downsampled_source,
645
+ finetuned_output_path=finetuned_ply,
646
+ sh_degree=3,
647
+ num_epochs=500,
648
+ lr_opacity=0.05,
649
+ lr_scaling=0.005,
650
+ lr_rotation=0.001,
651
+ lr_features_dc=0.0025,
652
+ lr_features_rest=0.000125,
653
+ white_background=False,
654
+ kernel_size=0.1,
655
+ gpu_id=0,
656
+ log_interval=50,
657
+ )