彩色图像:
%% 计算前后两副图像的均方根误差MSE、峰值信噪比PSNR X=imread('cat.jpg');
Y=imread('cat1.jpg');
[r,cl]=size(X); %读入图像尺寸
c=cl/3;
mse_m=double(zeros(r,c));
%选取算法
disp('1. 彩色图像灰度化');
disp('2. RGB各分量计算法');
choice=input('请选择算法(1,2):')
if(choice==2)
if nargin<2
Xr=X(:,:,1);
Xg=X(:,:,2);
Xb=X(:,:,3);
for i=1:r
for j=1:c
Dr = Xr;
Dg = Xg;
Db = Xb;
end
end
% MSE = sum(D(:).*D(:))/prod(size(X));
mse_r = sum(Dr(:).*Dr(:))/prod(r*c);
mse_g = sum(Dg(:).*Dg(:))/prod(r*c);
mse_b = sum(Db(:).*Db(:))/prod(r*c);
mse = (mse_r+mse_g+mse_b)/3;
else
if any(size(X)~=size(Y))
error('The input size is not equal to each other!');
end
Xr=X(:,:,1);
Xg=X(:,:,2);
Xb=X(:,:,3);
Yr=Y(:,:,1);
Yg=Y(:,:,2);
Yb=Y(:,:,3);
for i=1:r
for j=1:c
mse_mR(i,j)=(Xr(i,j)-Yr(i,j))^2;
mse_mG(i,j)=(Xg(i,j)-Yg(i,j))^2;
mse_mB(i,j)=(Xb(i,j)-Yb(i,j))^2;
end
end
%mse=sum(mse_m(:))/(r*c);
mseRGB=sum(mse_mR(:))+sum(mse_mG(:))+sum(mse_mB(:))
mse=mseRGB/(r*c*3)
end
end
% PSNR = 10*log10(255^2/MSE);
psnr=10*log(double(255*255/mse))/log(10)
灰度图像:
close all; clear all; clc; img=imread('cat.jpg'); [h w]=size(img); w=w/3; imgn=imresize(img,[floor(h/2) floor(w/2)]); imgn=imresize(imgn,[h w]); imwrite(imgn,'cat1.jpg'); figure,imshow(img) figure,imshow(imgn) img=double(img); imgn=double(imgn); B=8; %编码一个像素用多少二进制位 MAX=2^B-1; %图像有多少灰度级 MES=sum(sum((img-imgn).^2))/(h*w); %均方差 PSNR=20*log10(MAX/sqrt(MES)) %峰值信噪比