-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathbilateral.hpp
73 lines (56 loc) · 2.2 KB
/
bilateral.hpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
//zc: 2018-5-9 18:03:01
#ifndef _BILATERAL_H_
#define _BILATERAL_H_
#include <limits>
#include <cmath>
#include <opencv2/opencv.hpp>
//@param[in] src, input dmap of type *DTYPE*
//@param[in|out] dst, filtered output dmap of type *DTYPE*
template<typename DTYPE>
void bilateral_filter(cv::Mat src, cv::Mat dst){
using namespace std;
const float sigma_color = 30; //in mm
const float sigma_space = 2.5; // in pixels
float sigma_space2_inv_half = 0.5 / (sigma_space * sigma_space),
sigma_color2_inv_half = 0.5 / (sigma_color * sigma_color);
// const int R = 6;
const int R = static_cast<int>(sigma_space * 1.5);
const int D = R * 2 + 1;
for (int x = 0; x < src.cols; ++x)
{
for (int y = 0; y < src.rows; ++y)
{
// int value = src.at<ushort>(y, x);
DTYPE value = src.at<DTYPE>(y, x);
if (std::isinf(value) || abs(value) < 1e-8)
{
dst.at<DTYPE>(y, x) = value;
continue;
}
int tx = min(x - D / 2 + D, src.cols - 1);
int ty = min(y - D / 2 + D, src.rows - 1);
float sum1 = 0;
float sum2 = 0;
for (int cy = max(y - D / 2, 0); cy < ty; ++cy)
{
for (int cx = max(x - D / 2, 0); cx < tx; ++cx)
{
// int tmp = src.at<ushort>(cy, cx);
DTYPE tmp = src.at<DTYPE>(cy, cx);
if (std::isinf(tmp) || abs(tmp) < 1e-8)
continue;
float space2 = (x - cx) * (x - cx) + (y - cy) * (y - cy);
float color2 = (value - tmp) * (value - tmp);
float weight = expf(-(space2 * sigma_space2_inv_half + color2 * sigma_color2_inv_half));
sum1 += tmp * weight;
sum2 += weight;
}
}
// int res = __float2int_rn(sum1 / sum2);
// int res = int(sum1 / sum2 + 0.5); //round-nearest
DTYPE res = (DTYPE)(sum1 / sum2);
dst.at<DTYPE>(y, x) = max((DTYPE)0, min(res, (DTYPE)numeric_limits<DTYPE>::max()));
}
}
} //bilateral_filter
#endif // _BILATERAL_H_