-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathFiltering.pde
92 lines (77 loc) · 2.17 KB
/
Filtering.pde
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
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
FImage GaussianBlur(final FImage f, float sigma)
{
final int k_size = (int)(2.0f * floor( sqrt(-log(0.1f) * 2 * (sigma*sigma)) ) + 1.0f);
final int r = (k_size - 1) / 2;
final float sigmasquare = sigma * sigma;
// compute gaussian kernel
float[] kernel = new float[k_size];
for (int i = -r; i <= r; ++i)
{
kernel[i+r] = exp(-i*i/(2*sigmasquare)) / (sqrt(sigmasquare*TWO_PI));
}
// normalize kernel
float sum = 0;
for (int j = 0; j < kernel.length; ++j)
{
sum += kernel[j];
}
for (int j = 0; j < kernel.length; ++j)
{
kernel[j] = (kernel[j] / sum);
}
return convolveVertical1D(convolveHorizontal1D(f, kernel), kernel);
}
FImage convolveVertical1D(final FImage f, float[] kernel)
{
final int k_len = kernel.length;
final int r = (k_len - 1) / 2;
final int w = f.width;
final int h = f.height;
FImage out = new FImage(w, h, f.channels);
for (int c = 0; c < f.channels; c++)
{
for (int y = 0; y < h; y++) {
for (int x = 0; x < w; x++) {
// center pixel
float sum = kernel[r] * f.getSingle(x, y, c);
// neighbor pixels
for (int i = 1; i <= r; ++i)
{
float a = f.getSingle(x, f.border(y-i, h), c);
float b = f.getSingle(x, f.border(y+i, h), c);
sum += kernel[r+i] * b;
sum += kernel[r-i] * a;
}
out.setSingle(x, y, c, sum);
}
}
}
return out;
}
FImage convolveHorizontal1D(final FImage f, float[] kernel)
{
final int k_len = kernel.length;
final int r = (k_len - 1) / 2;
final int w = f.width;
final int h = f.height;
FImage out = new FImage(w, h, f.channels);
for (int c = 0; c < f.channels; c++)
{
for (int y = 0; y < h; y++) {
for (int x = 0; x < w; x++) {
// center pixel
float sum = kernel[r] * f.getSingle(x, y, c);
// neighbor pixels
for (int i = 1; i <= r; ++i)
{
float a = f.getSingle(f.border(x-i, w), y, c);
float b = f.getSingle(f.border(x+i, w), y, c);
sum += kernel[r+i] * b;
sum += kernel[r-i] * a;
}
out.setSingle(x, y, c, sum);
}
}
}
return out;
}