(Python+MatLab) 分别实现 PSNR 和 SSIM

前言

使用 MatLab 计算得到的指标比 Python 的高,具体原因没有研究,欢迎交流。

PSNR

Python

def calculate_psnr(img1, img2, border=0):
    '''
    img1, img2: [0, 255]
    '''
    if not img1.shape == img2.shape:
        raise ValueError('Input images must have the same dimensions.')
    h, w = img1.shape[:2]
    img1 = img1[border:h-border, border:w-border]
    img2 = img2[border:h-border, border:w-border]

    img1 = img1.astype(np.float64)
    img2 = img2.astype(np.float64)
    mse = np.mean((img1 - img2)**2)
    if mse == 0:
        return float('inf')
    return 20 * math.log10(255.0 / math.sqrt(mse))

MatLab

function [ PSNR ] = psnr( f1,f2 )
%PSNR Summary of this function goes here
%   Detailed explanation goes here


% % MSE = E( (img-Eimg)^2 ) 
% %     = SUM((img-Eimg)^2)/(M*N);
% function ERMS = erms(f1, f2)
% %
% e = double(f1) - double(f2);
% [m, n] = size(e);
% ERMS = sqrt(sum(e.^2)/(m*n));
% % PSNR=10log10(M*N/MSE); 
% function PSNR = psnr(f1, f2)
k=1;
if max(f1(:))>2
k = 8;
end
fmax = 2.^k - 1;
a = fmax.^2;
e = double(f1) - double(f2);
[m, n] = size(e);
MSE=sum(sum(e.^2))/(m*n);
PSNR = 10*log10(a/MSE);
end

SSIM

Python

def calculate_ssim(img1, img2, border=0):
    '''
    img1, img2: [0, 255]
    '''
    #img1 = img1.squeeze()
    #img2 = img2.squeeze()
    if not img1.shape == img2.shape:
        raise ValueError('Input images must have the same dimensions.')
    h, w = img1.shape[:2]
    img1 = img1[border:h-border, border:w-border]
    img2 = img2[border:h-border, border:w-border]

    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[:,:,i], img2[:,:,i]))
            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.')


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]  # 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()

MatLab

function [mssim, ssim_map] = ssim(img1, img2, K, window, L)
if (nargin < 2 || nargin > 5)
   mssim = -Inf;
   ssim_map = -Inf;
   return;
end

if (size(img1) ~= size(img2))
   mssim = -Inf;
   ssim_map = -Inf;
   return;
end

[M N] = size(img1);

if (nargin == 2)
   if ((M < 11) || (N < 11))
	   mssim = -Inf;
	   ssim_map = -Inf;
      return
   end
   window = fspecial('gaussian', 11, 1.5);
   K(1) = 0.01;
   K(2) = 0.03;
   L = 255;
end

if (nargin == 3)
   if ((M < 11) || (N < 11))
	   mssim = -Inf;
	   ssim_map = -Inf;
      return
   end
   window = fspecial('gaussian', 11, 1.5);
   L = 255;
   if (length(K) == 2)
      if (K(1) < 0 || K(2) < 0)
		   mssim = -Inf;
   		ssim_map = -Inf;
	   	return;
      end
   else
	   mssim = -Inf;
   	ssim_map = -Inf;
	   return;
   end
end

if (nargin == 4)
   [H W] = size(window);
   if ((H*W) < 4 || (H > M) || (W > N))
	   mssim = -Inf;
	   ssim_map = -Inf;
      return
   end
   L = 255;
   if (length(K) == 2)
      if (K(1) < 0 || K(2) < 0)
		   mssim = -Inf;
   		ssim_map = -Inf;
	   	return;
      end
   else
	   mssim = -Inf;
   	ssim_map = -Inf;
	   return;
   end
end

if (nargin == 5)
   [H W] = size(window);
   if ((H*W) < 4 || (H > M) || (W > N))
	   mssim = -Inf;
	   ssim_map = -Inf;
      return
   end
   if (length(K) == 2)
      if (K(1) < 0 || K(2) < 0)
		   mssim = -Inf;
   		ssim_map = -Inf;
	   	return;
      end
   else
	   mssim = -Inf;
   	ssim_map = -Inf;
	   return;
   end
end


img1 = double(img1);
img2 = double(img2);

f = max(1,round(min(M,N)/256));

if(f>1)
    lpf = ones(f,f);
    lpf = lpf/sum(lpf(:));
    img1 = imfilter(img1,lpf,'symmetric','same');
    img2 = imfilter(img2,lpf,'symmetric','same');

    img1 = img1(1:f:end,1:f:end);
    img2 = img2(1:f:end,1:f:end);
end

