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