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 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import torch
3
+ import numpy as np
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 gaussian_renderer import render, GaussianModel
12
+ from utils.graphics_utils import getWorld2View2, getProjectionMatrix, focal2fov
13
+ from scene.cameras import Camera
14
+ import torchvision
15
+
16
+ # 评估指标
17
+ from skimage.metrics import peak_signal_noise_ratio as psnr
18
+ from skimage.metrics import structural_similarity as ssim
19
+ import lpips
20
+ from scipy import linalg
21
+
22
+
23
+ class MetricsCalculator:
24
+ """评估指标计算器"""
25
+
26
+ def __init__(self, device='cuda'):
27
+ self.device = device
28
+
29
+ # LPIPS模型
30
+ self.lpips_fn = lpips.LPIPS(net='alex').to(device)
31
+
32
+ def calculate_psnr(self, img1, img2):
33
+ """计算PSNR"""
34
+ return psnr(img1, img2, data_range=1.0)
35
+
36
+ def calculate_ssim(self, img1, img2):
37
+ """计算SSIM"""
38
+ return ssim(img1, img2, data_range=1.0, channel_axis=2, multichannel=True)
39
+
40
+ def calculate_lpips(self, img1, img2):
41
+ """计算LPIPS"""
42
+ # 转换为torch tensor
43
+ img1_tensor = torch.from_numpy(img1).permute(2, 0, 1).unsqueeze(0).float().to(self.device)
44
+ img2_tensor = torch.from_numpy(img2).permute(2, 0, 1).unsqueeze(0).float().to(self.device)
45
+
46
+ # 归一化到[-1, 1]
47
+ img1_tensor = img1_tensor * 2 - 1
48
+ img2_tensor = img2_tensor * 2 - 1
49
+
50
+ with torch.no_grad():
51
+ lpips_value = self.lpips_fn(img1_tensor, img2_tensor)
52
+
53
+ return lpips_value.item()
54
+
55
+ def calculate_niqe(self, img):
56
+ """计算NIQE (无参考图像质量评估)"""
57
+ try:
58
+ import pyiqa
59
+ if not hasattr(self, 'niqe_metric'):
60
+ self.niqe_metric = pyiqa.create_metric('niqe', device=self.device)
61
+ img_tensor = torch.from_numpy(img).permute(2, 0, 1).unsqueeze(0).float().to(self.device)
62
+ score = self.niqe_metric(img_tensor).item()
63
+ return score
64
+ except ImportError:
65
+ print("警告: pyiqa未安装,无法计算NIQE。请运行: pip install pyiqa")
66
+ return None
67
+
68
+ def calculate_fid_features(self, img):
69
+ """提取FID特征"""
70
+ from torchvision.models import inception_v3
71
+
72
+ if not hasattr(self, 'inception_model'):
73
+ self.inception_model = inception_v3(pretrained=True, transform_input=False).to(self.device)
74
+ self.inception_model.eval()
75
+ self.inception_model.fc = torch.nn.Identity()
76
+
77
+ # 调整大小到299x299
78
+ img_pil = Image.fromarray((img * 255).astype(np.uint8))
79
+ img_pil = img_pil.resize((299, 299), Image.BILINEAR)
80
+ img_array = np.array(img_pil) / 255.0
81
+
82
+ # 转换为tensor并归一化
83
+ img_tensor = torch.from_numpy(img_array).permute(2, 0, 1).unsqueeze(0).float().to(self.device)
84
+ img_tensor = (img_tensor - 0.5) / 0.5
85
+
86
+ with torch.no_grad():
87
+ features = self.inception_model(img_tensor)
88
+
89
+ return features.cpu().numpy().flatten()
90
+
91
+ @staticmethod
92
+ def calculate_fid(features1, features2):
93
+ """计算FID分数"""
94
+ mu1, sigma1 = features1.mean(axis=0), np.cov(features1, rowvar=False)
95
+ mu2, sigma2 = features2.mean(axis=0), np.cov(features2, rowvar=False)
96
+
97
+ diff = mu1 - mu2
98
+ covmean, _ = linalg.sqrtm(sigma1.dot(sigma2), disp=False)
99
+
100
+ if np.iscomplexobj(covmean):
101
+ covmean = covmean.real
102
+
103
+ fid = diff.dot(diff) + np.trace(sigma1 + sigma2 - 2 * covmean)
104
+ return fid
105
+
106
+
107
+ def load_cameras_from_json(camera_json_path, device='cuda'):
108
+ """
109
+ 从cameras.json加载相机参数,创建Camera对象
110
+
111
+ Args:
112
+ camera_json_path: cameras.json文件路径
113
+ device: 计算设备
114
+
115
+ Returns:
116
+ cameras: Camera对象列表
117
+ """
118
+ with open(camera_json_path, 'r') as f:
119
+ camera_data = json.load(f)
120
+
121
+ cameras = []
122
+
123
+ for cam_info in camera_data:
124
+ uid = cam_info['id']
125
+ img_name = cam_info['img_name']
126
+ width = cam_info['width']
127
+ height = cam_info['height']
128
+
129
+ # 焦距
130
+ fx = cam_info['fx']
131
+ fy = cam_info['fy']
132
+
133
+ # 相机位置和旋转(相机到世界)
134
+ position = np.array(cam_info['position'])
135
+ rotation = np.array(cam_info['rotation'])
136
+
137
+ # 转换为世界到相机
138
+ R_w2c = rotation.T
139
+ T_w2c = -R_w2c @ position
140
+
141
+ # 构建变换矩阵
142
+ trans = np.array([0.0, 0.0, 0.0])
143
+ scale = 1.0
144
+
145
+ world_view_transform = torch.tensor(
146
+ getWorld2View2(R_w2c, T_w2c, trans, scale)
147
+ ).transpose(0, 1).to(device)
148
+
149
+ # 计算投影矩阵
150
+ znear = 0.01
151
+ zfar = 100.0
152
+ FovX = focal2fov(fx, width)
153
+ FovY = focal2fov(fy, height)
154
+ projection_matrix = getProjectionMatrix(
155
+ znear=znear, zfar=zfar, fovX=FovX, fovY=FovY
156
+ ).transpose(0, 1).to(device)
157
+
158
+ full_proj_transform = (
159
+ world_view_transform.unsqueeze(0).bmm(projection_matrix.unsqueeze(0))
160
+ ).squeeze(0)
161
+
162
+ camera_center = world_view_transform.inverse()[3, :3]
163
+
164
+ # 创建Camera对象
165
+ camera = Camera(
166
+ colmap_id=uid,
167
+ R=R_w2c,
168
+ T=T_w2c,
169
+ FoVx=FovX,
170
+ FoVy=FovY,
171
+ image=torch.zeros((3, height, width)),
172
+ gt_alpha_mask=None,
173
+ image_name=img_name,
174
+ uid=uid
175
+ )
176
+
177
+ # 手动设置必要的属性
178
+ camera.world_view_transform = world_view_transform
179
+ camera.projection_matrix = projection_matrix
180
+ camera.full_proj_transform = full_proj_transform
181
+ camera.camera_center = camera_center
182
+ camera.image_width = width
183
+ camera.image_height = height
184
+
185
+ cameras.append(camera)
186
+
187
+ return cameras
188
+
189
+
190
+ def render_and_evaluate(original_ply, compressed_ply, cameras_json, output_dir,
191
+ sh_degree=3, kernel_size=0.1, ground_truth_dir=None):
192
+ """
193
+ 渲染并评估压缩前后的3DGS
194
+
195
+ Args:
196
+ original_ply: 原始.ply文件路径
197
+ compressed_ply: 压缩后.ply文件路径
198
+ cameras_json: cameras.json文件路径
199
+ output_dir: 输出目录
200
+ sh_degree: 球谐函数阶数
201
+ kernel_size: 渲染kernel大小
202
+ ground_truth_dir: 真实图像目录(可选)
203
+ """
204
+ device = 'cuda'
205
+ output_dir = Path(output_dir)
206
+ output_dir.mkdir(parents=True, exist_ok=True)
207
+
208
+ # 创建子目录
209
+ original_render_dir = output_dir / "original"
210
+ compressed_render_dir = output_dir / "compressed"
211
+ original_render_dir.mkdir(exist_ok=True)
212
+ compressed_render_dir.mkdir(exist_ok=True)
213
+
214
+ # 背景颜色
215
+ bg_color = torch.tensor([1, 1, 1], dtype=torch.float32, device=device)
216
+
217
+ # Pipeline参数(根据你的代码设置)
218
+ class PipelineParams:
219
+ def __init__(self):
220
+ self.convert_SHs_python = False
221
+ self.compute_cov3D_python = False
222
+ self.debug = False
223
+
224
+ pipeline = PipelineParams()
225
+
226
+ # 加载原始模型
227
+ print("加载原始模型...")
228
+ gaussians_original = GaussianModel(sh_degree)
229
+ gaussians_original.load_ply(original_ply)
230
+ print(f" - 原始高斯点数: {len(gaussians_original.get_xyz)}")
231
+
232
+ # 加载压缩模型
233
+ print("加载压缩模型...")
234
+ gaussians_compressed = GaussianModel(sh_degree)
235
+ gaussians_compressed.load_ply(compressed_ply)
236
+ print(f" - 压缩后高斯点数: {len(gaussians_compressed.get_xyz)}")
237
+ print(f" - 压缩率: {len(gaussians_compressed.get_xyz)/len(gaussians_original.get_xyz)*100:.2f}%")
238
+
239
+ # 加载相机
240
+ print("加载相机参数...")
241
+ cameras = load_cameras_from_json(cameras_json, device=device)
242
+ print(f"加载了 {len(cameras)} 个相机视角")
243
+
244
+ # 初始化评估器
245
+ metrics_calc = MetricsCalculator(device=device)
246
+
247
+ # 存储指标
248
+ results = {
249
+ 'psnr': [],
250
+ 'ssim': [],
251
+ 'lpips': [],
252
+ 'niqe_original': [],
253
+ 'niqe_compressed': []
254
+ }
255
+
256
+ if ground_truth_dir:
257
+ results['psnr_vs_gt_original'] = []
258
+ results['psnr_vs_gt_compressed'] = []
259
+ results['ssim_vs_gt_original'] = []
260
+ results['ssim_vs_gt_compressed'] = []
261
+ results['lpips_vs_gt_original'] = []
262
+ results['lpips_vs_gt_compressed'] = []
263
+
264
+ # FID特征收集
265
+ original_features = []
266
+ compressed_features = []
267
+
268
+ print("\n开始渲染和评估...")
269
+ with torch.no_grad():
270
+ for i, camera in enumerate(tqdm(cameras, desc="渲染进度")):
271
+ # 渲染原始模型
272
+ rendering_original = render(camera, gaussians_original, pipeline, bg_color, kernel_size=kernel_size)
273
+ img_original = rendering_original["render"]
274
+
275
+ # 渲染压缩模型
276
+ rendering_compressed = render(camera, gaussians_compressed, pipeline, bg_color, kernel_size=kernel_size)
277
+ img_compressed = rendering_compressed["render"]
278
+
279
+ # 保存渲染图像
280
+ torchvision.utils.save_image(
281
+ img_original,
282
+ original_render_dir / f"{camera.image_name}.png"
283
+ )
284
+ torchvision.utils.save_image(
285
+ img_compressed,
286
+ compressed_render_dir / f"{camera.image_name}.png"
287
+ )
288
+
289
+ # 转换为numpy数组用于评估 (CHW -> HWC)
290
+ img_original_np = img_original.permute(1, 2, 0).cpu().numpy()
291
+ img_compressed_np = img_compressed.permute(1, 2, 0).cpu().numpy()
292
+
293
+ # 确保值域在[0, 1]
294
+ img_original_np = np.clip(img_original_np, 0, 1)
295
+ img_compressed_np = np.clip(img_compressed_np, 0, 1)
296
+
297
+ # 计算压缩前后的对比指标
298
+ results['psnr'].append(metrics_calc.calculate_psnr(img_original_np, img_compressed_np))
299
+ results['ssim'].append(metrics_calc.calculate_ssim(img_original_np, img_compressed_np))
300
+ results['lpips'].append(metrics_calc.calculate_lpips(img_original_np, img_compressed_np))
301
+
302
+ # NIQE(无参考)
303
+ niqe_orig = metrics_calc.calculate_niqe(img_original_np)
304
+ niqe_comp = metrics_calc.calculate_niqe(img_compressed_np)
305
+ if niqe_orig is not None:
306
+ results['niqe_original'].append(niqe_orig)
307
+ results['niqe_compressed'].append(niqe_comp)
308
+
309
+ # 提取FID特征
310
+ original_features.append(metrics_calc.calculate_fid_features(img_original_np))
311
+ compressed_features.append(metrics_calc.calculate_fid_features(img_compressed_np))
312
+
313
+ # 如果有ground truth图像
314
+ if ground_truth_dir:
315
+ possible_names = [
316
+ f"{camera.image_name}.png",
317
+ f"{camera.image_name}.jpg",
318
+ f"{camera.image_name}.PNG",
319
+ f"{camera.image_name}.JPG"
320
+ ]
321
+
322
+ gt_img = None
323
+ for name in possible_names:
324
+ gt_path = Path(ground_truth_dir) / name
325
+ if gt_path.exists():
326
+ gt_img = np.array(Image.open(gt_path).convert('RGB')) / 255.0
327
+ break
328
+
329
+ if gt_img is not None:
330
+ results['psnr_vs_gt_original'].append(
331
+ metrics_calc.calculate_psnr(gt_img, img_original_np)
332
+ )
333
+ results['psnr_vs_gt_compressed'].append(
334
+ metrics_calc.calculate_psnr(gt_img, img_compressed_np)
335
+ )
336
+ results['ssim_vs_gt_original'].append(
337
+ metrics_calc.calculate_ssim(gt_img, img_original_np)
338
+ )
339
+ results['ssim_vs_gt_compressed'].append(
340
+ metrics_calc.calculate_ssim(gt_img, img_compressed_np)
341
+ )
342
+ results['lpips_vs_gt_original'].append(
343
+ metrics_calc.calculate_lpips(gt_img, img_original_np)
344
+ )
345
+ results['lpips_vs_gt_compressed'].append(
346
+ metrics_calc.calculate_lpips(gt_img, img_compressed_np)
347
+ )
348
+
349
+ # 计算FID
350
+ print("\n计算FID...")
351
+ original_features = np.array(original_features)
352
+ compressed_features = np.array(compressed_features)
353
+ fid_score = MetricsCalculator.calculate_fid(original_features, compressed_features)
354
+
355
+ # 打印结果
356
+ print("\n" + "="*60)
357
+ print("评估结果 (压缩后 vs 原始)")
358
+ print("="*60)
359
+ print(f"PSNR: {np.mean(results['psnr']):.2f} ± {np.std(results['psnr']):.2f} dB")
360
+ print(f"SSIM: {np.mean(results['ssim']):.4f} ± {np.std(results['ssim']):.4f}")
361
+ print(f"LPIPS: {np.mean(results['lpips']):.4f} ± {np.std(results['lpips']):.4f}")
362
+ if results['niqe_original']:
363
+ print(f"NIQE (原始): {np.mean(results['niqe_original']):.4f} ± {np.std(results['niqe_original']):.4f}")
364
+ print(f"NIQE (压缩): {np.mean(results['niqe_compressed']):.4f} ± {np.std(results['niqe_compressed']):.4f}")
365
+ print(f"FID: {fid_score:.4f}")
366
+
367
+ if ground_truth_dir and results['psnr_vs_gt_original']:
368
+ print("\n" + "="*60)
369
+ print("与Ground Truth对比")
370
+ print("="*60)
371
+ print("原始模型 vs GT:")
372
+ print(f" PSNR: {np.mean(results['psnr_vs_gt_original']):.2f} ± {np.std(results['psnr_vs_gt_original']):.2f} dB")
373
+ print(f" SSIM: {np.mean(results['ssim_vs_gt_original']):.4f} ± {np.std(results['ssim_vs_gt_original']):.4f}")
374
+ print(f" LPIPS: {np.mean(results['lpips_vs_gt_original']):.4f} ± {np.std(results['lpips_vs_gt_original']):.4f}")
375
+ print("\n压缩模型 vs GT:")
376
+ print(f" PSNR: {np.mean(results['psnr_vs_gt_compressed']):.2f} ± {np.std(results['psnr_vs_gt_compressed']):.2f} dB")
377
+ print(f" SSIM: {np.mean(results['ssim_vs_gt_compressed']):.4f} ± {np.std(results['ssim_vs_gt_compressed']):.4f}")
378
+ print(f" LPIPS: {np.mean(results['lpips_vs_gt_compressed']):.4f} ± {np.std(results['lpips_vs_gt_compressed']):.4f}")
379
+
380
+ # 保存结果
381
+ results_summary = {
382
+ 'compression_comparison': {
383
+ 'psnr_mean': float(np.mean(results['psnr'])),
384
+ 'psnr_std': float(np.std(results['psnr'])),
385
+ 'ssim_mean': float(np.mean(results['ssim'])),
386
+ 'ssim_std': float(np.std(results['ssim'])),
387
+ 'lpips_mean': float(np.mean(results['lpips'])),
388
+ 'lpips_std': float(np.std(results['lpips'])),
389
+ 'fid': float(fid_score),
390
+ 'num_gaussians_original': len(gaussians_original.get_xyz),
391
+ 'num_gaussians_compressed': len(gaussians_compressed.get_xyz),
392
+ 'compression_ratio': float(len(gaussians_compressed.get_xyz) / len(gaussians_original.get_xyz))
393
+ }
394
+ }
395
+
396
+ if results['niqe_original']:
397
+ results_summary['compression_comparison']['niqe_original_mean'] = float(np.mean(results['niqe_original']))
398
+ results_summary['compression_comparison']['niqe_original_std'] = float(np.std(results['niqe_original']))
399
+ results_summary['compression_comparison']['niqe_compressed_mean'] = float(np.mean(results['niqe_compressed']))
400
+ results_summary['compression_comparison']['niqe_compressed_std'] = float(np.std(results['niqe_compressed']))
401
+
402
+ if ground_truth_dir and results['psnr_vs_gt_original']:
403
+ results_summary['vs_ground_truth'] = {
404
+ 'original': {
405
+ 'psnr_mean': float(np.mean(results['psnr_vs_gt_original'])),
406
+ 'psnr_std': float(np.std(results['psnr_vs_gt_original'])),
407
+ 'ssim_mean': float(np.mean(results['ssim_vs_gt_original'])),
408
+ 'ssim_std': float(np.std(results['ssim_vs_gt_original'])),
409
+ 'lpips_mean': float(np.mean(results['lpips_vs_gt_original'])),
410
+ 'lpips_std': float(np.std(results['lpips_vs_gt_original']))
411
+ },
412
+ 'compressed': {
413
+ 'psnr_mean': float(np.mean(results['psnr_vs_gt_compressed'])),
414
+ 'psnr_std': float(np.std(results['psnr_vs_gt_compressed'])),
415
+ 'ssim_mean': float(np.mean(results['ssim_vs_gt_compressed'])),
416
+ 'ssim_std': float(np.std(results['ssim_vs_gt_compressed'])),
417
+ 'lpips_mean': float(np.mean(results['lpips_vs_gt_compressed'])),
418
+ 'lpips_std': float(np.std(results['lpips_vs_gt_compressed']))
419
+ }
420
+ }
421
+
422
+ with open(output_dir / "metrics.json", 'w') as f:
423
+ json.dump(results_summary, f, indent=2)
424
+
425
+ # 保存详细数据
426
+ results_for_json = {}
427
+ for key, value in results.items():
428
+ if isinstance(value, list) and len(value) > 0:
429
+ results_for_json[key] = [float(v) for v in value]
430
+
431
+ with open(output_dir / "detailed_metrics.json", 'w') as f:
432
+ json.dump(results_for_json, f, indent=2)
433
+
434
+ print(f"\n结果已保存到: {output_dir}")
435
+ print(f" - 原始渲染图像: {original_render_dir}")
436
+ print(f" - 压缩渲染图像: {compressed_render_dir}")
437
+ print(f" - 评估指标摘要: {output_dir / 'metrics.json'}")
438
+ print(f" - 详细指标数据: {output_dir / 'detailed_metrics.json'}")
439
+
440
+
441
+ if __name__ == "__main__":
442
+ import argparse
443
+
444
+ parser = argparse.ArgumentParser(description="评估3DGS压缩前后的渲染质量")
445
+ parser.add_argument("--original_ply", type=str, required=True, help="原始.ply文件路径")
446
+ parser.add_argument("--compressed_ply", type=str, required=True, help="压缩后.ply文件路径")
447
+ parser.add_argument("--cameras_json", type=str, required=True, help="cameras.json文件路径")
448
+ parser.add_argument("--output_dir", type=str, default="evaluation_results", help="输出目录")
449
+ parser.add_argument("--ground_truth_dir", type=str, default=None, help="真实图像目录(可选)")
450
+ parser.add_argument("--sh_degree", type=int, default=3, help="球谐函数阶数")
451
+ parser.add_argument("--kernel_size", type=float, default=0.1, help="渲染kernel大小")
452
+
453
+ args = parser.parse_args()
454
+
455
+ # 检查文件
456
+ if not os.path.exists(args.original_ply):
457
+ print(f"错误: 找不到原始PLY文件: {args.original_ply}")
458
+ sys.exit(1)
459
+
460
+ if not os.path.exists(args.compressed_ply):
461
+ print(f"错误: 找不到压缩PLY文件: {args.compressed_ply}")
462
+ sys.exit(1)
463
+
464
+ if not os.path.exists(args.cameras_json):
465
+ print(f"错误: 找不到相机参数文件: {args.cameras_json}")
466
+ sys.exit(1)
467
+
468
+ render_and_evaluate(
469
+ original_ply=args.original_ply,
470
+ compressed_ply=args.compressed_ply,
471
+ cameras_json=args.cameras_json,
472
+ output_dir=args.output_dir,
473
+ sh_degree=args.sh_degree,
474
+ kernel_size=args.kernel_size,
475
+ ground_truth_dir=args.ground_truth_dir
476
+ )