% 分别在灰度图像中加入一定量的高斯噪声和椒盐噪声,然后采用3×3的均值滤波器和3×3中值滤波器分别对噪声图像进行处理,
%给出两种处理方法的峰值信噪比(PSNR);仿效“中值滤波”的方法,对原图像分别进行“极大值滤波”和“极小值滤波”,
%对所形成的图像给出说明
clear;clc;
%
im = imread('2-lena.tif');
% add noise
im_g = imnoise(im,'gaussian',0,0.05);
im_s = imnoise(im,'salt & pepper',0.1);
%
im = double(im);
im_g = double(im_g);
im_s = double(im_s);
% filtering by mean
h = fspecial('average', [3 3]);
im_g_mean = imfilter(im_g,h,'replicate');
im_s_mean = imfilter(im_s,h,'replicate');
% filtering by median
im_g_median = ordfilt2(im_g,5,ones(3,3));
im_s_median = ordfilt2(im_s,5,ones(3,3));
% filtering by min
im_g_min = ordfilt2(im_g,1,ones(3,3));
im_s_min = ordfilt2(im_s,1,ones(3,3));
% filtering by max
im_g_max = ordfilt2(im_g,9,ones(3,3));
im_s_max = ordfilt2(im_s,9,ones(3,3));
% plot Gaussian
figure
subplot(161)
imshow(mat2gray(im));
xlabel('Original')
subplot(162)
imshow(mat2gray(im_g));
xlabel('Gaussian')
subplot(163)
imshow(mat2gray(im_g_mean));
str = sprintf('Mean, PSNR = %.2f dB',PSNR(im,im_g_mean));
xlabel(str)
subplot(164)
imshow(mat2gray(im_g_median));
str = sprintf('Median, PSNR = %.2f dB',PSNR(im,im_g_median));
xlabel(str)
subplot(165)
imshow(mat2gray(im_g_min));
str = sprintf('Min, PSNR = %.2f dB',PSNR(im,im_g_min));
xlabel(str)
subplot(166)
imshow(mat2gray(im_g_max));
str = sprintf('Max, PSNR = %.2f dB',PSNR(im,im_g_max));
xlabel(str)
% plot salt%peppers
figure
subplot(161)
imshow(mat2gray(im));
xlabel('Original')
subplot(162)
imshow(mat2gray(im_s));
xlabel('Salt&Peppers')
subplot(163)
imshow(mat2gray(im_s_mean));
str = sprintf('Mean, PSNR = %.2f dB',PSNR(im,im_s_mean));
xlabel(str)
subplot(164)
imshow(mat2gray(im_s_median));
str = sprintf('Median, PSNR = %.2f dB',PSNR(im,im_s_median));
xlabel(str)
subplot(165)
imshow(mat2gray(im_s_min));
str = sprintf('Min, PSNR = %.2f dB',PSNR(im,im_s_min));
xlabel(str)
subplot(166)
imshow(mat2gray(im_s_max));
str = sprintf('Max, PSNR = %.2f dB',PSNR(im,im_s_max));
xlabel(str)
%
function psnr = PSNR(x,y)
x = double(x);
y = double(y);
cnt = length(x(:));
mse = sum((x(:)-y(:)).^2)/cnt;
psnr = 10*log10(255^2/mse);
end