使用pytorch和opencv计算两组图片的ssim(结构相似度)

SSIM的原理这里就不阐述了,直接上代码:

from math import exp

import numpy as np
import torch
import torch.nn.functional as F
from torch.autograd import Variable

import cv2

def ssim(image1, image2, K, window_size, L):
    _, channel1, _, _ = image1.size()
    _, channel2, _, _ = image2.size()
    channel = min(channel1, channel2)

    # gaussian window generation
    sigma = 1.5      # default
    gauss = torch.Tensor([exp(-(x - window_size//2)**2/float(2*sigma**2)) for x in range(window_size)])
    _1D_window = (gauss/gauss.sum()).unsqueeze(1)
    _2D_window = _1D_window.mm(_1D_window.t()).float().unsqueeze(0).unsqueeze(0)
    window = Variable(_2D_window.expand(channel, 1, window_size, window_size).contiguous())
            
    # define constants
    # * L = 255 for constants doesn't produce meaningful results; thus L = 1
    # C1 = (K[0]*L)**2;
    # C2 = (K[1]*L)**2;
    C1 = K[0]**2;
    C2 = K[1]**2;
    
    mu1 = F.conv2d(image1, window, padding = window_size//2, groups = channel)
    mu2 = F.conv2d(image2, window, padding = window_size//2, groups = channel)

    mu1_sq = mu1.pow(2)
    mu2_sq = mu2.pow(2)
    mu1_mu2 = mu1*mu2

    sigma1_sq = F.conv2d(image1*image1, window, padding = window_size//2, groups = channel) - mu1_sq
    sigma2_sq = F.conv2d(image2*image2, window, padding = window_size//2, groups = channel) - mu2_sq
    sigma12 = F.conv2d(image1*image2, window, padding = window_size//2, groups = channel) - 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()

if __name__=="__main__":
    # opencv image load
    I1 = cv2.imread('./sample.jpg')
    I2 = cv2.imread('./blur4.jpg')
    # I2 = cv2.imread('./blur.png')
    #I2 = cv2.resize(I2, I1.shape[0:2])
    # print(I1.shape, I2.shape) # returns (256,256,3)
    
    # tensors
    I1 = torch.from_numpy(np.rollaxis(I1, 2)).float().unsqueeze(0)/255.0
    I2 = torch.from_numpy(np.rollaxis(I2, 2)).float().unsqueeze(0)/255.0
    # print(I1.size(), I2.size()) # returns torch([1,3,256,256])
    
    # tensor.autograd.Variable (Automatic differentiation variable)
    I1 = Variable(I1, requires_grad = True)
    I2 = Variable(I2, requires_grad = True)
    
    # default constants
    K = [0.01, 0.03]
    L = 255; 
    window_size = 11
    
    ssim_value = ssim(I1, I2, K, window_size, L)
    
    print(ssim_value.data)
  • 5
    点赞
  • 15
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值