summaryrefslogtreecommitdiff
path: root/compute.cc
blob: 671756b0b877f6be5186f325584f5fd56a921ac7 (plain)
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
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
#include <queue>
#include <cstdio>
#include <limits>
#include <xmmintrin.h>
#include "cv.h"
#include "highgui.h"

#include "compute.h"
#include "path.h"
#include "pyramid.h"

#include "tictoc.h"
#include "stitch.h"
#include "explore.h"

inline
float blockpow_and_sum(Mat & f, Mat & g,
                        float p,
                        int fx0, int gx0, int y0)
{
  __m128 sum = _mm_setzero_ps();
  for (int y = y0; y < y0 + Y_CMP_WINDOW; ++y)
  {
    __m128* fx = (__m128*)((__m128*)(f.data + f.step*y) + fx0);
    const __m128* fend = (const __m128*)(fx + X_CMP_WIDTH);
    __m128* gx = (__m128*)((__m128*)(g.data + g.step*y) + gx0);
    for (; fx < fend; ++fx, ++gx)
      {
        __m128 delta = _mm_sub_ps(*fx, *gx);
        sum = _mm_add_ss(sum, _mm_mul_ps(delta, delta));
      }
  }
  float r[4];
  _mm_store_ps(r, sum);
  return r[0] + r[1] + r[2] + r[3];
}

