main2.cpp 16.3 KB
Newer Older
Edwin Carlinet's avatar
Edwin Carlinet committed
1
#include <mln/core/image/image2d.hpp>
2
#include <mln/core/image/morphers/casted_image.hpp>
Edwin Carlinet's avatar
Edwin Carlinet committed
3
4
#include <mln/core/colors.hpp>
#include <mln/core/trace.hpp>
5
#include <mln/core/algorithm/transform.hpp>
Edwin Carlinet's avatar
Edwin Carlinet committed
6
#include <mln/io/imsave.hpp>
7
8
9
10
11
12
#include <mln/colors/lab.hpp>
#include <mln/morpho/tos/ctos.hpp>
#include <mln/morpho/component_tree/compute_depth.hpp>
#include <mln/morpho/component_tree/reconstruction.hpp>
#include <mln/morpho/structural/opening.hpp>
#include <mln/morpho/structural/closing.hpp>
Edwin Carlinet's avatar
Edwin Carlinet committed
13
14
15

#include <tbb/pipeline.h>
#include <boost/format.hpp>
16
#include <mutex>
Edwin Carlinet's avatar
Edwin Carlinet committed
17
#include <apps/g2/compute_ctos.hpp>
18
#include <apps/tos/addborder.hpp>
19
#include <mln/io/imsave.hpp>
Edwin Carlinet's avatar
Edwin Carlinet committed
20
21
22
23
24
25
26
27
28
29
30
#include "video_tools.hh"
#include "smartdoc.hpp"
#include "export.hpp"


/****************************************************/
/**     CONFIG                                    ***/
/****************************************************/

const bool ENABLE_CACHING = true;
bool VIDEO_OUTPUT = false; // non-const modifiable by the cmdline
31

32
33
enum e_method { ON_LAB_L = 0, ON_LAB_B = 1, BACKUP_METHOD = 2, AUTO = 3, MTOS_METHOD = 4};
e_method APP_METHOD = AUTO;
Edwin Carlinet's avatar
Edwin Carlinet committed
34
35
36
37
38
39


/****************************************************/
/**     PROCESSORS                                ***/
/****************************************************/

40
41
std::mutex my_mutex;

Edwin Carlinet's avatar
Edwin Carlinet committed
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
/*
We have a pipeline with 3 filters:

Input filter -> Middle Filter -> Output Filter

The Input and Output filters are sequential and processes one item at a time
The Middle filter can process several items in parallel.

1. The input filter.
   Load a frame from a video and outputs a Milena image2d.

2. The Middle filter.
   Does the job. Gets an image2d and outputs an image2d.

3. The output filter.
   Write the frame. Gets an image2d and does nothing.
*/


///
class input_filter
{
public:

  input_filter(const char* filename)
  {
    m_videoStream = -1;
    m_nbframe = 0;

    av_init_packet(&packet_dec);

    pFormatCtx_Dec = init_format_context_decode(mln::trace::verbose,
                                                filename,
                                                m_videoStream,
                                                &pFrame_inYUV,
                                                &pFrame_inRGB,
                                                &Ctx_Dec);

    convert_ctx_yuv2rgb = sws_getContext(Ctx_Dec->width,
                                         Ctx_Dec->height,
                                         Ctx_Dec->pix_fmt,
                                         Ctx_Dec->width,
                                         Ctx_Dec->height,
                                         PIX_FMT_RGB24,
                                         SWS_BILINEAR, 0, 0, 0);

  }

  // No copy constructor !!
  input_filter(const input_filter& other) = delete;

  ~input_filter()
  {
    close_free_decode(&pFormatCtx_Dec, &Ctx_Dec, &pFrame_inYUV, &pFrame_inRGB);
  }

