| | import numpy as np
|
| | import torch
|
| | import os
|
| | from pathlib import Path
|
| | from PIL import Image
|
| | import json
|
| | from tqdm import tqdm
|
| | import sys
|
| |
|
| |
|
| | from skimage.metrics import peak_signal_noise_ratio as psnr
|
| | from skimage.metrics import structural_similarity as ssim
|
| | import lpips
|
| | from torchvision import transforms
|
| | from scipy import linalg
|
| |
|
| |
|
| | try:
|
| | from scene.gaussian_model import GaussianModel
|
| | from utils.graphics_utils import focal2fov
|
| | from scene.cameras import Camera
|
| | from gaussian_renderer import render
|
| | from argparse import Namespace
|
| | except ImportError as e:
|
| | print(f"错误: 无法导入gaussian-splatting模块: {e}")
|
| | print("请确保gaussian-splatting仓库在Python路径中")
|
| | sys.exit(1)
|
| |
|
| |
|
| | class GaussianRenderer:
|
| | """
|
| | 基于原版gaussian-splatting的渲染器包装类
|
| | """
|
| | def __init__(self, ply_path, sh_degree=3, device='cuda'):
|
| | """
|
| | 初始化渲染器
|
| |
|
| | Args:
|
| | ply_path: .ply文件路径
|
| | sh_degree: 球谐函数阶数
|
| | device: 计算设备
|
| | """
|
| | self.ply_path = ply_path
|
| | self.sh_degree = sh_degree
|
| | self.device = device
|
| |
|
| |
|
| | self.gaussians = GaussianModel(sh_degree)
|
| | self.gaussians.load_ply(ply_path)
|
| |
|
| |
|
| | self.bg_color = torch.tensor([1, 1, 1], dtype=torch.float32, device=device)
|
| |
|
| |
|
| | self.pipe = Namespace()
|
| | self.pipe.convert_SHs_python = False
|
| | self.pipe.compute_cov3D_python = False
|
| | self.pipe.debug = False
|
| |
|
| | print(f"加载模型: {ply_path}")
|
| | print(f" - 高斯点数: {len(self.gaussians.get_xyz)}")
|
| | print(f" - SH阶数: {sh_degree}")
|
| |
|
| | def render(self, camera):
|
| | """
|
| | 渲染单个视角
|
| |
|
| | Args:
|
| | camera: Camera对象
|
| |
|
| | Returns:
|
| | rendered_image: numpy array, shape (H, W, 3), 值域[0, 1]
|
| | """
|
| | with torch.no_grad():
|
| | rendering = render(camera, self.gaussians, self.pipe, self.bg_color)
|
| | image = rendering["render"]
|
| |
|
| |
|
| | image = image.cpu().numpy()
|
| | image = np.transpose(image, (1, 2, 0))
|
| |
|
| |
|
| | image = np.clip(image, 0, 1)
|
| |
|
| | return image
|
| |
|
| |
|
| | class MetricsCalculator:
|
| | """评估指标计算器"""
|
| |
|
| | def __init__(self, device='cuda'):
|
| | self.device = device
|
| |
|
| |
|
| | self.lpips_fn = lpips.LPIPS(net='alex').to(device)
|
| |
|
| |
|
| | self.transform = transforms.Compose([
|
| | transforms.ToTensor(),
|
| | transforms.Normalize(mean=[0.5, 0.5, 0.5], std=[0.5, 0.5, 0.5])
|
| | ])
|
| |
|
| | def calculate_psnr(self, img1, img2):
|
| | """
|
| | 计算PSNR
|
| |
|
| | Args:
|
| | img1, img2: numpy arrays, shape (H, W, 3), 值域[0, 1]
|
| | """
|
| | return psnr(img1, img2, data_range=1.0)
|
| |
|
| | def calculate_ssim(self, img1, img2):
|
| | """
|
| | 计算SSIM
|
| |
|
| | Args:
|
| | img1, img2: numpy arrays, shape (H, W, 3), 值域[0, 1]
|
| | """
|
| | return ssim(img1, img2, data_range=1.0, channel_axis=2, multichannel=True)
|
| |
|
| | def calculate_lpips(self, img1, img2):
|
| | """
|
| | 计算LPIPS
|
| |
|
| | Args:
|
| | img1, img2: numpy arrays, shape (H, W, 3), 值域[0, 1]
|
| | """
|
| |
|
| | img1_tensor = torch.from_numpy(img1).permute(2, 0, 1).unsqueeze(0).float().to(self.device)
|
| | img2_tensor = torch.from_numpy(img2).permute(2, 0, 1).unsqueeze(0).float().to(self.device)
|
| |
|
| |
|
| | img1_tensor = img1_tensor * 2 - 1
|
| | img2_tensor = img2_tensor * 2 - 1
|
| |
|
| | with torch.no_grad():
|
| | lpips_value = self.lpips_fn(img1_tensor, img2_tensor)
|
| |
|
| | return lpips_value.item()
|
| |
|
| | def calculate_niqe(self, img):
|
| | """
|
| | 计算NIQE (无参考图像质量评估)
|
| |
|
| | Args:
|
| | img: numpy array, shape (H, W, 3), 值域[0, 1]
|
| | """
|
| | try:
|
| | import pyiqa
|
| | niqe_metric = pyiqa.create_metric('niqe', device=self.device)
|
| | img_tensor = torch.from_numpy(img).permute(2, 0, 1).unsqueeze(0).float().to(self.device)
|
| | score = niqe_metric(img_tensor).item()
|
| | return score
|
| | except ImportError:
|
| | print("警告: pyiqa未安装,无法计算NIQE。请运行: pip install pyiqa")
|
| | return None
|
| |
|
| | def calculate_fid_features(self, img):
|
| | """
|
| | 提取FID特征(使用InceptionV3)
|
| |
|
| | Args:
|
| | img: numpy array, shape (H, W, 3), 值域[0, 1]
|
| | """
|
| | from torchvision.models import inception_v3
|
| |
|
| | if not hasattr(self, 'inception_model'):
|
| | self.inception_model = inception_v3(pretrained=True, transform_input=False).to(self.device)
|
| | self.inception_model.eval()
|
| |
|
| | self.inception_model.fc = torch.nn.Identity()
|
| |
|
| |
|
| | img_pil = Image.fromarray((img * 255).astype(np.uint8))
|
| | img_pil = img_pil.resize((299, 299), Image.BILINEAR)
|
| | img_array = np.array(img_pil) / 255.0
|
| |
|
| |
|
| | img_tensor = torch.from_numpy(img_array).permute(2, 0, 1).unsqueeze(0).float().to(self.device)
|
| | img_tensor = (img_tensor - 0.5) / 0.5
|
| |
|
| | with torch.no_grad():
|
| | features = self.inception_model(img_tensor)
|
| |
|
| | return features.cpu().numpy().flatten()
|
| |
|
| | @staticmethod
|
| | def calculate_fid(features1, features2):
|
| | """
|
| | 计算FID分数
|
| |
|
| | Args:
|
| | features1, features2: numpy arrays of shape (N, D), 特征向量
|
| | """
|
| | mu1, sigma1 = features1.mean(axis=0), np.cov(features1, rowvar=False)
|
| | mu2, sigma2 = features2.mean(axis=0), np.cov(features2, rowvar=False)
|
| |
|
| |
|
| | diff = mu1 - mu2
|
| |
|
| |
|
| | covmean, _ = linalg.sqrtm(sigma1.dot(sigma2), disp=False)
|
| |
|
| |
|
| | if np.iscomplexobj(covmean):
|
| | covmean = covmean.real
|
| |
|
| | fid = diff.dot(diff) + np.trace(sigma1 + sigma2 - 2 * covmean)
|
| | return fid
|
| |
|
| |
|
| | def load_cameras(camera_path, device='cuda'):
|
| | """
|
| | 从cameras.json加载相机参数
|
| |
|
| | Args:
|
| | camera_path: cameras.json文件路径
|
| | device: 计算设备
|
| |
|
| | Returns:
|
| | cameras: Camera对象列表
|
| | """
|
| | with open(camera_path, 'r') as f:
|
| | camera_data = json.load(f)
|
| |
|
| | cameras = []
|
| |
|
| | for cam_info in camera_data:
|
| |
|
| | uid = cam_info['id']
|
| | colmap_id = cam_info['id']
|
| | img_name = cam_info['img_name']
|
| | width = cam_info['width']
|
| | height = cam_info['height']
|
| |
|
| |
|
| | fx = cam_info['fx']
|
| | fy = cam_info['fy']
|
| |
|
| |
|
| | position = np.array(cam_info['position'])
|
| | rotation = np.array(cam_info['rotation'])
|
| |
|
| |
|
| |
|
| |
|
| | R_w2c = rotation.T
|
| | T_w2c = -R_w2c @ position
|
| |
|
| |
|
| | R_tensor = torch.from_numpy(R_w2c).float()
|
| | T_tensor = torch.from_numpy(T_w2c).float()
|
| |
|
| |
|
| | FovX = focal2fov(fx, width)
|
| | FovY = focal2fov(fy, height)
|
| |
|
| |
|
| |
|
| |
|
| | try:
|
| | camera = Camera(
|
| | colmap_id=colmap_id,
|
| | R=R_tensor,
|
| | T=T_tensor,
|
| | FoVx=FovX,
|
| | FoVy=FovY,
|
| | image=torch.zeros((3, height, width)),
|
| | gt_alpha_mask=None,
|
| | image_name=img_name,
|
| | uid=uid,
|
| | data_device=device
|
| | )
|
| | except TypeError:
|
| |
|
| | camera = Camera(
|
| | colmap_id=colmap_id,
|
| | R=R_tensor,
|
| | T=T_tensor,
|
| | FoVx=FovX,
|
| | FoVy=FovY,
|
| | image=torch.zeros((3, height, width)),
|
| | gt_alpha_mask=None,
|
| | image_name=img_name,
|
| | uid=uid
|
| | )
|
| |
|
| | cameras.append(camera)
|
| |
|
| | return cameras
|
| |
|
| |
|
| | def render_and_evaluate(original_ply, compressed_ply, camera_path, output_dir,
|
| | ground_truth_dir=None, sh_degree=3, device='cuda'):
|
| | """
|
| | 渲染并评估压缩前后的3DGS
|
| |
|
| | Args:
|
| | original_ply: 原始3DGS的.ply文件路径
|
| | compressed_ply: 压缩后3DGS的.ply文件路径
|
| | camera_path: 相机参数文件路径
|
| | output_dir: 输出目录
|
| | ground_truth_dir: 真实图像目录(如果有的话,用于计算与GT的指标)
|
| | sh_degree: 球谐函数阶数
|
| | device: 计算设备
|
| | """
|
| | output_dir = Path(output_dir)
|
| | output_dir.mkdir(parents=True, exist_ok=True)
|
| |
|
| |
|
| | original_render_dir = output_dir / "original"
|
| | compressed_render_dir = output_dir / "compressed"
|
| | original_render_dir.mkdir(exist_ok=True)
|
| | compressed_render_dir.mkdir(exist_ok=True)
|
| |
|
| |
|
| | print("初始化渲染器...")
|
| | original_renderer = GaussianRenderer(original_ply, sh_degree=sh_degree, device=device)
|
| | compressed_renderer = GaussianRenderer(compressed_ply, sh_degree=sh_degree, device=device)
|
| |
|
| |
|
| | metrics_calc = MetricsCalculator(device=device)
|
| |
|
| |
|
| | print("加载相机参数...")
|
| | cameras = load_cameras(camera_path, device=device)
|
| | print(f"加载了 {len(cameras)} 个相机视角")
|
| |
|
| |
|
| | results = {
|
| | 'psnr': [],
|
| | 'ssim': [],
|
| | 'lpips': [],
|
| | 'niqe_original': [],
|
| | 'niqe_compressed': []
|
| | }
|
| |
|
| |
|
| | if ground_truth_dir:
|
| | results['psnr_vs_gt_original'] = []
|
| | results['psnr_vs_gt_compressed'] = []
|
| | results['ssim_vs_gt_original'] = []
|
| | results['ssim_vs_gt_compressed'] = []
|
| | results['lpips_vs_gt_original'] = []
|
| | results['lpips_vs_gt_compressed'] = []
|
| |
|
| |
|
| | original_features = []
|
| | compressed_features = []
|
| |
|
| | print("开始渲染和评估...")
|
| | for i, camera in enumerate(tqdm(cameras, desc="渲染进度")):
|
| |
|
| | original_img = original_renderer.render(camera)
|
| | compressed_img = compressed_renderer.render(camera)
|
| |
|
| |
|
| | Image.fromarray((original_img * 255).astype(np.uint8)).save(
|
| | original_render_dir / f"render_{i:04d}.png"
|
| | )
|
| | Image.fromarray((compressed_img * 255).astype(np.uint8)).save(
|
| | compressed_render_dir / f"render_{i:04d}.png"
|
| | )
|
| |
|
| |
|
| | results['psnr'].append(metrics_calc.calculate_psnr(original_img, compressed_img))
|
| | results['ssim'].append(metrics_calc.calculate_ssim(original_img, compressed_img))
|
| | results['lpips'].append(metrics_calc.calculate_lpips(original_img, compressed_img))
|
| |
|
| |
|
| | niqe_orig = metrics_calc.calculate_niqe(original_img)
|
| | niqe_comp = metrics_calc.calculate_niqe(compressed_img)
|
| | if niqe_orig is not None:
|
| | results['niqe_original'].append(niqe_orig)
|
| | results['niqe_compressed'].append(niqe_comp)
|
| |
|
| |
|
| | original_features.append(metrics_calc.calculate_fid_features(original_img))
|
| | compressed_features.append(metrics_calc.calculate_fid_features(compressed_img))
|
| |
|
| |
|
| | if ground_truth_dir:
|
| |
|
| | possible_names = [
|
| | f"image_{i:04d}.png",
|
| | f"image_{i:04d}.jpg",
|
| | f"{i:04d}.png",
|
| | f"{i:04d}.jpg",
|
| | camera.image_name
|
| | ]
|
| |
|
| | gt_img = None
|
| | for name in possible_names:
|
| | gt_path = Path(ground_truth_dir) / name
|
| | if gt_path.exists():
|
| | gt_img = np.array(Image.open(gt_path).convert('RGB')) / 255.0
|
| | break
|
| |
|
| | if gt_img is not None:
|
| | results['psnr_vs_gt_original'].append(
|
| | metrics_calc.calculate_psnr(gt_img, original_img)
|
| | )
|
| | results['psnr_vs_gt_compressed'].append(
|
| | metrics_calc.calculate_psnr(gt_img, compressed_img)
|
| | )
|
| | results['ssim_vs_gt_original'].append(
|
| | metrics_calc.calculate_ssim(gt_img, original_img)
|
| | )
|
| | results['ssim_vs_gt_compressed'].append(
|
| | metrics_calc.calculate_ssim(gt_img, compressed_img)
|
| | )
|
| | results['lpips_vs_gt_original'].append(
|
| | metrics_calc.calculate_lpips(gt_img, original_img)
|
| | )
|
| | results['lpips_vs_gt_compressed'].append(
|
| | metrics_calc.calculate_lpips(gt_img, compressed_img)
|
| | )
|
| |
|
| |
|
| | print("计算FID...")
|
| | original_features = np.array(original_features)
|
| | compressed_features = np.array(compressed_features)
|
| | fid_score = MetricsCalculator.calculate_fid(original_features, compressed_features)
|
| |
|
| |
|
| | print("\n" + "="*50)
|
| | print("评估结果 (压缩后 vs 原始)")
|
| | print("="*50)
|
| | print(f"PSNR: {np.mean(results['psnr']):.2f} ± {np.std(results['psnr']):.2f} dB")
|
| | print(f"SSIM: {np.mean(results['ssim']):.4f} ± {np.std(results['ssim']):.4f}")
|
| | print(f"LPIPS: {np.mean(results['lpips']):.4f} ± {np.std(results['lpips']):.4f}")
|
| | if results['niqe_original']:
|
| | print(f"NIQE (原始): {np.mean(results['niqe_original']):.4f} ± {np.std(results['niqe_original']):.4f}")
|
| | print(f"NIQE (压缩): {np.mean(results['niqe_compressed']):.4f} ± {np.std(results['niqe_compressed']):.4f}")
|
| | print(f"FID: {fid_score:.4f}")
|
| |
|
| | if ground_truth_dir and results['psnr_vs_gt_original']:
|
| | print("\n" + "="*50)
|
| | print("与Ground Truth对比")
|
| | print("="*50)
|
| | print("原始模型 vs GT:")
|
| | print(f" PSNR: {np.mean(results['psnr_vs_gt_original']):.2f} ± {np.std(results['psnr_vs_gt_original']):.2f} dB")
|
| | print(f" SSIM: {np.mean(results['ssim_vs_gt_original']):.4f} ± {np.std(results['ssim_vs_gt_original']):.4f}")
|
| | print(f" LPIPS: {np.mean(results['lpips_vs_gt_original']):.4f} ± {np.std(results['lpips_vs_gt_original']):.4f}")
|
| | print("\n压缩模型 vs GT:")
|
| | print(f" PSNR: {np.mean(results['psnr_vs_gt_compressed']):.2f} ± {np.std(results['psnr_vs_gt_compressed']):.2f} dB")
|
| | print(f" SSIM: {np.mean(results['ssim_vs_gt_compressed']):.4f} ± {np.std(results['ssim_vs_gt_compressed']):.4f}")
|
| | print(f" LPIPS: {np.mean(results['lpips_vs_gt_compressed']):.4f} ± {np.std(results['lpips_vs_gt_compressed']):.4f}")
|
| |
|
| |
|
| | results_summary = {
|
| | 'compression_comparison': {
|
| | 'psnr_mean': float(np.mean(results['psnr'])),
|
| | 'psnr_std': float(np.std(results['psnr'])),
|
| | 'ssim_mean': float(np.mean(results['ssim'])),
|
| | 'ssim_std': float(np.std(results['ssim'])),
|
| | 'lpips_mean': float(np.mean(results['lpips'])),
|
| | 'lpips_std': float(np.std(results['lpips'])),
|
| | 'fid': float(fid_score)
|
| | }
|
| | }
|
| |
|
| | if results['niqe_original']:
|
| | results_summary['compression_comparison']['niqe_original_mean'] = float(np.mean(results['niqe_original']))
|
| | results_summary['compression_comparison']['niqe_original_std'] = float(np.std(results['niqe_original']))
|
| | results_summary['compression_comparison']['niqe_compressed_mean'] = float(np.mean(results['niqe_compressed']))
|
| | results_summary['compression_comparison']['niqe_compressed_std'] = float(np.std(results['niqe_compressed']))
|
| |
|
| | if ground_truth_dir and results['psnr_vs_gt_original']:
|
| | results_summary['vs_ground_truth'] = {
|
| | 'original': {
|
| | 'psnr_mean': float(np.mean(results['psnr_vs_gt_original'])),
|
| | 'psnr_std': float(np.std(results['psnr_vs_gt_original'])),
|
| | 'ssim_mean': float(np.mean(results['ssim_vs_gt_original'])),
|
| | 'ssim_std': float(np.std(results['ssim_vs_gt_original'])),
|
| | 'lpips_mean': float(np.mean(results['lpips_vs_gt_original'])),
|
| | 'lpips_std': float(np.std(results['lpips_vs_gt_original']))
|
| | },
|
| | 'compressed': {
|
| | 'psnr_mean': float(np.mean(results['psnr_vs_gt_compressed'])),
|
| | 'psnr_std': float(np.std(results['psnr_vs_gt_compressed'])),
|
| | 'ssim_mean': float(np.mean(results['ssim_vs_gt_compressed'])),
|
| | 'ssim_std': float(np.std(results['ssim_vs_gt_compressed'])),
|
| | 'lpips_mean': float(np.mean(results['lpips_vs_gt_compressed'])),
|
| | 'lpips_std': float(np.std(results['lpips_vs_gt_compressed']))
|
| | }
|
| | }
|
| |
|
| |
|
| | with open(output_dir / "metrics.json", 'w') as f:
|
| | json.dump(results_summary, f, indent=2)
|
| |
|
| |
|
| | with open(output_dir / "detailed_metrics.json", 'w') as f:
|
| |
|
| | results_for_json = {}
|
| | for key, value in results.items():
|
| | if isinstance(value, list) and len(value) > 0:
|
| | results_for_json[key] = [float(v) if not isinstance(v, (list, dict)) else v for v in value]
|
| | json.dump(results_for_json, f, indent=2)
|
| |
|
| | print(f"\n结果已保存到: {output_dir}")
|
| | print(f" - 原始渲染图像: {original_render_dir}")
|
| | print(f" - 压缩渲染图像: {compressed_render_dir}")
|
| | print(f" - 评估指标摘要: {output_dir / 'metrics.json'}")
|
| | print(f" - 详细指标数据: {output_dir / 'detailed_metrics.json'}")
|
| | """
|
| | 渲染并评估压缩前后的3DGS
|
| |
|
| | Args:
|
| | original_ply: 原始3DGS的.ply文件路径
|
| | compressed_ply: 压缩后3DGS的.ply文件路径
|
| | camera_path: 相机参数文件路径
|
| | output_dir: 输出目录
|
| | ground_truth_dir: 真实图像目录(如果有的话,用于计算与GT的指标)
|
| | """
|
| | output_dir = Path(output_dir)
|
| | output_dir.mkdir(parents=True, exist_ok=True)
|
| |
|
| |
|
| | original_render_dir = output_dir / "original"
|
| | compressed_render_dir = output_dir / "compressed"
|
| | original_render_dir.mkdir(exist_ok=True)
|
| | compressed_render_dir.mkdir(exist_ok=True)
|
| |
|
| |
|
| | print("初始化渲染器...")
|
| | original_renderer = GaussianRenderer(original_ply)
|
| | compressed_renderer = GaussianRenderer(compressed_ply)
|
| |
|
| |
|
| | metrics_calc = MetricsCalculator()
|
| |
|
| |
|
| | print("加载相机参数...")
|
| | cameras = load_cameras(camera_path)
|
| |
|
| |
|
| | results = {
|
| | 'psnr': [],
|
| | 'ssim': [],
|
| | 'lpips': [],
|
| | 'niqe_original': [],
|
| | 'niqe_compressed': []
|
| | }
|
| |
|
| |
|
| | if ground_truth_dir:
|
| | results['psnr_vs_gt_original'] = []
|
| | results['psnr_vs_gt_compressed'] = []
|
| | results['ssim_vs_gt_original'] = []
|
| | results['ssim_vs_gt_compressed'] = []
|
| | results['lpips_vs_gt_original'] = []
|
| | results['lpips_vs_gt_compressed'] = []
|
| |
|
| |
|
| | original_features = []
|
| | compressed_features = []
|
| |
|
| | print("开始渲染和评估...")
|
| | for i, camera in enumerate(tqdm(cameras)):
|
| |
|
| | original_img = original_renderer.render(camera)
|
| | compressed_img = compressed_renderer.render(camera)
|
| |
|
| |
|
| | Image.fromarray((original_img * 255).astype(np.uint8)).save(
|
| | original_render_dir / f"render_{i:04d}.png"
|
| | )
|
| | Image.fromarray((compressed_img * 255).astype(np.uint8)).save(
|
| | compressed_render_dir / f"render_{i:04d}.png"
|
| | )
|
| |
|
| |
|
| | results['psnr'].append(metrics_calc.calculate_psnr(original_img, compressed_img))
|
| | results['ssim'].append(metrics_calc.calculate_ssim(original_img, compressed_img))
|
| | results['lpips'].append(metrics_calc.calculate_lpips(original_img, compressed_img))
|
| |
|
| |
|
| | niqe_orig = metrics_calc.calculate_niqe(original_img)
|
| | niqe_comp = metrics_calc.calculate_niqe(compressed_img)
|
| | if niqe_orig is not None:
|
| | results['niqe_original'].append(niqe_orig)
|
| | results['niqe_compressed'].append(niqe_comp)
|
| |
|
| |
|
| | original_features.append(metrics_calc.calculate_fid_features(original_img))
|
| | compressed_features.append(metrics_calc.calculate_fid_features(compressed_img))
|
| |
|
| |
|
| | if ground_truth_dir:
|
| | gt_path = Path(ground_truth_dir) / f"image_{i:04d}.png"
|
| | if gt_path.exists():
|
| | gt_img = np.array(Image.open(gt_path)) / 255.0
|
| |
|
| | results['psnr_vs_gt_original'].append(
|
| | metrics_calc.calculate_psnr(gt_img, original_img)
|
| | )
|
| | results['psnr_vs_gt_compressed'].append(
|
| | metrics_calc.calculate_psnr(gt_img, compressed_img)
|
| | )
|
| | results['ssim_vs_gt_original'].append(
|
| | metrics_calc.calculate_ssim(gt_img, original_img)
|
| | )
|
| | results['ssim_vs_gt_compressed'].append(
|
| | metrics_calc.calculate_ssim(gt_img, compressed_img)
|
| | )
|
| | results['lpips_vs_gt_original'].append(
|
| | metrics_calc.calculate_lpips(gt_img, original_img)
|
| | )
|
| | results['lpips_vs_gt_compressed'].append(
|
| | metrics_calc.calculate_lpips(gt_img, compressed_img)
|
| | )
|
| |
|
| |
|
| | original_features = np.array(original_features)
|
| | compressed_features = np.array(compressed_features)
|
| | fid_score = MetricsCalculator.calculate_fid(original_features, compressed_features)
|
| |
|
| |
|
| | print("\n" + "="*50)
|
| | print("评估结果 (压缩后 vs 原始)")
|
| | print("="*50)
|
| | print(f"PSNR: {np.mean(results['psnr']):.2f} ± {np.std(results['psnr']):.2f} dB")
|
| | print(f"SSIM: {np.mean(results['ssim']):.4f} ± {np.std(results['ssim']):.4f}")
|
| | print(f"LPIPS: {np.mean(results['lpips']):.4f} ± {np.std(results['lpips']):.4f}")
|
| | if results['niqe_original']:
|
| | print(f"NIQE (原始): {np.mean(results['niqe_original']):.4f}")
|
| | print(f"NIQE (压缩): {np.mean(results['niqe_compressed']):.4f}")
|
| | print(f"FID: {fid_score:.4f}")
|
| |
|
| | if ground_truth_dir:
|
| | print("\n" + "="*50)
|
| | print("与Ground Truth对比")
|
| | print("="*50)
|
| | print("原始模型 vs GT:")
|
| | print(f" PSNR: {np.mean(results['psnr_vs_gt_original']):.2f} dB")
|
| | print(f" SSIM: {np.mean(results['ssim_vs_gt_original']):.4f}")
|
| | print(f" LPIPS: {np.mean(results['lpips_vs_gt_original']):.4f}")
|
| | print("\n压缩模型 vs GT:")
|
| | print(f" PSNR: {np.mean(results['psnr_vs_gt_compressed']):.2f} dB")
|
| | print(f" SSIM: {np.mean(results['ssim_vs_gt_compressed']):.4f}")
|
| | print(f" LPIPS: {np.mean(results['lpips_vs_gt_compressed']):.4f}")
|
| |
|
| |
|
| | results_summary = {
|
| | 'compression_comparison': {
|
| | 'psnr_mean': float(np.mean(results['psnr'])),
|
| | 'psnr_std': float(np.std(results['psnr'])),
|
| | 'ssim_mean': float(np.mean(results['ssim'])),
|
| | 'ssim_std': float(np.std(results['ssim'])),
|
| | 'lpips_mean': float(np.mean(results['lpips'])),
|
| | 'lpips_std': float(np.std(results['lpips'])),
|
| | 'fid': float(fid_score)
|
| | }
|
| | }
|
| |
|
| | if results['niqe_original']:
|
| | results_summary['compression_comparison']['niqe_original'] = float(np.mean(results['niqe_original']))
|
| | results_summary['compression_comparison']['niqe_compressed'] = float(np.mean(results['niqe_compressed']))
|
| |
|
| | if ground_truth_dir:
|
| | results_summary['vs_ground_truth'] = {
|
| | 'original': {
|
| | 'psnr': float(np.mean(results['psnr_vs_gt_original'])),
|
| | 'ssim': float(np.mean(results['ssim_vs_gt_original'])),
|
| | 'lpips': float(np.mean(results['lpips_vs_gt_original']))
|
| | },
|
| | 'compressed': {
|
| | 'psnr': float(np.mean(results['psnr_vs_gt_compressed'])),
|
| | 'ssim': float(np.mean(results['ssim_vs_gt_compressed'])),
|
| | 'lpips': float(np.mean(results['lpips_vs_gt_compressed']))
|
| | }
|
| | }
|
| |
|
| |
|
| | with open(output_dir / "metrics.json", 'w') as f:
|
| | json.dump(results_summary, f, indent=2)
|
| |
|
| |
|
| | with open(output_dir / "detailed_metrics.json", 'w') as f:
|
| | json.dump(results, f, indent=2)
|
| |
|
| | print(f"\n结果已保存到: {output_dir}")
|
| | print(f" - 原始渲染图像: {original_render_dir}")
|
| | print(f" - 压缩渲染图像: {compressed_render_dir}")
|
| | print(f" - 评估指标: {output_dir / 'metrics.json'}")
|
| |
|
| |
|
| | if __name__ == "__main__":
|
| | import argparse
|
| |
|
| | parser = argparse.ArgumentParser(description="评估3DGS压缩前后的渲染质量")
|
| | parser.add_argument("--original_ply", type=str, required=True, help="原始.ply文件路径")
|
| | parser.add_argument("--compressed_ply", type=str, required=True, help="压缩后.ply文件路径")
|
| | parser.add_argument("--cameras", type=str, required=True, help="cameras.json文件路径")
|
| | parser.add_argument("--output_dir", type=str, default="evaluation_results", help="输出目录")
|
| | parser.add_argument("--ground_truth_dir", type=str, default=None, help="真实图像目录(可选)")
|
| | parser.add_argument("--sh_degree", type=int, default=3, help="球谐函数阶数")
|
| | parser.add_argument("--device", type=str, default="cuda", help="计算设备")
|
| |
|
| | args = parser.parse_args()
|
| |
|
| |
|
| | if not os.path.exists(args.original_ply):
|
| | print(f"错误: 找不到原始PLY文件: {args.original_ply}")
|
| | sys.exit(1)
|
| |
|
| | if not os.path.exists(args.compressed_ply):
|
| | print(f"错误: 找不到压缩PLY文件: {args.compressed_ply}")
|
| | sys.exit(1)
|
| |
|
| | if not os.path.exists(args.cameras):
|
| | print(f"错误: 找不到相机参数文件: {args.cameras}")
|
| | sys.exit(1)
|
| |
|
| | render_and_evaluate(
|
| | original_ply=args.original_ply,
|
| | compressed_ply=args.compressed_ply,
|
| | camera_path=args.cameras,
|
| | output_dir=args.output_dir,
|
| | ground_truth_dir=args.ground_truth_dir,
|
| | sh_degree=args.sh_degree,
|
| | device=args.device
|
| | ) |