imagedata=imread('Fig4.jpg');
figure, imshow(imagedata);
title('原图像');
[m,n]=size(imagedata);
%加上高斯噪声的图像
variance=225;
result1=uint8(double(imagedata)+randn(m,n).*sqrt(variance)+5);
figure, imshow(result1);
title('加上高斯噪声的图像');
result1=double(result1);
%加上椒盐噪声的图像
result2=imagedata;
a=rand(m,n);
for i=1:m
for j=1:n
if(a(i,j)>0.975)
result2(i,j)=255;
elseif(a(i,j)<0.05)
result2(i,j)=0;
end
end
end
figure, imshow(result2);
title('加上椒盐噪声的图像');
result2=double(result2);
%补充:采用均值滤波器去除图像中的噪声
%step1: 补充滤波器:滤波器定义为3*3大小的mask数组
% 将已定义的数组赋值给mask数组
mask = [1, 2, 1; 2, 4, 2; 1, 2, 1];
%step2: 计算滤波器中各元素的累加值
%调用sum()函数
%累加的值数值给k
k = sum(mask(:));
%step3:实现均值滤波处理
res1 = zeros(m, n);
res2 = zeros(m, n);
for i = 2 : m - 1
for j = 2 : n - 1
f1 = 0; f2 = 0;
for dx = -1 : 1
for dy = -1 : 1
f1 = f1 + mask(2 + dx, 2 + dy) * result1(i + dx, j + dy);
f2 = f2 + mask(2 + dx, 2 + dy) * result2(i + dx, j + dy);
end
end
res1(i, j) = uint8(f1 / k);
res2(i, j) = uint8(f2 / k);
end
end
for i = 1 : m
res1(i, 1) = result1(i, 1);
res1(i, n) = result1(i, n);
res2(i, 1) = result2(i, 1);
res2(i, n) = result2(i, n);
end
for j = 1 : n
res1(1, j) = result1(1, j);
res1(m, j) = result1(m, j);
res2(1, j) = result2(1, j);
res2(m, j) = result2(m, j);
end
%显示处理后结果
figure, imshow(uint8(res1));
title('均值滤波器消除高斯噪声的图像');
figure, imshow(uint8(res2));
title('均值滤波器消除椒盐噪声的图像');
%锐化操作
mask_x = [-1, -2, -1; 0, 0, 0; 1, 2, 1];
mask_y = [-1, 0, 1; -2, 0, 2; -1, 0, 1];
res3 = zeros(m, n);
for i = 2 : m - 1
for j = 2 : n - 1
f3 = 0; f4 = 0;
for dx = -1 : 1
for dy = -1 : 1
f3 = f3 + mask_x(2 + dx, 2 + dy) * imagedata(i + dx, j + dy);
f4 = f4 + mask_y(2 + dx, 2 + dy) * imagedata(i + dx, j + dy);
end
end
res3(i, j) = uint8(abs(f3) + abs(f4));
end
end
%叠加
res5 = res1 + res3;
res6 = res2 + res3;
figure, imshow(uint8(res3));
title('锐化');
figure, imshow(uint8(res5));
title('锐化高斯噪声的图像');
figure, imshow(uint8(res6));
title('锐化椒盐噪声的图像');
|