【图像处理】引导滤波c++
参考matlab源码,翻译成c++
matlab源码:
function q = 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
[hei, wid] = size(I);
N = boxfilter(ones(hei, wid), r); % the size of each local patch; N=(2r+1)^2 except for boundary pixels.
mean_I = boxfilter(I, r) ./ N;
mean_p = boxfilter(p, r) ./ N;
mean_Ip = boxfilter(I.*p, r) ./ N;
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) ./ N;
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) ./ N;
mean_b = boxfilter(b, r) ./ N;
q = mean_a .* I + mean_b; % Eqn. (8) in the paper;
end
c++实现:
#include
#include
#include
cv::Mat guidefilter(const cv::Mat& I, const cv::Mat& p, int r, float eps)
{
assert(I.type() == p.type());
assert(I.size() == p.size());
cv::Mat mean_I, mean_p, mean_Ip, cov_Ip;
cv::Mat mean_II, var_I;
cv::boxFilter(I, mean_I, -1, cv::Size(r, r));
cv::boxFilter(p, mean_p, -1, cv::Size(r, r));
cv::boxFilter(I.mul(p), mean_Ip, -1, cv::Size(r, r));
cov_Ip = mean_Ip - mean_I.mul(mean_p);
cv::boxFilter(I.mul(I), mean_II, -1, cv::Size(r, r));
var_I = mean_II - mean_I.mul(mean_I);
cv::Mat a, b;
cv::divide(cov_Ip, var_I + eps, a);
b = mean_p - a.mul(mean_I);
cv::Mat mean_a, mean_b;
cv::boxFilter(a, mean_a, -1, cv::Size(r, r));
cv::boxFilter(b, mean_b, -1, cv::Size(r, r));
return mean_a.mul(I) + mean_b;
}
int main()
{
cv::Mat src = cv::imread("cat.bmp");
cv::Mat guide = src.clone();
int r = 16;
float eps = 0.01;
cv::Mat q = guidefilter(src, guide, r, eps);
cv::Mat I_enhanced = (src - q) * 2 + q;
cv::imshow("enhanced.jpg", I_enhanced);
cv::imshow("original.jpg", src);
cv::waitKey(0);
return 0;
}