来自冈萨雷斯数字图像处理Matlab中文版附录C
相对原文程序,(1)将第8行的‘|’更改为‘||’(2)第11行注释。其余保持不变。
%自适应中值滤波
function f = adpmedian (g, Smax)
% ADPMEDIAN Parform adaptive median filtering.
% F = ADPMEDIAN(G, SMAX) performs adaptive median filtering of
% image G. The median filter starts at size 3-by-3 and iterates up
% to size SMAX-by-SMAX. SMAX must be an odd integer greater than 1.
% SMAX must be an odd, positive integer greater than 1.
if (Smax <= 1) || (Smax/2 == round(Smax/2)) || (Smax ~= round(Smax))
error ('SMAX must be an odd integer > 1.')
end
% [M, N] = size(g);
% Initial setup.
f = g;
f(:) = 0;
alreadyProcessed = false (size(g));
% Begin filtering.
for k = 3:2:Smax
zmin = ordfilt2(g, 1, ones(k, k),'symmetric');
zmax = ordfilt2(g, k * k, ones(k, k), 'symmetric');
zmed = medfilt2(g, [k k], 'symmetric');
processUsingLevelB = (zmed > zmin) & (zmax > zmed) &...
~alreadyProcessed;
zB = (g > zmin) & (zmax > g);
outputZxy = processUsingLevelB & zB;
outputZmed = processUsingLevelB & ~zB;
f (outputZxy) = g(outputZxy);
f (outputZmed) = zmed(outputZmed);
alreadyProcessed = alreadyProcessed | processUsingLevelB;
if all (alreadyProcessed (:))
break;
end
end
% Output zmed for any remaining unprocessed pixels. Note that this
% zmed was computed using a window of size Smax-by-Smax, which is
% the final value of k in the loop.
f (~alreadyProcessed) = zmed (~alreadyProcessed);
end
使用方法: f = adpmedian (g, Smax)
其中:g为输入二维图像,Smax为最大滤波尺寸,f为自适应滤波后输出图像
参考实例:
Gray = imread('cameraman.tif'); %读取图像文件
%加入各种浓度的椒盐噪声
N1 = imnoise(Gray,'salt & pepper',0.05);%椒盐噪声,噪声密度0.05
N2 = imnoise(Gray,'salt & pepper',0.25);%椒盐噪声,噪声密度0.25
N3 = imnoise(Gray,'salt & pepper',0.45);%椒盐噪声,噪声密度0.45
N4 = imnoise(Gray,'salt & pepper',0.65);%椒盐噪声,噪声密度0.65
%中值滤波
M1 = medfilt2(N1);
M2 = medfilt2(N2);
M3 = medfilt2(N3);
M4 = medfilt2(N4);
%自适应中值滤波
f1 = adpmedian(N1,11);
f2 = adpmedian(N2,11);
f3 = adpmedian(N3,11);
f4 = adpmedian(N4,11);
figure
subplot(341);
imshow(N1);
subplot(342);
imshow(N2);
subplot(343);
imshow(N3);
subplot(344);
imshow(N4);
subplot(345);
imshow(M1);
subplot(346);
imshow(M2);
subplot(347);
imshow(M3);
subplot(348);
imshow(M4);
subplot(349);
imshow(f1);
subplot(3,4,10);
imshow(f2);
subplot(3,4,11);
imshow(f3);
subplot(3,4,12);
imshow(f4);
实验效果如下:
第一行分别为加入浓度0.05、0.25、0.45、0.65的椒盐噪声
第二行为中值滤波medfilt2处理效果,默认滤波尺寸 3*3
第三行为自适应中值滤波adpmedian 处理效果,最大滤波尺寸为11*11