计算PSNR和SSIM代码
时间: 2024-06-11 19:01:01 浏览: 197
以下是Python中计算PSNR和SSIM的代码:
```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):
C1 = (0.01 * 255) ** 2
C2 = (0.03 * 255) ** 2
img1 = img1.astype(np.float64)
img2 = img2.astype(np.float64)
kernel = cv2.getGaussianKernel(11, 1.5)
window = np.outer(kernel, kernel.transpose())
mu1 = cv2.filter2D(img1, -1, window)[5:-5, 5:-5]
mu2 = cv2.filter2D(img2, -1, window)[5:-5, 5:-5]
mu1_sq = mu1 ** 2
mu2_sq = mu2 ** 2
mu1_mu2 = mu1 * mu2
sigma1_sq = cv2.filter2D(img1 ** 2, -1, window)[5:-5, 5:-5] - mu1_sq
sigma2_sq = cv2.filter2D(img2 ** 2, -1, window)[5:-5, 5:-5] - mu2_sq
sigma12 = cv2.filter2D(img1 * img2, -1, window)[5:-5, 5:-5] - mu1_mu2
ssim_map = ((2 * mu1_mu2 + C1) * (2 * sigma12 + C2)) / ((mu1_sq + mu2_sq + C1) * (sigma1_sq + sigma2_sq + C2))
return ssim_map.mean()
# 读取图像
img1 = cv2.imread('img1.png')
img2 = cv2.imread('img2.png')
# 计算PSNR和SSIM
psnr_value = psnr(img1, img2)
ssim_value = ssim(img1, img2)
# 输出结果
print("PSNR value is:", psnr_value)
print("SSIM value is:", ssim_value)
```
其中,`psnr()`函数用于计算PSNR值,`ssim()`函数用于计算SSIM值。在代码中,我们使用OpenCV库读取图像,并使用numpy库进行计算。需要注意的是,计算SSIM值需要使用高斯滤波器,这里我们使用OpenCV库中的`getGaussianKernel()`函数生成高斯滤波器。
阅读全文