编写程序,使用Numpy库函数对图像求解MSE、PSNR、SSIM评价参数。
时间: 2023-07-10 20:03:48 浏览: 131
以下是使用Numpy库函数对图像求解MSE、PSNR、SSIM评价参数的示例代码:
```python
import numpy as np
import cv2
def mse(imageA, imageB):
err = np.sum((imageA.astype("float") - imageB.astype("float")) ** 2)
err /= float(imageA.shape[0] * imageA.shape[1])
return err
def psnr(imageA, imageB):
mse_value = mse(imageA, imageB)
if mse_value == 0:
return float('inf')
else:
max_pixel = 255.0
psnr_value = 20 * np.log10(max_pixel / np.sqrt(mse_value))
return psnr_value
def ssim(imageA, imageB):
K1 = 0.01
K2 = 0.03
L = 255
C1 = (K1 * L) ** 2
C2 = (K2 * L) ** 2
window = cv2.createWindow('window', (128, 128), cv2.WINDOW_AUTOSIZE)
window.show()
window_imageA = cv2.resize(imageA, (128, 128))
window_imageB = cv2.resize(imageB, (128, 128))
window_imageA = window_imageA.astype(np.float32)
window_imageB = window_imageB.astype(np.float32)
meanA = cv2.GaussianBlur(window_imageA, (11, 11), 1.5)
meanB = cv2.GaussianBlur(window_imageB, (11, 11), 1.5)
meanA_meanB = meanA * meanB
meanA_squared = meanA ** 2
meanB_squared = meanB ** 2
varianceA = cv2.GaussianBlur(window_imageA ** 2, (11, 11), 1.5) - meanA_squared
varianceB = cv2.GaussianBlur(window_imageB ** 2, (11, 11), 1.5) - meanB_squared
covariance = cv2.GaussianBlur(window_imageA * window_imageB, (11, 11), 1.5) - meanA_meanB
ssim_value = ((2 * meanA_meanB + C1) * (2 * covariance + C2)) / ((meanA_squared + meanB_squared + C1) * (varianceA + varianceB + C2))
return ssim_value.mean()
# 读取图片
img1 = cv2.imread('img1.jpg')
img2 = cv2.imread('img2.jpg')
# 计算MSE、PSNR、SSIM
mse_value = mse(img1, img2)
psnr_value = psnr(img1, img2)
ssim_value = ssim(img1, img2)
# 输出结果
print("MSE: ", mse_value)
print("PSNR: ", psnr_value)
print("SSIM: ", ssim_value)
```
其中 `mse()` 函数计算MSE,`psnr()` 函数计算PSNR,`ssim()` 函数计算SSIM。
需要注意的是,计算SSIM时需要使用OpenCV库中的GaussianBlur函数来进行高斯模糊,以及创建一个128x128的窗口用于计算SSIM值。
阅读全文