psnr和ssim的代码
时间: 2023-06-25 07:05:39 浏览: 123
PSNR+SSIM代码
3星 · 编辑精心推荐
PSNR和SSIM是两种用于评估图像质量的指标,其中PSNR是峰值信噪比,SSIM是结构相似性。以下是PSNR和SSIM的Python代码示例:
```python
import cv2
import numpy as np
def psnr(img1, img2):
mse = np.mean((img1 - img2) ** 2)
if mse == 0:
return float('inf')
max_pixel = 255.0
psnr = 20 * np.log10(max_pixel / np.sqrt(mse))
return psnr
def ssim(img1, img2):
C1 = 6.5025
C2 = 58.5225
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 np.mean(ssim_map)
```
其中,PSNR函数计算两幅图像之间的PSNR值,SSIM函数计算两幅图像之间的SSIM值。这两个函数都接收两个参数:img1和img2,表示要进行比较的两幅图像。函数返回值为PSNR或SSIM值。需要注意的是,这两个函数都要求输入的图像形状相同。
阅读全文