图片评价指标SSIM代码
时间: 2023-10-10 16:08:52 浏览: 95
SSIM(结构相似性指标)是一种常用的图像评价指标,用于比较两幅图像的相似程度。以下是Python中计算SSIM的示例代码:
```python
import numpy as np
import cv2
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 np.mean(ssim_map)
# 示例用法
img1 = cv2.imread('img1.png')
img2 = cv2.imread('img2.png')
score = ssim(img1, img2)
print(score)
```
在上面的代码中,我们首先计算SSIM所需的参数值,然后使用高斯滤波器对图像进行平滑处理,计算图像均值和标准差,并计算结构相似性指标。最后,我们将SSIM值的平均值返回作为两幅图像的相似度评分。
阅读全文