clear,clc,close all;
orignal=imread('C:\Users\86137\Desktop\图片\lena.jpg');%根据图片位置自定义
noiseimg=imnoise(orignal,'salt & pepper',0.01);%椒盐噪声
[col,row,c]=size(noiseimg);
r=noiseimg(:,:,1),g=noiseimg(:,:,2),b=noiseimg(:,:,3);
[newr]=zhongzhilv(r);
[newg]=zhongzhilv(g);
[newb]=zhongzhilv(b);
newimage=cat(3,newr,newg,newb);
subplot(131),imshow(orignal),title('原图');
subplot(132),imshow(noiseimg),title('加入椒盐噪声');
subplot(133),imshow(newimage),title('中值噪声');
function [newimage]=zhongzhilv(img)
[col,row]=size(img);
for i=2:col-1
for j=2:row-1
temp=img(i-1:i+1,j-1:j+1);
b=sort(temp(:)');
newimage(i,j)=b(1,3);
end
end
end