直接上代码
function img = myBilateralFilter(Image, kerSize, delta)
% Image 待滤波图像
% kerSize 滤波核大小
% delta 标准差
% img 输出图像
%%
% c,r分别为核kerSize的垂直半径和水平半径
c = floor(kerSize(1)/2);
r = floor(kerSize(2)/2);
% 镜像填充边界
padImage = padarray(Image, [c, r], 'symmetric');
img = zeros(size(Image));
% G distance weight
siz = (kerSize-1)/2;
std = delta;
[x, y] = meshgrid(-siz(2): siz(2), -siz(1): siz(1));
arg = -(x.*x + y.*y)/(2*std*std);
G = exp(arg);
G(G<eps*max(G(:))) = 0;
sumG = sum(G(:));
if sumG ~= 0
G = G/sumG;
end;
% H为intensity weight
[iHeight, iWidth] = size(Image);
padImage = double(padImage);
for i = c+1: iHeight+c
for j = r+1: iWidth+r
tmp = padImage(i-c: i+c, j-r: j+r);
t = tmp - double(Image(i-c, j-r)).*ones(2*c+1, 2*r+1);
H = exp(-t.*t/(2*delta*delta));
sumH = sum(H(:));
if sumH ~= 0
H = H/sumH;
end
W = G.*H;
s = tmp.*W;
img(i-r, j-r) = sum(s(:))/sum(W(:));
end
end
函数调用
delta = 5;
bilateralImg = myBilateralFilter(Image, [5, 5], delta);
bilateralImg = uint8(bilateralImg);