数字图像处理——中值滤波

原理:模板中心对准待处理像素,对模板下的对应像素进行灰度值排序,将中值赋给当前像素

Matlab代码:

clear,clc;
car = imread('sport car.pgm');
noise_car = imnoise(car,'salt & pepper',0.02);
[h,w] = size(car);
% zeros padding
new_car1 = zeros(h+2,w+2);
new_car1(2:h+1,2:w+1) = noise_car;
copy_car = double(new_car1);
% 滑动窗口,进行中值滤波
for i = 2:h+1
    for j = 2:w+1
        mask = copy_car(i-1:i+1,j-1:j+1);   % 获得当前mask
        new_car1(i,j) = median(mask(:));
    end
end
new_car1 = new_car1(2:h+1,2:w+1);
new_car1 = uint8(new_car1);
new_car2 = medfilt2(noise_car,[3,3]);   % 调用medfilt2()函数

figure;
subplot(121),imshow(car),title('原图像');
subplot(122),imshow(noise_car),title('椒盐噪声图像');
figure;
subplot(121),imshow(new_car1),title('中值滤波图像');
subplot(122),imshow(new_car2),title('中值滤波图像(medfilt2)')

运行结果:

数字图像处理——中值滤波_第1张图片数字图像处理——中值滤波_第2张图片

 

 

 

你可能感兴趣的:(数字图像处理)