双边滤波matlab代码

%简单地说:
%A为给定图像,归一化到[0,1]的矩阵
%W为双边滤波器(核)的边长/2
%定义域方差σd记为SIGMA(1),值域方差σr记为SIGMA(2)

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Pre-process input and select appropriate filter.
function B = bfilter2(A,w,sigma)

% Verify that the input image exists and is valid.
if ~exist('A','var') || isempty(A)
   error('Input image A is undefined or invalid.');
end
if ~isfloat(A) || ~sum([1,3] == size(A,3)) || ...
      min(A(:)) < 0 || max(A(:)) > 1
   error(['Input image A must be a double precision ',...
          'matrix of size NxMx1 or NxMx3 on the closed ',...
          'interval [0,1].']);      
end

% Verify bilateral filter window size.
if ~exist('w','var') || isempty(w) || ...
      numel(w) ~= 1 || w < 1
   w = 5;
end
w = ceil(w);

% Verify bilateral filter standard deviations.
if ~exist('sigma','var') || isempty(sigma) || ...
      numel(sigma) ~= 2 || sigma(1) <= 0 || sigma(2) <= 0
   sigma = [3 0.1];
end

% Apply either grayscale or color bilateral filtering.
if size(A,3) == 1
   B = bfltGray(A,w,sigma(1),sigma(2));
else
   B = bfltColor(A,w,sigma(1),sigma(2));
end


%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Implements bilateral filtering for grayscale images.
function B = bfltGray(A,w,sigma_d,sigma_r)

% Pre-compute Gaussian distance weights.
[X,Y] = meshgrid(-w:w,-w:w);
%创建核距离矩阵,e.g.
%  [x,y]=meshgrid(-1:1,-1:1)
% 
% x =
% 
%     -1     0     1
%     -1     0     1
%     -1     0     1
% 
% 
% y =
% 
%     -1    -1    -1
%      0     0     0
%      1     1     1
%计算定义域核
G = exp(-(X.^2+Y.^2)/(2*sigma_d^2));

% Create waitbar.
h = waitbar(0,'Applying bilateral filter...');
set(h,'Name','Bilateral Filter Progress');

% Apply bilateral filter.
%计算值域核H 并与定义域核G 乘积得到双边权重函数F
dim = size(A);
B = zeros(dim);
for i = 1:dim(1)
   for j = 1:dim(2)
      
         % Extract local region.
         iMin = max(i-w,1);
         iMax = min(i+w,dim(1));
         jMin = max(j-w,1);
         jMax = min(j+w,dim(2));
         %定义当前核所作用的区域为(iMin:iMax,jMin:jMax)
         I = A(iMin:iMax,jMin:jMax);%提取该区域的源图像值赋给I
      
         % Compute Gaussian intensity weights.
         H = exp(-(I-A(i,j)).^2/(2*sigma_r^2));
      
         % Calculate bilateral filter response.
         F = H.*G((iMin:iMax)-i+w+1,(jMin:jMax)-j+w+1);
         B(i,j) = sum(F(:).*I(:))/sum(F(:));
               
   end
   waitbar(i/dim(1));
end

% Close waitbar.
close(h);


%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Implements bilateral filter for color images.
function B = bfltColor(A,w,sigma_d,sigma_r)

% Convert input sRGB image to CIELab color space.
if exist('applycform','file')
   A = applycform(A,makecform('srgb2lab'));
else
   A = colorspace('Lab<-RGB',A);
end

% Pre-compute Gaussian domain weights.
[X,Y] = meshgrid(-w:w,-w:w);
G = exp(-(X.^2+Y.^2)/(2*sigma_d^2));

% Rescale range variance (using maximum luminance).
sigma_r = 100*sigma_r;

% Create waitbar.
h = waitbar(0,'Applying bilateral filter...');
set(h,'Name','Bilateral Filter Progress');

% Apply bilateral filter.
dim = size(A);
B = zeros(dim);
for i = 1:dim(1)
   for j = 1:dim(2)
      
         % Extract local region.
         iMin = max(i-w,1);
         iMax = min(i+w,dim(1));
         jMin = max(j-w,1);
         jMax = min(j+w,dim(2));
         I = A(iMin:iMax,jMin:jMax,:);
      
         % Compute Gaussian range weights.
         dL = I(:,:,1)-A(i,j,1);
         da = I(:,:,2)-A(i,j,2);
         db = I(:,:,3)-A(i,j,3);
         H = exp(-(dL.^2+da.^2+db.^2)/(2*sigma_r^2));
      
         % Calculate bilateral filter response.
         F = H.*G((iMin:iMax)-i+w+1,(jMin:jMax)-j+w+1);
         norm_F = sum(F(:));
         B(i,j,1) = sum(sum(F.*I(:,:,1)))/norm_F;
         B(i,j,2) = sum(sum(F.*I(:,:,2)))/norm_F;
         B(i,j,3) = sum(sum(F.*I(:,:,3)))/norm_F;
                
   end
   waitbar(i/dim(1));
