传统引导滤波获得细节层的超级详细完整代码matlabR2016b
时间: 2023-08-27 12:03:49 浏览: 141
基于快速双边滤波的细节增强算法(matlab代码)
5星 · 资源好评率100%
以下是传统引导滤波的Matlab代码,包括获得细节层的部分:
```matlab
function J = guidedfilter(I, p, r, eps)
% GUIDEDFILTER O(1) time implementation of guided filter.
%
% - guidance image: I (should be a gray-scale/single channel image)
% - filtering input image: p (should be a gray-scale/single channel image)
% - local window radius: r
% - regularization parameter: eps
%
% References:
% [1] K. He, J. Sun, and X. Tang, "Guided Image Filtering,"
% IEEE Transactions on Pattern Analysis and Machine Intelligence, Vol. 35, No. 6, pp. 1397-1409, June 2013.
% [2] http://kaiminghe.com/eccv10/
% eps = 0.01^2; % default value (as in the paper)
if ~isa(I,'double')
I = double(I);
end
if ~isa(p,'double')
p = double(p);
end
mean_I = boxfilter(I, r) ./ boxfilter(ones(size(I)), r);
mean_p = boxfilter(p, r) ./ boxfilter(ones(size(p)), r);
mean_Ip = boxfilter(I.*p, r) ./ boxfilter(ones(size(I)), r);
cov_Ip = mean_Ip - mean_I .* mean_p; % this is the covariance of (I, p) in each local patch.
mean_II = boxfilter(I.*I, r) ./ boxfilter(ones(size(I)), r);
var_I = mean_II - mean_I .* mean_I;
a = cov_Ip ./ (var_I + eps); % Eqn. (5) in the paper;
b = mean_p - a .* mean_I; % Eqn. (6) in the paper;
mean_a = boxfilter(a, r) ./ boxfilter(ones(size(a)), r);
mean_b = boxfilter(b, r) ./ boxfilter(ones(size(b)), r);
q = mean_a .* I + mean_b; % Eqn. (8) in the paper;
J = q; % output the filtering result
end
function imDst = boxfilter(imSrc, r)
% BOXFILTER O(1) time box filtering using cumulative sum
%
% - Definition imDst(x, y)=sum(sum(imSrc(x-r:x+r,y-r:y+r)));
% - Running time independent of r;
% - Equivalent to the function: colfilt(imSrc, [2*r+1, 2*r+1], 'sliding', @sum);
% - But much faster.
[hei, wid] = size(imSrc);
imDst = zeros(size(imSrc));
% cumulative sum over Y axis
imCum = cumsum(imSrc, 1);
% difference over Y axis
imDst(1:r+1, :) = imCum(1+r:2*r+1, :);
imDst(r+2:hei-r, :) = imCum(2*r+2:hei, :) - imCum(1:hei-2*r-1, :);
imDst(hei-r+1:hei, :) = repmat(imCum(hei, :), [r, 1]) - imCum(hei-2*r:hei-r-1, :);
% cumulative sum over X axis
imCum = cumsum(imDst, 2);
% difference over X axis
imDst(:, 1:r+1) = imCum(:, 1+r:2*r+1);
imDst(:, r+2:wid-r) = imCum(:, 2*r+2:wid) - imCum(:, 1:wid-2*r-1);
imDst(:, wid-r+1:wid) = repmat(imCum(:, wid), [1, r]) - imCum(:, wid-2*r:wid-r-1);
end
```
其中,`guidedfilter`函数是传统引导滤波的主体函数,输入参数包括引导图像`I`、待处理图像`p`、局部窗口半径`r`和正则化参数`eps`,输出为滤波结果`J`。`boxfilter`函数是一个用于快速计算累加和的函数,用于加速滤波过程。
阅读全文