  mln::image2d<mln::rgb8>*
  operator () (tbb::flow_control& fc) const
  {
    /***********************************************************************/
    /**           De/en-coding loop with ffmpeg                           **/
    /***********************************************************************/
    int frameFinished = 0;
    while (av_read_frame(pFormatCtx_Dec, &packet_dec) >= 0)
      {
        if (packet_dec.stream_index == m_videoStream)
          {
            avcodec_decode_video2(Ctx_Dec, pFrame_inYUV, &frameFinished, &packet_dec);
            if (frameFinished)
              {
                mln::image2d<mln::rgb8>* out = new mln::image2d<mln::rgb8> ();
113
                *out = this->getCurrentFrame();
Edwin Carlinet's avatar
Edwin Carlinet committed
114
115
116
117
118
                ++m_nbframe;
                return out;
              }
          }
      }
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138

    packet_dec.data = NULL;
    packet_dec.size = 0;
    packet_dec.stream_index = m_videoStream;

    while (avcodec_decode_video2(Ctx_Dec, pFrame_inYUV,
                                 &frameFinished, &packet_dec) >= 0)
      {
        if (frameFinished)
          {
            mln::image2d<mln::rgb8>* out = new mln::image2d<mln::rgb8> ();
            *out = this->getCurrentFrame();
            ++m_nbframe;
            return out;
          }
        else
          {
            break;
          }
      }
Edwin Carlinet's avatar
Edwin Carlinet committed
139
140
141
142
    fc.stop(); // NO MORE FRAME
    return NULL;
  }

143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
  mln::image2d<mln::rgb8>
  getCurrentFrame() const
  {
    /* convert from YUV to RGB24 to decode video */
    sws_scale(convert_ctx_yuv2rgb,
              (const uint8_t * const*) pFrame_inYUV->data,
              pFrame_inYUV->linesize,
              0,
              Ctx_Dec->height,
              pFrame_inRGB->data,
              pFrame_inRGB->linesize);

    /* copy to mln image2d */

    size_t strides[2] = {(size_t)pFrame_inRGB->linesize[0], sizeof(mln::rgb8)};
    mln::box2d domain{{0,0},{(short)pFrame_inRGB->height,
          (short)pFrame_inRGB->width}};

    return mln::image2d<mln::rgb8>::from_buffer(pFrame_inRGB->data[0],
                                                domain, strides, true);
  }


Edwin Carlinet's avatar
Edwin Carlinet committed
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
  AVCodecContext*
  get_context()
  {
    return Ctx_Dec;
  }

  AVFormatContext*
  get_format_context()
  {
    return pFormatCtx_Dec;
  }

private:
  mutable AVPacket packet_dec;
  AVFrame *pFrame_inYUV, *pFrame_inRGB;
  AVCodecContext *Ctx_Dec;
  AVFormatContext *pFormatCtx_Dec;
  struct SwsContext *convert_ctx_yuv2rgb;


  int           m_videoStream;
  mutable int           m_nbframe;
};


191

Edwin Carlinet's avatar
Edwin Carlinet committed
192
193
struct middle_filter_result
{
194
  mln::image2d<mln::rgb8>               input;
195
  mln::image2d<mln::uint16>             depth;
196
  std::array<process_result_t, NQUAD>   res;
Edwin Carlinet's avatar
Edwin Carlinet committed
197
198
199
200
201
202
203
204
205
206
};


class middle_filter
{
public:

