[Python] 纯文本查看 复制代码
def ssim(img1: list, img2: list, width: int, height: int, sigma: int) -> float:
"""
计算结构相似性指数
:param img1: 图像1
:param img2: 图像2
:param width: 图像宽度
:param height: 图像高度
:param sigma: 高斯核标准差
:return:
"""
mu1, mu2, mu1_mu2, sigma1_pow, sigma2_pow, sigma12 = 0, 0, 0, 0, 0, 0
sum1, sum2, sum3, sum4 = 0, 0, 0, 0
ssim_value = 0.0
# 计算每个像素的均值
for y in range(height):
for x in range(width):
mu1 = mu2 = 0.0
for i in range(-sigma, sigma + 1):
if y + i < 0 or y + i >= height:
continue
mu1 += img1[y + i * width + x]
mu2 += img2[y + i * width + x]
mu1 /= (2 * sigma + 1)
mu2 /= (2 * sigma + 1)
mu1_mu2 += mu1 * mu2
# 计算每个像素的标准差
for y in range(height):
for x in range(width):
sigma1_pow = sigma2_pow = 0.0
for i in range(-sigma, sigma + 1):
if y + i < 0 or y + i >= height:
continue
sigma1_pow += (img1[y + i * width + x] - mu1) ** 2
sigma2_pow += (img2[y + i * width + x] - mu2) ** 2
sigma1_pow /= (2 * sigma + 1)
sigma2_pow /= (2 * sigma + 1)
sigma12 += (sigma1_pow - pow(mu1_mu2, 0.5)) * (sigma2_pow - pow(mu1_mu2, 0.5))
# 计算结构相似性指数
for y in range(height):
for x in range(width):
sum1 += (img1[y * width + x] - mu1_mu2) ** 2
sum2 += (img2[y * width + x] - mu1_mu2) ** 2
sum3 += (sigma1_pow - pow(mu1_mu2, 0.5)) ** 2
sum4 += (sigma2_pow - pow(mu1_mu2, 0.5)) ** 2
ssim_value += ((2 * mu1_mu2 * sigma12 + sum1 + sum2) /
(2 * sigma1_pow + 2 * sigma2_pow + sum3 + sum4))
return ssim_value / (width * height)
_img1 = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
_img2 = [0, 1, 3, 3, 4, 5, 6, 7, 8, 9]
_sigma = 3
_width = len(_img1)
_height = len(_img1) // _width
print("SSIM value:", ssim(_img1, _img2, _width, _height, _sigma))