首页 > 代码库 > 用 OpenCV 实现 Guided Filter
用 OpenCV 实现 Guided Filter
最近发现 OpenCV 的 C++ 接口写得和 Matlab 实在是太相似了。我用 OpenCV 2.49 来实现 Guided Filter 的时候几乎是直接照抄作者公开的 Matlab 代码。废话不多直接贴我的代码:
cv::Mat guidedFilter(cv::Mat I, cv::Mat p, int r, double 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 */ cv::Mat _I; I.convertTo(_I, CV_64FC1); I = _I; cv::Mat _p; p.convertTo(_p, CV_64FC1); p = _p; //[hei, wid] = size(I); int hei = I.rows; int wid = I.cols; //N = boxfilter(ones(hei, wid), r); % the size of each local patch; N=(2r+1)^2 except for boundary pixels. cv::Mat N; cv::boxFilter(cv::Mat::ones(hei, wid, I.type()), N, CV_64FC1, cv::Size(r, r)); //mean_I = boxfilter(I, r) ./ N; cv::Mat mean_I; cv::boxFilter(I, mean_I, CV_64FC1, cv::Size(r, r)); //mean_p = boxfilter(p, r) ./ N; cv::Mat mean_p; cv::boxFilter(p, mean_p, CV_64FC1, cv::Size(r, r)); //mean_Ip = boxfilter(I.*p, r) ./ N; cv::Mat mean_Ip; cv::boxFilter(I.mul(p), mean_Ip, CV_64FC1, cv::Size(r, r)); //cov_Ip = mean_Ip - mean_I .* mean_p; % this is the covariance of (I, p) in each local patch. cv::Mat cov_Ip = mean_Ip - mean_I.mul(mean_p); //mean_II = boxfilter(I.*I, r) ./ N; cv::Mat mean_II; cv::boxFilter(I.mul(I), mean_II, CV_64FC1, cv::Size(r, r)); //var_I = mean_II - mean_I .* mean_I; cv::Mat var_I = mean_II - mean_I.mul(mean_I); //a = cov_Ip ./ (var_I + eps); % Eqn. (5) in the paper; cv::Mat a = cov_Ip/(var_I + eps); //b = mean_p - a .* mean_I; % Eqn. (6) in the paper; cv::Mat b = mean_p - a.mul(mean_I); //mean_a = boxfilter(a, r) ./ N; cv::Mat mean_a; cv::boxFilter(a, mean_a, CV_64FC1, cv::Size(r, r)); mean_a = mean_a/N; //mean_b = boxfilter(b, r) ./ N; cv::Mat mean_b; cv::boxFilter(b, mean_b, CV_64FC1, cv::Size(r, r)); mean_b = mean_b/N; //q = mean_a .* I + mean_b; % Eqn. (8) in the paper; cv::Mat q = mean_a.mul(I) + mean_b; return q; }
上面这段代码的注释就是 Guided Filter 的原作者给出的 Matlab 代码,我按照这些 Matlab 代码,一行一行改写就很快地完成了基于 OpenCV 的 Guided Filter 实现。我大致搜索了一下,似乎很难找到公开的 Guided Filter 实现,所以这里我分享一下我的代码。另,再次感谢 Guided Filter 的作者 Kaiming He 公开的 Matlab 源码。
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。