  middle_filter_result*
  operator() (mln::image2d<mln::rgb8>* input) const
  {
207
208
    using namespace mln;

Edwin Carlinet's avatar
Edwin Carlinet committed
209
210
211
    // Process
    middle_filter_result* mdr = new middle_filter_result;

212
213
214
    mdr->input = std::move(*input);
    delete input;

215
216
217
218
219
220
221
    // if (VIDEO_OUTPUT) {
    //   mln::box2d d;
    //   d.pmin = {0,0};
    //   d.pmax = (input->domain().pmax + 2) * 2 - 1;
    //   mdr->ima.resize(d);
    //   ptr_img_out = &(mdr->ima);
    // }
Edwin Carlinet's avatar
Edwin Carlinet committed
222

223
224
225
    typedef morpho::component_tree< unsigned, image2d<unsigned> > tree_t;
    tree_t tree;

226
    if (APP_METHOD == MTOS_METHOD)
227
      {
228
        tree = compute_ctos(mdr->input, &(mdr->depth));
229
230
231
232
      }
    else
      {
        //std::array<process_result_t, NQUAD>       resL, resB;
233
        //image2d< lab<float> > f = transform(mdr->input, [](rgb8 x) { return rgb2lab(x); });
234
235
236
237
238
239
240
241
242
243
244

        image2d<uint8> f;
        property_map<tree_t, unsigned> vmap;

        my_mutex.lock();
        if (APP_METHOD == AUTO)
          {
            std::array<process_result_t, NQUAD> resL, resB;

            // 1st try on LAB_B
            {
245
              f = transform(mdr->input, [](rgb8 x) -> uint8 {
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
                  lab<float> v = rgb2lab(x);
                  return (v[2] + 110) * 256 / 220;
                });

              f = addborder(f);
              tree = morpho::cToS(f, c4);
              resize(mdr->depth, tree._get_data()->m_pmap);
              vmap = morpho::compute_depth(tree);
              morpho::reconstruction(tree, vmap, mdr->depth);
              resB = process(tree, mdr->depth);
            }

            if (resB[0].energy > 0.78)
              {
                std::cout << "==> Using the B component." << std::endl;
                APP_METHOD = ON_LAB_B;
                mdr->res = resB;
                my_mutex.unlock();
                return mdr;
              }

            // 2nd try on LAB_L
            {
269
              f = transform(mdr->input, [](rgb8 x) -> uint8 {
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
                  lab<float> v = rgb2lab(x);
                  return v[0] * 256 / 100;
              });
              f = addborder(f);
              tree = morpho::cToS(f, c4);
              vmap = morpho::compute_depth(tree);
              morpho::reconstruction(tree, vmap, mdr->depth);
              resL = process(tree, mdr->depth);
            }
            if (resB[0].energy > 0.72 and resL[0].energy < 0.8)
              {
                std::cout << "==> Using the B component." << std::endl;
                APP_METHOD = ON_LAB_B;
                mdr->res = resB;
                my_mutex.unlock();
                return mdr;
              }
            else if (resL[0].energy > 0.8)
              {
                std::cout << "==> Using the L component." << std::endl;
                APP_METHOD = ON_LAB_L;
                mdr->res = resL;
                my_mutex.unlock();
                return mdr;
              }
            // 3. Backup
            {
297
              f = transform(mdr->input, [](rgb8 x) -> uint8 {
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
                  lab<float> v = rgb2lab(x);
                return (v[2] + 110) * 256 / 220;
                });

              rect2d r = make_rectangle2d(101, 1);
              f = morpho::structural::opening(f, r);
              f = morpho::structural::closing(f, r);
              f = addborder(f);
              tree = morpho::cToS(f, c4);
              vmap = morpho::compute_depth(tree);
              morpho::reconstruction(tree, vmap, mdr->depth);
              mdr->res = process(tree, mdr->depth);
            }
            {
              std::cout << "==> Using the BACKUP method." << std::endl;
              APP_METHOD = BACKUP_METHOD;
              my_mutex.unlock();
              return mdr;
            }
          }

        // We now which method to run OK.
        my_mutex.unlock();
        if (APP_METHOD == ON_LAB_B)
          {
323
            f = transform(mdr->input, [](rgb8 x) -> uint8 {
324
325
326
327
328
329
                lab<float> v = rgb2lab(x);
                return (v[2] + 110) * 256 / 220;
              });
          }
        else if (APP_METHOD == ON_LAB_L)
          {
330
            f = transform(mdr->input, [](rgb8 x) -> uint8 {
331
332
333
334
335
336
                lab<float> v = rgb2lab(x);
                return v[0] * 256 / 100;
              });
          }
        else if (APP_METHOD == BACKUP_METHOD)
          {
337
            f = transform(mdr->input, [](rgb8 x) -> uint8 {
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
                lab<float> v = rgb2lab(x);
                return (v[2] + 110) * 256 / 220;
              });

            rect2d r = make_rectangle2d(101, 1);
            f = morpho::structural::opening(f, r);
            f = morpho::structural::closing(f, r);
          }

        f = addborder(f);
        tree = morpho::cToS(f, c4);
        resize(mdr->depth, tree._get_data()->m_pmap);
        vmap = morpho::compute_depth(tree);
        morpho::reconstruction(tree, vmap, mdr->depth);
      }
353
    mdr->res = process(tree, mdr->depth);
Edwin Carlinet's avatar
Edwin Carlinet committed
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375

    return mdr;
  }

};


