Matlab中值滤波代码

来源:互联网 发布:js前端解析excel 编辑:程序博客网 时间:2024/04/30 12:49
img=imread('lena.png');
img=rgb2gray(img)
img=im2double(img)%输入图像类型为uint8,将其转换为double类型进行运算
gau=imnoise(img,'gaussian');
subplot(2,2,1);imshow(gau);title('添加高斯噪声的图像');%imshow()函数在显示图像时会自动将类型转换为uint8
subplot(2,2,2);imshow(median_filter(gau,3));title('滤除高斯噪声后的图像');
salt=imnoise(img,'salt & pepper');
subplot(2,2,3);imshow(salt);title('添加椒盐噪声的图像');
subplot(2,2,4);imshow(median_filter(salt,3));title('滤除椒盐噪声后的图像');

%中值滤波,接受两个参数,一个参数是原图像x,另一个参数是滤波器大小n
function d=median_filter(x,n)
d=x;
[width,height]=size(x);%得到图像的长和宽
for ii=1:width-(n-1)
    for jj=1:height-(n-1)%height表示的个数为可完整滤波的格子数
        tmp1=d(ii:ii+(n-1),jj:jj+(n-1));%取出要滤波的n*n的方阵
        tmp2=tmp1(1,:);
        for kk=2:n
            tmp2=[tmp2,tmp1(kk,:)];%把所有的行排成一行方便后面求中值
        end
       y= median(tmp2);
        d(ii+(n-1)/2,jj+(n-1)/2)=y;
    end
end

0 0