NLmeansfilter 非邻域去噪算法matlab实现

function Im = NLmeansfilter(I, nb, sw, h)
%NLFILTER Denoise the image of I
%   IM = NLFILTER(I, NB, SW, H) outputs the denoised image of I
%   I is the original image.
%   NB is a number which shows the neiborhood of the point(i,j) the
%   neiborhood of the point(i,j) is (2*nb + 1) * (2*nb + 1)
%   SW is the search window. The size of the search window is (2*SW +
%   1)*(2*SW + 1)
%   H acts as the filtering parameter
%     Create the mirror(I_extend) of image I

sw = sw + nb;
[height, width] = size(I);
I_extend = uint8(zeros(2*sw + height, 2*sw + width));
I_extend(1:sw, 1:sw) = I(sw:-1:1, sw:-1:1);
I_extend(1:sw, sw + 1:sw + width) = I(sw:-1:1,1:width);
I_extend(1:sw, sw + width + 1:2*sw + width) = I(sw:-1:1, width:-1:width-sw+1);
I_extend(sw + 1:sw + height, 1:sw) = I(1:height,sw:-1:1);
I_extend(sw + 1: sw +height, sw + 1:sw + width) = I(:, :);
I_extend(sw + 1: sw + height, sw + width + 1:2*sw + width) = ...
I(1:height,width:-1:width - sw + 1);
I_extend(sw + height + 1: 2*sw + height, 1:sw) =...
I(height:-1:height-sw + 1, sw:-1:1);
I_extend(sw + height + 1: 2*sw + height, sw + 1:sw + width) = ...
I(height:-1:height - sw + 1, 1:width);
I_extend(sw + height + 1: 2*sw + height, sw + width + 1:2*sw + width) = ...
I(height:-1:height-sw + 1, width:-1:width-sw +1);
Im = zeros(height, width);
I_extend = double(I_extend);
h = h*h;
for i = sw+1 : sw + height
for j = sw + 1: sw + width
disp([i-sw,j-sw]);
tw = 0.0;
im = 0.0;
for m = i - sw + nb : i + sw -nb
for n = j - sw + nb :j + sw - nb
%WEIGHT Calculate the weight of (x2,y2) to (x1,y1)
% Pay attention to the class type conversion uint8 to double
Ndif = I_extend(i-nb:i+nb, j-nb:j+nb) - I_extend(m - nb:m + nb, n-nb:n+nb);
Euclidean2 = (Ndif(:))'*Ndif(:);
% Euclidean2 = sum(Ndif(:).*Ndif(:));
w = exp(- Euclidean2/h);
%   (m,n)'s weight to (i,j);
im = im + w*I_extend(m,n);
tw = tw + w;
end
end
Im(i - sw, j-sw) = im/tw;
end
end
Im = uint8(Im);
figure, imshow(Im);

• 写评论