class output_filter
{
public:
  output_filter(std::vector<SmartDoc_t>* results,
                const char* filename,
                AVCodecContext* Ctx_Dec,
                AVFormatContext* pFormatCtx_Dec)
  {
    if (VIDEO_OUTPUT) {
      pFormatCtx_Enc = init_format_context_encode(mln::trace::verbose,
                                                  filename,
                                                  Ctx_Dec, pFormatCtx_Dec,
                                                  &pFrame_outYUV, NULL, &Ctx_Enc);

      // Because the output image is in K0 + border
376
377
378
379
380
      // short w = (Ctx_Dec->width + 2) * 2 - 1;
      // short h = (Ctx_Dec->height + 2) * 2 - 1;
      short w = Ctx_Dec->width;
      short h = Ctx_Dec->height;

Edwin Carlinet's avatar
Edwin Carlinet committed
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396

      pFrame_outRGB = avcodec_alloc_frame();
      av_image_alloc(pFrame_outRGB->data,
                     pFrame_outRGB->linesize,
                     w, h, PIX_FMT_RGB24, 32);
      pFrame_outRGB->width = w;
      pFrame_outRGB->height = h;
      pFrame_outRGB->format = PIX_FMT_RGB24;

      convert_ctx_rgb2out = sws_getContext(w,
                                           h,
                                           PIX_FMT_RGB24,
                                           Ctx_Enc->width,
                                           Ctx_Enc->height,
                                           Ctx_Enc->pix_fmt,
                                           SWS_BILINEAR, 0, 0, 0);
397

398
      m_output.resize(mln::box2d{{0,0}, {h,w}}, 5);
Edwin Carlinet's avatar
Edwin Carlinet committed
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
    }
    m_filename = filename;
    m_nbframe = 0;
    m_skipped = 0;
    m_results = results;
  }

  output_filter(const output_filter& other) = delete;

  ~output_filter()
  {
    if (VIDEO_OUTPUT) {
      encode_skipped_frames(m_skipped, m_nbframe, &pFormatCtx_Enc, m_filename,
                            &pFrame_outYUV, &Ctx_Enc, packet_enc);
      close_free_encode(&pFormatCtx_Enc, &Ctx_Enc, &pFrame_outYUV, &pFrame_outRGB);
    }
  }

417
418
419
420
  std::array<mln::point2d, 4>
  getquad(middle_filter_result* mdr) const
  {
    int selection = 0;
421
    bool dismissed[NQUAD] = {0,};
422
423
424
    if (not m_results->empty() and m_results->back().good)
      {
        auto lastr = m_results->back().quad;
425
        for (int i = 0; i < NQUAD; ++i)
426
427
428
429
430
431
432
          {
            bool dismiss = false;
            for (int j = 0; j < 4; ++j)
              if (l2dist(mdr->res[i].points[j], lastr[j]) > MAX_DISTANCE_INTER_FRAME) {
                dismiss = true;
                break;
              }
433
            dismissed[i] = dismiss;
434
435
436
437
438
439
440
441
442
            if (not dismiss) {
              selection = i;
              break;
            }
          }
      }


    std::cout << "### FRAME: " << m_nbframe << std::endl;
443
    for (int i = 0; i < NQUAD; ++i) {
444
445
446
447
448
      std::cout << "\t" << (selection == i ? '*' : ' ')
                << "Quad " << i << ": " << mdr->res[i].energy << " "
                << mdr->res[i].points[0]
                << mdr->res[i].points[1]
                << mdr->res[i].points[3]
449
450
451
452
                << mdr->res[i].points[2];
      if (dismissed[i])
        std::cout << " (dissmissed)";
      std::cout << std::endl;
453
454
455
    }
    return mdr->res[selection].points;
  }
Edwin Carlinet's avatar
Edwin Carlinet committed
456
457
458
459