end

% Convert filtered image back to sRGB color space.
if exist('applycform','file')
   B = applycform(B,makecform('lab2srgb'));
else  
   B = colorspace('RGB<-Lab',B);
end

% Close waitbar.
close(h);

调用方法:

I=imread('einstein.jpg');
I=double(I)/255;

w     = 5;       % bilateral filter half-width
sigma = [3 0.1]; % bilateral filter standard deviations

I1=bfilter2(I,w,sigma);

subplot(1,2,1);
imshow(I);
subplot(1,2,2);
imshow(I1)
实验结果:

第二种实现

 双边滤波模板主要有两个模板生成,第一个是高斯模板,第二个是以灰度级的差值作为函数系数生成的模板。然后这两个模板点乘就得到了最终的双边滤波模板。

  第一个模板是全局模板,所以只需要生成一次。第二个模板需要对每个像素都计算一次,所以需要放到循环的里面来生成,这很像表面模糊啊。哦,表面模糊就是用了一个截尾滤波器。

  这里的公式我参考了这里,不过她给的第二个好像不是截尾均值滤波器,而是以灰度差值为自变量的高斯滤波器。截尾均值滤波器这里有一些理论和实现,

代码如下:

clear all;
close all;
clc;

img=imread('lena.jpg');
img=mat2gray(img);
[m n]=size(img);
imshow(img);

r=10;        %模板半径
imgn=zeros(m+2*r+1,n+2*r+1);
imgn(r+1:m+r,r+1:n+r)=img;
imgn(1:r,r+1:n+r)=img(1:r,1:n);                 %扩展上边界
imgn(1:m+r,n+r+1:n+2*r+1)=imgn(1:m+r,n:n+r);    %扩展右边界
imgn(m+r+1:m+2*r+1,r+1:n+2*r+1)=imgn(m:m+r,r+1:n+2*r+1);    %扩展下边界
imgn(1:m+2*r+1,1:r)=imgn(1:m+2*r+1,r+1:2*r);       %扩展左边界

sigma_d=2;
sigma_r=0.1;
[x,y] = meshgrid(-r:r,-r:r);
w1=exp(-(x.^2+y.^2)/(2*sigma_d^2));     %以距离作为自变量高斯滤波器

h=waitbar(0,'wait...');
for i=r+1:m+r
    for j=r+1:n+r        
        w2=exp(-(imgn(i-r:i+r,j-r:j+r)-imgn(i,j)).^2/(2*sigma_r^2)); %以周围和当前像素灰度差值作为自变量的高斯滤波器
        w=w1.*w2;
        
        s=imgn(i-r:i+r,j-r:j+r).*w;
        imgn(i,j)=sum(sum(s))/sum(sum(w));
    
    end
    waitbar(i/m);
end
close(h)

figure;
imshow(mat2gray(imgn(r+1:m+r,r+1:n+r)));



第三种实现

双边滤波与一般的高斯滤波的不同就是:双边滤波既利用了位置信息又利用了像素信息来定义滤波窗口的权重。


像素值越接近,权重越大。双边滤波会去除图像的细节信息,又能保持边界。


对于彩色图像,像素值的接近与否不能使用RGB空间值,双边滤波的原始文献建议使用CIE颜色空间。

代码如下:

function resultI = BilateralFilt2(I,d,sigma)
%%%
%Author:LiFeiteng
%Version:1.0——灰色图像  Time:2013/05/01
%Version:1.1——灰色/彩色图像  Time:2013/05/02  2013/05/05
%d 半窗口宽度
I = double(I);
if size(I,3)==1
    resultI = BilateralFiltGray(I,d,sigma);
elseif size(I,3)==3
    resultI = BilateralFiltColor(I,d,sigma);
else 
    error('Incorrect image size')    
end
end

function resultI = BilateralFiltGray(I,d,sigma)

