SSIM,Structural Similarity,结构相似性算法,用于衡量两幅图片相似度,也被用于图片质量评价(如压缩后图像与原图的相似度).
1. SSIM 基本原理
针对两幅图片,SSIM 计算组成包括三部分:亮度(luminance)对比、对比度(contrast)对比、结构(structure)对比.
其中,
[1] - C1,C2,C3为常数,以避免分母为0. 一般来说,C3=C2/2.
[2] - $\mu_x, \mu_y$ 分别为 x, y 的均值.
[3] - $\sigma_x^2, \sigma_y^2$ 分别为 x, y 的方差.
[4] - $\sigma_{xy}$ 为 x 和 y 的协方差.
[5] - S(x, y) 具有对称性、有界性和最大值唯一性.
[6] - SSIM值越大代表图像越相似 当且仅当 x=y 时, S(x,y)=1,即两幅图片完全一致.
每次计算的时候都从图片上取一个 NxN 的窗口,然后不断滑动窗口进行计算,最后取平均值作为全局的 SSIM.
2. SSIM skimage 实现
Scikit-image 库中提供了 structural_similarity 函数,计算 SSIM.
skimage.metrics.structural_similarity(im1, im2, *, #im1 和 im2 具有相同的尺寸.
win_size=None, #滑窗大小,必须是奇数值.
gradient=False, #是否返回关于 im2 的梯度.
data_range=None,
multichannel=False,
gaussian_weights=False,
full=False, **kwargs)
具体实现可见:skimage/metrics/_structural_similarity.py
其中,
[1] - multichannl - 若为True,则仅将数组最后一维作为通道;SSIM是分别对每个通道分别计算相似性,然后求均值.
[2] - gaussian_weights - 若为True,每个图像块的均值和方差均采用一个标准差 sigma=1.5的高斯函数进行加权.
[3] - full - 若为 True,则还返回全局结构相似性图片结果S(x,y).
3. SSIM Python 实现
import cv2
import numpy as np
def ssim(img1, img2):
img1 = img1.astype(np.float64)
img2 = img2.astype(np.float64)
C1 = (0.01 * 255)**2
C2 = (0.03 * 255)**2
kernel = cv2.getGaussianKernel(11, 1.5)
window = np.outer(kernel, kernel.transpose())
mu1 = cv2.filter2D(img1, -1, window)[5:-5, 5:-5] # valid
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 ssim_map.mean()
def calculate_ssim(img1, img2):
'''
calculate SSIM
the same outputs as MATLAB's
img1, img2: [0, 255]
'''
if not img1.shape == img2.shape:
raise ValueError('Input images must have the same dimensions.')
if img1.ndim == 2:
return ssim(img1, img2)
elif img1.ndim == 3:
if img1.shape[2] == 3:
ssims = []
for i in range(3):
ssims.append(ssim(img1, img2))
return np.array(ssims).mean()
elif img1.shape[2] == 1:
return ssim(np.squeeze(img1), np.squeeze(img2))
else:
raise ValueError('Wrong input image dimensions.')
#
img1 = cv2.imread("Test2_HR.bmp", 0)
img2 = cv2.imread("Test2_LR2.bmp", 0)
ss = calculate_ssim(img1, img2)
print(ss)
4. SSIM Pytorch 实现
import torch
import torch.nn.functional as F
from math import exp
import numpy as np
def gaussian(window_size, sigma):
gauss = torch.Tensor([exp(-(x - window_size//2)**2/float(2*sigma**2)) for x in range(window_size)])
return gauss/gauss.sum()
def create_window(window_size, channel=1):
_1D_window = gaussian(window_size, 1.5).unsqueeze(1)
_2D_window = _1D_window.mm(_1D_window.t()).float().unsqueeze(0).unsqueeze(0)
window = _2D_window.expand(channel, 1, window_size, window_size).contiguous()
return window
def ssim(img1, img2, window_size=11, window=None, size_average=True, full=False, val_range=None):
# Value range can be different from 255. Other common ranges are 1 (sigmoid) and 2 (tanh).
if val_range is None:
if torch.max(img1) > 128:
max_val = 255
else:
max_val = 1
if torch.min(img1) < -0.5:
min_val = -1
else:
min_val = 0
L = max_val - min_val
else:
L = val_range
padd = 0
(_, channel, height, width) = img1.size()
if window is None:
real_size = min(window_size, height, width)
window = create_window(real_size, channel=channel).to(img1.device)
mu1 = F.conv2d(img1, window, padding=padd, groups=channel)
mu2 = F.conv2d(img2, window, padding=padd, groups=channel)
mu1_sq = mu1.pow(2)
mu2_sq = mu2.pow(2)
mu1_mu2 = mu1 * mu2
sigma1_sq = F.conv2d(img1 * img1, window, padding=padd, groups=channel) - mu1_sq
sigma2_sq = F.conv2d(img2 * img2, window, padding=padd, groups=channel) - mu2_sq
sigma12 = F.conv2d(img1 * img2, window, padding=padd, groups=channel) - mu1_mu2
C1 = (0.01 * L) ** 2
C2 = (0.03 * L) ** 2
v1 = 2.0 * sigma12 + C2
v2 = sigma1_sq + sigma2_sq + C2
cs = torch.mean(v1 / v2) # contrast sensitivity
ssim_map = ((2 * mu1_mu2 + C1) * v1) / ((mu1_sq + mu2_sq + C1) * v2)
if size_average:
ret = ssim_map.mean()
else:
ret = ssim_map.mean(1).mean(1).mean(1)
if full:
return ret, cs
return ret
def msssim(img1, img2, window_size=11, size_average=True, val_range=None, normalize=None):
device = img1.device
weights = torch.FloatTensor([0.0448, 0.2856, 0.3001, 0.2363, 0.1333]).to(device)
levels = weights.size()[0]
ssims = []
mcs = []
for _ in range(levels):
sim, cs = ssim(img1, img2, window_size=window_size, size_average=size_average, full=True, val_range=val_range)
# Relu normalize (not compliant with original definition)
if normalize == "relu":
ssims.append(torch.relu(sim))
mcs.append(torch.relu(cs))
else:
ssims.append(sim)
mcs.append(cs)
img1 = F.avg_pool2d(img1, (2, 2))
img2 = F.avg_pool2d(img2, (2, 2))
ssims = torch.stack(ssims)
mcs = torch.stack(mcs)
# Simple normalize (not compliant with original definition)
# TODO: remove support for normalize == True (kept for backward support)
if normalize == "simple" or normalize == True:
ssims = (ssims + 1) / 2
mcs = (mcs + 1) / 2
pow1 = mcs ** weights
pow2 = ssims ** weights
# From Matlab implementation https://ece.uwaterloo.ca/~z70wang/research/iwssim/
output = torch.prod(pow1[:-1] * pow2[-1])
return output
# Classes to re-use window
class SSIM(torch.nn.Module):
def __init__(self, window_size=11, size_average=True, val_range=None):
super(SSIM, self).__init__()
self.window_size = window_size
self.size_average = size_average
self.val_range = val_range
# Assume 1 channel for SSIM
self.channel = 1
self.window = create_window(window_size)
def forward(self, img1, img2):
(_, channel, _, _) = img1.size()
if channel == self.channel and self.window.dtype == img1.dtype:
window = self.window
else:
window = create_window(self.window_size, channel).to(img1.device).type(img1.dtype)
self.window = window
self.channel = channel
return ssim(img1, img2, window=window, window_size=self.window_size, size_average=self.size_average)
class MSSSIM(torch.nn.Module):
def __init__(self, window_size=11, size_average=True, channel=3):
super(MSSSIM, self).__init__()
self.window_size = window_size
self.size_average = size_average
self.channel = channel
def forward(self, img1, img2):
# TODO: store window between calls if possible
return msssim(img1, img2, window_size=self.window_size, size_average=self.size_average)
使用示例如:
import pytorch_msssim
import torch
device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
m = pytorch_msssim.MSSSIM()
img1 = torch.rand(1, 1, 256, 256)
img2 = torch.rand(1, 1, 256, 256)
print(pytorch_msssim.msssim(img1, img2))
print(m(img1, img2))
SSIM 可作为损失函数,但要取负号,如 loss = 1 - SSIM.
实现如:
from pytorch_msssim import msssim, ssim
import torch
from torch import optim
from PIL import Image
from torchvision.transforms.functional import to_tensor
import numpy as np
# display = True requires matplotlib
display = True
metric = 'MSSSIM' # MSSSIM or SSIM
device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
def post_process(img):
img = img.detach().cpu().numpy()
img = np.transpose(np.squeeze(img, axis=0), (1, 2, 0))
img = np.squeeze(img) # works if grayscale
return img
# Preprocessing
img1 = to_tensor(Image.open('einstein.png')).unsqueeze(0).type(torch.FloatTensor)
img2 = torch.rand(img1.size())
img2 = torch.nn.functional.sigmoid(img2) # use sigmoid to clamp between [0, 1]
img1 = img1.to(device)
img2 = img2.to(device)
img1.requires_grad = False
img2.requires_grad = True
loss_func = msssim if metric == 'MSSSIM' else ssim
value = loss_func(img1, img2)
print("Initial %s: %.5f" % (metric, value.item()))
optimizer = optim.Adam([img2], lr=0.01)
# MSSSIM yields higher values for worse results, because noise is removed in scales with lower resolutions
threshold = 0.999 if metric == 'MSSSIM' else 0.9
while value < threshold:
optimizer.zero_grad()
msssim_out = -loss_func(img1, img2)
value = -msssim_out.item()
print('Current MS-SSIM = %.5f' % value)
msssim_out.backward()
optimizer.step()
if display:
# Post processing
img1np = post_process(img1)
img2 = torch.nn.functional.sigmoid(img2)
img2np = post_process(img2)
import matplotlib.pyplot as plt
cmap = 'gray' if len(img1np.shape) == 2 else None
plt.subplot(1, 2, 1)
plt.imshow(img1np, cmap=cmap)
plt.title('Original')
plt.subplot(1, 2, 2)
plt.imshow(img2np, cmap=cmap)
plt.title('Generated, {:s}: {:.3f}'.format(metric, value))
plt.show()
5. 参考
[1] - 图片结构相似性算法:SSIM - 2019.11.24
[2] - 图像质量评价指标之 PSNR 和 SSIM - 2020.06.04 - 知乎
[3] - SSIM算法图像去重 - 2020.07.19