| import numpy as np
|
| from plyfile import PlyData, PlyElement
|
| from sklearn.cluster import AgglomerativeClustering
|
| from sklearn.neighbors import NearestNeighbors
|
| from scipy.spatial.transform import Rotation as R
|
| from scipy.sparse import csr_matrix
|
| from scipy.sparse.csgraph import connected_components
|
| import os
|
| import json
|
|
|
|
|
|
|
|
|
|
|
|
|
| def read_ply(ply_path):
|
| plydata = PlyData.read(ply_path)
|
| vertex = plydata['vertex']
|
| positions = np.stack([vertex['x'], vertex['y'], vertex['z']], axis=1)
|
| opacities = vertex['opacity'][:, np.newaxis]
|
| scales = np.stack([vertex['scale_0'], vertex['scale_1'], vertex['scale_2']], axis=1)
|
| rotations = np.stack([vertex['rot_0'], vertex['rot_1'], vertex['rot_2'], vertex['rot_3']], axis=1)
|
| filter_3D = np.stack([vertex['filter_3D']], axis=1)
|
| dc = np.stack([vertex['f_dc_0'], vertex['f_dc_1'], vertex['f_dc_2']], axis=1)
|
| sh_keys = [key for key in vertex.data.dtype.names if key.startswith('f_rest_')]
|
| sh_rest = np.stack([vertex[key] for key in sh_keys], axis=1) if sh_keys else None
|
|
|
|
|
| if 'point_id' in vertex.data.dtype.names:
|
| point_ids = vertex['point_id'].astype(np.int64)
|
| else:
|
| point_ids = np.arange(len(positions), dtype=np.int64)
|
|
|
| return {
|
| 'positions': positions, 'opacities': opacities, 'scales': scales,
|
| 'rotations': rotations, 'dc': dc, 'sh_rest': sh_rest,
|
| 'plydata': plydata, 'filter_3D': filter_3D,
|
| 'point_ids': point_ids,
|
| }
|
|
|
|
|
| def quaternion_to_rotation_matrix(q):
|
| try:
|
| rot = R.from_quat(q)
|
| except:
|
| rot = R.from_quat([q[1], q[2], q[3], q[0]])
|
| return rot.as_matrix()
|
|
|
|
|
| def compute_covariance(rotation, scale_log):
|
| R_mat = quaternion_to_rotation_matrix(rotation)
|
| scale_actual = np.exp(scale_log)
|
| S_mat = np.diag(scale_actual)
|
| return R_mat @ S_mat @ S_mat.T @ R_mat.T
|
|
|
|
|
| def covariance_to_rotation_scale(cov):
|
| eigenvalues, eigenvectors = np.linalg.eigh(cov)
|
| eigenvalues = np.maximum(eigenvalues, 1e-7)
|
| scale = np.sqrt(eigenvalues)
|
| if np.linalg.det(eigenvectors) < 0:
|
| eigenvectors[:, 0] *= -1
|
| rotation = R.from_matrix(eigenvectors).as_quat()
|
| return rotation, scale
|
|
|
|
|
| def dc_to_rgb(dc):
|
| C0 = 0.28209479177387814
|
| return np.clip(dc * C0 + 0.5, 0, 1)
|
|
|
|
|
| def build_octree(positions, max_points=5000):
|
| cells = []
|
| def subdivide(indices, bbox_min, bbox_max, depth=0):
|
| if len(indices) <= max_points or depth > 10:
|
| cells.append({'indices': indices, 'bbox_min': bbox_min, 'bbox_max': bbox_max})
|
| return
|
| center = (bbox_min + bbox_max) / 2
|
| for i in range(8):
|
| sub_min = np.array([
|
| center[0] if (i & 1) else bbox_min[0],
|
| center[1] if (i >> 1 & 1) else bbox_min[1],
|
| center[2] if (i >> 2 & 1) else bbox_min[2],
|
| ])
|
| sub_max = np.array([
|
| bbox_max[0] if (i & 1) else center[0],
|
| bbox_max[1] if (i >> 1 & 1) else center[1],
|
| bbox_max[2] if (i >> 2 & 1) else center[2],
|
| ])
|
| mask = np.all((positions[indices] >= sub_min) & (positions[indices] < sub_max), axis=1)
|
| sub_indices = indices[mask]
|
| if len(sub_indices) > 0:
|
| subdivide(sub_indices, sub_min, sub_max, depth + 1)
|
| subdivide(np.arange(len(positions)), positions.min(axis=0), positions.max(axis=0))
|
| return cells
|
|
|
|
|
| def build_knn_connectivity_graph(positions, k=10):
|
| n_points = len(positions)
|
| nbrs = NearestNeighbors(n_neighbors=min(k+1, n_points), algorithm='kd_tree').fit(positions)
|
| _, indices = nbrs.kneighbors(positions)
|
| rows, cols = [], []
|
| for i in range(n_points):
|
| for j in range(1, len(indices[i])):
|
| rows += [i, indices[i][j]]
|
| cols += [indices[i][j], i]
|
| return csr_matrix((np.ones(len(rows)), (rows, cols)), shape=(n_points, n_points))
|
|
|
|
|
| def get_connected_clusters(labels, connectivity_matrix):
|
| refined_labels = labels.copy()
|
| next_label = labels.max() + 1
|
| for cluster_id in np.unique(labels):
|
| cluster_indices = np.where(labels == cluster_id)[0]
|
| if len(cluster_indices) <= 1:
|
| continue
|
| subgraph = connectivity_matrix[cluster_indices, :][:, cluster_indices]
|
| n_components, component_labels = connected_components(subgraph, directed=False, return_labels=True)
|
| if n_components > 1:
|
| for comp_id in range(1, n_components):
|
| refined_labels[cluster_indices[component_labels == comp_id]] = next_label
|
| next_label += 1
|
| return refined_labels
|
|
|
|
|
| def cluster_and_merge_cell(data, cell_indices, bbox_min, bbox_max,
|
| k_neighbors=5, spread_factor=0.01,
|
| aspect_ratio_threshold=5.0, compress_ratio=4,
|
| id_counter=None):
|
| """
|
| 对单个 cell 内的点进行聚类和合并。
|
|
|
| id_counter: 一个长度为1的列表 [int],用于跨cell生成全局唯一的新point_id。
|
| 每产生一个合并点就将其自增1。
|
|
|
| 返回:
|
| merged_data : 合并后各属性(含 point_ids 字段)
|
| cell_lineage : dict { child_id(int): [parent_id(int), ...] }
|
| """
|
| if len(cell_indices) < 4:
|
| return None, None
|
|
|
| n_clusters = max(1, len(cell_indices) // compress_ratio)
|
|
|
| cell_positions = data['positions'][cell_indices]
|
| cell_dc = data['dc'][cell_indices]
|
| cell_opacities = data['opacities'][cell_indices]
|
| cell_scales = data['scales'][cell_indices]
|
| cell_rotations = data['rotations'][cell_indices]
|
| cell_filter_3D = data['filter_3D'][cell_indices]
|
| cell_point_ids = data['point_ids'][cell_indices]
|
|
|
| connectivity_matrix = build_knn_connectivity_graph(cell_positions, k=k_neighbors)
|
|
|
| cell_size = np.maximum(bbox_max - bbox_min, 1e-6)
|
| norm_positions = (cell_positions - bbox_min) / cell_size
|
| rgb = dc_to_rgb(cell_dc)
|
|
|
| features = np.concatenate([norm_positions * np.sqrt(0.8), rgb * np.sqrt(0.2)], axis=1)
|
| labels = AgglomerativeClustering(n_clusters=n_clusters, linkage='ward').fit_predict(features)
|
| refined_labels = get_connected_clusters(labels, connectivity_matrix)
|
| final_n_clusters = len(np.unique(refined_labels))
|
| print(f" 原始簇数: {n_clusters}, 连通性约束后簇数: {final_n_clusters}")
|
|
|
| merged_data = {
|
| 'positions': [], 'opacities': [], 'scales': [], 'rotations': [],
|
| 'dc': [], 'sh_rest': [] if data['sh_rest'] is not None else None,
|
| 'filter_3D': [], 'point_ids': []
|
| }
|
|
|
| cell_lineage = {}
|
|
|
| for cluster_id in np.unique(refined_labels):
|
| idx_in_cell = np.where(refined_labels == cluster_id)[0]
|
| if len(idx_in_cell) == 0:
|
| continue
|
|
|
|
|
| parent_ids = [int(x) for x in cell_point_ids[idx_in_cell]]
|
|
|
|
|
| child_id = int(id_counter[0])
|
| id_counter[0] += 1
|
|
|
| scale_actual = np.exp(cell_scales[idx_in_cell])
|
| approx_volumes = np.prod(scale_actual, axis=1, keepdims=True)
|
| actual_opacities = 1.0 / (1.0 + np.exp(-cell_opacities[idx_in_cell]))
|
| weights = actual_opacities * approx_volumes
|
| normalized_weights = weights / weights.sum()
|
|
|
| merged_position = (cell_positions[idx_in_cell] * normalized_weights).sum(axis=0)
|
| merged_dc = (cell_dc[idx_in_cell] * normalized_weights).sum(axis=0)
|
| merged_filter_3D = (cell_filter_3D[idx_in_cell] * normalized_weights).sum(axis=0)
|
|
|
| if data['sh_rest'] is not None:
|
| merged_sh_rest = (data['sh_rest'][cell_indices][idx_in_cell] * normalized_weights).sum(axis=0)
|
|
|
| covariances = np.array([compute_covariance(cell_rotations[i], cell_scales[i]) for i in idx_in_cell])
|
| merged_cov = np.zeros((3, 3))
|
| for i, orig_idx in enumerate(idx_in_cell):
|
| diff = cell_positions[orig_idx] - merged_position
|
| merged_cov += normalized_weights[i, 0] * (covariances[i] + spread_factor * np.outer(diff, diff))
|
|
|
| merged_rotation, merged_scale = covariance_to_rotation_scale(merged_cov)
|
|
|
| min_s = merged_scale.min()
|
| if merged_scale.max() / (min_s + 1e-8) > aspect_ratio_threshold:
|
| merged_scale = np.clip(merged_scale, None, min_s * aspect_ratio_threshold)
|
|
|
| merged_opacity_actual = (cell_opacities[idx_in_cell] * normalized_weights).sum(axis=0)
|
| merged_opacity_actual = np.clip(merged_opacity_actual, 1e-5, 1.0 - 1e-5)
|
| merged_opacity = np.log(merged_opacity_actual / (1.0 - merged_opacity_actual))
|
|
|
| merged_data['positions'].append(merged_position)
|
| merged_data['opacities'].append(merged_opacity)
|
| merged_data['scales'].append(merged_scale)
|
| merged_data['rotations'].append(merged_rotation)
|
| merged_data['dc'].append(merged_dc)
|
| merged_data['point_ids'].append(child_id)
|
| if data['sh_rest'] is not None:
|
| merged_data['sh_rest'].append(merged_sh_rest)
|
| merged_data['filter_3D'].append(merged_filter_3D)
|
|
|
|
|
| cell_lineage[child_id] = parent_ids
|
|
|
| for key in merged_data:
|
| if merged_data[key] is not None and len(merged_data[key]) > 0:
|
| merged_data[key] = np.array(merged_data[key])
|
|
|
| return merged_data, cell_lineage
|
|
|
|
|
| def validate_data(merged_data):
|
| print("\n" + "="*60 + "\n数据验证报告\n" + "="*60)
|
| total = len(merged_data['positions'])
|
| has_nan = np.zeros(total, dtype=bool)
|
| has_inf = np.zeros(total, dtype=bool)
|
| for key in ['positions', 'opacities', 'scales', 'rotations', 'dc']:
|
| arr = merged_data[key]
|
| if arr.ndim == 1:
|
| has_nan |= np.isnan(arr)
|
| has_inf |= np.isinf(arr)
|
| else:
|
| has_nan |= np.isnan(arr).any(axis=1)
|
| has_inf |= np.isinf(arr).any(axis=1)
|
| print(f"总点数: {total} NaN点: {has_nan.sum()} Inf点: {has_inf.sum()}")
|
| print("="*60 + "\n")
|
| return {'has_nan': has_nan.sum(), 'has_inf': has_inf.sum(), 'total': total}
|
|
|
|
|
| def save_ply(merged_data, original_plydata, output_path):
|
| n_points = len(merged_data['positions'])
|
| dtype_list = [
|
| ('x','f4'),('y','f4'),('z','f4'),('opacity','f4'),
|
| ('scale_0','f4'),('scale_1','f4'),('scale_2','f4'),
|
| ('rot_0','f4'),('rot_1','f4'),('rot_2','f4'),('rot_3','f4'),
|
| ('f_dc_0','f4'),('f_dc_1','f4'),('f_dc_2','f4'),
|
| ('point_id', 'i8'),
|
| ]
|
| n_sh = 0
|
| if merged_data['sh_rest'] is not None:
|
| n_sh = merged_data['sh_rest'].shape[1]
|
| dtype_list += [(f'f_rest_{i}','f4') for i in range(n_sh)]
|
| if merged_data.get('filter_3D') is not None:
|
| dtype_list.append(('filter_3D','f4'))
|
|
|
| vd = np.empty(n_points, dtype=dtype_list)
|
| vd['x'] = merged_data['positions'][:,0]
|
| vd['y'] = merged_data['positions'][:,1]
|
| vd['z'] = merged_data['positions'][:,2]
|
| vd['opacity'] = merged_data['opacities'].flatten()
|
| vd['scale_0'] = np.log(merged_data['scales'][:,0])
|
| vd['scale_1'] = np.log(merged_data['scales'][:,1])
|
| vd['scale_2'] = np.log(merged_data['scales'][:,2])
|
| vd['rot_0'] = merged_data['rotations'][:,0]
|
| vd['rot_1'] = merged_data['rotations'][:,1]
|
| vd['rot_2'] = merged_data['rotations'][:,2]
|
| vd['rot_3'] = merged_data['rotations'][:,3]
|
| vd['f_dc_0'] = merged_data['dc'][:,0]
|
| vd['f_dc_1'] = merged_data['dc'][:,1]
|
| vd['f_dc_2'] = merged_data['dc'][:,2]
|
| vd['point_id'] = merged_data['point_ids'].astype(np.int64)
|
| if merged_data['sh_rest'] is not None:
|
| for i in range(n_sh):
|
| vd[f'f_rest_{i}'] = merged_data['sh_rest'][:,i]
|
| if merged_data.get('filter_3D') is not None:
|
| vd['filter_3D'] = merged_data['filter_3D'].flatten()
|
|
|
| PlyData([PlyElement.describe(vd, 'vertex')]).write(output_path)
|
|
|
|
|
|
|
|
|
|
|
|
|
| def run_merge(data, compress_ratio=4, k_neighbors=5,
|
| spread_factor=0.0, aspect_ratio_threshold=15.0,
|
| id_counter=None):
|
| """
|
| 对整份数据执行一次 merge,返回合并后数据和本级族谱。
|
|
|
| 族谱格式(level_lineage):
|
| dict { child_point_id(int): [parent_point_id(int), ...] }
|
| 与点的存储顺序完全无关,通过 point_id 唯一定位每个点。
|
|
|
| id_counter: [int],跨 cell 全局唯一ID生成器,由外部传入以保证跨级唯一性。
|
| """
|
| if id_counter is None:
|
| id_counter = [0]
|
|
|
| n_input = len(data['positions'])
|
| cells = build_octree(data['positions'], max_points=5000)
|
| print(f"划分为 {len(cells)} 个 cells")
|
|
|
| all_merged = {
|
| 'positions': [], 'opacities': [], 'scales': [], 'rotations': [],
|
| 'dc': [], 'sh_rest': [] if data['sh_rest'] is not None else None,
|
| 'filter_3D': [], 'point_ids': []
|
| }
|
| level_lineage = {}
|
|
|
| for i, cell in enumerate(cells):
|
| if i % 100 == 0:
|
| print(f" 处理进度: {i}/{len(cells)}")
|
|
|
| merged, cell_lineage = cluster_and_merge_cell(
|
| data, cell['indices'], cell['bbox_min'], cell['bbox_max'],
|
| k_neighbors=k_neighbors, spread_factor=spread_factor,
|
| aspect_ratio_threshold=aspect_ratio_threshold,
|
| compress_ratio=compress_ratio,
|
| id_counter=id_counter,
|
| )
|
| if merged is None:
|
| continue
|
|
|
| for key in all_merged:
|
| if all_merged[key] is not None and len(merged[key]) > 0:
|
| all_merged[key].append(merged[key])
|
|
|
| level_lineage.update(cell_lineage)
|
|
|
| final_data = {
|
| key: np.concatenate(all_merged[key], axis=0)
|
| for key in all_merged
|
| if all_merged[key] is not None and len(all_merged[key]) > 0
|
| }
|
| n_merged = len(final_data['positions'])
|
| print(f"合并后点数: {n_merged} 压缩率: {n_merged/n_input*100:.2f}%")
|
|
|
| return final_data, level_lineage
|
|
|
|
|
|
|
|
|
|
|
|
|
| def finetune_merged_gaussians(
|
| merged_ply_path,
|
| original_source_path,
|
| output_ply_path,
|
| image_resolution=1,
|
| sh_degree=3,
|
| num_epochs=500,
|
| lr_opacity=0.05,
|
| lr_scaling=0.005,
|
| lr_rotation=0.001,
|
| lr_features_dc=0.0025,
|
| lr_features_rest=0.000125,
|
| white_background=False,
|
| kernel_size=0.1,
|
| gpu_id=0,
|
| log_interval=50,
|
| ):
|
| """
|
| 冻结高斯点位置,用下采样 GT 图像对其余参数做 fine-tuning。
|
|
|
| original_source_path : 原始分辨率 COLMAP 目录,程序内部自动 in-memory 下采样。
|
| image_resolution : GT 图像边长缩小倍率(1=原图, 2=1/2边长, 4=1/4边长, 8=1/8边长)。
|
| """
|
| import torch
|
| import torch.nn.functional as F
|
| from gaussian_renderer import render, GaussianModel
|
| from scene.dataset_readers import sceneLoadTypeCallbacks
|
| from utils.camera_utils import loadCam
|
| from utils.loss_utils import l1_loss, ssim
|
| import random
|
|
|
| device = f'cuda:{gpu_id}'
|
| torch.cuda.set_device(device)
|
| bg_color = [1,1,1] if white_background else [0,0,0]
|
| background = torch.tensor(bg_color, dtype=torch.float32, device=device)
|
|
|
|
|
| print("\n[Fine-tune] 加载 merge 后的高斯模型...")
|
| gaussians = GaussianModel(sh_degree)
|
| gaussians.load_ply(merged_ply_path)
|
| print(f"[Fine-tune] 高斯点数: {gaussians.get_xyz.shape[0]}")
|
|
|
|
|
| gaussians._xyz.requires_grad_(False)
|
| optimizer = torch.optim.Adam([
|
| {'params': [gaussians._features_dc], 'lr': lr_features_dc, 'name': 'f_dc'},
|
| {'params': [gaussians._features_rest], 'lr': lr_features_rest, 'name': 'f_rest'},
|
| {'params': [gaussians._opacity], 'lr': lr_opacity, 'name': 'opacity'},
|
| {'params': [gaussians._scaling], 'lr': lr_scaling, 'name': 'scaling'},
|
| {'params': [gaussians._rotation], 'lr': lr_rotation, 'name': 'rotation'},
|
| ], eps=1e-15)
|
|
|
|
|
| print(f"[Fine-tune] 读取相机,GT 将 in-memory 下采样 1/{image_resolution} 边长...")
|
| if os.path.exists(os.path.join(original_source_path, "sparse")):
|
| scene_info = sceneLoadTypeCallbacks["Colmap"](
|
| original_source_path, "images", eval=False, resolution=1)
|
| elif os.path.exists(os.path.join(original_source_path, "transforms_train.json")):
|
| scene_info = sceneLoadTypeCallbacks["Blender"](
|
| original_source_path, white_background, eval=False, resolution=1)
|
| else:
|
| raise ValueError(f"[Fine-tune] 无法识别数据集格式: {original_source_path}")
|
|
|
| class _LoadArgs:
|
| resolution = 1
|
| data_device = device
|
|
|
| cameras = []
|
| for i, ci in enumerate(scene_info.train_cameras):
|
| try:
|
| cameras.append(loadCam(_LoadArgs(), i, ci, 1.0, load_image=True))
|
| except Exception as e:
|
| print(f"[Fine-tune] 跳过相机 {i}: {e}")
|
|
|
| if not cameras:
|
| raise RuntimeError("[Fine-tune] 没有可用的训练相机。")
|
|
|
|
|
| if image_resolution > 1:
|
| print(f"[Fine-tune] 对 {len(cameras)} 个相机做 1/{image_resolution} 边长下采样...")
|
| for cam in cameras:
|
| gt_orig = cam.original_image.to(device)
|
| H, W = gt_orig.shape[1], gt_orig.shape[2]
|
| new_H, new_W = H // image_resolution, W // image_resolution
|
| cam.original_image = F.interpolate(
|
| gt_orig.unsqueeze(0), size=(new_H, new_W),
|
| mode='bilinear', align_corners=False
|
| ).squeeze(0).cpu()
|
|
|
| cam.image_width = new_W
|
| cam.image_height = new_H
|
| print(f"[Fine-tune] 下采样后尺寸: {cameras[0].image_height} x {cameras[0].image_width}")
|
|
|
|
|
| class _Pipeline:
|
| convert_SHs_python = False
|
| compute_cov3D_python = False
|
| debug = False
|
|
|
| pipeline = _Pipeline()
|
| lambda_dssim = 0.2
|
|
|
| print(f"\n[Fine-tune] 开始优化,共 {num_epochs} epochs,{len(cameras)} 张图像...")
|
| for epoch in range(1, num_epochs + 1):
|
| random.shuffle(cameras)
|
| epoch_loss = 0.0
|
| for cam in cameras:
|
| optimizer.zero_grad()
|
| rendered = render(cam, gaussians, pipeline, background, kernel_size=kernel_size)["render"]
|
| gt = cam.original_image.to(device)
|
| if rendered.shape != gt.shape:
|
| gt = F.interpolate(gt.unsqueeze(0), size=rendered.shape[1:],
|
| mode='bilinear', align_corners=False).squeeze(0)
|
| loss = (1.0 - lambda_dssim) * l1_loss(rendered, gt) \
|
| + lambda_dssim * (1.0 - ssim(rendered, gt))
|
| loss.backward()
|
| optimizer.step()
|
| epoch_loss += loss.item()
|
| if epoch % log_interval == 0 or epoch == 1:
|
| print(f"[Fine-tune] Epoch {epoch:4d}/{num_epochs} avg_loss={epoch_loss/len(cameras):.6f}")
|
|
|
|
|
| print(f"\n[Fine-tune] 保存至 {output_ply_path} ...")
|
| os.makedirs(os.path.dirname(os.path.abspath(output_ply_path)), exist_ok=True)
|
| gaussians.save_ply(output_ply_path)
|
| print("[Fine-tune] 保存完成。")
|
|
|
|
|
|
|
|
|
|
|
|
|
| def run_all(
|
| input_ply,
|
| original_source_path,
|
| output_base,
|
|
|
| k_neighbors=5,
|
| spread_factor=0.0,
|
| aspect_ratio_threshold=15.0,
|
|
|
| sh_degree=3,
|
| num_epochs=500,
|
| lr_opacity=0.05,
|
| lr_scaling=0.005,
|
| lr_rotation=0.001,
|
| lr_features_dc=0.0025,
|
| lr_features_rest=0.000125,
|
| white_background=False,
|
| kernel_size=0.1,
|
| gpu_id=0,
|
| log_interval=50,
|
| ):
|
| """
|
| 完整流程:级联 merge(三级)+ 每级 fine-tune + 族谱保存。
|
|
|
| 输出目录结构:
|
| output_base/
|
| ├── L1/
|
| │ ├── merged.ply # 1/4 点数,merge 后未微调
|
| │ └── finetuned.ply # 1/4 点数,微调后
|
| ├── L2/
|
| │ ├── merged.ply # 1/16 点数
|
| │ └── finetuned.ply
|
| ├── L3/
|
| │ ├── merged.ply # 1/64 点数
|
| │ └── finetuned.ply
|
| └── lineage.json # 完整族谱
|
|
|
| 族谱结构(lineage.json):
|
| {
|
| "L1": [[idx, ...], [idx, ...], ...],
|
| // L1[i] = 原始 PLY 中哪些点合并成了 L1 第 i 个点
|
|
|
| "L2": [[idx, ...], ...],
|
| // L2[i] = L1 finetuned PLY 中哪些点合并成了 L2 第 i 个点
|
|
|
| "L3": [[idx, ...], ...]
|
| // L3[i] = L2 finetuned PLY 中哪些点合并成了 L3 第 i 个点
|
| }
|
|
|
| 层级恢复示例(从 L3 追溯到原始点):
|
| L3[i] 由 L2 中的 lineage["L3"][i] 合并而来
|
| 其中 L2[j] 又由 L1 中的 lineage["L2"][j] 合并而来
|
| 其中 L1[k] 又由原始点中的 lineage["L1"][k] 合并而来
|
| """
|
|
|
|
|
|
|
| levels = [
|
| ("L1", 2),
|
| ("L2", 4),
|
| ("L3", 8),
|
| ]
|
|
|
| finetune_kwargs = dict(
|
| original_source_path=original_source_path,
|
| sh_degree=sh_degree,
|
| num_epochs=num_epochs,
|
| lr_opacity=lr_opacity,
|
| lr_scaling=lr_scaling,
|
| lr_rotation=lr_rotation,
|
| lr_features_dc=lr_features_dc,
|
| lr_features_rest=lr_features_rest,
|
| white_background=white_background,
|
| kernel_size=kernel_size,
|
| gpu_id=gpu_id,
|
| log_interval=log_interval,
|
| )
|
|
|
| merge_kwargs = dict(
|
| compress_ratio=4,
|
| k_neighbors=k_neighbors,
|
| spread_factor=spread_factor,
|
| aspect_ratio_threshold=aspect_ratio_threshold,
|
| )
|
|
|
|
|
|
|
|
|
|
|
| current_data = read_ply(input_ply)
|
| n_original = len(current_data['positions'])
|
| id_counter = [n_original]
|
| full_lineage = {}
|
| current_ply_path = input_ply
|
|
|
| for level, image_resolution in levels:
|
| print("\n" + "=" * 70)
|
| print(f"级别: {level} | 本级压缩 1/4 | 图像边长缩小 1/{image_resolution}")
|
| print(f"输入 PLY: {current_ply_path}")
|
| print("=" * 70)
|
|
|
| level_dir = os.path.join(output_base, level)
|
| merged_ply = os.path.join(level_dir, "merged.ply")
|
| finetuned_ply = os.path.join(level_dir, "finetuned.ply")
|
| os.makedirs(level_dir, exist_ok=True)
|
|
|
|
|
| print(f"\n[{level}] Step 1: Merge")
|
| final_data, level_lineage = run_merge(
|
| current_data, id_counter=id_counter, **merge_kwargs)
|
|
|
| result = validate_data(final_data)
|
| if result['has_nan'] or result['has_inf']:
|
| print(f"⚠️ NaN={result['has_nan']} Inf={result['has_inf']}")
|
|
|
| save_ply(final_data, current_data['plydata'], merged_ply)
|
| print(f"[{level}] Merge PLY 已保存: {merged_ply}")
|
|
|
|
|
|
|
| full_lineage[level] = {str(k): v for k, v in level_lineage.items()}
|
| lineage_path = os.path.join(output_base, "lineage.json")
|
| with open(lineage_path, 'w') as f:
|
| json.dump(full_lineage, f)
|
| print(f"[{level}] 族谱已保存(当前已完成: {list(full_lineage.keys())})")
|
|
|
|
|
| print(f"\n[{level}] Step 2: Fine-tune (image_resolution=1/{image_resolution})")
|
| finetune_merged_gaussians(
|
| merged_ply_path=merged_ply,
|
| output_ply_path=finetuned_ply,
|
| image_resolution=image_resolution,
|
| **finetune_kwargs,
|
| )
|
|
|
|
|
| current_ply_path = finetuned_ply
|
| current_data = read_ply(finetuned_ply)
|
|
|
|
|
| lineage_path = os.path.join(output_base, "lineage.json")
|
| print(f"\n✅ 族谱完整保存至: {lineage_path}")
|
|
|
| print("\n🎉 所有级别完成!")
|
| print(f"输出目录: {output_base}")
|
| print(" L1/merged.ply, L1/finetuned.ply — 1/4 点数")
|
| print(" L2/merged.ply, L2/finetuned.ply — 1/16 点数")
|
| print(" L3/merged.ply, L3/finetuned.ply — 1/64 点数")
|
| print(" lineage.json — 完整族谱")
|
|
|
|
|
|
|
|
|
|
|
|
|
| def load_lineage(lineage_path):
|
| """加载族谱文件"""
|
| with open(lineage_path, 'r') as f:
|
| lineage = json.load(f)
|
| return lineage
|
|
|
|
|
| def trace_to_original(child_point_id, level, lineage):
|
| """
|
| 从某一级的点(通过 point_id 指定)追溯到原始点的 point_id 集合。
|
|
|
| 参数:
|
| child_point_id : 要追溯的点的 point_id(int 或 str 均可)
|
| level : 该点所在级别,"L1" / "L2" / "L3"
|
| lineage : load_lineage() 返回的族谱 dict
|
|
|
| 返回:
|
| List[int],原始 PLY 中的 point_id 列表(即 0 ~ N_original-1 范围内的值)
|
|
|
| 示例:
|
| lineage = load_lineage("low_results/lineage.json")
|
| # 查询 L3 中 point_id=500100 的点对应的所有原始点
|
| orig_ids = trace_to_original(500100, "L3", lineage)
|
| """
|
| levels = ["L1", "L2", "L3"]
|
| level_idx = levels.index(level)
|
|
|
|
|
| current_ids = lineage[level][str(child_point_id)]
|
|
|
|
|
| for parent_level in reversed(levels[:level_idx]):
|
| next_ids = []
|
| for pid in current_ids:
|
|
|
| key = str(pid)
|
| if key in lineage[parent_level]:
|
| next_ids.extend(lineage[parent_level][key])
|
| else:
|
| next_ids.append(pid)
|
| current_ids = next_ids
|
|
|
| return [int(x) for x in current_ids]
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| if __name__ == "__main__":
|
|
|
| run_all(
|
| input_ply = "merge/original_3dgs.ply",
|
| original_source_path = "data",
|
| output_base = "outputs",
|
|
|
|
|
| k_neighbors=5,
|
| spread_factor=0.0,
|
| aspect_ratio_threshold=15.0,
|
|
|
|
|
| sh_degree=3,
|
| num_epochs=250,
|
| lr_opacity=0.05,
|
| lr_scaling=0.005,
|
| lr_rotation=0.001,
|
| lr_features_dc=0.0025,
|
| lr_features_rest=0.000125,
|
| white_background=False,
|
| kernel_size=0.1,
|
| gpu_id=2,
|
| log_interval=50,
|
| ) |