[m n] = size(I);
newI = ReflectEdge(I,d);
resultI = zeros(m,n);
width = 2*d+1;
%Distance
D = fspecial('gaussian',[width,width],sigma(1));
S = zeros(width,width);%pix Similarity
h = waitbar(0,'Applying bilateral filter...');
set(h,'Name','Bilateral Filter Progress');
for i=1+d:m+d
    for j=1+d:n+d
        pixValue = newI(i-d:i+d,j-d:j+d);
        subValue = pixValue-newI(i,j);
        S = exp(-subValue.^2/(2*sigma(2)^2));
        H = S.*D;
        resultI(i-d,j-d) = sum(pixValue(:).*H(:))/sum(H(:)); 
    end
    waitbar(i/m);
end
close(h);
end

function resultI = BilateralFiltColor(I,d,sigma)
I = applycform(I,makecform('srgb2lab'));
[m n ~] = size(I);
newI = ReflectEdge(I,d);
resultI = zeros(m,n,3);
width = 2*d+1;
%Distance
D = fspecial('gaussian',[width,width],sigma(1));
% [X,Y] = meshgrid(-d:d,-d:d);
% D = exp(-(X.^2+Y.^2)/(2*sigma(1)^2));
S = zeros(width,width);%pix Similarity
h = waitbar(0,'Applying bilateral filter...');
set(h,'Name','Bilateral Filter Progress');
sigma_r = 100*sigma(2);
for i=1+d:m+d
    for j=1+d:n+d
        pixValue = newI(i-d:i+d,j-d:j+d,1:3);
        %subValue = pixValue-repmat(newI(i,j,1:3),width,width);
        dL = pixValue(:,:,1)-newI(i,j,1);
        da = pixValue(:,:,2)-newI(i,j,2);
        db = pixValue(:,:,3)-newI(i,j,3);
        S = exp(-(dL.^2+da.^2+db.^2)/(2*sigma_r^2));
        H = S.*D;
        H = H./sum(H(:));
        resultI(i-d,j-d,1) = sum(sum(pixValue(:,:,1).*H)); 
        resultI(i-d,j-d,2) = sum(sum(pixValue(:,:,2).*H));    
        resultI(i-d,j-d,3) = sum(sum(pixValue(:,:,3).*H));    
    end
    waitbar(i/m);
end
close(h);
resultI = applycform(resultI,makecform('lab2srgb'));
end
其中newI = ReflectEdge(I,d); %对称地扩展边界,在原始图像I的边界处镜像映射像素值 

function newI = ReflectEdge(I,d)
%Version:1.0——灰色图像  Time:2013/05/01
%Version:1.1——灰色/彩色图像  Time:2013/05/02
%考虑到实用性,决定不添加更多的边界处理选择,统一使用:reflect across edge

if size(I,3)==1
    newI = ReflectEdgeGray(I,d);
elseif size(I,3)==3
    newI = ReflectEdgeColor(I,d);
else 
    error('Incorrect image size')    
end
end

function newI = ReflectEdgeGray(I,d)
[m n] = size(I);
newI = zeros(m+2*d,n+2*d);
%中间部分
newI(d+1:d+m,d+1:d+n) = I;
%上
newI(1:d,d+1:d+n) = I(d:-1:1,:);
%下
newI(end-d:end,d+1:d+n) = I(end:-1:end-d,:);
%左
newI(:,1:d) = newI(:,2*d:-1:d+1);
%右
newI(:,m+d+1:m+2*d) = newI(:,m+d:-1:m+1);
end

function newI = ReflectEdgeColor(I,d)
%扩展图像边界
[m n ~] = size(I);
newI = zeros(m+2*d,n+2*d,3);
%中间部分
newI(d+1:d+m,d+1:d+n,1:3) = I;
%上
newI(1:d,d+1:d+n,1:3) = I(d:-1:1,:,1:3);
%下
newI(end-d:end,d+1:d+n,1:3) = I(end:-1:end-d,:,1:3);
%左
newI(:,1:d,1:3) = newI(:,2*d:-1:d+1,1:3);
%右
newI(:,m+d+1:m+2*d,1:3) = newI(:,m+d:-1:m+1,1:3);
end
测试用例:
img = imread('.\lena.tif');
%%img = imread('.\images\lena_gray.tif');
img = double(img)/255;
img = img+0.05*randn(size(img));
img(img<0) = 0; img(img>1) = 1;
%img = imnoise(img,'gaussian');
figure, imshow(img,[])
title('原始图像')
d = 6;
sigma = [3 0.1];
resultI = BilateralFilt2(double(img), d, sigma);

figure, imshow(resultI,[])
title('双边滤波后的图像')

结果:

双边滤波matlab代码_第1张图片


你可能感兴趣的:(ISP)