double edgecost(Mat & f, int i, Mat & g, int j)
{
  int frame_height = f.size().height;
  int blocks_count = frame_height / Y_CMP_WINDOW;
  int block_offset = (frame_height - blocks_count * Y_CMP_WINDOW) / 2;
  double weights[2];
#ifdef BLOCKSUM_PARALLEL
#pragma omp parallel
  {
    int tid = omp_get_thread_num();
    if (tid == 0 || tid == 1)
    {
#else
  for (int tid = 0; tid <= 1; ++tid)
  {
#endif
      double weight = 0;
      int fx = (tid == 0) ? i + 1 : i - X_CMP_WIDTH + 1;
      int gx = (tid == 0) ? j : j - X_CMP_WIDTH;
      for (int block = 0; block < blocks_count; ++block)
      {
        int y = block * Y_CMP_WINDOW + block_offset;
        double bsum = blockpow_and_sum(f, g, CMP_NORM,
                                       fx, gx, y);
        weight = max(weight, bsum);
      }
      weights[tid] = weight;
#ifdef BLOCKSUM_PARALLEL
    }
#endif
  }
  return min(weights[0], weights[1]);
}

class pqueue_comparison
{
public:
  /* Returns if step b is better than step a */
  bool operator() (ppdii a, ppdii b)
  {
    #define length(n) n.first.first
    #define hops(n) n.first.second
    #define nid(n) n.second
    return length(b) < length(a)
        || (length(b) == length(a) && hops(b) > hops(a))
        || (length(b) == length(a) && hops(b) == hops(a) && nid(b) < nid(a));
    #undef length
    #undef hops
    #undef nid
  }
};

Path constrained_dijkstra(vector<Mat> & frames, vector<vector<bool> > mask,
                          double *length, int direction)
{
  double infinity = std::numeric_limits<double>::infinity ();
  int frames_count = frames.size();
  int cur_width = frames[0].size().width;
  int cur_height = frames[0].size().height;
  int nodes_count = (frames_count * cur_width);
  vector<double> dists (nodes_count, infinity);
  vector<int> hops (nodes_count, 0);
  vector<int> prev (nodes_count, -1);
  vector<bool> visited (nodes_count, false);
  priority_queue <ppdii, vector<ppdii>, pqueue_comparison > Q;
  int init_delta = (direction == 1) ? 0 : (frames_count - 1) * cur_width;
  for (int strip = 0; strip < cur_width; ++strip)
  {
    Q.push(ppdii (pdi(0, 0), init_delta + strip));
    dists[init_delta + strip] = 0;
  }
  int processed = 0;
  while (!Q.empty ())
  {
    double d = Q.top ().first.first;
    int h = Q.top ().first.second;
    int v = Q.top ().second; 
    Q.pop (); 
    if (visited[v])
      continue;
    visited[v] = true;
    int frame = v / cur_width;
    int strip = (v - frame * cur_width);
    if (direction == 1 && frame == frames_count - 1 && strip == cur_width - 1)
    {
      fprintf(stderr, "Reached final node (frame %d, strip %d)\n", frame, strip);
      break;
    }
    if (direction == -1 && frame == 0 && strip == cur_width - 1)
    {
      fprintf(stderr, "Reached final node (frame %d, strip %d)\n", frame, strip);
      break;
    }
    int frame_delta_factor = 1;
    if (strip < X_CMP_WIDTH || strip >= cur_width - X_CMP_WIDTH)
    {
      frame_delta_factor = 0;
    }
    #pragma omp parallel for
    for (int delta_frame_0 = 0;
         delta_frame_0 <= T_DELTA_WIDTH * frame_delta_factor; ++delta_frame_0)
    {
      int delta_frame = delta_frame_0 * direction;
      if (frame + delta_frame >= frames_count || frame + delta_frame < 0)
        continue;
      for (int delta_strip = -X_DELTA_WIDTH;
           delta_strip <= X_DELTA_WIDTH; ++delta_strip)
      {
        if (strip + delta_strip < 0 || strip + delta_strip >= cur_width)
          continue;
        if (!mask[frame + delta_frame][strip + delta_strip])
          continue;
        double cost = infinity;
        int v2 = (frame + delta_frame) * cur_width + (strip + delta_strip);
        if (delta_frame != 0)
        {
          if (strip + delta_strip < X_CMP_WIDTH
           || strip + delta_strip >= cur_width - X_CMP_WIDTH)
            continue;
          cost = edgecost(frames[frame], strip,
                          frames[frame + delta_frame], strip + delta_strip);
        }
        else if (delta_frame == 0 && delta_strip == 1)
        {
          cost = 0;
        }
        else
        {
          continue;
        }
        if (cost < infinity)
        {
          double d2 = d + pow(cost, WEIGHT_NORM);
          int hops2 = h + 1;
          if (dists[v2] > d2 || (dists[v2] == d2 && hops[v2] < hops2))
          {
            dists[v2] = d2;
            prev[v2] = v;
            hops[v2] = hops2;
            #pragma omp critical
            Q.push(ppdii(pdi(d2, hops2), v2));
          }
        }
      }
    }
    processed++;
    if (processed % (2<<12) == 0)
    {
      fprintf(stdout, "Processed %d nodes (%.3lfs)\n", processed, toc());
    }
  }
  double best_length = infinity;
  int best_end = -1;
  int final_delta = (direction == 1) ? (frames_count - 1) * cur_width : 0;
  /* Search from right to left to get as much strips as possible */
  for (int strip = cur_width - 1; strip >= 0; --strip)
  {
    double v = final_delta + strip;
    if (dists[v] < best_length)
    {
      best_length = dists[v];
      best_end = v;
    }
  }
  *length = best_length;
  if (best_end == -1)
    return Path();
  else
  {
    Path path;
    int v = best_end;
    double prev_cost = best_length;
    fprintf(stdout, "Path length %.3le\n", best_length);
    while (v != -1)
    {
      int frame = v / cur_width;
      int strip = (v - frame * cur_width);
      path.push_front(FrameStrip(frame, strip));
      fprintf(stdout, "Edge to (%d, %d) cost %.3le\n", frame, strip,
                                                       prev_cost - dists[v]);
      prev_cost = dists[v];
      v = prev[v];
    }
    return path;
  }
}

vector<vector<bool> > constant_mask(int frames_count, int strips_count, bool value)
{
  vector<vector<bool> > mask;
  for (int frame = 0; frame < frames_count; ++frame)
  {
    vector<bool> frame_mask(strips_count, true);
    mask.push_back(frame_mask);
  }
  return mask;
}

Path compute_at_level(vector<Mat> & frames,
                      bool first_scale,
                      Path parent_path,
                      int direction,
                      double *length)
{
  vector<vector<bool> > mask;
  Path path;
  int scale_frames = frames.size();
  if (scale_frames == 0)
    return path;
  int scale_width = frames[0].size().width;
  if (first_scale)
  {
    /* Trick : build all-in mask for first scale level */
    mask.clear();
    mask = constant_mask(scale_frames, scale_width, true);
  }
  else
  {
    mask.clear();
    mask = constant_mask(scale_frames, scale_width, false);
    int path_k = 0;
    for (Path::iterator it = parent_path.begin();
         it != parent_path.end(); ++it)
    {
      int frame = it->first, strip = it->second;
      frame *= 2;
      strip *= 2;
      for (int delta_frame = -T_SCALE_WIDTH;
            delta_frame <= T_SCALE_WIDTH; ++delta_frame)
      {
        if (frame + delta_frame >= scale_frames || frame + delta_frame < 0)
          continue;
        for (int delta_strip = -X_SCALE_WIDTH;
             delta_strip <= X_SCALE_WIDTH; ++delta_strip)
        {
          if (strip + delta_strip >= scale_width || strip + delta_strip < 0)
            continue;
          mask[frame + delta_frame][strip + delta_strip] = true;
        }
      }
    }
  }
  fprintf(stderr, "Finding shortest path...\n");
  tic();
  path = constrained_dijkstra(frames, mask, length, direction);
  fprintf(stderr, "Took %.3lfs\n", toc());
  return path;
}

Mat compute_mosaic(vector<Mat> & frames,
                   int direction,
                   vector<vector<Mat> > & downscaled,
                   vector<Mat> & mosaics,
                   vector<Path> & paths)
{
  double length;
  Path path;

  /* Compute pyramid */
  build_pyramid(frames, PYRAMID_LEVELS, downscaled);
  mosaics.resize(PYRAMID_LEVELS);
  paths.resize(PYRAMID_LEVELS);

  for (int i = PYRAMID_LEVELS - 1; i >= 0; --i)
  {
    path = compute_at_level(downscaled[i],
                            i == PYRAMID_LEVELS - 1,
                            path,
                            direction,
                            &length);
    explore_path(downscaled[i], path);
    Mat mosaic = stitch_path(downscaled[i], path);
    char buf[200];
    sprintf(buf, "temp-%d.png", i);
    imwrite(buf, mosaic * 255);
    paths[i] = path;
    mosaics[i] = mosaic;
    fprintf(stdout, "Length at scale level %d = %.3le\n", i, length);
  }

  Mat mosaic = stitch_path(frames, path);
  return mosaic;
}