图像评估指标
FID、PSNR、SSIM、LPIPS等图像评估指标
图像评估指标
FID
FID(Frechet Inception Distance)是一种评估生成模型生成图像质量的指标。它通过比较生成图像与实际图像在Inception网络特征空间的分布来计算两者之间的距离。FID值越小,表示生成图像与实际图像越相似,质量越高。FID可以反映图像的多样性及生成模型的性能。
from torch_fidelity import calculate_metrics
# 输入生成图像和实际图像的路径
metrics_dict = calculate_metrics(
input1='path_to_generated_images', # 生成图像的路径
input2='path_to_real_images', # 实际图像的路径
cuda=True, # 如果有GPU,可以启用 CUDA 加速
isc=False, # 计算 Inception Score 可选,默认 False
fid=True # 计算 FID
)
fid_score = metrics_dict['frechet_inception_distance']
print(f'FID: {fid_score}')
PSNR
PSNR(Peak Signal-to-Noise Ratio)用于量化图像重建质量,尤其适用于图像压缩和去噪等任务。它通过比较原始图像和重建图像之间的峰值信噪比来评估图像的恢复质量。PSNR值越高,表示重建图像与原始图像越接近。典型计算方法公式如下:
[ \text{PSNR} = 10 \cdot \log_{10}\left(\frac{\text{MAX}_I^2}{\text{MSE}}\right) ]
其中,MAX_I为图像中像素的最大可能值,MSE为均方误差。
import numpy as np
from skimage.metrics import peak_signal_noise_ratio
from skimage.io import imread
# 读取图像
original_image = imread('path_to_original_image')
compressed_image = imread('path_to_compressed_image')
# 计算 PSNR
psnr_value = peak_signal_noise_ratio(original_image, compressed_image)
print(f'PSNR: {psnr_value} dB')
SSIM
SSIM(Structural Similarity Index)是一种衡量两幅图像相似度的方法。不同于PSNR和MSE,SSIM更注重图像的结构信息,包括亮度、对比度和结构这三个方面。SSIM值从-1到1,越接近1表示两幅图像越相似。SSIM公式如下:
[ \text{SSIM}(x, y) = \frac{(2\mu_x\mu_y + c_1)(2\sigma_{xy} + c_2)}{(\mu_x^2 + \mu_y^2 + c_1)(\sigma_x^2 + \sigma_y^2 + c_2)} ]
其中,( \mu_x )、( \mu_y ) 是均值,( \sigma_x^2 )、( \sigma_y^2 ) 是方差,( \sigma_{xy} ) 是协方差,( c_1 )、( c_2 ) 是用来稳定分母的常数。
from skimage.metrics import structural_similarity
# 读取图像
original_image = imread('path_to_original_image')
compressed_image = imread('path_to_compressed_image')
# 计算 SSIM
ssim_value, ssim_map = structural_similarity(original_image, compressed_image, full=True, multichannel=True)
print(f'SSIM: {ssim_value}')
LPIPS
LPIPS(Learned Perceptual Image Patch Similarity)是一种基于深度学习的感知相似度指标, 用于评估两张图像之间的感知差异。不同于传统的图像相似度算法,LPIPS使用预训练的卷积神经网络根据单个图像块生成特征,并计算特征之间的距离来评估图像相似度。主要公式如下:
[ \text{LPIPS}(x, y) = \sum_l \frac{1}{H_l W_l} \sum_{h=1}^{H_l} \sum_{w=1}^{W_l} ||\hat{y}_l^{(h,w)} - \hat{x}_l{(h,w)}||2 ]
其中,( x )、( y ) 是输入图像,( \hat{x}_l )、( \hat{y}_l ) 是预训练网络l层的特征图,H_l 和 W_l 是特征图的高度和宽度。LPIPS值越小,表示两张图像在感知上越相似。
import torch
import lpips
from skimage.io import imread
from skimage.transform import resize
# 读取和预处理图像
def preprocess_image(image_path):
image = imread(image_path)
image = resize(image, (256, 256), anti_aliasing=True) # 调整图像大小以匹配模型要求
image = torch.tensor(image).permute(2, 0, 1).unsqueeze(0).float() # 转换成 PyTorch 张量
return image
image1 = preprocess_image('path_to_image1')
image2 = preprocess_image('path_to_image2')
# 初始化 LPIPS 模型
loss_fn = lpips.LPIPS(net='alex') # 使用 alex 作为底层网络
# 计算 LPIPS value
lpips_value = loss_fn(image1, image2)
print(f'LPIPS: {lpips_value.item()}')
更多推荐
所有评论(0)