SlekLi commited on
Commit
b6619c1
·
verified ·
1 Parent(s): 5b9b1ed

Upload merge.py

Browse files
Files changed (1) hide show
  1. merge.py +720 -0
merge.py ADDED
@@ -0,0 +1,720 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ import json
10
+
11
+
12
+ # ============================================================
13
+ # Merge 相关函数
14
+ # ============================================================
15
+
16
+ def read_ply(ply_path):
17
+ plydata = PlyData.read(ply_path)
18
+ vertex = plydata['vertex']
19
+ positions = np.stack([vertex['x'], vertex['y'], vertex['z']], axis=1)
20
+ opacities = vertex['opacity'][:, np.newaxis]
21
+ scales = np.stack([vertex['scale_0'], vertex['scale_1'], vertex['scale_2']], axis=1)
22
+ rotations = np.stack([vertex['rot_0'], vertex['rot_1'], vertex['rot_2'], vertex['rot_3']], axis=1)
23
+ filter_3D = np.stack([vertex['filter_3D']], axis=1)
24
+ dc = np.stack([vertex['f_dc_0'], vertex['f_dc_1'], vertex['f_dc_2']], axis=1)
25
+ sh_keys = [key for key in vertex.data.dtype.names if key.startswith('f_rest_')]
26
+ sh_rest = np.stack([vertex[key] for key in sh_keys], axis=1) if sh_keys else None
27
+
28
+ # point_id:每个点的唯一标识,原始PLY没有该字段时自动生成 0~N-1
29
+ if 'point_id' in vertex.data.dtype.names:
30
+ point_ids = vertex['point_id'].astype(np.int64)
31
+ else:
32
+ point_ids = np.arange(len(positions), dtype=np.int64)
33
+
34
+ return {
35
+ 'positions': positions, 'opacities': opacities, 'scales': scales,
36
+ 'rotations': rotations, 'dc': dc, 'sh_rest': sh_rest,
37
+ 'plydata': plydata, 'filter_3D': filter_3D,
38
+ 'point_ids': point_ids, # shape (N,),每个点的唯一ID
39
+ }
40
+
41
+
42
+ def quaternion_to_rotation_matrix(q):
43
+ try:
44
+ rot = R.from_quat(q)
45
+ except:
46
+ rot = R.from_quat([q[1], q[2], q[3], q[0]])
47
+ return rot.as_matrix()
48
+
49
+
50
+ def compute_covariance(rotation, scale_log):
51
+ R_mat = quaternion_to_rotation_matrix(rotation)
52
+ scale_actual = np.exp(scale_log)
53
+ S_mat = np.diag(scale_actual)
54
+ return R_mat @ S_mat @ S_mat.T @ R_mat.T
55
+
56
+
57
+ def covariance_to_rotation_scale(cov):
58
+ eigenvalues, eigenvectors = np.linalg.eigh(cov)
59
+ eigenvalues = np.maximum(eigenvalues, 1e-7)
60
+ scale = np.sqrt(eigenvalues)
61
+ if np.linalg.det(eigenvectors) < 0:
62
+ eigenvectors[:, 0] *= -1
63
+ rotation = R.from_matrix(eigenvectors).as_quat() # [x,y,z,w]
64
+ return rotation, scale
65
+
66
+
67
+ def dc_to_rgb(dc):
68
+ C0 = 0.28209479177387814
69
+ return np.clip(dc * C0 + 0.5, 0, 1)
70
+
71
+
72
+ def build_octree(positions, max_points=5000):
73
+ cells = []
74
+ def subdivide(indices, bbox_min, bbox_max, depth=0):
75
+ if len(indices) <= max_points or depth > 10:
76
+ cells.append({'indices': indices, 'bbox_min': bbox_min, 'bbox_max': bbox_max})
77
+ return
78
+ center = (bbox_min + bbox_max) / 2
79
+ for i in range(8):
80
+ sub_min = np.array([
81
+ center[0] if (i & 1) else bbox_min[0],
82
+ center[1] if (i >> 1 & 1) else bbox_min[1],
83
+ center[2] if (i >> 2 & 1) else bbox_min[2],
84
+ ])
85
+ sub_max = np.array([
86
+ bbox_max[0] if (i & 1) else center[0],
87
+ bbox_max[1] if (i >> 1 & 1) else center[1],
88
+ bbox_max[2] if (i >> 2 & 1) else center[2],
89
+ ])
90
+ mask = np.all((positions[indices] >= sub_min) & (positions[indices] < sub_max), axis=1)
91
+ sub_indices = indices[mask]
92
+ if len(sub_indices) > 0:
93
+ subdivide(sub_indices, sub_min, sub_max, depth + 1)
94
+ subdivide(np.arange(len(positions)), positions.min(axis=0), positions.max(axis=0))
95
+ return cells
96
+
97
+
98
+ def build_knn_connectivity_graph(positions, k=10):
99
+ n_points = len(positions)
100
+ nbrs = NearestNeighbors(n_neighbors=min(k+1, n_points), algorithm='kd_tree').fit(positions)
101
+ _, indices = nbrs.kneighbors(positions)
102
+ rows, cols = [], []
103
+ for i in range(n_points):
104
+ for j in range(1, len(indices[i])):
105
+ rows += [i, indices[i][j]]
106
+ cols += [indices[i][j], i]
107
+ return csr_matrix((np.ones(len(rows)), (rows, cols)), shape=(n_points, n_points))
108
+
109
+
110
+ def get_connected_clusters(labels, connectivity_matrix):
111
+ refined_labels = labels.copy()
112
+ next_label = labels.max() + 1
113
+ for cluster_id in np.unique(labels):
114
+ cluster_indices = np.where(labels == cluster_id)[0]
115
+ if len(cluster_indices) <= 1:
116
+ continue
117
+ subgraph = connectivity_matrix[cluster_indices, :][:, cluster_indices]
118
+ n_components, component_labels = connected_components(subgraph, directed=False, return_labels=True)
119
+ if n_components > 1:
120
+ for comp_id in range(1, n_components):
121
+ refined_labels[cluster_indices[component_labels == comp_id]] = next_label
122
+ next_label += 1
123
+ return refined_labels
124
+
125
+
126
+ def cluster_and_merge_cell(data, cell_indices, bbox_min, bbox_max,
127
+ k_neighbors=5, spread_factor=0.01,
128
+ aspect_ratio_threshold=5.0, compress_ratio=4,
129
+ id_counter=None):
130
+ """
131
+ 对单个 cell 内的点进行聚类和合并。
132
+
133
+ id_counter: 一个长度为1的列表 [int],用于跨cell生成全局唯一的新point_id。
134
+ 每产生一个合并点就将其自增1。
135
+
136
+ 返回:
137
+ merged_data : 合并后各属性(含 point_ids 字段)
138
+ cell_lineage : dict { child_id(int): [parent_id(int), ...] }
139
+ """
140
+ if len(cell_indices) < 4:
141
+ return None, None
142
+
143
+ n_clusters = max(1, len(cell_indices) // compress_ratio)
144
+
145
+ cell_positions = data['positions'][cell_indices]
146
+ cell_dc = data['dc'][cell_indices]
147
+ cell_opacities = data['opacities'][cell_indices]
148
+ cell_scales = data['scales'][cell_indices]
149
+ cell_rotations = data['rotations'][cell_indices]
150
+ cell_filter_3D = data['filter_3D'][cell_indices]
151
+ cell_point_ids = data['point_ids'][cell_indices] # 父节点的 point_id
152
+
153
+ connectivity_matrix = build_knn_connectivity_graph(cell_positions, k=k_neighbors)
154
+
155
+ cell_size = np.maximum(bbox_max - bbox_min, 1e-6)
156
+ norm_positions = (cell_positions - bbox_min) / cell_size
157
+ rgb = dc_to_rgb(cell_dc)
158
+
159
+ features = np.concatenate([norm_positions * np.sqrt(0.8), rgb * np.sqrt(0.2)], axis=1)
160
+ labels = AgglomerativeClustering(n_clusters=n_clusters, linkage='ward').fit_predict(features)
161
+ refined_labels = get_connected_clusters(labels, connectivity_matrix)
162
+ final_n_clusters = len(np.unique(refined_labels))
163
+ print(f" 原始簇数: {n_clusters}, 连通性约束后簇数: {final_n_clusters}")
164
+
165
+ merged_data = {
166
+ 'positions': [], 'opacities': [], 'scales': [], 'rotations': [],
167
+ 'dc': [], 'sh_rest': [] if data['sh_rest'] is not None else None,
168
+ 'filter_3D': [], 'point_ids': []
169
+ }
170
+ # 族谱:{child_point_id: [parent_point_id, ...]}
171
+ cell_lineage = {}
172
+
173
+ for cluster_id in np.unique(refined_labels):
174
+ idx_in_cell = np.where(refined_labels == cluster_id)[0]
175
+ if len(idx_in_cell) == 0:
176
+ continue
177
+
178
+ # 父节点的 point_id(与顺序无关的唯一标识)
179
+ parent_ids = [int(x) for x in cell_point_ids[idx_in_cell]]
180
+
181
+ # 为本合并点分配新的唯一 point_id
182
+ child_id = int(id_counter[0])
183
+ id_counter[0] += 1
184
+
185
+ scale_actual = np.exp(cell_scales[idx_in_cell])
186
+ approx_volumes = np.prod(scale_actual, axis=1, keepdims=True)
187
+ actual_opacities = 1.0 / (1.0 + np.exp(-cell_opacities[idx_in_cell]))
188
+ weights = actual_opacities * approx_volumes
189
+ normalized_weights = weights / weights.sum()
190
+
191
+ merged_position = (cell_positions[idx_in_cell] * normalized_weights).sum(axis=0)
192
+ merged_dc = (cell_dc[idx_in_cell] * normalized_weights).sum(axis=0)
193
+ merged_filter_3D = (cell_filter_3D[idx_in_cell] * normalized_weights).sum(axis=0)
194
+
195
+ if data['sh_rest'] is not None:
196
+ merged_sh_rest = (data['sh_rest'][cell_indices][idx_in_cell] * normalized_weights).sum(axis=0)
197
+
198
+ covariances = np.array([compute_covariance(cell_rotations[i], cell_scales[i]) for i in idx_in_cell])
199
+ merged_cov = np.zeros((3, 3))
200
+ for i, orig_idx in enumerate(idx_in_cell):
201
+ diff = cell_positions[orig_idx] - merged_position
202
+ merged_cov += normalized_weights[i, 0] * (covariances[i] + spread_factor * np.outer(diff, diff))
203
+
204
+ merged_rotation, merged_scale = covariance_to_rotation_scale(merged_cov)
205
+
206
+ min_s = merged_scale.min()
207
+ if merged_scale.max() / (min_s + 1e-8) > aspect_ratio_threshold:
208
+ merged_scale = np.clip(merged_scale, None, min_s * aspect_ratio_threshold)
209
+
210
+ merged_opacity_actual = (cell_opacities[idx_in_cell] * normalized_weights).sum(axis=0)
211
+ merged_opacity_actual = np.clip(merged_opacity_actual, 1e-5, 1.0 - 1e-5)
212
+ merged_opacity = np.log(merged_opacity_actual / (1.0 - merged_opacity_actual))
213
+
214
+ merged_data['positions'].append(merged_position)
215
+ merged_data['opacities'].append(merged_opacity)
216
+ merged_data['scales'].append(merged_scale)
217
+ merged_data['rotations'].append(merged_rotation)
218
+ merged_data['dc'].append(merged_dc)
219
+ merged_data['point_ids'].append(child_id)
220
+ if data['sh_rest'] is not None:
221
+ merged_data['sh_rest'].append(merged_sh_rest)
222
+ merged_data['filter_3D'].append(merged_filter_3D)
223
+
224
+ # 族谱:child_id → parent_ids(均为 point_id,与顺序无关)
225
+ cell_lineage[child_id] = parent_ids
226
+
227
+ for key in merged_data:
228
+ if merged_data[key] is not None and len(merged_data[key]) > 0:
229
+ merged_data[key] = np.array(merged_data[key])
230
+
231
+ return merged_data, cell_lineage
232
+
233
+
234
+ def validate_data(merged_data):
235
+ print("\n" + "="*60 + "\n数据验证报告\n" + "="*60)
236
+ total = len(merged_data['positions'])
237
+ has_nan = np.zeros(total, dtype=bool)
238
+ has_inf = np.zeros(total, dtype=bool)
239
+ for key in ['positions', 'opacities', 'scales', 'rotations', 'dc']:
240
+ arr = merged_data[key]
241
+ if arr.ndim == 1:
242
+ has_nan |= np.isnan(arr)
243
+ has_inf |= np.isinf(arr)
244
+ else:
245
+ has_nan |= np.isnan(arr).any(axis=1)
246
+ has_inf |= np.isinf(arr).any(axis=1)
247
+ print(f"总点数: {total} NaN点: {has_nan.sum()} Inf点: {has_inf.sum()}")
248
+ print("="*60 + "\n")
249
+ return {'has_nan': has_nan.sum(), 'has_inf': has_inf.sum(), 'total': total}
250
+
251
+
252
+ def save_ply(merged_data, original_plydata, output_path):
253
+ n_points = len(merged_data['positions'])
254
+ dtype_list = [
255
+ ('x','f4'),('y','f4'),('z','f4'),('opacity','f4'),
256
+ ('scale_0','f4'),('scale_1','f4'),('scale_2','f4'),
257
+ ('rot_0','f4'),('rot_1','f4'),('rot_2','f4'),('rot_3','f4'),
258
+ ('f_dc_0','f4'),('f_dc_1','f4'),('f_dc_2','f4'),
259
+ ('point_id', 'i8'), # 每个点的唯一ID,用于族谱对应,与顺序无关
260
+ ]
261
+ n_sh = 0
262
+ if merged_data['sh_rest'] is not None:
263
+ n_sh = merged_data['sh_rest'].shape[1]
264
+ dtype_list += [(f'f_rest_{i}','f4') for i in range(n_sh)]
265
+ if merged_data.get('filter_3D') is not None:
266
+ dtype_list.append(('filter_3D','f4'))
267
+
268
+ vd = np.empty(n_points, dtype=dtype_list)
269
+ vd['x'] = merged_data['positions'][:,0]
270
+ vd['y'] = merged_data['positions'][:,1]
271
+ vd['z'] = merged_data['positions'][:,2]
272
+ vd['opacity'] = merged_data['opacities'].flatten()
273
+ vd['scale_0'] = np.log(merged_data['scales'][:,0])
274
+ vd['scale_1'] = np.log(merged_data['scales'][:,1])
275
+ vd['scale_2'] = np.log(merged_data['scales'][:,2])
276
+ vd['rot_0'] = merged_data['rotations'][:,0]
277
+ vd['rot_1'] = merged_data['rotations'][:,1]
278
+ vd['rot_2'] = merged_data['rotations'][:,2]
279
+ vd['rot_3'] = merged_data['rotations'][:,3]
280
+ vd['f_dc_0'] = merged_data['dc'][:,0]
281
+ vd['f_dc_1'] = merged_data['dc'][:,1]
282
+ vd['f_dc_2'] = merged_data['dc'][:,2]
283
+ vd['point_id'] = merged_data['point_ids'].astype(np.int64)
284
+ if merged_data['sh_rest'] is not None:
285
+ for i in range(n_sh):
286
+ vd[f'f_rest_{i}'] = merged_data['sh_rest'][:,i]
287
+ if merged_data.get('filter_3D') is not None:
288
+ vd['filter_3D'] = merged_data['filter_3D'].flatten()
289
+
290
+ PlyData([PlyElement.describe(vd, 'vertex')]).write(output_path)
291
+
292
+
293
+ # ============================================================
294
+ # Merge 主流程(含族谱收集)
295
+ # ============================================================
296
+
297
+ def run_merge(data, compress_ratio=4, k_neighbors=5,
298
+ spread_factor=0.0, aspect_ratio_threshold=15.0,
299
+ id_counter=None):
300
+ """
301
+ 对整份数据执行一次 merge,返回合并后数据和本级族谱。
302
+
303
+ 族谱格式(level_lineage):
304
+ dict { child_point_id(int): [parent_point_id(int), ...] }
305
+ 与点的存储顺序完全无关,通过 point_id 唯一定位每个点。
306
+
307
+ id_counter: [int],跨 cell 全局唯一ID生成器,由外部传入以保证跨级唯一性。
308
+ """
309
+ if id_counter is None:
310
+ id_counter = [0]
311
+
312
+ n_input = len(data['positions'])
313
+ cells = build_octree(data['positions'], max_points=5000)
314
+ print(f"划分为 {len(cells)} 个 cells")
315
+
316
+ all_merged = {
317
+ 'positions': [], 'opacities': [], 'scales': [], 'rotations': [],
318
+ 'dc': [], 'sh_rest': [] if data['sh_rest'] is not None else None,
319
+ 'filter_3D': [], 'point_ids': []
320
+ }
321
+ level_lineage = {} # {child_id: [parent_id, ...]}
322
+
323
+ for i, cell in enumerate(cells):
324
+ if i % 100 == 0:
325
+ print(f" 处理进度: {i}/{len(cells)}")
326
+
327
+ merged, cell_lineage = cluster_and_merge_cell(
328
+ data, cell['indices'], cell['bbox_min'], cell['bbox_max'],
329
+ k_neighbors=k_neighbors, spread_factor=spread_factor,
330
+ aspect_ratio_threshold=aspect_ratio_threshold,
331
+ compress_ratio=compress_ratio,
332
+ id_counter=id_counter,
333
+ )
334
+ if merged is None:
335
+ continue
336
+
337
+ for key in all_merged:
338
+ if all_merged[key] is not None and len(merged[key]) > 0:
339
+ all_merged[key].append(merged[key])
340
+
341
+ level_lineage.update(cell_lineage) # 合并各cell的族谱dict
342
+
343
+ final_data = {
344
+ key: np.concatenate(all_merged[key], axis=0)
345
+ for key in all_merged
346
+ if all_merged[key] is not None and len(all_merged[key]) > 0
347
+ }
348
+ n_merged = len(final_data['positions'])
349
+ print(f"合并后点数: {n_merged} 压缩率: {n_merged/n_input*100:.2f}%")
350
+
351
+ return final_data, level_lineage
352
+
353
+
354
+ # ============================================================
355
+ # Fine-tuning 阶段
356
+ # ============================================================
357
+
358
+ def finetune_merged_gaussians(
359
+ merged_ply_path,
360
+ original_source_path,
361
+ output_ply_path,
362
+ image_resolution=1,
363
+ sh_degree=3,
364
+ num_epochs=500,
365
+ lr_opacity=0.05,
366
+ lr_scaling=0.005,
367
+ lr_rotation=0.001,
368
+ lr_features_dc=0.0025,
369
+ lr_features_rest=0.000125,
370
+ white_background=False,
371
+ kernel_size=0.1,
372
+ gpu_id=0,
373
+ log_interval=50,
374
+ ):
375
+ """
376
+ 冻结高斯点位置,用下采样 GT 图像对其余参数做 fine-tuning。
377
+
378
+ original_source_path : 原始分辨率 COLMAP 目录,程序内部自动 in-memory 下采样。
379
+ image_resolution : GT 图像边长缩小倍率(1=原图, 2=1/2边长, 4=1/4边长, 8=1/8边长)。
380
+ """
381
+ import torch
382
+ import torch.nn.functional as F
383
+ from gaussian_renderer import render, GaussianModel
384
+ from scene.dataset_readers import sceneLoadTypeCallbacks
385
+ from utils.camera_utils import loadCam
386
+ from utils.loss_utils import l1_loss, ssim
387
+ import random
388
+
389
+ device = f'cuda:{gpu_id}'
390
+ torch.cuda.set_device(device)
391
+ bg_color = [1,1,1] if white_background else [0,0,0]
392
+ background = torch.tensor(bg_color, dtype=torch.float32, device=device)
393
+
394
+ # 1. 加载高斯模型
395
+ print("\n[Fine-tune] 加载 merge 后的高斯模型...")
396
+ gaussians = GaussianModel(sh_degree)
397
+ gaussians.load_ply(merged_ply_path)
398
+ print(f"[Fine-tune] 高斯点数: {gaussians.get_xyz.shape[0]}")
399
+
400
+ # 2. 冻结位置
401
+ gaussians._xyz.requires_grad_(False)
402
+ optimizer = torch.optim.Adam([
403
+ {'params': [gaussians._features_dc], 'lr': lr_features_dc, 'name': 'f_dc'},
404
+ {'params': [gaussians._features_rest], 'lr': lr_features_rest, 'name': 'f_rest'},
405
+ {'params': [gaussians._opacity], 'lr': lr_opacity, 'name': 'opacity'},
406
+ {'params': [gaussians._scaling], 'lr': lr_scaling, 'name': 'scaling'},
407
+ {'params': [gaussians._rotation], 'lr': lr_rotation, 'name': 'rotation'},
408
+ ], eps=1e-15)
409
+
410
+ # 3. 读取相机(原始分辨率)
411
+ print(f"[Fine-tune] 读取相机,GT 将 in-memory 下采样 1/{image_resolution} 边长...")
412
+ if os.path.exists(os.path.join(original_source_path, "sparse")):
413
+ scene_info = sceneLoadTypeCallbacks["Colmap"](
414
+ original_source_path, "images", eval=False, resolution=1)
415
+ elif os.path.exists(os.path.join(original_source_path, "transforms_train.json")):
416
+ scene_info = sceneLoadTypeCallbacks["Blender"](
417
+ original_source_path, white_background, eval=False, resolution=1)
418
+ else:
419
+ raise ValueError(f"[Fine-tune] 无法识别数据集格式: {original_source_path}")
420
+
421
+ class _LoadArgs:
422
+ resolution = 1
423
+ data_device = device
424
+
425
+ cameras = []
426
+ for i, ci in enumerate(scene_info.train_cameras):
427
+ try:
428
+ cameras.append(loadCam(_LoadArgs(), i, ci, 1.0, load_image=True))
429
+ except Exception as e:
430
+ print(f"[Fine-tune] 跳过相机 {i}: {e}")
431
+
432
+ if not cameras:
433
+ raise RuntimeError("[Fine-tune] 没有可用的训练相机。")
434
+
435
+ # 4. in-memory 下采样:GT 图像 + 渲染分辨率同步缩小
436
+ if image_resolution > 1:
437
+ print(f"[Fine-tune] 对 {len(cameras)} 个相机做 1/{image_resolution} 边长下采样...")
438
+ for cam in cameras:
439
+ gt_orig = cam.original_image.to(device)
440
+ H, W = gt_orig.shape[1], gt_orig.shape[2]
441
+ new_H, new_W = H // image_resolution, W // image_resolution
442
+ cam.original_image = F.interpolate(
443
+ gt_orig.unsqueeze(0), size=(new_H, new_W),
444
+ mode='bilinear', align_corners=False
445
+ ).squeeze(0).cpu()
446
+ # FoVx/FoVy 不变,渲染器根据新 image_width/height 自动反算 focal length
447
+ cam.image_width = new_W
448
+ cam.image_height = new_H
449
+ print(f"[Fine-tune] 下采样后尺寸: {cameras[0].image_height} x {cameras[0].image_width}")
450
+
451
+ # 5. 训练循环
452
+ class _Pipeline:
453
+ convert_SHs_python = False
454
+ compute_cov3D_python = False
455
+ debug = False
456
+
457
+ pipeline = _Pipeline()
458
+ lambda_dssim = 0.2
459
+
460
+ print(f"\n[Fine-tune] 开始优化,共 {num_epochs} epochs,{len(cameras)} 张图像...")
461
+ for epoch in range(1, num_epochs + 1):
462
+ random.shuffle(cameras)
463
+ epoch_loss = 0.0
464
+ for cam in cameras:
465
+ optimizer.zero_grad()
466
+ rendered = render(cam, gaussians, pipeline, background, kernel_size=kernel_size)["render"]
467
+ gt = cam.original_image.to(device)
468
+ if rendered.shape != gt.shape:
469
+ gt = F.interpolate(gt.unsqueeze(0), size=rendered.shape[1:],
470
+ mode='bilinear', align_corners=False).squeeze(0)
471
+ loss = (1.0 - lambda_dssim) * l1_loss(rendered, gt) \
472
+ + lambda_dssim * (1.0 - ssim(rendered, gt))
473
+ loss.backward()
474
+ optimizer.step()
475
+ epoch_loss += loss.item()
476
+ if epoch % log_interval == 0 or epoch == 1:
477
+ print(f"[Fine-tune] Epoch {epoch:4d}/{num_epochs} avg_loss={epoch_loss/len(cameras):.6f}")
478
+
479
+ # 6. 保存
480
+ print(f"\n[Fine-tune] 保存至 {output_ply_path} ...")
481
+ os.makedirs(os.path.dirname(os.path.abspath(output_ply_path)), exist_ok=True)
482
+ gaussians.save_ply(output_ply_path)
483
+ print("[Fine-tune] 保存完成。")
484
+
485
+
486
+ # ============================================================
487
+ # 完整流程入口
488
+ # ============================================================
489
+
490
+ def run_all(
491
+ input_ply,
492
+ original_source_path,
493
+ output_base,
494
+ # merge 参数
495
+ k_neighbors=5,
496
+ spread_factor=0.0,
497
+ aspect_ratio_threshold=15.0,
498
+ # fine-tune 参数
499
+ sh_degree=3,
500
+ num_epochs=500,
501
+ lr_opacity=0.05,
502
+ lr_scaling=0.005,
503
+ lr_rotation=0.001,
504
+ lr_features_dc=0.0025,
505
+ lr_features_rest=0.000125,
506
+ white_background=False,
507
+ kernel_size=0.1,
508
+ gpu_id=0,
509
+ log_interval=50,
510
+ ):
511
+ """
512
+ 完整流程:级联 merge(三级)+ 每级 fine-tune + 族谱保存。
513
+
514
+ 输出目录结构:
515
+ output_base/
516
+ ├── L1/
517
+ │ ├── merged.ply # 1/4 点数,merge 后未微调
518
+ │ └── finetuned.ply # 1/4 点数,微调后
519
+ ├── L2/
520
+ │ ├── merged.ply # 1/16 点数
521
+ │ └── finetuned.ply
522
+ ├── L3/
523
+ │ ├── merged.ply # 1/64 点数
524
+ │ └── finetuned.ply
525
+ └── lineage.json # 完整族谱
526
+
527
+ 族谱结构(lineage.json):
528
+ {
529
+ "L1": [[idx, ...], [idx, ...], ...],
530
+ // L1[i] = 原始 PLY 中哪些点合并成了 L1 第 i 个点
531
+
532
+ "L2": [[idx, ...], ...],
533
+ // L2[i] = L1 finetuned PLY 中哪些点合并成了 L2 第 i 个点
534
+
535
+ "L3": [[idx, ...], ...]
536
+ // L3[i] = L2 finetuned PLY 中哪些点合并成了 L3 第 i 个点
537
+ }
538
+
539
+ 层级恢复示例(从 L3 追溯到原始点):
540
+ L3[i] 由 L2 中的 lineage["L3"][i] 合并而来
541
+ 其中 L2[j] 又由 L1 中的 lineage["L2"][j] 合并而来
542
+ 其中 L1[k] 又由原始点中的 lineage["L1"][k] 合并而来
543
+ """
544
+
545
+ # 三级配置:(级别名, image_resolution)
546
+ # compress_ratio 固定为 4,每级压缩 1/4 点数
547
+ levels = [
548
+ ("L1", 2), # 原始 → 1/4 点,图像边长 1/2
549
+ ("L2", 4), # L1结果 → 1/16 点,图像边长 1/4
550
+ ("L3", 8), # L2结果 → 1/64 点,图像边长 1/8
551
+ ]
552
+
553
+ finetune_kwargs = dict(
554
+ original_source_path=original_source_path,
555
+ sh_degree=sh_degree,
556
+ num_epochs=num_epochs,
557
+ lr_opacity=lr_opacity,
558
+ lr_scaling=lr_scaling,
559
+ lr_rotation=lr_rotation,
560
+ lr_features_dc=lr_features_dc,
561
+ lr_features_rest=lr_features_rest,
562
+ white_background=white_background,
563
+ kernel_size=kernel_size,
564
+ gpu_id=gpu_id,
565
+ log_interval=log_interval,
566
+ )
567
+
568
+ merge_kwargs = dict(
569
+ compress_ratio=4,
570
+ k_neighbors=k_neighbors,
571
+ spread_factor=spread_factor,
572
+ aspect_ratio_threshold=aspect_ratio_threshold,
573
+ )
574
+
575
+ # id_counter 跨三级共享,保证所有点的 point_id 全局唯一:
576
+ # 原始点 : point_id = 0 ~ N_original-1 (read_ply 自动生成)
577
+ # L1合并点 : point_id 从 N_original 开始递增
578
+ # L2、L3 : 继续递增,绝不与任何已有 point_id 冲突
579
+ current_data = read_ply(input_ply)
580
+ n_original = len(current_data['positions'])
581
+ id_counter = [n_original] # 合并点编号从原始点数量之后开始
582
+ full_lineage = {} # {level: {str(child_id): [parent_id, ...]}}
583
+ current_ply_path = input_ply
584
+
585
+ for level, image_resolution in levels:
586
+ print("\n" + "=" * 70)
587
+ print(f"级别: {level} | 本级压缩 1/4 | 图像边长缩小 1/{image_resolution}")
588
+ print(f"输入 PLY: {current_ply_path}")
589
+ print("=" * 70)
590
+
591
+ level_dir = os.path.join(output_base, level)
592
+ merged_ply = os.path.join(level_dir, "merged.ply")
593
+ finetuned_ply = os.path.join(level_dir, "finetuned.ply")
594
+ os.makedirs(level_dir, exist_ok=True)
595
+
596
+ # --- Merge ---
597
+ print(f"\n[{level}] Step 1: Merge")
598
+ final_data, level_lineage = run_merge(
599
+ current_data, id_counter=id_counter, **merge_kwargs)
600
+
601
+ result = validate_data(final_data)
602
+ if result['has_nan'] or result['has_inf']:
603
+ print(f"⚠️ NaN={result['has_nan']} Inf={result['has_inf']}")
604
+
605
+ save_ply(final_data, current_data['plydata'], merged_ply)
606
+ print(f"[{level}] Merge PLY 已保存: {merged_ply}")
607
+
608
+ # 族谱 key 转 str(JSON 要求 key 必须是字符串)
609
+ # 格式:{"child_point_id": [parent_point_id, ...], ...}
610
+ full_lineage[level] = {str(k): v for k, v in level_lineage.items()}
611
+ lineage_path = os.path.join(output_base, "lineage.json")
612
+ with open(lineage_path, 'w') as f:
613
+ json.dump(full_lineage, f)
614
+ print(f"[{level}] 族谱已保存(当前已完成: {list(full_lineage.keys())})")
615
+
616
+ # --- Fine-tune ---
617
+ print(f"\n[{level}] Step 2: Fine-tune (image_resolution=1/{image_resolution})")
618
+ finetune_merged_gaussians(
619
+ merged_ply_path=merged_ply,
620
+ output_ply_path=finetuned_ply,
621
+ image_resolution=image_resolution,
622
+ **finetune_kwargs,
623
+ )
624
+
625
+ # 下一级从 finetuned.ply 出发(fine-tune 不改变点数和 point_id,只改属性)
626
+ current_ply_path = finetuned_ply
627
+ current_data = read_ply(finetuned_ply)
628
+
629
+ # 族谱已在每级完成后实时写盘,此处仅做最终确认
630
+ lineage_path = os.path.join(output_base, "lineage.json")
631
+ print(f"\n✅ 族谱完整保存至: {lineage_path}")
632
+
633
+ print("\n🎉 所有级别完成!")
634
+ print(f"输出目录: {output_base}")
635
+ print(" L1/merged.ply, L1/finetuned.ply — 1/4 点数")
636
+ print(" L2/merged.ply, L2/finetuned.ply — 1/16 点数")
637
+ print(" L3/merged.ply, L3/finetuned.ply — 1/64 点数")
638
+ print(" lineage.json — 完整族谱")
639
+
640
+
641
+ # ============================================================
642
+ # 族谱工具函数(供后续训练代码使用)
643
+ # ============================================================
644
+
645
+ def load_lineage(lineage_path):
646
+ """加载族谱文件"""
647
+ with open(lineage_path, 'r') as f:
648
+ lineage = json.load(f)
649
+ return lineage
650
+
651
+
652
+ def trace_to_original(child_point_id, level, lineage):
653
+ """
654
+ 从某一级的点(通过 point_id 指定)追溯到原始点的 point_id 集合。
655
+
656
+ 参数:
657
+ child_point_id : 要追溯的点的 point_id(int 或 str 均可)
658
+ level : 该点所在级别,"L1" / "L2" / "L3"
659
+ lineage : load_lineage() 返回的族谱 dict
660
+
661
+ 返回:
662
+ List[int],原始 PLY 中的 point_id 列表(即 0 ~ N_original-1 范围内的值)
663
+
664
+ 示例:
665
+ lineage = load_lineage("low_results/lineage.json")
666
+ # 查询 L3 中 point_id=500100 的点对应的所有原始点
667
+ orig_ids = trace_to_original(500100, "L3", lineage)
668
+ """
669
+ levels = ["L1", "L2", "L3"]
670
+ level_idx = levels.index(level)
671
+
672
+ # 当前层的父节点 point_id 列表
673
+ current_ids = lineage[level][str(child_point_id)]
674
+
675
+ # 逐级向上追溯,直到 L1 的父节点(即原始点 point_id)
676
+ for parent_level in reversed(levels[:level_idx]):
677
+ next_ids = []
678
+ for pid in current_ids:
679
+ # 原始点的 point_id 不在族谱里(它们是叶子节点),直接保留
680
+ key = str(pid)
681
+ if key in lineage[parent_level]:
682
+ next_ids.extend(lineage[parent_level][key])
683
+ else:
684
+ next_ids.append(pid)
685
+ current_ids = next_ids
686
+
687
+ return [int(x) for x in current_ids]
688
+
689
+
690
+ # ============================================================
691
+ # 入口
692
+ # ============================================================
693
+
694
+
695
+
696
+ if __name__ == "__main__":
697
+
698
+ run_all(
699
+ input_ply = "merge/original_3dgs.ply",
700
+ original_source_path = "data", # 唯一需要提供的 COLMAP 目录
701
+ output_base = "outputs",
702
+
703
+ # merge 参数
704
+ k_neighbors=5,
705
+ spread_factor=0.0,
706
+ aspect_ratio_threshold=15.0,
707
+
708
+ # fine-tune 参数
709
+ sh_degree=3,
710
+ num_epochs=250,
711
+ lr_opacity=0.05,
712
+ lr_scaling=0.005,
713
+ lr_rotation=0.001,
714
+ lr_features_dc=0.0025,
715
+ lr_features_rest=0.000125,
716
+ white_background=False,
717
+ kernel_size=0.1,
718
+ gpu_id=2,
719
+ log_interval=50,
720
+ )