中值滤波

中值滤波

1.算法描述

中值滤波的算法思想很简单,例如说选定3*3大小的方阵,那么:

首先建立和原图像等大的矩阵,将作为中值滤波后的图像。

然后对于原图像的每一个像素点,都取出它本身和它的八邻域共9个元素,按大小排序。

取出排序后的9个元素中的中位数,令它成为新图象的在该像素点处的像素值。

2.Matlab代码

函数MedianFiltering:

MedianFiltering.m

function new_img = MedianFiltering(img)
    [height,width] = size(img);
    new_img = img;
    for i = 2 : height - 1
        for j = 2 : width - 1
            tmp = img(i - 1 : i + 1, j - 1 : j + 1);
            tmp = sort(tmp(:));
            new_img(i - 1, j - 1) = tmp(5);
        end
    end
    new_img = uint8(new_img);

调用函数的脚本Task2:

Task2.m

img = imread('sport car.pgm');
[height,width] = size(img);

set(figure, 'name', 'MedianFiltering');
subplot(2, 2, 1);
imshow(img);
title('Original Image');

t1 = uint8(255 * rand(height, width));
t2 = uint8(255 * rand(height, width));

for i = 1 : height
    for j = 1 : width
        if img(i, j) > t1(i, j) && img(i, j) > t2(i, j)
           img(i, j) = 255;
        end
        if img(i, j) < t1(i, j) && img(i, j) < t2(i, j)
           img(i, j) = 0;
        end
    end
end
subplot(2, 2, 2);
imshow(img);
title('Polluted Image');

new_img = MedianFiltering(img);

subplot(2, 2, 3);
imshow(new_img);
title('MedianFiltered Image');

subplot(2, 2, 4);
imshow(medfilt2(img));
title('medfilt2 Image');

3.处理结果

下图为中值滤波效果图对比,其中,左上角为原图,右上角为椒盐噪声污染后的图像,左下角为使用自己编写的中值滤波函数MedianFiltering得到的图像,右下角为使用matlab函数medfilt2得到的图像。明显看到两个函数处理后的图像效果一致。

这里写图片描述

猜你喜欢

转载自blog.csdn.net/jacknights/article/details/79438816