  void
  operator() (middle_filter_result* mdr) const
  {
460
461
462
    std::array<mln::point2d, 4> quad = this->getquad(mdr);
    //mln::io::imsave(mdr->depth, "depth.tiff");

Edwin Carlinet's avatar
Edwin Carlinet committed
463
464
465
466
    if (VIDEO_OUTPUT)
      {
        // Copy the image to the output buffer.
        {
467
468
469
          //draw_quad_superimpose(quad, mdr->depth, m_output);
          m_output = mdr->input;
          draw_quad_superimpose(quad, m_output);
470
471

          char* ptrin = (char*) &(m_output.at(0,0));
Edwin Carlinet's avatar
Edwin Carlinet committed
472
          char* ptrout = (char*) pFrame_outRGB->data[0];
473
474
          size_t stride = m_output.strides()[0];
          for (unsigned i = 0; i < m_output.nrows(); ++i)
Edwin Carlinet's avatar
Edwin Carlinet committed
475
            {
476
              std::copy(ptrin, ptrin + (m_output.ncols() * sizeof(mln::rgb8)), ptrout);
Edwin Carlinet's avatar
Edwin Carlinet committed
477
478
479
480
481
482
483
              ptrin += stride;
              ptrout += pFrame_outRGB->linesize[0];
            }
        }
        const_cast<output_filter*>(this)->encode();
      }
    // Insert the smartdoc result in the vector.
484
    m_results->push_back({true, quad});
Edwin Carlinet's avatar
Edwin Carlinet committed
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
    delete mdr;
  }

private:
  void encode()
  {
    encode_video(m_skipped, &pFormatCtx_Enc, m_filename,
                 &pFrame_outRGB, &pFrame_outYUV, m_nbframe,
                 &Ctx_Enc, packet_enc, &convert_ctx_rgb2out);
    m_nbframe++;
  }


private:
  // For encoding
  AVPacket packet_enc;
  AVFrame *pFrame_outYUV, *pFrame_outRGB;
  AVCodecContext *Ctx_Enc;
  AVFormatContext *pFormatCtx_Enc;
  struct SwsContext *convert_ctx_rgb2out;

  // For other stuff
507
  mutable mln::image2d<mln::rgb8>  m_output;
Edwin Carlinet's avatar
Edwin Carlinet committed
508
509
510
511
512
513
514
515
516
517
518
519
520
521
  const char*              m_filename;
  mutable int              m_nbframe;
  mutable int              m_skipped;
  std::vector<SmartDoc_t>* m_results;
};






int main(int argc, char** argv)
{
  if (argc < 3) {
522
    std::cerr << "Usage: " << argv[0] << " input.mpg output.xml [method = 0] [number of threads=10] [output.mpg]\n"
523
      "method: (0) LAB_L, (1): LAB_B, (2): BACKUP, (3) AUTO, (4) MTOS\n";
Edwin Carlinet's avatar
Edwin Carlinet committed
524
525
526
527
528
    std::exit(1);
  }

  const char* input_path = argv[1];
  const char* output_path = argv[2];
529
530
531
532
533
534
535
  if (argc > 3) {
    APP_METHOD = (e_method) std::atoi(argv[3]);
  }

  int nthread = (argc > 4) ? std::atoi(argv[4]) : 10;
  const char* output_video_path = (argc > 5) ? argv[5] : NULL;
  VIDEO_OUTPUT = argc > 5;
Edwin Carlinet's avatar
Edwin Carlinet committed
536
537
538
539
540
541
542

  using namespace mln;

  // Initialization of the library
  av_register_all();
  avcodec_register_all();

543
  std::cout << input_path << std::endl;
Edwin Carlinet's avatar
Edwin Carlinet committed
544
545
546
547
548
549
550
551
552
553
554
555
556
  std::vector<SmartDoc_t> results;

  input_filter func1(input_path);
  output_filter func3(&results, output_video_path, func1.get_context(), func1.get_format_context());

  tbb::filter_t<void, image2d<rgb8>* > f1(tbb::filter::serial_in_order, std::ref(func1));

  tbb::filter_t<image2d<rgb8>*, middle_filter_result*> f2(tbb::filter::parallel, middle_filter ());

  tbb::filter_t<middle_filter_result*,void> f3(tbb::filter::serial_in_order, std::ref(func3));

  tbb::filter_t<void,void> f = f1 & f2 & f3;

557
  tbb::parallel_pipeline(nthread,f);
Edwin Carlinet's avatar
Edwin Carlinet committed
558
559
560

  export_xml(output_path, input_path, &results[0], results.size());
}