C1 = (K(1)*L)^2;
C2 = (K(2)*L)^2;
window = window/sum(sum(window));

mu1   = filter2(window, img1, 'valid');
mu2   = filter2(window, img2, 'valid');
mu1_sq = mu1.*mu1;
mu2_sq = mu2.*mu2;
mu1_mu2 = mu1.*mu2;
sigma1_sq = filter2(window, img1.*img1, 'valid') - mu1_sq;
sigma2_sq = filter2(window, img2.*img2, 'valid') - mu2_sq;
sigma12 = filter2(window, img1.*img2, 'valid') - mu1_mu2;

if (C1 > 0 && C2 > 0)
   ssim_map = ((2*mu1_mu2 + C1).*(2*sigma12 + C2))./((mu1_sq + mu2_sq + C1).*(sigma1_sq + sigma2_sq + C2));
else
   numerator1 = 2*mu1_mu2 + C1;
   numerator2 = 2*sigma12 + C2;
	denominator1 = mu1_sq + mu2_sq + C1;
   denominator2 = sigma1_sq + sigma2_sq + C2;
   ssim_map = ones(size(mu1));
   index = (denominator1.*denominator2 > 0);
   ssim_map(index) = (numerator1(index).*numerator2(index))./(denominator1(index).*denominator2(index));
   index = (denominator1 ~= 0) & (denominator2 == 0);
   ssim_map(index) = numerator1(index)./denominator1(index);
end

mssim = mean2(ssim_map);

return
MATLAB提供了计算图像质量评价指标PSNRSSIM的函数,可以通过以下步骤使用MATLAB GUI来计算: 1. 在MATLAB中创建一个GUI界面,在界面上创建两个按钮,一个用于选择参考图像,另一个用于选择待评价的图像。 2. 为每个按钮添加回调函数,使其分别调用MATLAB的`uigetfile`函数用于选择参考图像和待评价图像。 3. 在GUI界面上添加一个用于显示结果的文本框。 4. 编写一个计算PSNRSSIM的函数,该函数的输入为参考图像和待评价图像的路径,输出为PSNRSSIM的值。 5. 在每个按钮的回调函数中,调用计算函数并将结果显示在文本框中。 下面是一个简单的示例代码来实现上述步骤: ```matlab function psnr_ssim_gui % 创建GUI界面 fig = uifigure('Name', 'PSNR and SSIM Calculation'); % 创建显示结果的文本框 resultTextBox = uitextarea(fig, 'Position', [50, 100, 200, 100]); % 创建选择参考图像的按钮 refButton = uibutton(fig, 'Position', [50, 250, 200, 30], 'Text', 'Select Reference Image', 'ButtonPushedFcn', @(src, event) selectImage(src, event, 'reference')); % 创建选择待评价图像的按钮 evalButton = uibutton(fig, 'Position', [50, 300, 200, 30], 'Text', 'Select Evaluation Image', 'ButtonPushedFcn', @(src, event) selectImage(src, event, 'evaluation')); function selectImage(src, event, imageType) % 弹出文件选择对话框 [filename, pathname] = uigetfile({'*.jpg;*.png', 'Image Files (*.jpg, *.png)'}, 'Select an image'); if ~isequal(filename, 0) % 获取图像的完整路径 imagepath = fullfile(pathname, filename); % 根据图像类型,更新参考图像或待评价图像的路径 if isequal(imageType, 'reference') refImagePath = imagepath; else evalImagePath = imagepath; end end end function calculatePSNR_SSIM % 计算PSNRSSIM [psnrValue, ssimValue] = calculate(refImagePath, evalImagePath); % 将结果显示在文本框中 resultText = sprintf('PSNR: %.2f\nSSIM: %.2f', psnrValue, ssimValue); resultTextBox.Value = resultText; end function [psnrValue, ssimValue] = calculate(refImagePath, evalImagePath) % 读取图像 refImage = imread(refImagePath); evalImage = imread(evalImagePath); % 在此编写计算PSNRSSIM的代码 % 这里只是举例计算了图像的差异,你需要根据实际需要进行计算 diff = abs(evalImage - refImage); mse = mean(diff(:).^2); maxval = 255; psnrValue = 10 * log10(maxval^2 / mse); % 这里的ssimValue也只是个示例,你需要根据实际需要进行计算 ssimValue = ssim(evalImage, refImage); end end ``` 以上代码创建了一个简单的GUI界面,包括选择参考图像和待评价图像的按钮,并显示计算结果的文本框。当用户点击按钮时,会调用相应的回调函数来选择图像,并调用计算函数来计算PSNRSSIM的值,最后将结果显示在文本框中。请注意,这只是一个示例代码,你需要根据实际需要进行适当的修改和完善。
评论 4
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

听 风、

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值