请用代码实现psnr和ssim的计算
时间: 2023-08-23 15:05:49 浏览: 127
计算PSNR和SSIM C++代码
好的,下面给出Python代码实现PSNR和SSIM的计算。
首先,我们需要导入相关的库:numpy、scipy和opencv-python。
```python
import cv2
import numpy as np
from scipy import signal
from scipy.ndimage import gaussian_filter
```
接着,我们定义计算PSNR的函数psnr():
```python
def psnr(img1, img2):
mse = np.mean((img1 - img2) ** 2)
if mse == 0:
return 100.0
PIXEL_MAX = 255.0
return 20 * np.log10(PIXEL_MAX / np.sqrt(mse))
```
其中,img1和img2分别为两张图片,函数返回它们的PSNR值。
然后,我们定义计算SSIM的函数ssim():
```python
def ssim(img1, img2, K=0.01, window_size=11, sigma=1.5):
img1 = img1.astype(np.float64)
img2 = img2.astype(np.float64)
window = _gaussian_window(window_size, sigma)
K1 = K ** 2
K2 = K ** 2
L = 255
C1 = (K1 * L) ** 2
C2 = (K2 * L) ** 2
mu1 = signal.convolve2d(img1, window, mode='valid') / np.sum(window)
mu2 = signal.convolve2d(img2, window, mode='valid') / np.sum(window)
mu1_sq = mu1 ** 2
mu2_sq = mu2 ** 2
mu1_mu2 = mu1 * mu2
sigma1_sq = signal.convolve2d(img1 ** 2, window, mode='valid') / np.sum(window) - mu1_sq
sigma2_sq = signal.convolve2d(img2 ** 2, window, mode='valid') / np.sum(window) - mu2_sq
sigma12 = signal.convolve2d(img1 * img2, window, mode='valid') / np.sum(window) - 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)
```
其中,img1和img2分别为两张图片,K、window_size和sigma是SSIM算法中的参数。函数返回它们的SSIM值。
最后,我们定义一个辅助函数_gaussian_window(),用于生成高斯窗口:
```python
def _gaussian_window(window_size, sigma):
gaussian = np.zeros((window_size, window_size), dtype=np.float64)
center = window_size // 2
for i in range(window_size):
for j in range(window_size):
gaussian[i, j] = np.exp(-0.5 * ((i - center) ** 2 + (j - center) ** 2) / sigma ** 2)
return gaussian / np.sum(gaussian)
```
现在,我们可以用psnr()和ssim()函数来计算两张图片之间的PSNR和SSIM了。
例如,下面的代码演示了如何计算两张图片image1和image2之间的PSNR和SSIM:
```python
image1 = cv2.imread('image1.jpg')
image2 = cv2.imread('image2.jpg')
print('PSNR:', psnr(image1, image2))
print('SSIM:', ssim(image1, image2))
```
阅读全文