]> git.sesse.net Git - movit/blob - deconvolution_sharpen_effect.cpp
260266403852a2beb22232e29924d4c25a873b2d
[movit] / deconvolution_sharpen_effect.cpp
1 // NOTE: Throughout, we use the symbol ⊙ for convolution.
2 // Since all of our signals are symmetrical, discrete correlation and convolution
3 // is the same operation, and so we won't make a difference in notation.
4
5 #include <Eigen/Dense>
6 #include <Eigen/Cholesky>
7 #include <GL/glew.h>
8 #include <assert.h>
9 #include <math.h>
10 #include <stdio.h>
11 #include <stdlib.h>
12 #include <algorithm>
13 #include <new>
14
15 #include "deconvolution_sharpen_effect.h"
16 #include "util.h"
17
18 using namespace Eigen;
19
20 DeconvolutionSharpenEffect::DeconvolutionSharpenEffect()
21         : R(5),
22           circle_radius(2.0f),
23           gaussian_radius(0.0f),
24           correlation(0.95f),
25           noise(0.01f),
26           last_R(-1),
27           last_circle_radius(-1.0f),
28           last_gaussian_radius(-1.0f),
29           last_correlation(-1.0f),
30           last_noise(-1.0f)
31 {
32         register_int("matrix_size", &R);
33         register_float("circle_radius", &circle_radius);
34         register_float("gaussian_radius", &gaussian_radius);
35         register_float("correlation", &correlation);
36         register_float("noise", &noise);
37 }
38
39 std::string DeconvolutionSharpenEffect::output_fragment_shader()
40 {
41         char buf[256];
42         sprintf(buf, "#define R %u\n", R);
43
44         assert(R >= 1);
45         assert(R <= 25);  // Same limit as Refocus.
46
47         last_R = R;
48         return buf + read_file("deconvolution_sharpen_effect.frag");
49 }
50
51 namespace {
52
53 // Integral of sqrt(r² - x²) dx over x=0..a.
54 float circle_integral(float a, float r)
55 {
56         assert(a >= 0.0f);
57         if (a <= 0.0f) {
58                 return 0.0f;
59         }
60         if (a >= r) {
61                 return 0.25f * M_PI * r * r;
62         }
63         return 0.5f * (a * sqrt(r*r - a*a) + r*r * asin(a / r));
64 }
65
66 // Yields the impulse response of a circular blur with radius r.
67 // We basically look at each element as a square centered around (x,y),
68 // and figure out how much of its area is covered by the circle.
69 float circle_impulse_response(int x, int y, float r)
70 {
71         if (r < 1e-3) {
72                 // Degenerate case: radius = 0 yields the impulse response.
73                 return (x == 0 && y == 0) ? 1.0f : 0.0f;
74         }
75
76         // Find the extents of this cell. Due to symmetry, we can cheat a bit
77         // and pretend we're always in the upper-right quadrant, except when
78         // we're right at an axis crossing (x = 0 or y = 0), in which case we
79         // simply use the evenness of the function; shrink the cell, make
80         // the calculation, and down below we'll normalize by the cell's area.
81         float min_x, max_x, min_y, max_y;
82         if (x == 0) {
83                 min_x = 0.0f;
84                 max_x = 0.5f;
85         } else {
86                 min_x = abs(x) - 0.5f;
87                 max_x = abs(x) + 0.5f;
88         }
89         if (y == 0) {
90                 min_y = 0.0f;
91                 max_y = 0.5f;
92         } else {
93                 min_y = abs(y) - 0.5f;
94                 max_y = abs(y) + 0.5f;
95         }
96         assert(min_x >= 0.0f && max_x >= 0.0f);
97         assert(min_y >= 0.0f && max_y >= 0.0f);
98
99         float cell_height = max_y - min_y;
100         float cell_width = max_x - min_x;
101
102         if (min_x * min_x + min_y * min_y > r * r) {
103                 // Lower-left corner is outside the circle, so the entire cell is.
104                 return 0.0f;
105         }
106         if (max_x * max_x + max_y * max_y < r * r) {
107                 // Upper-right corner is inside the circle, so the entire cell is.
108                 return 1.0f;
109         }
110
111         // OK, so now we know the cell is partially covered by the circle:
112         //
113         //      \           .
114         //  -------------
115         // |####|#\      |
116         // |####|##|     |
117         //  -------------
118         //   A   ###|
119         //       ###|
120         //
121         // The edge of the circle is defined by x² + y² = r², 
122         // or x = sqrt(r² - y²) (since x is nonnegative).
123         // Find out where the curve crosses our given y values.
124         float mid_x1 = (max_y >= r) ? min_x : sqrt(r * r - max_y * max_y);
125         float mid_x2 = sqrt(r * r - min_y * min_y);
126         if (mid_x1 < min_x) {
127                 mid_x1 = min_x;
128         }
129         if (mid_x2 > max_x) {
130                 mid_x2 = max_x;
131         }
132         assert(mid_x1 >= min_x);
133         assert(mid_x2 >= mid_x1);
134         assert(max_x >= mid_x2);
135
136         // The area marked A in the figure above.
137         float covered_area = cell_height * (mid_x1 - min_x);
138
139         // The area marked B in the figure above. Note that the integral gives the entire
140         // shaded space down to zero, so we need to subtract the rectangle that does not
141         // belong to our cell.
142         covered_area += circle_integral(mid_x2, r) - circle_integral(mid_x1, r);
143         covered_area -= min_y * (mid_x2 - mid_x1);
144
145         assert(covered_area <= cell_width * cell_height);
146         return covered_area / (cell_width * cell_height);
147 }
148
149 // Compute a ⊙ b. Note that we compute the “full” convolution,
150 // ie., our matrix will be big enough to hold every nonzero element of the result.
151 MatrixXf convolve(const MatrixXf &a, const MatrixXf &b)
152 {
153         MatrixXf result(a.rows() + b.rows() - 1, a.cols() + b.cols() - 1);
154         for (int yr = 0; yr < result.rows(); ++yr) {
155                 for (int xr = 0; xr < result.cols(); ++xr) {
156                         float sum = 0.0f;
157
158                         // Given that x_b = x_r - x_a, find the values of x_a where
159                         // x_a is in [0, a_cols> and x_b is in [0, b_cols>. (y is similar.)
160                         //
161                         // The second demand gives:
162                         //
163                         //   0 <= x_r - x_a < b_cols
164                         //   0 >= x_a - x_r > -b_cols
165                         //   x_r >= x_a > x_r - b_cols
166                         int ya_min = yr - b.rows() + 1;
167                         int ya_max = yr;
168                         int xa_min = xr - b.rows() + 1;
169                         int xa_max = xr;
170
171                         // Now fit to the first demand.
172                         ya_min = std::max<int>(ya_min, 0);
173                         ya_max = std::min<int>(ya_max, a.rows() - 1);
174                         xa_min = std::max<int>(xa_min, 0);
175                         xa_max = std::min<int>(xa_max, a.cols() - 1);
176
177                         assert(ya_max >= ya_min);
178                         assert(xa_max >= xa_min);
179
180                         for (int ya = ya_min; ya <= ya_max; ++ya) {
181                                 for (int xa = xa_min; xa <= xa_max; ++xa) {
182                                         sum += a(ya, xa) * b(yr - ya, xr - xa);
183                                 }
184                         }
185
186                         result(yr, xr) = sum;
187                 }
188         }
189         return result;
190 }
191
192 // Similar to convolve(), but instead of assuming every element outside
193 // of b is zero, we make no such assumption and instead return only the
194 // elements where we know the right answer. (This is the only difference
195 // between the two.)
196 // This is the same as conv2(a, b, 'valid') in Octave.
197 //
198 // a must be the larger matrix of the two.
199 MatrixXf central_convolve(const MatrixXf &a, const MatrixXf &b)
200 {
201         assert(a.rows() >= b.rows());
202         assert(a.cols() >= b.cols());
203         MatrixXf result(a.rows() - b.rows() + 1, a.cols() - b.cols() + 1);
204         for (int yr = b.rows() - 1; yr < result.rows() + b.rows() - 1; ++yr) {
205                 for (int xr = b.cols() - 1; xr < result.cols() + b.cols() - 1; ++xr) {
206                         float sum = 0.0f;
207
208                         // Given that x_b = x_r - x_a, find the values of x_a where
209                         // x_a is in [0, a_cols> and x_b is in [0, b_cols>. (y is similar.)
210                         //
211                         // The second demand gives:
212                         //
213                         //   0 <= x_r - x_a < b_cols
214                         //   0 >= x_a - x_r > -b_cols
215                         //   x_r >= x_a > x_r - b_cols
216                         int ya_min = yr - b.rows() + 1;
217                         int ya_max = yr;
218                         int xa_min = xr - b.rows() + 1;
219                         int xa_max = xr;
220
221                         // Now fit to the first demand.
222                         ya_min = std::max<int>(ya_min, 0);
223                         ya_max = std::min<int>(ya_max, a.rows() - 1);
224                         xa_min = std::max<int>(xa_min, 0);
225                         xa_max = std::min<int>(xa_max, a.cols() - 1);
226
227                         assert(ya_max >= ya_min);
228                         assert(xa_max >= xa_min);
229
230                         for (int ya = ya_min; ya <= ya_max; ++ya) {
231                                 for (int xa = xa_min; xa <= xa_max; ++xa) {
232                                         sum += a(ya, xa) * b(yr - ya, xr - xa);
233                                 }
234                         }
235
236                         result(yr - b.rows() + 1, xr - b.cols() + 1) = sum;
237                 }
238         }
239         return result;
240 }
241
242 void print_matrix(const MatrixXf &m)
243 {
244         for (int y = 0; y < m.rows(); ++y) {
245                 for (int x = 0; x < m.cols(); ++x) {
246                         printf("%7.4f ", m(x, y));
247                 }
248                 printf("\n");
249         }
250 }
251
252 }  // namespace
253
254 void DeconvolutionSharpenEffect::update_deconvolution_kernel()
255 {
256         // Figure out the impulse response for the circular part of the blur.
257         MatrixXf circ_h(2 * R + 1, 2 * R + 1);
258         for (int y = -R; y <= R; ++y) { 
259                 for (int x = -R; x <= R; ++x) {
260                         circ_h(y + R, x + R) = circle_impulse_response(x, y, circle_radius);
261                 }
262         }
263
264         // Same, for the Gaussian part of the blur. We make this a lot larger
265         // since we're going to convolve with it soon, and it has infinite support
266         // (see comments for central_convolve()).
267         MatrixXf gaussian_h(4 * R + 1, 4 * R + 1);
268         for (int y = -2 * R; y <= 2 * R; ++y) { 
269                 for (int x = -2 * R; x <= 2 * R; ++x) {
270                         float val;
271                         if (gaussian_radius < 1e-3) {
272                                 val = (x == 0 && y == 0) ? 1.0f : 0.0f;
273                         } else {
274                                 val = exp(-(x*x + y*y) / (2.0 * gaussian_radius * gaussian_radius));
275                         }
276                         gaussian_h(y + 2 * R, x + 2 * R) = val;
277                 }
278         }
279
280         // h, the (assumed) impulse response that we're trying to invert.
281         MatrixXf h = central_convolve(gaussian_h, circ_h);
282         assert(h.rows() == 2 * R + 1);
283         assert(h.cols() == 2 * R + 1);
284
285         // Normalize the impulse response.
286         float sum = 0.0f;
287         for (int y = 0; y < 2 * R + 1; ++y) {
288                 for (int x = 0; x < 2 * R + 1; ++x) {
289                         sum += h(y, x);
290                 }
291         }
292         for (int y = 0; y < 2 * R + 1; ++y) {
293                 for (int x = 0; x < 2 * R + 1; ++x) {
294                         h(y, x) /= sum;
295                 }
296         }
297
298         // r_uu, the (estimated/assumed) autocorrelation of the input signal (u).
299         // The signal is modelled a standard autoregressive process with the
300         // given correlation coefficient.
301         //
302         // We have to take a bit of care with the size of this matrix.
303         // The pow() function naturally has an infinite support (except for the
304         // degenerate case of correlation=0), but we have to chop it off
305         // somewhere. Since we convolve it with a 4*R+1 large matrix below,
306         // we need to make it twice as big as that, so that we have enough
307         // data to make r_vv valid. (central_convolve() effectively enforces
308         // that we get at least the right size.)
309         MatrixXf r_uu(8 * R + 1, 8 * R + 1);
310         for (int y = -4 * R; y <= 4 * R; ++y) { 
311                 for (int x = -4 * R; x <= 4 * R; ++x) {
312                         r_uu(x + 4 * R, y + 4 * R) = pow(correlation, hypot(x, y));
313                 }
314         }
315
316         // Estimate r_vv, the autocorrelation of the output signal v.
317         // Since we know that v = h ⊙ u and both are symmetrical,
318         // convolution and correlation are the same, and
319         // r_vv = v ⊙ v = (h ⊙ u) ⊙ (h ⊙ u) = (h ⊙ h) ⊙ r_uu.
320         MatrixXf r_vv = central_convolve(r_uu, convolve(h, h));
321         assert(r_vv.rows() == 4 * R + 1);
322         assert(r_vv.cols() == 4 * R + 1);
323
324         // Similarly, r_uv = u ⊙ v = u ⊙ (h ⊙ u) = h ⊙ r_uu.
325         MatrixXf r_uu_center = r_uu.block(2 * R, 2 * R, 4 * R + 1, 4 * R + 1);
326         MatrixXf r_uv = central_convolve(r_uu_center, h);
327         assert(r_uv.rows() == 2 * R + 1);
328         assert(r_uv.cols() == 2 * R + 1);
329         
330         // Add the noise term (we assume the noise is uncorrelated,
331         // so it only affects the central element).
332         r_vv(2 * R, 2 * R) += noise;
333
334         // Now solve the Wiener-Hopf equations to find the deconvolution kernel g.
335         // Most texts show this only for the simpler 1D case:
336         //
337         // [ r_vv(0)  r_vv(1) r_vv(2) ... ] [ g(0) ]   [ r_uv(0) ]
338         // [ r_vv(-1) r_vv(0) ...         ] [ g(1) ] = [ r_uv(1) ]
339         // [ r_vv(-2) ...                 ] [ g(2) ]   [ r_uv(2) ]
340         // [ ...                          ] [ g(3) ]   [ r_uv(3) ]
341         //
342         // (Since r_vv is symmetrical, we can drop the minus signs.)
343         //
344         // Generally, row i of the matrix contains (dropping _vv for brevity):
345         //
346         // [ r(0-i) r(1-i) r(2-i) ... ]
347         //
348         // However, we have the 2D case. We flatten the vectors out to
349         // 1D quantities; this means we must think of the row number
350         // as a pair instead of as a scalar. Row (i,j) then contains:
351         //
352         // [ r(0-i,0-j) r(1-i,0-j) r(2-i,0-j) ... r(0-i,1-j) r_(1-i,1-j) r(2-i,1-j) ... ]
353         //
354         // g and r_uv are flattened in the same fashion.
355         //
356         // Note that even though this matrix is block Toeplitz, it is _not_ Toeplitz,
357         // and thus can not be inverted through the standard Levinson-Durbin method.
358         // There exists a block Levinson-Durbin method, which we may or may not
359         // want to use later. (Eigen's solvers are fast enough that for big matrices,
360         // the convolution operation and not the matrix solving is the bottleneck.)
361         //
362         // One thing we definitely want to use, though, is the symmetry properties.
363         // Since we know that g(i, j) = g(|i|, |j|), we can reduce the amount of
364         // unknowns to about 1/4th of the total size. The method is quite simple,
365         // as can be seen from the following toy equation system:
366         //
367         //   A x0 + B x1 + C x2 = y0
368         //   D x0 + E x1 + F x2 = y1
369         //   G x0 + H x1 + I x2 = y2
370         //
371         // If we now know that e.g. x0=x1 and y0=y1, we can rewrite this to
372         //
373         //   (A+B+D+E) x0 + (C+F) x2 = 2 y0
374         //   (G+H)     x0 + I x2     = y2
375         //
376         // This both increases accuracy and provides us with a very nice speed
377         // boost.
378         MatrixXf M(MatrixXf::Zero((R + 1) * (R + 1), (R + 1) * (R + 1)));
379         MatrixXf r_uv_flattened(MatrixXf::Zero((R + 1) * (R + 1), 1));
380         for (int outer_i = 0; outer_i < 2 * R + 1; ++outer_i) {
381                 int folded_outer_i = abs(outer_i - R);
382                 for (int outer_j = 0; outer_j < 2 * R + 1; ++outer_j) {
383                         int folded_outer_j = abs(outer_j - R);
384                         int row = folded_outer_i * (R + 1) + folded_outer_j;
385                         for (int inner_i = 0; inner_i < 2 * R + 1; ++inner_i) {
386                                 int folded_inner_i = abs(inner_i - R);
387                                 for (int inner_j = 0; inner_j < 2 * R + 1; ++inner_j) {
388                                         int folded_inner_j = abs(inner_j - R);
389                                         int col = folded_inner_i * (R + 1) + folded_inner_j;
390                                         M(row, col) += r_vv((inner_i - R) - (outer_i - R) + 2 * R,
391                                                             (inner_j - R) - (outer_j - R) + 2 * R);
392                                 }
393                         }
394                         r_uv_flattened(row) += r_uv(outer_i, outer_j);
395                 }
396         }
397
398         LLT<MatrixXf> llt(M);
399         MatrixXf g_flattened = llt.solve(r_uv_flattened);
400         assert(g_flattened.rows() == (R + 1) * (R + 1)),
401         assert(g_flattened.cols() == 1);
402
403         // Normalize and de-flatten the deconvolution matrix.
404         g = MatrixXf(R + 1, R + 1);
405         sum = 0.0f;
406         for (int i = 0; i < g_flattened.rows(); ++i) {
407                 int y = i / (R + 1);
408                 int x = i % (R + 1);
409                 if (y == 0 && x == 0) {
410                         sum += g_flattened(i);
411                 } else if (y == 0 || x == 0) {
412                         sum += 2.0f * g_flattened(i);
413                 } else {
414                         sum += 4.0f * g_flattened(i);
415                 }
416         }
417         for (int i = 0; i < g_flattened.rows(); ++i) {
418                 int y = i / (R + 1);
419                 int x = i % (R + 1);
420                 g(y, x) = g_flattened(i) / sum;
421         }
422
423         last_circle_radius = circle_radius;
424         last_gaussian_radius = gaussian_radius;
425         last_correlation = correlation;
426         last_noise = noise;
427 }
428
429 void DeconvolutionSharpenEffect::set_gl_state(GLuint glsl_program_num, const std::string &prefix, unsigned *sampler_num)
430 {
431         Effect::set_gl_state(glsl_program_num, prefix, sampler_num);
432
433         assert(R == last_R);
434
435         if (fabs(circle_radius - last_circle_radius) > 1e-3 ||
436             fabs(gaussian_radius - last_gaussian_radius) > 1e-3 ||
437             fabs(correlation - last_correlation) > 1e-3 ||
438             fabs(noise - last_noise) > 1e-3) {
439                 update_deconvolution_kernel();
440         }
441         // Now encode it as uniforms, and pass it on to the shader.
442         float samples[4 * (R + 1) * (R + 1)];
443         for (int y = 0; y <= R; ++y) {
444                 for (int x = 0; x <= R; ++x) {
445                         int i = y * (R + 1) + x;
446                         samples[i * 4 + 0] = x / float(width);
447                         samples[i * 4 + 1] = y / float(height);
448                         samples[i * 4 + 2] = g(y, x);
449                         samples[i * 4 + 3] = 0.0f;
450                 }
451         }
452
453         set_uniform_vec4_array(glsl_program_num, prefix, "samples", samples, (R + 1) * (R + 1));
454 }