|
|
import numpy as np
|
|
|
import torch
|
|
|
from sklearn.cluster import AgglomerativeClustering
|
|
|
from plyfile import PlyData, PlyElement
|
|
|
import os
|
|
|
from pathlib import Path
|
|
|
|
|
|
|
|
|
from skimage.metrics import structural_similarity as ssim
|
|
|
from skimage.metrics import peak_signal_noise_ratio as psnr
|
|
|
import lpips
|
|
|
import cv2
|
|
|
|
|
|
class GaussianMerger:
|
|
|
"""
|
|
|
3DGS聚类Merge实现
|
|
|
核心思路:
|
|
|
1. 空间划分为带padding的cells
|
|
|
2. 在每个cell内使用AgglomerativeClustering聚类
|
|
|
3. 使用矩匹配合并高斯参数
|
|
|
4. 只保留中心在no-padding区域的簇
|
|
|
"""
|
|
|
def __init__(self, cell_size, padding_ratio=0.1, target_points_per_cluster=3):
|
|
|
"""
|
|
|
Args:
|
|
|
cell_size: float, cell边长
|
|
|
padding_ratio: float, padding占边长的比例
|
|
|
target_points_per_cluster: int, 目标每簇点数(2-4)
|
|
|
"""
|
|
|
self.cell_size = cell_size
|
|
|
self.padding_ratio = padding_ratio
|
|
|
self.padding_size = cell_size * padding_ratio
|
|
|
self.target_points_per_cluster = target_points_per_cluster
|
|
|
|
|
|
|
|
|
|
|
|
self.feature_weights = {
|
|
|
'position': 1.0,
|
|
|
'opacity': 1.0,
|
|
|
'sh': 0.2,
|
|
|
}
|
|
|
|
|
|
def load_ply(self, ply_path):
|
|
|
"""
|
|
|
加载3DGS的.ply文件
|
|
|
|
|
|
3DGS数据格式:
|
|
|
- xyz: 3个坐标
|
|
|
- opacity: 1个不透明度
|
|
|
- f_dc_0/1/2: DC分量(3维)
|
|
|
- f_rest_0~44: SH系数(45维,对应RGB各15个三阶SH系数)
|
|
|
- scale_0/1/2: 3个尺度
|
|
|
- rot_0/1/2/3: 四元数旋转(4维)
|
|
|
|
|
|
Returns:
|
|
|
dict: {
|
|
|
'xyz': (N,3),
|
|
|
'opacity': (N,1),
|
|
|
'dc': (N,3), DC颜色分量
|
|
|
'sh': (N,45), SH系数
|
|
|
'scale': (N,3),
|
|
|
'rotation': (N,4) 四元数 [w,x,y,z]
|
|
|
}
|
|
|
"""
|
|
|
print(f"Loading 3DGS from {ply_path}...")
|
|
|
plydata = PlyData.read(ply_path)
|
|
|
vertices = plydata['vertex']
|
|
|
|
|
|
|
|
|
xyz = np.stack([vertices['x'], vertices['y'], vertices['z']], axis=1)
|
|
|
|
|
|
|
|
|
opacity = vertices['opacity'][:, np.newaxis]
|
|
|
|
|
|
|
|
|
dc = np.stack([vertices['f_dc_0'], vertices['f_dc_1'], vertices['f_dc_2']], axis=1)
|
|
|
|
|
|
|
|
|
sh_features = []
|
|
|
for i in range(45):
|
|
|
sh_features.append(vertices[f'f_rest_{i}'])
|
|
|
sh = np.stack(sh_features, axis=1)
|
|
|
|
|
|
|
|
|
scale = np.stack([vertices['scale_0'], vertices['scale_1'], vertices['scale_2']], axis=1)
|
|
|
|
|
|
|
|
|
rotation = np.stack([vertices['rot_0'], vertices['rot_1'],
|
|
|
vertices['rot_2'], vertices['rot_3']], axis=1)
|
|
|
|
|
|
print(f"Loaded {len(xyz)} Gaussians")
|
|
|
print(f"Scene bounds: {xyz.min(axis=0)} to {xyz.max(axis=0)}")
|
|
|
|
|
|
return {
|
|
|
'xyz': xyz,
|
|
|
'opacity': opacity,
|
|
|
'dc': dc,
|
|
|
'sh': sh,
|
|
|
'scale': scale,
|
|
|
'rotation': rotation
|
|
|
}
|
|
|
|
|
|
def save_ply(self, gaussians, output_path):
|
|
|
"""
|
|
|
保存merge后的高斯到.ply文件
|
|
|
|
|
|
Args:
|
|
|
gaussians: dict, merge后的高斯参数
|
|
|
output_path: str, 输出路径
|
|
|
"""
|
|
|
print(f"Saving merged 3DGS to {output_path}...")
|
|
|
|
|
|
xyz = gaussians['xyz']
|
|
|
opacity = gaussians['opacity'].flatten()
|
|
|
dc = gaussians['dc']
|
|
|
sh = gaussians['sh']
|
|
|
scale = gaussians['scale']
|
|
|
rotation = gaussians['rotation']
|
|
|
|
|
|
n_points = len(xyz)
|
|
|
|
|
|
|
|
|
dtype_list = [
|
|
|
('x', 'f4'), ('y', 'f4'), ('z', 'f4'),
|
|
|
('opacity', 'f4'),
|
|
|
('f_dc_0', 'f4'), ('f_dc_1', 'f4'), ('f_dc_2', 'f4'),
|
|
|
]
|
|
|
|
|
|
|
|
|
for i in range(45):
|
|
|
dtype_list.append((f'f_rest_{i}', 'f4'))
|
|
|
|
|
|
|
|
|
dtype_list.extend([
|
|
|
('scale_0', 'f4'), ('scale_1', 'f4'), ('scale_2', 'f4'),
|
|
|
('rot_0', 'f4'), ('rot_1', 'f4'), ('rot_2', 'f4'), ('rot_3', 'f4')
|
|
|
])
|
|
|
|
|
|
|
|
|
elements = np.empty(n_points, dtype=dtype_list)
|
|
|
|
|
|
|
|
|
elements['x'] = xyz[:, 0]
|
|
|
elements['y'] = xyz[:, 1]
|
|
|
elements['z'] = xyz[:, 2]
|
|
|
elements['opacity'] = opacity
|
|
|
elements['f_dc_0'] = dc[:, 0]
|
|
|
elements['f_dc_1'] = dc[:, 1]
|
|
|
elements['f_dc_2'] = dc[:, 2]
|
|
|
|
|
|
for i in range(45):
|
|
|
elements[f'f_rest_{i}'] = sh[:, i]
|
|
|
|
|
|
elements['scale_0'] = scale[:, 0]
|
|
|
elements['scale_1'] = scale[:, 1]
|
|
|
elements['scale_2'] = scale[:, 2]
|
|
|
elements['rot_0'] = rotation[:, 0]
|
|
|
elements['rot_1'] = rotation[:, 1]
|
|
|
elements['rot_2'] = rotation[:, 2]
|
|
|
elements['rot_3'] = rotation[:, 3]
|
|
|
|
|
|
|
|
|
el = PlyElement.describe(elements, 'vertex')
|
|
|
|
|
|
|
|
|
PlyData([el]).write(output_path)
|
|
|
print(f"Saved {n_points} merged Gaussians")
|
|
|
|
|
|
def partition_space(self, xyz):
|
|
|
"""
|
|
|
空间划分: 将场景划分为cell网格
|
|
|
|
|
|
策略:
|
|
|
- 每个cell有padding区域用于聚类
|
|
|
- 但只保留中心在no-padding区域的簇
|
|
|
|
|
|
Args:
|
|
|
xyz: (N, 3) 点的位置
|
|
|
Returns:
|
|
|
cell_dict: {cell_id: [point_indices]} cell内的点索引(含padding)
|
|
|
cell_info: {cell_id: {'center', 'bounds_no_padding', 'bounds_with_padding'}}
|
|
|
"""
|
|
|
print("Partitioning space into cells...")
|
|
|
|
|
|
|
|
|
min_bound = xyz.min(axis=0) - self.padding_size
|
|
|
max_bound = xyz.max(axis=0) + self.padding_size
|
|
|
|
|
|
|
|
|
cell_indices = np.floor((xyz - min_bound) / self.cell_size).astype(int)
|
|
|
|
|
|
|
|
|
unique_cells = np.unique(cell_indices, axis=0)
|
|
|
|
|
|
cell_dict = {}
|
|
|
cell_info = {}
|
|
|
|
|
|
for cell_idx in unique_cells:
|
|
|
cell_id = tuple(cell_idx)
|
|
|
|
|
|
|
|
|
cell_min = min_bound + cell_idx * self.cell_size
|
|
|
cell_max = cell_min + self.cell_size
|
|
|
|
|
|
|
|
|
cell_min_padded = cell_min - self.padding_size
|
|
|
cell_max_padded = cell_max + self.padding_size
|
|
|
|
|
|
|
|
|
mask = np.all((xyz >= cell_min_padded) & (xyz < cell_max_padded), axis=1)
|
|
|
point_indices = np.where(mask)[0]
|
|
|
|
|
|
if len(point_indices) > 0:
|
|
|
cell_dict[cell_id] = point_indices
|
|
|
cell_info[cell_id] = {
|
|
|
'center': (cell_min + cell_max) / 2,
|
|
|
'bounds_no_padding': (cell_min, cell_max),
|
|
|
'bounds_with_padding': (cell_min_padded, cell_max_padded)
|
|
|
}
|
|
|
|
|
|
print(f"Created {len(cell_dict)} cells")
|
|
|
points_per_cell = [len(indices) for indices in cell_dict.values()]
|
|
|
print(f"Points per cell: min={min(points_per_cell)}, max={max(points_per_cell)}, avg={np.mean(points_per_cell):.1f}")
|
|
|
|
|
|
return cell_dict, cell_info
|
|
|
|
|
|
def compute_features_for_clustering(self, gaussians, point_indices, cell_bounds):
|
|
|
"""
|
|
|
计算聚类特征: 归一化位置(3) + 不透明度(1) + SH系数(48)
|
|
|
|
|
|
注意:
|
|
|
- 位置需要在padding后的cell内归一化
|
|
|
- SH系数包含DC(3维)和高阶(45维),共48维
|
|
|
- 不同特征使用不同权重
|
|
|
|
|
|
Args:
|
|
|
gaussians: 完整的高斯数据
|
|
|
point_indices: 当前cell内的点索引
|
|
|
cell_bounds: (min_xyz, max_xyz) with padding
|
|
|
Returns:
|
|
|
features: (N, 52) 归一化后的特征向量
|
|
|
"""
|
|
|
xyz = gaussians['xyz'][point_indices]
|
|
|
opacity = gaussians['opacity'][point_indices]
|
|
|
dc = gaussians['dc'][point_indices]
|
|
|
sh = gaussians['sh'][point_indices]
|
|
|
|
|
|
cell_min, cell_max = cell_bounds
|
|
|
cell_size_padded = cell_max - cell_min
|
|
|
|
|
|
|
|
|
normalized_pos = (xyz - cell_min) / cell_size_padded
|
|
|
|
|
|
|
|
|
sh_features = np.concatenate([dc, sh], axis=1)
|
|
|
|
|
|
|
|
|
features = np.concatenate([
|
|
|
normalized_pos * self.feature_weights['position'],
|
|
|
opacity * self.feature_weights['opacity'],
|
|
|
sh_features * self.feature_weights['sh']
|
|
|
], axis=1)
|
|
|
|
|
|
return features
|
|
|
|
|
|
def quaternion_to_rotation_matrix(self, q):
|
|
|
"""
|
|
|
四元数转旋转矩阵
|
|
|
|
|
|
Args:
|
|
|
q: (4,) [w, x, y, z] 或 (N, 4)
|
|
|
Returns:
|
|
|
R: (3, 3) 或 (N, 3, 3)
|
|
|
"""
|
|
|
if q.ndim == 1:
|
|
|
w, x, y, z = q
|
|
|
R = np.array([
|
|
|
[1-2*(y**2+z**2), 2*(x*y-w*z), 2*(x*z+w*y)],
|
|
|
[2*(x*y+w*z), 1-2*(x**2+z**2), 2*(y*z-w*x)],
|
|
|
[2*(x*z-w*y), 2*(y*z+w*x), 1-2*(x**2+y**2)]
|
|
|
])
|
|
|
return R
|
|
|
else:
|
|
|
|
|
|
w, x, y, z = q[:, 0], q[:, 1], q[:, 2], q[:, 3]
|
|
|
R = np.zeros((len(q), 3, 3))
|
|
|
R[:, 0, 0] = 1 - 2*(y**2 + z**2)
|
|
|
R[:, 0, 1] = 2*(x*y - w*z)
|
|
|
R[:, 0, 2] = 2*(x*z + w*y)
|
|
|
R[:, 1, 0] = 2*(x*y + w*z)
|
|
|
R[:, 1, 1] = 1 - 2*(x**2 + z**2)
|
|
|
R[:, 1, 2] = 2*(y*z - w*x)
|
|
|
R[:, 2, 0] = 2*(x*z - w*y)
|
|
|
R[:, 2, 1] = 2*(y*z + w*x)
|
|
|
R[:, 2, 2] = 1 - 2*(x**2 + y**2)
|
|
|
return R
|
|
|
|
|
|
def compute_covariance(self, scale, rotation):
|
|
|
"""
|
|
|
计算协方差矩阵: Σ = R·S·S^T·R^T
|
|
|
|
|
|
Args:
|
|
|
scale: (N, 3) 三个轴的尺度
|
|
|
rotation: (N, 4) 四元数 [w,x,y,z]
|
|
|
Returns:
|
|
|
covariances: (N, 3, 3)
|
|
|
"""
|
|
|
N = len(scale)
|
|
|
R = self.quaternion_to_rotation_matrix(rotation)
|
|
|
|
|
|
|
|
|
S = np.zeros((N, 3, 3))
|
|
|
S[:, 0, 0] = scale[:, 0]
|
|
|
S[:, 1, 1] = scale[:, 1]
|
|
|
S[:, 2, 2] = scale[:, 2]
|
|
|
|
|
|
|
|
|
covariances = np.einsum('nij,njk,nlk,nli->nil', R, S, S, R)
|
|
|
|
|
|
return covariances
|
|
|
|
|
|
def moment_matching(self, means, covariances, opacities, scales):
|
|
|
"""
|
|
|
矩匹配: 合并多个高斯分布
|
|
|
|
|
|
公式:
|
|
|
- 权重: wi = opacity_i * volume_i
|
|
|
- 新均值: μ_new = Σ(wi * μi) / Σwi
|
|
|
- 新协方差: Σ_new = Σ(wi * (Σi + (μi-μ_new)(μi-μ_new)^T)) / Σwi
|
|
|
- 新不透明度: 质量守恒,Σ(opacity_i * volume_i) = opacity_new * volume_new
|
|
|
|
|
|
Args:
|
|
|
means: (K, 3) 各高斯均值
|
|
|
covariances: (K, 3, 3) 各高斯协方差矩阵
|
|
|
opacities: (K, 1) 不透明度
|
|
|
scales: (K, 3) 尺度
|
|
|
Returns:
|
|
|
new_mean: (3,)
|
|
|
new_covariance: (3, 3)
|
|
|
new_opacity: float
|
|
|
new_scale: (3,)
|
|
|
new_rotation: (4,) 四元数
|
|
|
"""
|
|
|
|
|
|
scale_volumes = np.prod(scales, axis=1, keepdims=True)
|
|
|
weights = opacities * scale_volumes
|
|
|
total_weight = weights.sum()
|
|
|
weights_normalized = weights / total_weight
|
|
|
|
|
|
|
|
|
new_mean = np.sum(weights_normalized * means, axis=0)
|
|
|
|
|
|
|
|
|
mean_diff = means - new_mean
|
|
|
outer_products = np.einsum('ki,kj->kij', mean_diff, mean_diff)
|
|
|
|
|
|
new_covariance = np.sum(
|
|
|
weights_normalized[:, :, np.newaxis] * (covariances + outer_products),
|
|
|
axis=0
|
|
|
)
|
|
|
|
|
|
|
|
|
|
|
|
eigenvalues, eigenvectors = np.linalg.eigh(new_covariance)
|
|
|
|
|
|
|
|
|
new_scale = np.sqrt(np.abs(eigenvalues))
|
|
|
new_scale_volume = np.prod(new_scale)
|
|
|
|
|
|
|
|
|
|
|
|
if new_scale_volume > 1e-10:
|
|
|
new_opacity = total_weight / new_scale_volume
|
|
|
new_opacity = np.clip(new_opacity, 0, 1)
|
|
|
else:
|
|
|
new_opacity = np.mean(opacities)
|
|
|
|
|
|
|
|
|
R_new = eigenvectors
|
|
|
|
|
|
|
|
|
new_rotation = self.rotation_matrix_to_quaternion(R_new)
|
|
|
|
|
|
return new_mean, new_covariance, new_opacity, new_scale, new_rotation
|
|
|
|
|
|
def rotation_matrix_to_quaternion(self, R):
|
|
|
"""
|
|
|
旋转矩阵转四元数 [w, x, y, z]
|
|
|
使用Shepperd方法,数值稳定
|
|
|
"""
|
|
|
trace = np.trace(R)
|
|
|
|
|
|
if trace > 0:
|
|
|
s = 0.5 / np.sqrt(trace + 1.0)
|
|
|
w = 0.25 / s
|
|
|
x = (R[2, 1] - R[1, 2]) * s
|
|
|
y = (R[0, 2] - R[2, 0]) * s
|
|
|
z = (R[1, 0] - R[0, 1]) * s
|
|
|
elif R[0, 0] > R[1, 1] and R[0, 0] > R[2, 2]:
|
|
|
s = 2.0 * np.sqrt(1.0 + R[0, 0] - R[1, 1] - R[2, 2])
|
|
|
w = (R[2, 1] - R[1, 2]) / s
|
|
|
x = 0.25 * s
|
|
|
y = (R[0, 1] + R[1, 0]) / s
|
|
|
z = (R[0, 2] + R[2, 0]) / s
|
|
|
elif R[1, 1] > R[2, 2]:
|
|
|
s = 2.0 * np.sqrt(1.0 + R[1, 1] - R[0, 0] - R[2, 2])
|
|
|
w = (R[0, 2] - R[2, 0]) / s
|
|
|
x = (R[0, 1] + R[1, 0]) / s
|
|
|
y = 0.25 * s
|
|
|
z = (R[1, 2] + R[2, 1]) / s
|
|
|
else:
|
|
|
s = 2.0 * np.sqrt(1.0 + R[2, 2] - R[0, 0] - R[1, 1])
|
|
|
w = (R[1, 0] - R[0, 1]) / s
|
|
|
x = (R[0, 2] + R[2, 0]) / s
|
|
|
y = (R[1, 2] + R[2, 1]) / s
|
|
|
z = 0.25 * s
|
|
|
|
|
|
q = np.array([w, x, y, z])
|
|
|
q = q / np.linalg.norm(q)
|
|
|
return q
|
|
|
|
|
|
def cluster_and_merge_cell(self, gaussians, point_indices, cell_info):
|
|
|
"""
|
|
|
在单个cell内进行聚类和merge
|
|
|
|
|
|
流程:
|
|
|
1. 提取padding区域内的所有点
|
|
|
2. 计算聚类特征(归一化位置+不透明度+SH)
|
|
|
3. 使用AgglomerativeClustering聚类
|
|
|
4. 对每个簇使用矩匹配合并
|
|
|
5. 只保留中心在no-padding区域的簇
|
|
|
|
|
|
Args:
|
|
|
gaussians: 完整的高斯数据dict
|
|
|
point_indices: 当前cell内的点索引 (包含padding区域)
|
|
|
cell_info: cell的边界信息
|
|
|
Returns:
|
|
|
merged_gaussians: dict, merge后的高斯参数
|
|
|
"""
|
|
|
if len(point_indices) == 0:
|
|
|
return None
|
|
|
|
|
|
|
|
|
xyz = gaussians['xyz'][point_indices]
|
|
|
|
|
|
|
|
|
cell_bounds = cell_info['bounds_with_padding']
|
|
|
features = self.compute_features_for_clustering(gaussians, point_indices, cell_bounds)
|
|
|
|
|
|
|
|
|
n_clusters = max(1, len(point_indices) // self.target_points_per_cluster)
|
|
|
|
|
|
|
|
|
clustering = AgglomerativeClustering(
|
|
|
n_clusters=n_clusters,
|
|
|
metric='euclidean',
|
|
|
linkage='ward'
|
|
|
)
|
|
|
labels = clustering.fit_predict(features)
|
|
|
|
|
|
|
|
|
merged_results = {
|
|
|
'xyz': [],
|
|
|
'opacity': [],
|
|
|
'dc': [],
|
|
|
'sh': [],
|
|
|
'scale': [],
|
|
|
'rotation': []
|
|
|
}
|
|
|
|
|
|
no_padding_min, no_padding_max = cell_info['bounds_no_padding']
|
|
|
|
|
|
for cluster_id in range(n_clusters):
|
|
|
cluster_mask = labels == cluster_id
|
|
|
cluster_point_indices = point_indices[cluster_mask]
|
|
|
|
|
|
if len(cluster_point_indices) == 0:
|
|
|
continue
|
|
|
|
|
|
|
|
|
cluster_xyz = gaussians['xyz'][cluster_point_indices]
|
|
|
cluster_opacity = gaussians['opacity'][cluster_point_indices]
|
|
|
cluster_dc = gaussians['dc'][cluster_point_indices]
|
|
|
cluster_sh = gaussians['sh'][cluster_point_indices]
|
|
|
cluster_scale = gaussians['scale'][cluster_point_indices]
|
|
|
cluster_rotation = gaussians['rotation'][cluster_point_indices]
|
|
|
|
|
|
|
|
|
cluster_covariances = self.compute_covariance(cluster_scale, cluster_rotation)
|
|
|
|
|
|
|
|
|
new_mean, new_cov, new_opacity, new_scale, new_rotation = self.moment_matching(
|
|
|
cluster_xyz, cluster_covariances, cluster_opacity, cluster_scale
|
|
|
)
|
|
|
|
|
|
|
|
|
if np.all(new_mean >= no_padding_min) and np.all(new_mean < no_padding_max):
|
|
|
|
|
|
scale_volumes = np.prod(cluster_scale, axis=1, keepdims=True)
|
|
|
weights = cluster_opacity * scale_volumes
|
|
|
weights = weights / weights.sum()
|
|
|
|
|
|
new_dc = np.sum(weights * cluster_dc, axis=0)
|
|
|
new_sh = np.sum(weights * cluster_sh, axis=0)
|
|
|
|
|
|
|
|
|
merged_results['xyz'].append(new_mean)
|
|
|
merged_results['opacity'].append([new_opacity])
|
|
|
merged_results['dc'].append(new_dc)
|
|
|
merged_results['sh'].append(new_sh)
|
|
|
merged_results['scale'].append(new_scale)
|
|
|
merged_results['rotation'].append(new_rotation)
|
|
|
|
|
|
|
|
|
if len(merged_results['xyz']) == 0:
|
|
|
return None
|
|
|
|
|
|
for key in merged_results:
|
|
|
merged_results[key] = np.array(merged_results[key])
|
|
|
|
|
|
return merged_results
|
|
|
|
|
|
def merge_all(self, gaussians):
|
|
|
"""
|
|
|
对所有cell进行聚类merge
|
|
|
|
|
|
Args:
|
|
|
gaussians: 原始高斯数据
|
|
|
Returns:
|
|
|
merged_gaussians: merge后的高斯数据
|
|
|
"""
|
|
|
|
|
|
cell_dict, cell_info = self.partition_space(gaussians['xyz'])
|
|
|
|
|
|
|
|
|
all_merged = {
|
|
|
'xyz': [],
|
|
|
'opacity': [],
|
|
|
'dc': [],
|
|
|
'sh': [],
|
|
|
'scale': [],
|
|
|
'rotation': []
|
|
|
}
|
|
|
|
|
|
total_cells = len(cell_dict)
|
|
|
for idx, (cell_id, point_indices) in enumerate(cell_dict.items()):
|
|
|
if (idx + 1) % 100 == 0:
|
|
|
print(f"Processing cell {idx+1}/{total_cells}...")
|
|
|
|
|
|
merged = self.cluster_and_merge_cell(gaussians, point_indices, cell_info[cell_id])
|
|
|
|
|
|
if merged is not None:
|
|
|
for key in all_merged:
|
|
|
all_merged[key].append(merged[key])
|
|
|
|
|
|
|
|
|
final_merged = {}
|
|
|
for key in all_merged:
|
|
|
final_merged[key] = np.concatenate(all_merged[key], axis=0)
|
|
|
|
|
|
print(f"\nMerge Statistics:")
|
|
|
print(f" Original points: {len(gaussians['xyz'])}")
|
|
|
print(f" Merged points: {len(final_merged['xyz'])}")
|
|
|
print(f" Compression ratio: {len(gaussians['xyz']) / len(final_merged['xyz']):.2f}x")
|
|
|
|
|
|
return final_merged
|
|
|
|
|
|
|
|
|
class ImageEvaluator:
|
|
|
"""
|
|
|
图像质量评估
|
|
|
支持: PSNR, SSIM, LPIPS, NIQE, FID, MEt3R
|
|
|
"""
|
|
|
def __init__(self, device='cuda' if torch.cuda.is_available() else 'cpu'):
|
|
|
self.device = device
|
|
|
|
|
|
|
|
|
self.lpips_model = lpips.LPIPS(net='alex').to(device)
|
|
|
|
|
|
def load_image(self, image_path):
|
|
|
"""
|
|
|
加载图像,支持jpg和png
|
|
|
Returns:
|
|
|
img: (H, W, 3) numpy array, range [0, 1]
|
|
|
"""
|
|
|
img = cv2.imread(image_path)
|
|
|
img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)
|
|
|
img = img.astype(np.float32) / 255.0
|
|
|
return img
|
|
|
|
|
|
def compute_psnr(self, img1, img2):
|
|
|
"""
|
|
|
计算PSNR
|
|
|
"""
|
|
|
return psnr(img1, img2, data_range=1.0)
|
|
|
|
|
|
def compute_ssim(self, img1, img2):
|
|
|
"""
|
|
|
计算SSIM
|
|
|
"""
|
|
|
return ssim(img1, img2, multichannel=True, data_range=1.0, channel_axis=2)
|
|
|
|
|
|
def compute_lpips(self, img1, img2):
|
|
|
"""
|
|
|
计算LPIPS (需要转换为tensor)
|
|
|
"""
|
|
|
|
|
|
img1_t = torch.from_numpy(img1).permute(2, 0, 1).unsqueeze(0).to(self.device)
|
|
|
img2_t = torch.from_numpy(img2).permute(2, 0, 1).unsqueeze(0).to(self.device)
|
|
|
|
|
|
|
|
|
img1_t = img1_t * 2 - 1
|
|
|
img2_t = img2_t * 2 - 1
|
|
|
|
|
|
with torch.no_grad():
|
|
|
lpips_value = self.lpips_model(img1_t, img2_t).item()
|
|
|
|
|
|
return lpips_value
|
|
|
|
|
|
def compute_niqe(self, img):
|
|
|
"""
|
|
|
计算NIQE (无参考图像质量评估)
|
|
|
注意: 需要安装piq库或使用opencv实现
|
|
|
这里使用简化版本
|
|
|
"""
|
|
|
try:
|
|
|
import piq
|
|
|
img_t = torch.from_numpy(img).permute(2, 0, 1).unsqueeze(0).to(self.device)
|
|
|
niqe_value = piq.niqe(img_t).item()
|
|
|
return niqe_value
|
|
|
except:
|
|
|
print("Warning: NIQE requires 'piq' library. Returning 0.")
|
|
|
return 0.0
|
|
|
|
|
|
def compute_fid(self, real_images, fake_images):
|
|
|
"""
|
|
|
计算FID (Frechet Inception Distance)
|
|
|
需要多张图像,这里提供接口
|
|
|
|
|
|
Args:
|
|
|
real_images: list of image paths or numpy arrays
|
|
|
fake_images: list of image paths or numpy arrays
|
|
|
"""
|
|
|
try:
|
|
|
from pytorch_fid import fid_score
|
|
|
|
|
|
print("Warning: FID computation requires pytorch-fid library and image directories.")
|
|
|
print("Please use fid_score.calculate_fid_given_paths() separately.")
|
|
|
return 0.0
|
|
|
except:
|
|
|
print("Warning: FID computation not available. Install pytorch-fid.")
|
|
|
return 0.0
|
|
|
|
|
|
def compute_meter(self, img1, img2):
|
|
|
"""
|
|
|
计算MEt3R (需要MEt3R模型)
|
|
|
这是一个学习型指标,需要预训练模型
|
|
|
"""
|
|
|
print("Warning: MEt3R computation requires specific model weights.")
|
|
|
print("Please refer to MEt3R paper and implementation.")
|
|
|
return 0.0
|
|
|
|
|
|
def evaluate_image_pair(self, gt_path, rendered_path):
|
|
|
"""
|
|
|
评估一对图像
|
|
|
|
|
|
Args:
|
|
|
gt_path: 高分辨率ground truth图像路径
|
|
|
rendered_path: 渲染的图像路径
|
|
|
Returns:
|
|
|
dict: 包含所有评估指标
|
|
|
"""
|
|
|
print(f"Evaluating: {rendered_path}")
|
|
|
|
|
|
|
|
|
gt_img = self.load_image(gt_path)
|
|
|
rendered_img = self.load_image(rendered_path)
|
|
|
|
|
|
|
|
|
if gt_img.shape != rendered_img.shape:
|
|
|
print(f"Warning: Image size mismatch. GT: {gt_img.shape}, Rendered: {rendered_img.shape}")
|
|
|
|
|
|
rendered_img = cv2.resize(rendered_img, (gt_img.shape[1], gt_img.shape[0]))
|
|
|
|
|
|
|
|
|
metrics = {
|
|
|
'PSNR': self.compute_psnr(gt_img, rendered_img),
|
|
|
'SSIM': self.compute_ssim(gt_img, rendered_img),
|
|
|
'LPIPS': self.compute_lpips(gt_img, rendered_img),
|
|
|
'NIQE': self.compute_niqe(rendered_img),
|
|
|
}
|
|
|
|
|
|
return metrics
|
|
|
|
|
|
def evaluate_multiple_views(self, gt_dir, rendered_dir):
|
|
|
"""
|
|
|
评估多个视角
|
|
|
|
|
|
Args:
|
|
|
gt_dir: ground truth图像目录
|
|
|
rendered_dir: 渲染图像目录
|
|
|
Returns:
|
|
|
dict: 平均指标
|
|
|
"""
|
|
|
import glob
|
|
|
|
|
|
|
|
|
gt_images = sorted(glob.glob(os.path.join(gt_dir, '*.jpg')) +
|
|
|
glob.glob(os.path.join(gt_dir, '*.png')))
|
|
|
rendered_images = sorted(glob.glob(os.path.join(rendered_dir, '*.jpg')) +
|
|
|
glob.glob(os.path.join(rendered_dir, '*.png')))
|
|
|
|
|
|
if len(gt_images) != len(rendered_images):
|
|
|
print(f"Warning: Number of images mismatch. GT: {len(gt_images)}, Rendered: {len(rendered_images)}")
|
|
|
|
|
|
all_metrics = []
|
|
|
|
|
|
for gt_path, rendered_path in zip(gt_images, rendered_images):
|
|
|
metrics = self.evaluate_image_pair(gt_path, rendered_path)
|
|
|
all_metrics.append(metrics)
|
|
|
|
|
|
|
|
|
avg_metrics = {}
|
|
|
for key in all_metrics[0].keys():
|
|
|
avg_metrics[key] = np.mean([m[key] for m in all_metrics])
|
|
|
avg_metrics[key + '_std'] = np.std([m[key] for m in all_metrics])
|
|
|
|
|
|
return avg_metrics, all_metrics
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
def main():
|
|
|
"""
|
|
|
完整流程示例:
|
|
|
1. 加载原始3DGS
|
|
|
2. 执行聚类merge
|
|
|
3. 保存merged模型
|
|
|
4. 调用渲染(需要外部实现)
|
|
|
5. 评估图像质量
|
|
|
"""
|
|
|
|
|
|
|
|
|
config = {
|
|
|
'original_ply': 'path/to/original_3dgs.ply',
|
|
|
'merged_ply': 'path/to/merged_3dgs.ply',
|
|
|
'gt_image_dir': 'path/to/high_res_images',
|
|
|
'rendered_image_dir': 'path/to/rendered_images',
|
|
|
'cell_size': 1.0,
|
|
|
'padding_ratio': 0.1,
|
|
|
'target_points_per_cluster': 3
|
|
|
}
|
|
|
|
|
|
|
|
|
print("="*50)
|
|
|
print("Step 1: Merging Gaussians")
|
|
|
print("="*50)
|
|
|
|
|
|
merger = GaussianMerger(
|
|
|
cell_size=config['cell_size'],
|
|
|
padding_ratio=config['padding_ratio'],
|
|
|
target_points_per_cluster=config['target_points_per_cluster']
|
|
|
)
|
|
|
|
|
|
|
|
|
gaussians = merger.load_ply(config['original_ply'])
|
|
|
|
|
|
|
|
|
merged_gaussians = merger.merge_all(gaussians)
|
|
|
|
|
|
|
|
|
merger.save_ply(merged_gaussians, config['merged_ply'])
|
|
|
|
|
|
|
|
|
print("\n" + "="*50)
|
|
|
print("Step 2: Rendering (Please implement separately)")
|
|
|
print("="*50)
|
|
|
print(f"Please use your 3DGS renderer to render images from:")
|
|
|
print(f" Model: {config['merged_ply']}")
|
|
|
print(f" Output to: {config['rendered_image_dir']}")
|
|
|
print("\nExample command (using gaussian-splatting):")
|
|
|
print(f" python render.py -m {config['merged_ply']} -s <scene_path>")
|
|
|
|
|
|
|
|
|
print("\n" + "="*50)
|
|
|
print("Step 3: Evaluating Image Quality")
|
|
|
print("="*50)
|
|
|
|
|
|
evaluator = ImageEvaluator()
|
|
|
|
|
|
|
|
|
avg_metrics, all_metrics = evaluator.evaluate_multiple_views(
|
|
|
config['gt_image_dir'],
|
|
|
config['rendered_image_dir']
|
|
|
)
|
|
|
|
|
|
|
|
|
print("\n" + "="*50)
|
|
|
print("Evaluation Results")
|
|
|
print("="*50)
|
|
|
for metric_name, value in avg_metrics.items():
|
|
|
if not metric_name.endswith('_std'):
|
|
|
std = avg_metrics.get(metric_name + '_std', 0)
|
|
|
print(f"{metric_name:10s}: {value:.4f} ± {std:.4f}")
|
|
|
|
|
|
|
|
|
import json
|
|
|
results = {
|
|
|
'config': config,
|
|
|
'merge_stats': {
|
|
|
'original_points': len(gaussians['xyz']),
|
|
|
'merged_points': len(merged_gaussians['xyz']),
|
|
|
'compression_ratio': len(gaussians['xyz']) / len(merged_gaussians['xyz'])
|
|
|
},
|
|
|
'average_metrics': {k: float(v) for k, v in avg_metrics.items()},
|
|
|
'per_view_metrics': [{k: float(v) for k, v in m.items()} for m in all_metrics]
|
|
|
}
|
|
|
|
|
|
with open('evaluation_results.json', 'w') as f:
|
|
|
json.dump(results, f, indent=2)
|
|
|
|
|
|
print(f"\nResults saved to: evaluation_results.json")
|
|
|
|
|
|
|
|
|
if __name__ == "__main__":
|
|
|
main() |