自编一个中值滤波函数mymedfilt2(A, [m,n]),实现Matlab中的medfilt2函数的功能(边缘采用复制的方式);对自选的灰度图像加上椒盐噪声,用自编的函数对其进行中值滤波。
主程序:
// An highlighted block
clear;clc;
img=imread('rice.png');
n=3;m=4;
str='sample';
%str='zeros';
[img1,img2,img3]=mymedfilt2(img,n,m,str);
subplot(221), imshow(img), title('原图')
subplot(222), imshow(img1), title('加入椒盐噪声后')
subplot(223), imshow(img2), title([num2str(n),'X',num2str(m),'自定中值滤波'])
subplot(224), imshow(img3), title([num2str(n),'X',num2str(m),'原有中值滤波'])
mymedfilt2类:
// An highlighted block
function [J,x2,x3] = mymedfilt2(img, n, m, str)
% clear;clc;
% str='sample';
% img=imread('rice.png');
% n=3;m=3;
% if(strcmp(str,'sample')==strcmp(str,'zeros'))
% return
% end
J=imnoise(img, 'salt & pepper',0.04);
tend_img=img;
[h,w]=size(img);
if(mod(n,2)~=mod(m,2)) %若模板行与列分别为偶数和奇数
if (strcmp(str,'sample'))
for i=1:round((n/2))-1 %复制填充
tend_img=[img(1:h);tend_img];
end
for i=1:n/2
tend_img=[tend_img;img(end,:)];
end
[h,w]=size(tend_img);
for i=1:round((m/2))-1
tend_img=[tend_img(1:h,1),tend_img];
end
for j=1:m/2
tend_img=[tend_img,tend_img(:,end)];
end
else
for i=1:(n/2)-1 %零填充
tend_img=[zeros(1,h);tend_img];
end
for i=1:n/2
tend_img=[tend_img;zeros(1,h)];
end
[h,w]=size(tend_img);
for i=1:(m/2)-1
tend_img=[zeros(h,1),tend_img];
end
for j=1:m/2
tend_img=[tend_img,zeros(h,1)];
end
end
elseif (strcmp(str,'sample')) %奇数 复制填充
for i=1:n/2
tend_img=[img(1,:);tend_img;img(end,:)];
end
for j=1:m/2
tend_img=[tend_img(:,1),tend_img,tend_img(:,end)];
end
elseif(strcmp(str,'zeros')) %奇数 零填充
for i=1:n/2
tend_img=[zeros(1,h);tend_img;zeros(1,h)];
end
[r,h]=size(tend_img);
for j=1:m/2
tend_img=[zeros(r,1),tend_img,zeros(r,1)];
end
end
[h,w]=size(tend_img);
x1=double(tend_img);
for i=1:h-n+1
for j=1:w-m+1
c=x1(i:i+(n-1),j:j+(m-1)); %取模板覆盖图像
c=c(:); %转变为列
mid=median(c); %取中值
x2(i,j)=round(mid); %四舍五入
end
end
x2=uint8(x2);
x3=medfilt2(img,[n,m]); %原中值滤波函数
end
%img(1:end+3,end+1:end+3)=0;
% clc
% for I=248:256
% A=[tend_img(2:4,I:I+2)]
% mid=round(median(A(:)))
% end
效果图:
原图:
加入噪声后:
自定义中值滤波:
自带中值滤波: