- 图像PSNR及其计算OpenCV和matlab实现
图像PSNR及其计算(OpenCV和matlab实现)
引言:在图像处理中,要对图像进行客观的评价,常常需要计算PSNR,本文将简单介绍PSNR的定义,并给出相关的源代码。
PSNR的概念
PSNR (Peak Signal to Noise Ratio)
峰值信噪比PSNR衡量图像失真或是噪声水平的客观标准。2个图像之间PSNR值越大,则越相似。普遍基准为30dB,30dB以下的图像劣化较为明显。定义为,
PSNR=10log10(MAX2MSE)
这里MAX表示图像颜色的最大数值,8bit图像取值为255。我们还要介绍MSE(均方差),即m×n单色图像 I 和 K(原图像与处理图像)之间均方误差,定义为:
MSE=1mn∑i=1n∑j=1m∥K(i,j)−I(i,j)∥2
PSNR编程实现
matlab实现
第一种实现方法:
- 在matlab 2016版本中是带有psnr的计算的,只需调用相关函数就好。官方详细说明链接
peaksnr = psnr(A,ref)
第二种直观方法
function [PSNR, MSE]=psnr(I,K)
[M,N,D] = size(I);
Diff = double(I)-double(K);
MSE = sum(Diff(:).^2)/numel(I);
PSNR=10*log10(255^2/MSE);
end
第三种实现方法:
- 在matlab中新建m文件,复制进去保存就可以调用了。
function PSNR(A,B)
if A == B
error('Images are identical: PSNR has infinite value')
end
max2_A = max(max(A));
max2_B = max(max(B));
min2_A = min(min(A));
min2_B = min(min(B));
if max2_A > 1 || max2_B > 1 || min2_A < 0 || min2_B < 0
error('input matrices must have values in the interval [0,1]')
end
error_diff = A - B;
decibels = 20*log10(1/(sqrt(mean(mean(error_diff.^2)))));
disp(sprintf('PSNR = +%5.2f dB',decibels))
OpenCV实现
- 使用的是opencv 2.0版本,核心程序如下,很简单的程序,详细的注释可以帮助你理解getPSNR函数:
double getPSNR(const Mat& I1, const Mat& I2)
{
Mat s1;
absdiff(I1, I2, s1);
s1.convertTo(s1, CV_32F);
s1 = s1.mul(s1);
Scalar s = sum(s1);
double sse = s.val[0] + s.val[1] + s.val[2];
if( sse <= 1e-10)
return 0;
else
{
double mse =sse /(double)(I1.channels() * I1.total());
double psnr = 10.0*log10((255*255)/mse);
return psnr;
}
}
可能需要添加的头文件是:
#include <opencv2/core/core.hpp>
#include <opencv2/highgui/highgui.hpp>
使用说明:
double psnr;
Mat img1=imread('1.jpg');
Mat img2=imread('2.jpg');
psnr = getPSNR(img1,img2);
参考资料
[1]http://www.opencv.org.cn/opencvdoc/2.3.2/html/doc/tutorials/highgui/video-input-psnr-ssim/video-input-psnr-ssim.html
[2]http://www.mathworks.com/matlabcentral/fileexchange/135-psnr
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)