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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import numpy as np
|
| 2 |
+
import torch
|
| 3 |
+
import os
|
| 4 |
+
from pathlib import Path
|
| 5 |
+
from PIL import Image
|
| 6 |
+
import json
|
| 7 |
+
from tqdm import tqdm
|
| 8 |
+
import sys
|
| 9 |
+
|
| 10 |
+
# 评估指标
|
| 11 |
+
from skimage.metrics import peak_signal_noise_ratio as psnr
|
| 12 |
+
from skimage.metrics import structural_similarity as ssim
|
| 13 |
+
import lpips
|
| 14 |
+
from torchvision import transforms
|
| 15 |
+
from scipy import linalg
|
| 16 |
+
|
| 17 |
+
# 导入gaussian-splatting渲染库
|
| 18 |
+
try:
|
| 19 |
+
from scene.gaussian_model import GaussianModel
|
| 20 |
+
from utils.graphics_utils import focal2fov
|
| 21 |
+
from scene.cameras import Camera
|
| 22 |
+
from gaussian_renderer import render
|
| 23 |
+
from argparse import Namespace
|
| 24 |
+
except ImportError as e:
|
| 25 |
+
print(f"错误: 无法导入gaussian-splatting模块: {e}")
|
| 26 |
+
print("请确保gaussian-splatting仓库在Python路径中")
|
| 27 |
+
sys.exit(1)
|
| 28 |
+
|
| 29 |
+
|
| 30 |
+
class GaussianRenderer:
|
| 31 |
+
"""
|
| 32 |
+
基于原版gaussian-splatting的渲染器包装类
|
| 33 |
+
"""
|
| 34 |
+
def __init__(self, ply_path, sh_degree=3, device='cuda'):
|
| 35 |
+
"""
|
| 36 |
+
初始化渲染器
|
| 37 |
+
|
| 38 |
+
Args:
|
| 39 |
+
ply_path: .ply文件路径
|
| 40 |
+
sh_degree: 球谐函数阶数
|
| 41 |
+
device: 计算设备
|
| 42 |
+
"""
|
| 43 |
+
self.ply_path = ply_path
|
| 44 |
+
self.sh_degree = sh_degree
|
| 45 |
+
self.device = device
|
| 46 |
+
|
| 47 |
+
# 初始化GaussianModel
|
| 48 |
+
self.gaussians = GaussianModel(sh_degree)
|
| 49 |
+
self.gaussians.load_ply(ply_path)
|
| 50 |
+
|
| 51 |
+
# 设置渲染参数
|
| 52 |
+
self.bg_color = torch.tensor([1, 1, 1], dtype=torch.float32, device=device)
|
| 53 |
+
|
| 54 |
+
# 创建pipeline和background参数
|
| 55 |
+
self.pipe = Namespace()
|
| 56 |
+
self.pipe.convert_SHs_python = False
|
| 57 |
+
self.pipe.compute_cov3D_python = False
|
| 58 |
+
self.pipe.debug = False
|
| 59 |
+
|
| 60 |
+
print(f"加载模型: {ply_path}")
|
| 61 |
+
print(f" - 高斯点数: {len(self.gaussians.get_xyz)}")
|
| 62 |
+
print(f" - SH阶数: {sh_degree}")
|
| 63 |
+
|
| 64 |
+
def render(self, camera):
|
| 65 |
+
"""
|
| 66 |
+
渲染单个视角
|
| 67 |
+
|
| 68 |
+
Args:
|
| 69 |
+
camera: Camera对象
|
| 70 |
+
|
| 71 |
+
Returns:
|
| 72 |
+
rendered_image: numpy array, shape (H, W, 3), 值域[0, 1]
|
| 73 |
+
"""
|
| 74 |
+
with torch.no_grad():
|
| 75 |
+
rendering = render(camera, self.gaussians, self.pipe, self.bg_color)
|
| 76 |
+
image = rendering["render"]
|
| 77 |
+
|
| 78 |
+
# 转换为numpy数组 CHW -> HWC
|
| 79 |
+
image = image.cpu().numpy()
|
| 80 |
+
image = np.transpose(image, (1, 2, 0))
|
| 81 |
+
|
| 82 |
+
# 确保值域在[0, 1]
|
| 83 |
+
image = np.clip(image, 0, 1)
|
| 84 |
+
|
| 85 |
+
return image
|
| 86 |
+
|
| 87 |
+
|
| 88 |
+
class MetricsCalculator:
|
| 89 |
+
"""评估指标计算器"""
|
| 90 |
+
|
| 91 |
+
def __init__(self, device='cuda'):
|
| 92 |
+
self.device = device
|
| 93 |
+
|
| 94 |
+
# LPIPS模型
|
| 95 |
+
self.lpips_fn = lpips.LPIPS(net='alex').to(device)
|
| 96 |
+
|
| 97 |
+
# 图像预处理
|
| 98 |
+
self.transform = transforms.Compose([
|
| 99 |
+
transforms.ToTensor(),
|
| 100 |
+
transforms.Normalize(mean=[0.5, 0.5, 0.5], std=[0.5, 0.5, 0.5])
|
| 101 |
+
])
|
| 102 |
+
|
| 103 |
+
def calculate_psnr(self, img1, img2):
|
| 104 |
+
"""
|
| 105 |
+
计算PSNR
|
| 106 |
+
|
| 107 |
+
Args:
|
| 108 |
+
img1, img2: numpy arrays, shape (H, W, 3), 值域[0, 1]
|
| 109 |
+
"""
|
| 110 |
+
return psnr(img1, img2, data_range=1.0)
|
| 111 |
+
|
| 112 |
+
def calculate_ssim(self, img1, img2):
|
| 113 |
+
"""
|
| 114 |
+
计算SSIM
|
| 115 |
+
|
| 116 |
+
Args:
|
| 117 |
+
img1, img2: numpy arrays, shape (H, W, 3), 值域[0, 1]
|
| 118 |
+
"""
|
| 119 |
+
return ssim(img1, img2, data_range=1.0, channel_axis=2, multichannel=True)
|
| 120 |
+
|
| 121 |
+
def calculate_lpips(self, img1, img2):
|
| 122 |
+
"""
|
| 123 |
+
计算LPIPS
|
| 124 |
+
|
| 125 |
+
Args:
|
| 126 |
+
img1, img2: numpy arrays, shape (H, W, 3), 值域[0, 1]
|
| 127 |
+
"""
|
| 128 |
+
# 转换为torch tensor
|
| 129 |
+
img1_tensor = torch.from_numpy(img1).permute(2, 0, 1).unsqueeze(0).float().to(self.device)
|
| 130 |
+
img2_tensor = torch.from_numpy(img2).permute(2, 0, 1).unsqueeze(0).float().to(self.device)
|
| 131 |
+
|
| 132 |
+
# 归一化到[-1, 1]
|
| 133 |
+
img1_tensor = img1_tensor * 2 - 1
|
| 134 |
+
img2_tensor = img2_tensor * 2 - 1
|
| 135 |
+
|
| 136 |
+
with torch.no_grad():
|
| 137 |
+
lpips_value = self.lpips_fn(img1_tensor, img2_tensor)
|
| 138 |
+
|
| 139 |
+
return lpips_value.item()
|
| 140 |
+
|
| 141 |
+
def calculate_niqe(self, img):
|
| 142 |
+
"""
|
| 143 |
+
计算NIQE (无参考图像质量评估)
|
| 144 |
+
|
| 145 |
+
Args:
|
| 146 |
+
img: numpy array, shape (H, W, 3), 值域[0, 1]
|
| 147 |
+
"""
|
| 148 |
+
try:
|
| 149 |
+
import pyiqa
|
| 150 |
+
niqe_metric = pyiqa.create_metric('niqe', device=self.device)
|
| 151 |
+
img_tensor = torch.from_numpy(img).permute(2, 0, 1).unsqueeze(0).float().to(self.device)
|
| 152 |
+
score = niqe_metric(img_tensor).item()
|
| 153 |
+
return score
|
| 154 |
+
except ImportError:
|
| 155 |
+
print("警告: pyiqa未安装,无法计算NIQE。请运行: pip install pyiqa")
|
| 156 |
+
return None
|
| 157 |
+
|
| 158 |
+
def calculate_fid_features(self, img):
|
| 159 |
+
"""
|
| 160 |
+
提取FID特征(使用InceptionV3)
|
| 161 |
+
|
| 162 |
+
Args:
|
| 163 |
+
img: numpy array, shape (H, W, 3), 值域[0, 1]
|
| 164 |
+
"""
|
| 165 |
+
from torchvision.models import inception_v3
|
| 166 |
+
|
| 167 |
+
if not hasattr(self, 'inception_model'):
|
| 168 |
+
self.inception_model = inception_v3(pretrained=True, transform_input=False).to(self.device)
|
| 169 |
+
self.inception_model.eval()
|
| 170 |
+
# 移除最后的全连接层
|
| 171 |
+
self.inception_model.fc = torch.nn.Identity()
|
| 172 |
+
|
| 173 |
+
# 调整大小到299x299 (InceptionV3要求)
|
| 174 |
+
img_pil = Image.fromarray((img * 255).astype(np.uint8))
|
| 175 |
+
img_pil = img_pil.resize((299, 299), Image.BILINEAR)
|
| 176 |
+
img_array = np.array(img_pil) / 255.0
|
| 177 |
+
|
| 178 |
+
# 转换为tensor并归一化
|
| 179 |
+
img_tensor = torch.from_numpy(img_array).permute(2, 0, 1).unsqueeze(0).float().to(self.device)
|
| 180 |
+
img_tensor = (img_tensor - 0.5) / 0.5
|
| 181 |
+
|
| 182 |
+
with torch.no_grad():
|
| 183 |
+
features = self.inception_model(img_tensor)
|
| 184 |
+
|
| 185 |
+
return features.cpu().numpy().flatten()
|
| 186 |
+
|
| 187 |
+
@staticmethod
|
| 188 |
+
def calculate_fid(features1, features2):
|
| 189 |
+
"""
|
| 190 |
+
计算FID分数
|
| 191 |
+
|
| 192 |
+
Args:
|
| 193 |
+
features1, features2: numpy arrays of shape (N, D), 特征向量
|
| 194 |
+
"""
|
| 195 |
+
mu1, sigma1 = features1.mean(axis=0), np.cov(features1, rowvar=False)
|
| 196 |
+
mu2, sigma2 = features2.mean(axis=0), np.cov(features2, rowvar=False)
|
| 197 |
+
|
| 198 |
+
# 计算均值差的平方
|
| 199 |
+
diff = mu1 - mu2
|
| 200 |
+
|
| 201 |
+
# 计算协方差矩阵的平方根
|
| 202 |
+
covmean, _ = linalg.sqrtm(sigma1.dot(sigma2), disp=False)
|
| 203 |
+
|
| 204 |
+
# 处理数值误差
|
| 205 |
+
if np.iscomplexobj(covmean):
|
| 206 |
+
covmean = covmean.real
|
| 207 |
+
|
| 208 |
+
fid = diff.dot(diff) + np.trace(sigma1 + sigma2 - 2 * covmean)
|
| 209 |
+
return fid
|
| 210 |
+
|
| 211 |
+
|
| 212 |
+
def load_cameras(camera_path, device='cuda'):
|
| 213 |
+
"""
|
| 214 |
+
从cameras.json加载相机参数
|
| 215 |
+
|
| 216 |
+
Args:
|
| 217 |
+
camera_path: cameras.json文件路径
|
| 218 |
+
device: 计算设备
|
| 219 |
+
|
| 220 |
+
Returns:
|
| 221 |
+
cameras: Camera对象列表
|
| 222 |
+
"""
|
| 223 |
+
with open(camera_path, 'r') as f:
|
| 224 |
+
camera_data = json.load(f)
|
| 225 |
+
|
| 226 |
+
cameras = []
|
| 227 |
+
|
| 228 |
+
for cam_info in camera_data:
|
| 229 |
+
# 提取相机参数
|
| 230 |
+
uid = cam_info['id']
|
| 231 |
+
colmap_id = cam_info['id']
|
| 232 |
+
img_name = cam_info['img_name']
|
| 233 |
+
width = cam_info['width']
|
| 234 |
+
height = cam_info['height']
|
| 235 |
+
|
| 236 |
+
# 焦距
|
| 237 |
+
fx = cam_info['fx']
|
| 238 |
+
fy = cam_info['fy']
|
| 239 |
+
|
| 240 |
+
# 相机位置和旋转(这里是相机到世界的变换)
|
| 241 |
+
position = np.array(cam_info['position']) # 相机在世界坐标系中的位置
|
| 242 |
+
rotation = np.array(cam_info['rotation']) # 3x3旋转矩阵(相机到世界)
|
| 243 |
+
|
| 244 |
+
# 转换为世界到相机的变换
|
| 245 |
+
# 对于相机到世界的旋转矩阵R_c2w和位置t_c2w:
|
| 246 |
+
# 世界到相机: R_w2c = R_c2w^T, t_w2c = -R_c2w^T @ t_c2w
|
| 247 |
+
R_w2c = rotation.T
|
| 248 |
+
T_w2c = -R_w2c @ position
|
| 249 |
+
|
| 250 |
+
# 转换为torch tensor
|
| 251 |
+
R_tensor = torch.from_numpy(R_w2c).float()
|
| 252 |
+
T_tensor = torch.from_numpy(T_w2c).float()
|
| 253 |
+
|
| 254 |
+
# 计算FoV
|
| 255 |
+
FovX = focal2fov(fx, width)
|
| 256 |
+
FovY = focal2fov(fy, height)
|
| 257 |
+
|
| 258 |
+
# 创建Camera对象
|
| 259 |
+
# 注意:不同版本的gaussian-splatting可能有不同的Camera构造函数
|
| 260 |
+
# 如果遇到错误,可能需要调整参数
|
| 261 |
+
try:
|
| 262 |
+
camera = Camera(
|
| 263 |
+
colmap_id=colmap_id,
|
| 264 |
+
R=R_tensor,
|
| 265 |
+
T=T_tensor,
|
| 266 |
+
FoVx=FovX,
|
| 267 |
+
FoVy=FovY,
|
| 268 |
+
image=torch.zeros((3, height, width)), # 占位图像
|
| 269 |
+
gt_alpha_mask=None,
|
| 270 |
+
image_name=img_name,
|
| 271 |
+
uid=uid,
|
| 272 |
+
data_device=device
|
| 273 |
+
)
|
| 274 |
+
except TypeError:
|
| 275 |
+
# 如果上面的构造函数不工作,尝试另一种形式
|
| 276 |
+
camera = Camera(
|
| 277 |
+
colmap_id=colmap_id,
|
| 278 |
+
R=R_tensor,
|
| 279 |
+
T=T_tensor,
|
| 280 |
+
FoVx=FovX,
|
| 281 |
+
FoVy=FovY,
|
| 282 |
+
image=torch.zeros((3, height, width)),
|
| 283 |
+
gt_alpha_mask=None,
|
| 284 |
+
image_name=img_name,
|
| 285 |
+
uid=uid
|
| 286 |
+
)
|
| 287 |
+
|
| 288 |
+
cameras.append(camera)
|
| 289 |
+
|
| 290 |
+
return cameras
|
| 291 |
+
|
| 292 |
+
|
| 293 |
+
def render_and_evaluate(original_ply, compressed_ply, camera_path, output_dir,
|
| 294 |
+
ground_truth_dir=None, sh_degree=3, device='cuda'):
|
| 295 |
+
"""
|
| 296 |
+
渲染并评估压缩前后的3DGS
|
| 297 |
+
|
| 298 |
+
Args:
|
| 299 |
+
original_ply: 原始3DGS的.ply文件路径
|
| 300 |
+
compressed_ply: 压缩后3DGS的.ply文件路径
|
| 301 |
+
camera_path: 相机参数文件路径
|
| 302 |
+
output_dir: 输出目录
|
| 303 |
+
ground_truth_dir: 真实图像目录(如���有的话,用于计算与GT的指标)
|
| 304 |
+
sh_degree: 球谐函数阶数
|
| 305 |
+
device: 计算设备
|
| 306 |
+
"""
|
| 307 |
+
output_dir = Path(output_dir)
|
| 308 |
+
output_dir.mkdir(parents=True, exist_ok=True)
|
| 309 |
+
|
| 310 |
+
# 创建子目录
|
| 311 |
+
original_render_dir = output_dir / "original"
|
| 312 |
+
compressed_render_dir = output_dir / "compressed"
|
| 313 |
+
original_render_dir.mkdir(exist_ok=True)
|
| 314 |
+
compressed_render_dir.mkdir(exist_ok=True)
|
| 315 |
+
|
| 316 |
+
# 初始化渲染器
|
| 317 |
+
print("初始化渲染器...")
|
| 318 |
+
original_renderer = GaussianRenderer(original_ply, sh_degree=sh_degree, device=device)
|
| 319 |
+
compressed_renderer = GaussianRenderer(compressed_ply, sh_degree=sh_degree, device=device)
|
| 320 |
+
|
| 321 |
+
# 初始化评估器
|
| 322 |
+
metrics_calc = MetricsCalculator(device=device)
|
| 323 |
+
|
| 324 |
+
# 加载相机
|
| 325 |
+
print("加载相机参数...")
|
| 326 |
+
cameras = load_cameras(camera_path, device=device)
|
| 327 |
+
print(f"加载了 {len(cameras)} 个相机视角")
|
| 328 |
+
|
| 329 |
+
# 存储所有指标
|
| 330 |
+
results = {
|
| 331 |
+
'psnr': [],
|
| 332 |
+
'ssim': [],
|
| 333 |
+
'lpips': [],
|
| 334 |
+
'niqe_original': [],
|
| 335 |
+
'niqe_compressed': []
|
| 336 |
+
}
|
| 337 |
+
|
| 338 |
+
# 如果有真实图像,也计算与GT的指标
|
| 339 |
+
if ground_truth_dir:
|
| 340 |
+
results['psnr_vs_gt_original'] = []
|
| 341 |
+
results['psnr_vs_gt_compressed'] = []
|
| 342 |
+
results['ssim_vs_gt_original'] = []
|
| 343 |
+
results['ssim_vs_gt_compressed'] = []
|
| 344 |
+
results['lpips_vs_gt_original'] = []
|
| 345 |
+
results['lpips_vs_gt_compressed'] = []
|
| 346 |
+
|
| 347 |
+
# FID特征收集
|
| 348 |
+
original_features = []
|
| 349 |
+
compressed_features = []
|
| 350 |
+
|
| 351 |
+
print("开始渲染和评估...")
|
| 352 |
+
for i, camera in enumerate(tqdm(cameras, desc="渲染进度")):
|
| 353 |
+
# 渲染
|
| 354 |
+
original_img = original_renderer.render(camera)
|
| 355 |
+
compressed_img = compressed_renderer.render(camera)
|
| 356 |
+
|
| 357 |
+
# 保存渲染图像
|
| 358 |
+
Image.fromarray((original_img * 255).astype(np.uint8)).save(
|
| 359 |
+
original_render_dir / f"render_{i:04d}.png"
|
| 360 |
+
)
|
| 361 |
+
Image.fromarray((compressed_img * 255).astype(np.uint8)).save(
|
| 362 |
+
compressed_render_dir / f"render_{i:04d}.png"
|
| 363 |
+
)
|
| 364 |
+
|
| 365 |
+
# 计算压缩前后的对比指标
|
| 366 |
+
results['psnr'].append(metrics_calc.calculate_psnr(original_img, compressed_img))
|
| 367 |
+
results['ssim'].append(metrics_calc.calculate_ssim(original_img, compressed_img))
|
| 368 |
+
results['lpips'].append(metrics_calc.calculate_lpips(original_img, compressed_img))
|
| 369 |
+
|
| 370 |
+
# NIQE(无参考)
|
| 371 |
+
niqe_orig = metrics_calc.calculate_niqe(original_img)
|
| 372 |
+
niqe_comp = metrics_calc.calculate_niqe(compressed_img)
|
| 373 |
+
if niqe_orig is not None:
|
| 374 |
+
results['niqe_original'].append(niqe_orig)
|
| 375 |
+
results['niqe_compressed'].append(niqe_comp)
|
| 376 |
+
|
| 377 |
+
# 提取FID特征
|
| 378 |
+
original_features.append(metrics_calc.calculate_fid_features(original_img))
|
| 379 |
+
compressed_features.append(metrics_calc.calculate_fid_features(compressed_img))
|
| 380 |
+
|
| 381 |
+
# 如果有真实图像
|
| 382 |
+
if ground_truth_dir:
|
| 383 |
+
# 尝试多种可能的文件名格式
|
| 384 |
+
possible_names = [
|
| 385 |
+
f"image_{i:04d}.png",
|
| 386 |
+
f"image_{i:04d}.jpg",
|
| 387 |
+
f"{i:04d}.png",
|
| 388 |
+
f"{i:04d}.jpg",
|
| 389 |
+
camera.image_name
|
| 390 |
+
]
|
| 391 |
+
|
| 392 |
+
gt_img = None
|
| 393 |
+
for name in possible_names:
|
| 394 |
+
gt_path = Path(ground_truth_dir) / name
|
| 395 |
+
if gt_path.exists():
|
| 396 |
+
gt_img = np.array(Image.open(gt_path).convert('RGB')) / 255.0
|
| 397 |
+
break
|
| 398 |
+
|
| 399 |
+
if gt_img is not None:
|
| 400 |
+
results['psnr_vs_gt_original'].append(
|
| 401 |
+
metrics_calc.calculate_psnr(gt_img, original_img)
|
| 402 |
+
)
|
| 403 |
+
results['psnr_vs_gt_compressed'].append(
|
| 404 |
+
metrics_calc.calculate_psnr(gt_img, compressed_img)
|
| 405 |
+
)
|
| 406 |
+
results['ssim_vs_gt_original'].append(
|
| 407 |
+
metrics_calc.calculate_ssim(gt_img, original_img)
|
| 408 |
+
)
|
| 409 |
+
results['ssim_vs_gt_compressed'].append(
|
| 410 |
+
metrics_calc.calculate_ssim(gt_img, compressed_img)
|
| 411 |
+
)
|
| 412 |
+
results['lpips_vs_gt_original'].append(
|
| 413 |
+
metrics_calc.calculate_lpips(gt_img, original_img)
|
| 414 |
+
)
|
| 415 |
+
results['lpips_vs_gt_compressed'].append(
|
| 416 |
+
metrics_calc.calculate_lpips(gt_img, compressed_img)
|
| 417 |
+
)
|
| 418 |
+
|
| 419 |
+
# 计算FID
|
| 420 |
+
print("计算FID...")
|
| 421 |
+
original_features = np.array(original_features)
|
| 422 |
+
compressed_features = np.array(compressed_features)
|
| 423 |
+
fid_score = MetricsCalculator.calculate_fid(original_features, compressed_features)
|
| 424 |
+
|
| 425 |
+
# 汇总结果
|
| 426 |
+
print("\n" + "="*50)
|
| 427 |
+
print("评估结果 (压缩后 vs 原始)")
|
| 428 |
+
print("="*50)
|
| 429 |
+
print(f"PSNR: {np.mean(results['psnr']):.2f} ± {np.std(results['psnr']):.2f} dB")
|
| 430 |
+
print(f"SSIM: {np.mean(results['ssim']):.4f} ± {np.std(results['ssim']):.4f}")
|
| 431 |
+
print(f"LPIPS: {np.mean(results['lpips']):.4f} ± {np.std(results['lpips']):.4f}")
|
| 432 |
+
if results['niqe_original']:
|
| 433 |
+
print(f"NIQE (原始): {np.mean(results['niqe_original']):.4f} ± {np.std(results['niqe_original']):.4f}")
|
| 434 |
+
print(f"NIQE (压缩): {np.mean(results['niqe_compressed']):.4f} ± {np.std(results['niqe_compressed']):.4f}")
|
| 435 |
+
print(f"FID: {fid_score:.4f}")
|
| 436 |
+
|
| 437 |
+
if ground_truth_dir and results['psnr_vs_gt_original']:
|
| 438 |
+
print("\n" + "="*50)
|
| 439 |
+
print("与Ground Truth对比")
|
| 440 |
+
print("="*50)
|
| 441 |
+
print("原始模型 vs GT:")
|
| 442 |
+
print(f" PSNR: {np.mean(results['psnr_vs_gt_original']):.2f} ± {np.std(results['psnr_vs_gt_original']):.2f} dB")
|
| 443 |
+
print(f" SSIM: {np.mean(results['ssim_vs_gt_original']):.4f} ± {np.std(results['ssim_vs_gt_original']):.4f}")
|
| 444 |
+
print(f" LPIPS: {np.mean(results['lpips_vs_gt_original']):.4f} ± {np.std(results['lpips_vs_gt_original']):.4f}")
|
| 445 |
+
print("\n压缩模型 vs GT:")
|
| 446 |
+
print(f" PSNR: {np.mean(results['psnr_vs_gt_compressed']):.2f} ± {np.std(results['psnr_vs_gt_compressed']):.2f} dB")
|
| 447 |
+
print(f" SSIM: {np.mean(results['ssim_vs_gt_compressed']):.4f} ± {np.std(results['ssim_vs_gt_compressed']):.4f}")
|
| 448 |
+
print(f" LPIPS: {np.mean(results['lpips_vs_gt_compressed']):.4f} ± {np.std(results['lpips_vs_gt_compressed']):.4f}")
|
| 449 |
+
|
| 450 |
+
# 保存详细结果
|
| 451 |
+
results_summary = {
|
| 452 |
+
'compression_comparison': {
|
| 453 |
+
'psnr_mean': float(np.mean(results['psnr'])),
|
| 454 |
+
'psnr_std': float(np.std(results['psnr'])),
|
| 455 |
+
'ssim_mean': float(np.mean(results['ssim'])),
|
| 456 |
+
'ssim_std': float(np.std(results['ssim'])),
|
| 457 |
+
'lpips_mean': float(np.mean(results['lpips'])),
|
| 458 |
+
'lpips_std': float(np.std(results['lpips'])),
|
| 459 |
+
'fid': float(fid_score)
|
| 460 |
+
}
|
| 461 |
+
}
|
| 462 |
+
|
| 463 |
+
if results['niqe_original']:
|
| 464 |
+
results_summary['compression_comparison']['niqe_original_mean'] = float(np.mean(results['niqe_original']))
|
| 465 |
+
results_summary['compression_comparison']['niqe_original_std'] = float(np.std(results['niqe_original']))
|
| 466 |
+
results_summary['compression_comparison']['niqe_compressed_mean'] = float(np.mean(results['niqe_compressed']))
|
| 467 |
+
results_summary['compression_comparison']['niqe_compressed_std'] = float(np.std(results['niqe_compressed']))
|
| 468 |
+
|
| 469 |
+
if ground_truth_dir and results['psnr_vs_gt_original']:
|
| 470 |
+
results_summary['vs_ground_truth'] = {
|
| 471 |
+
'original': {
|
| 472 |
+
'psnr_mean': float(np.mean(results['psnr_vs_gt_original'])),
|
| 473 |
+
'psnr_std': float(np.std(results['psnr_vs_gt_original'])),
|
| 474 |
+
'ssim_mean': float(np.mean(results['ssim_vs_gt_original'])),
|
| 475 |
+
'ssim_std': float(np.std(results['ssim_vs_gt_original'])),
|
| 476 |
+
'lpips_mean': float(np.mean(results['lpips_vs_gt_original'])),
|
| 477 |
+
'lpips_std': float(np.std(results['lpips_vs_gt_original']))
|
| 478 |
+
},
|
| 479 |
+
'compressed': {
|
| 480 |
+
'psnr_mean': float(np.mean(results['psnr_vs_gt_compressed'])),
|
| 481 |
+
'psnr_std': float(np.std(results['psnr_vs_gt_compressed'])),
|
| 482 |
+
'ssim_mean': float(np.mean(results['ssim_vs_gt_compressed'])),
|
| 483 |
+
'ssim_std': float(np.std(results['ssim_vs_gt_compressed'])),
|
| 484 |
+
'lpips_mean': float(np.mean(results['lpips_vs_gt_compressed'])),
|
| 485 |
+
'lpips_std': float(np.std(results['lpips_vs_gt_compressed']))
|
| 486 |
+
}
|
| 487 |
+
}
|
| 488 |
+
|
| 489 |
+
# 保存结果
|
| 490 |
+
with open(output_dir / "metrics.json", 'w') as f:
|
| 491 |
+
json.dump(results_summary, f, indent=2)
|
| 492 |
+
|
| 493 |
+
# 保存详细数据
|
| 494 |
+
with open(output_dir / "detailed_metrics.json", 'w') as f:
|
| 495 |
+
# 转换numpy类型为Python原生类型
|
| 496 |
+
results_for_json = {}
|
| 497 |
+
for key, value in results.items():
|
| 498 |
+
if isinstance(value, list) and len(value) > 0:
|
| 499 |
+
results_for_json[key] = [float(v) if not isinstance(v, (list, dict)) else v for v in value]
|
| 500 |
+
json.dump(results_for_json, f, indent=2)
|
| 501 |
+
|
| 502 |
+
print(f"\n结果已保存到: {output_dir}")
|
| 503 |
+
print(f" - 原始渲染图像: {original_render_dir}")
|
| 504 |
+
print(f" - 压缩渲染图像: {compressed_render_dir}")
|
| 505 |
+
print(f" - 评估指标摘要: {output_dir / 'metrics.json'}")
|
| 506 |
+
print(f" - 详细指标数据: {output_dir / 'detailed_metrics.json'}")
|
| 507 |
+
"""
|
| 508 |
+
渲染并评估压缩前后的3DGS
|
| 509 |
+
|
| 510 |
+
Args:
|
| 511 |
+
original_ply: 原始3DGS的.ply文件路径
|
| 512 |
+
compressed_ply: 压缩后3DGS的.ply文件路径
|
| 513 |
+
camera_path: 相机参数文件路径
|
| 514 |
+
output_dir: 输出目录
|
| 515 |
+
ground_truth_dir: 真实图像目录(如果有的话,用于计算与GT的指标)
|
| 516 |
+
"""
|
| 517 |
+
output_dir = Path(output_dir)
|
| 518 |
+
output_dir.mkdir(parents=True, exist_ok=True)
|
| 519 |
+
|
| 520 |
+
# 创建子目录
|
| 521 |
+
original_render_dir = output_dir / "original"
|
| 522 |
+
compressed_render_dir = output_dir / "compressed"
|
| 523 |
+
original_render_dir.mkdir(exist_ok=True)
|
| 524 |
+
compressed_render_dir.mkdir(exist_ok=True)
|
| 525 |
+
|
| 526 |
+
# 初始化渲染器
|
| 527 |
+
print("初始化渲染器...")
|
| 528 |
+
original_renderer = GaussianRenderer(original_ply)
|
| 529 |
+
compressed_renderer = GaussianRenderer(compressed_ply)
|
| 530 |
+
|
| 531 |
+
# 初始化评估器
|
| 532 |
+
metrics_calc = MetricsCalculator()
|
| 533 |
+
|
| 534 |
+
# 加载相机
|
| 535 |
+
print("加载相机参数...")
|
| 536 |
+
cameras = load_cameras(camera_path)
|
| 537 |
+
|
| 538 |
+
# 存储所有指标
|
| 539 |
+
results = {
|
| 540 |
+
'psnr': [],
|
| 541 |
+
'ssim': [],
|
| 542 |
+
'lpips': [],
|
| 543 |
+
'niqe_original': [],
|
| 544 |
+
'niqe_compressed': []
|
| 545 |
+
}
|
| 546 |
+
|
| 547 |
+
# 如果有真实图像,也计算与GT的指标
|
| 548 |
+
if ground_truth_dir:
|
| 549 |
+
results['psnr_vs_gt_original'] = []
|
| 550 |
+
results['psnr_vs_gt_compressed'] = []
|
| 551 |
+
results['ssim_vs_gt_original'] = []
|
| 552 |
+
results['ssim_vs_gt_compressed'] = []
|
| 553 |
+
results['lpips_vs_gt_original'] = []
|
| 554 |
+
results['lpips_vs_gt_compressed'] = []
|
| 555 |
+
|
| 556 |
+
# FID特征收集
|
| 557 |
+
original_features = []
|
| 558 |
+
compressed_features = []
|
| 559 |
+
|
| 560 |
+
print("开始渲染和评估...")
|
| 561 |
+
for i, camera in enumerate(tqdm(cameras)):
|
| 562 |
+
# 渲染
|
| 563 |
+
original_img = original_renderer.render(camera)
|
| 564 |
+
compressed_img = compressed_renderer.render(camera)
|
| 565 |
+
|
| 566 |
+
# 保存渲染图像
|
| 567 |
+
Image.fromarray((original_img * 255).astype(np.uint8)).save(
|
| 568 |
+
original_render_dir / f"render_{i:04d}.png"
|
| 569 |
+
)
|
| 570 |
+
Image.fromarray((compressed_img * 255).astype(np.uint8)).save(
|
| 571 |
+
compressed_render_dir / f"render_{i:04d}.png"
|
| 572 |
+
)
|
| 573 |
+
|
| 574 |
+
# 计算压缩前后的对比指标
|
| 575 |
+
results['psnr'].append(metrics_calc.calculate_psnr(original_img, compressed_img))
|
| 576 |
+
results['ssim'].append(metrics_calc.calculate_ssim(original_img, compressed_img))
|
| 577 |
+
results['lpips'].append(metrics_calc.calculate_lpips(original_img, compressed_img))
|
| 578 |
+
|
| 579 |
+
# NIQE(无参考)
|
| 580 |
+
niqe_orig = metrics_calc.calculate_niqe(original_img)
|
| 581 |
+
niqe_comp = metrics_calc.calculate_niqe(compressed_img)
|
| 582 |
+
if niqe_orig is not None:
|
| 583 |
+
results['niqe_original'].append(niqe_orig)
|
| 584 |
+
results['niqe_compressed'].append(niqe_comp)
|
| 585 |
+
|
| 586 |
+
# 提取FID特征
|
| 587 |
+
original_features.append(metrics_calc.calculate_fid_features(original_img))
|
| 588 |
+
compressed_features.append(metrics_calc.calculate_fid_features(compressed_img))
|
| 589 |
+
|
| 590 |
+
# 如果有真实图像
|
| 591 |
+
if ground_truth_dir:
|
| 592 |
+
gt_path = Path(ground_truth_dir) / f"image_{i:04d}.png" # 根据实际命名调整
|
| 593 |
+
if gt_path.exists():
|
| 594 |
+
gt_img = np.array(Image.open(gt_path)) / 255.0
|
| 595 |
+
|
| 596 |
+
results['psnr_vs_gt_original'].append(
|
| 597 |
+
metrics_calc.calculate_psnr(gt_img, original_img)
|
| 598 |
+
)
|
| 599 |
+
results['psnr_vs_gt_compressed'].append(
|
| 600 |
+
metrics_calc.calculate_psnr(gt_img, compressed_img)
|
| 601 |
+
)
|
| 602 |
+
results['ssim_vs_gt_original'].append(
|
| 603 |
+
metrics_calc.calculate_ssim(gt_img, original_img)
|
| 604 |
+
)
|
| 605 |
+
results['ssim_vs_gt_compressed'].append(
|
| 606 |
+
metrics_calc.calculate_ssim(gt_img, compressed_img)
|
| 607 |
+
)
|
| 608 |
+
results['lpips_vs_gt_original'].append(
|
| 609 |
+
metrics_calc.calculate_lpips(gt_img, original_img)
|
| 610 |
+
)
|
| 611 |
+
results['lpips_vs_gt_compressed'].append(
|
| 612 |
+
metrics_calc.calculate_lpips(gt_img, compressed_img)
|
| 613 |
+
)
|
| 614 |
+
|
| 615 |
+
# 计算FID
|
| 616 |
+
original_features = np.array(original_features)
|
| 617 |
+
compressed_features = np.array(compressed_features)
|
| 618 |
+
fid_score = MetricsCalculator.calculate_fid(original_features, compressed_features)
|
| 619 |
+
|
| 620 |
+
# 汇总结果
|
| 621 |
+
print("\n" + "="*50)
|
| 622 |
+
print("评估结果 (压缩后 vs 原始)")
|
| 623 |
+
print("="*50)
|
| 624 |
+
print(f"PSNR: {np.mean(results['psnr']):.2f} ± {np.std(results['psnr']):.2f} dB")
|
| 625 |
+
print(f"SSIM: {np.mean(results['ssim']):.4f} ± {np.std(results['ssim']):.4f}")
|
| 626 |
+
print(f"LPIPS: {np.mean(results['lpips']):.4f} ± {np.std(results['lpips']):.4f}")
|
| 627 |
+
if results['niqe_original']:
|
| 628 |
+
print(f"NIQE (原始): {np.mean(results['niqe_original']):.4f}")
|
| 629 |
+
print(f"NIQE (压缩): {np.mean(results['niqe_compressed']):.4f}")
|
| 630 |
+
print(f"FID: {fid_score:.4f}")
|
| 631 |
+
|
| 632 |
+
if ground_truth_dir:
|
| 633 |
+
print("\n" + "="*50)
|
| 634 |
+
print("与Ground Truth对比")
|
| 635 |
+
print("="*50)
|
| 636 |
+
print("原始模型 vs GT:")
|
| 637 |
+
print(f" PSNR: {np.mean(results['psnr_vs_gt_original']):.2f} dB")
|
| 638 |
+
print(f" SSIM: {np.mean(results['ssim_vs_gt_original']):.4f}")
|
| 639 |
+
print(f" LPIPS: {np.mean(results['lpips_vs_gt_original']):.4f}")
|
| 640 |
+
print("\n压缩模型 vs GT:")
|
| 641 |
+
print(f" PSNR: {np.mean(results['psnr_vs_gt_compressed']):.2f} dB")
|
| 642 |
+
print(f" SSIM: {np.mean(results['ssim_vs_gt_compressed']):.4f}")
|
| 643 |
+
print(f" LPIPS: {np.mean(results['lpips_vs_gt_compressed']):.4f}")
|
| 644 |
+
|
| 645 |
+
# 保存详细结果
|
| 646 |
+
results_summary = {
|
| 647 |
+
'compression_comparison': {
|
| 648 |
+
'psnr_mean': float(np.mean(results['psnr'])),
|
| 649 |
+
'psnr_std': float(np.std(results['psnr'])),
|
| 650 |
+
'ssim_mean': float(np.mean(results['ssim'])),
|
| 651 |
+
'ssim_std': float(np.std(results['ssim'])),
|
| 652 |
+
'lpips_mean': float(np.mean(results['lpips'])),
|
| 653 |
+
'lpips_std': float(np.std(results['lpips'])),
|
| 654 |
+
'fid': float(fid_score)
|
| 655 |
+
}
|
| 656 |
+
}
|
| 657 |
+
|
| 658 |
+
if results['niqe_original']:
|
| 659 |
+
results_summary['compression_comparison']['niqe_original'] = float(np.mean(results['niqe_original']))
|
| 660 |
+
results_summary['compression_comparison']['niqe_compressed'] = float(np.mean(results['niqe_compressed']))
|
| 661 |
+
|
| 662 |
+
if ground_truth_dir:
|
| 663 |
+
results_summary['vs_ground_truth'] = {
|
| 664 |
+
'original': {
|
| 665 |
+
'psnr': float(np.mean(results['psnr_vs_gt_original'])),
|
| 666 |
+
'ssim': float(np.mean(results['ssim_vs_gt_original'])),
|
| 667 |
+
'lpips': float(np.mean(results['lpips_vs_gt_original']))
|
| 668 |
+
},
|
| 669 |
+
'compressed': {
|
| 670 |
+
'psnr': float(np.mean(results['psnr_vs_gt_compressed'])),
|
| 671 |
+
'ssim': float(np.mean(results['ssim_vs_gt_compressed'])),
|
| 672 |
+
'lpips': float(np.mean(results['lpips_vs_gt_compressed']))
|
| 673 |
+
}
|
| 674 |
+
}
|
| 675 |
+
|
| 676 |
+
# 保存结果
|
| 677 |
+
with open(output_dir / "metrics.json", 'w') as f:
|
| 678 |
+
json.dump(results_summary, f, indent=2)
|
| 679 |
+
|
| 680 |
+
# 保存详细数据
|
| 681 |
+
with open(output_dir / "detailed_metrics.json", 'w') as f:
|
| 682 |
+
json.dump(results, f, indent=2)
|
| 683 |
+
|
| 684 |
+
print(f"\n结果已保存到: {output_dir}")
|
| 685 |
+
print(f" - 原始渲染图像: {original_render_dir}")
|
| 686 |
+
print(f" - 压缩渲染图像: {compressed_render_dir}")
|
| 687 |
+
print(f" - 评估指标: {output_dir / 'metrics.json'}")
|
| 688 |
+
|
| 689 |
+
|
| 690 |
+
if __name__ == "__main__":
|
| 691 |
+
import argparse
|
| 692 |
+
|
| 693 |
+
parser = argparse.ArgumentParser(description="评估3DGS压缩前后的渲染质量")
|
| 694 |
+
parser.add_argument("--original_ply", type=str, required=True, help="原始.ply文件路径")
|
| 695 |
+
parser.add_argument("--compressed_ply", type=str, required=True, help="压缩后.ply文件路径")
|
| 696 |
+
parser.add_argument("--cameras", type=str, required=True, help="cameras.json文件路径")
|
| 697 |
+
parser.add_argument("--output_dir", type=str, default="evaluation_results", help="输出目录")
|
| 698 |
+
parser.add_argument("--ground_truth_dir", type=str, default=None, help="真实图像目录(可选)")
|
| 699 |
+
parser.add_argument("--sh_degree", type=int, default=3, help="球谐函数阶数")
|
| 700 |
+
parser.add_argument("--device", type=str, default="cuda", help="计算设备")
|
| 701 |
+
|
| 702 |
+
args = parser.parse_args()
|
| 703 |
+
|
| 704 |
+
# 检查文件是否存在
|
| 705 |
+
if not os.path.exists(args.original_ply):
|
| 706 |
+
print(f"错误: 找不到原始PLY文件: {args.original_ply}")
|
| 707 |
+
sys.exit(1)
|
| 708 |
+
|
| 709 |
+
if not os.path.exists(args.compressed_ply):
|
| 710 |
+
print(f"错误: 找不到压缩PLY文件: {args.compressed_ply}")
|
| 711 |
+
sys.exit(1)
|
| 712 |
+
|
| 713 |
+
if not os.path.exists(args.cameras):
|
| 714 |
+
print(f"错误: 找不到相机参数文件: {args.cameras}")
|
| 715 |
+
sys.exit(1)
|
| 716 |
+
|
| 717 |
+
render_and_evaluate(
|
| 718 |
+
original_ply=args.original_ply,
|
| 719 |
+
compressed_ply=args.compressed_ply,
|
| 720 |
+
camera_path=args.cameras,
|
| 721 |
+
output_dir=args.output_dir,
|
| 722 |
+
ground_truth_dir=args.ground_truth_dir,
|
| 723 |
+
sh_degree=args.sh_degree,
|
| 724 |
+
device=args.device
|
| 725 |
+
)
|