psnr和ssim的实现
时间: 2023-09-01 19:10:42 浏览: 96
PSNR(Peak Signal to Noise Ratio)和SSIM(Structural Similarity Index)是图像质量评价的两个常用指标。它们的实现可以用以下两种方式:
1. 使用Python的OpenCV库:
```python
import cv2
import numpy as np
def psnr(img1, img2):
mse = np.mean((img1 - img2) ** 2)
if mse == 0:
return 100
PIXEL_MAX = 255.0
return 20 * np.log10(PIXEL_MAX / np.sqrt(mse))
def ssim(img1, img2):
ssim = cv2.SSIM(img1, img2)
return ssim
```
2. 自己实现:
```python
import numpy as np
from scipy import signal
def psnr(img1, img2):
mse = np.mean((img1 - img2) ** 2)
if mse == 0:
return 100
PIXEL_MAX = 255
return 20 * np.log10(PIXEL_MAX / np.sqrt(mse))
def ssim(img1, img2):
# constants
K1 = 0.01
K2 = 0.03
L = 255
C1 = (K1 * L) ** 2
C2 = (K2 * L) ** 2
# mean of the images
mu1 = np.mean(img1)
mu2 = np.mean(img2)
# variance of the images
sigma1_sq = np.var(img1)
sigma2_sq = np.var(img2)
# covariance of the images
sigma12 = signal.correlate2d(img1, img2, boundary='symm', mode='same') / img1.size
# numerator of SSIM
numerator = ((2 * mu1 * mu2 + C1) * (2 * sigma12 + C2))
# denominator of SSIM
denominator = ((mu1 ** 2 + mu2 ** 2 + C1) * (sigma1_sq + sigma2_sq + C2))
# SSIM
ssim = numerator / denominator
return ssim
```
其中,PSNR的计算公式为:
$PSNR = 20 \log_{10} \frac{MAX_I}{\sqrt{MSE}}$
其中,$MAX_I$为像素值的最大值,通常为255;$MSE$为均方误差,计算公式为:
$MSE = \frac{1}{mn} \sum_{i=0}^{m-1} \sum_{j=0}^{n-1} [I(i,j) - K(i,j)]^2$
其中,$m$和$n$为图像的大小,$I(i,j)$和$K(i,j)$分别为两幅图像的像素值。
SSIM的计算公式为:
$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$为两个常数,用于避免分母为0。
阅读全文