File: BackgroundSubtractor.cc

package info (click to toggle)
node-opencv 6.0.0+git20180416.cfc96ba0-3
  • links: PTS, VCS
  • area: main
  • in suites: buster, sid
  • size: 24,632 kB
  • sloc: xml: 476,707; cpp: 5,950; makefile: 114; sh: 59; ansic: 20
file content (524 lines) | stat: -rw-r--r-- 14,323 bytes parent folder | download
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
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
#include "BackgroundSubtractor.h"
#include "Matrix.h"
#include <iostream>
#include <nan.h>

#ifdef HAVE_BACKGROUNDSUBTRACTOR

#ifdef HAVE_OPENCV_BGSEGM

#ifdef __GNUC__
#warning Building with HAVE_OPENCV_BGSEGM
#else
// vs style message pragma
#pragma message ( "Building with HAVE_OPENCV_BGSEGM" )
#endif
cv::bgsegm::BackgroundSubtractorMOG* getMOG(BackgroundSubtractorWrap *wrap) {
  return dynamic_cast<cv::bgsegm::BackgroundSubtractorMOG *>(wrap->subtractor.get());
}
#else
#ifdef __GNUC__
#warning Building without HAVE_OPENCV_BGSEGM
#else
// vs style message pragma
#pragma message ( "Building without HAVE_OPENCV_BGSEGM - only MOG2 will be available" )
#endif
// without bgsem, it can't be MOG anyway
void* getMOG(BackgroundSubtractorWrap *wrap) {
  return NULL;
}
#endif


class BGAutoMutex {
public:
    BGAutoMutex(cv::Mutex &m){
        mutex = &m;
        mutex->lock();
    };
    
    ~BGAutoMutex(){
        mutex->unlock();
        mutex = NULL;
    };
private:
    cv::Mutex *mutex;
};

Nan::Persistent<FunctionTemplate> BackgroundSubtractorWrap::constructor;

void BackgroundSubtractorWrap::Init(Local<Object> target) {
  Nan::HandleScope scope;

  // Constructor
  Local<FunctionTemplate> ctor = Nan::New<FunctionTemplate>(BackgroundSubtractorWrap::New);
  constructor.Reset(ctor);
  ctor->InstanceTemplate()->SetInternalFieldCount(1);
  ctor->SetClassName(Nan::New("BackgroundSubtractor").ToLocalChecked());

  Nan::SetMethod(ctor, "createMOG", CreateMOG);
  Nan::SetMethod(ctor, "createMOG2", CreateMOG2);
  Nan::SetMethod(ctor, "createGMG", CreateGMG);
  Nan::SetPrototypeMethod(ctor, "applyMOG", ApplyMOG);
  Nan::SetPrototypeMethod(ctor, "apply", Apply);
  Nan::SetPrototypeMethod(ctor, "history", History);
  Nan::SetPrototypeMethod(ctor, "nmixtures", Mixtures);
  Nan::SetPrototypeMethod(ctor, "noiseSigma", NoiseSigma);
  Nan::SetPrototypeMethod(ctor, "backgroundRatio", BackgroundRatio);

  target->Set(Nan::New("BackgroundSubtractor").ToLocalChecked(), ctor->GetFunction());
}

NAN_METHOD(BackgroundSubtractorWrap::New) {
  Nan::HandleScope scope;

  if (info.This()->InternalFieldCount() == 0) {
    JSTHROW_TYPE("Cannot Instantiate without new")
  }

  // Create MOG by default
#if CV_MAJOR_VERSION >= 3
#ifdef HAVE_OPENCV_BGSEGM
  cv::Ptr<cv::BackgroundSubtractor> bg = cv::bgsegm::createBackgroundSubtractorMOG();
  if (NULL == bg){
   JSTHROW_TYPE("OpenCV NULL from cv::bgsegm::createBackgroundSubtractorMOG()");
  }
  BackgroundSubtractorWrap *pt = new BackgroundSubtractorWrap(bg);

  pt->Wrap(info.This());

  info.GetReturnValue().Set(info.This());
#else
  // if no bgsem, then default to MOG2
  cv::Ptr<cv::BackgroundSubtractor> bg = cv::createBackgroundSubtractorMOG2();
  if (NULL == bg){
   JSTHROW_TYPE("OpenCV NULL from cv::createBackgroundSubtractorMOG2()");
  }
  BackgroundSubtractorWrap *pt = new BackgroundSubtractorWrap(bg);

  pt->Wrap(info.This());

  info.GetReturnValue().Set(info.This());
#endif
  
#else
  cv::Ptr<cv::BackgroundSubtractor> bg = new cv::BackgroundSubtractorMOG();
  if (NULL == bg){
   JSTHROW_TYPE("OpenCV NULL from new cv::BackgroundSubtractorMOG()");
  }
  BackgroundSubtractorWrap *pt = new BackgroundSubtractorWrap(bg);

  pt->Wrap(info.This());

  info.GetReturnValue().Set(info.This());
#endif
}

NAN_METHOD(BackgroundSubtractorWrap::CreateMOG) {
  Nan::HandleScope scope;

  // int history = 200;
  // int nmixtures = 5;
  // double backgroundRatio = 0.7;
  // double noiseSigma = 0;
  //
  // if(info.Length() > 1){
  //   INT_FROM_ARGS(history, 0)
  //   INT_FROM_ARGS(nmixtures, 1)
  //   DOUBLE_FROM_ARGS(backgroundRatio, 2)
  //   DOUBLE_FROM_ARGS(noiseSigma, 3)
  // }

  Local<Object> n = Nan::NewInstance(Nan::GetFunction(Nan::New(BackgroundSubtractorWrap::constructor)).ToLocalChecked()).ToLocalChecked();

#if CV_MAJOR_VERSION >= 3
#ifdef HAVE_OPENCV_BGSEGM
  cv::Ptr<cv::BackgroundSubtractor> bg = cv::bgsegm::createBackgroundSubtractorMOG();
  if (NULL == bg){
   JSTHROW_TYPE("OpenCV NULL from cv::bgsegm::createBackgroundSubtractorMOG()");
  }
  BackgroundSubtractorWrap *pt = new BackgroundSubtractorWrap(bg);

  pt->Wrap(n);
  info.GetReturnValue().Set( n );
#else
  JSTHROW_TYPE("OpenCV built without bgsem (opencv_contrib)")
#endif
#else
  cv::Ptr<cv::BackgroundSubtractor> bg = new cv::BackgroundSubtractorMOG();
  if (NULL == bg){
   JSTHROW_TYPE("OpenCV NULL from new cv::BackgroundSubtractorMOG()");
  }
  BackgroundSubtractorWrap *pt = new BackgroundSubtractorWrap(bg);

  pt->Wrap(n);
  info.GetReturnValue().Set( n );
#endif
}

NAN_METHOD(BackgroundSubtractorWrap::CreateMOG2) {
  Nan::HandleScope scope;

  // int history = 200;
  // int nmixtures = 5;
  // double backgroundRatio = 0.7;
  // double noiseSigma = 0;
  //
  // if(info.Length() > 1){
  //   INT_FROM_ARGS(history, 0)
  //   INT_FROM_ARGS(nmixtures, 1)
  //   DOUBLE_FROM_ARGS(backgroundRatio, 2)
  //   DOUBLE_FROM_ARGS(noiseSigma, 3)
  // }

  Local<Object> n = Nan::NewInstance(Nan::GetFunction(Nan::New(BackgroundSubtractorWrap::constructor)).ToLocalChecked()).ToLocalChecked();

#if CV_MAJOR_VERSION >= 3
  cv::Ptr<cv::BackgroundSubtractor> bg = cv::createBackgroundSubtractorMOG2();
  if (NULL == bg){
   JSTHROW_TYPE("OpenCV NULL from cv::createBackgroundSubtractorMOG2()");
  }
#else
  cv::Ptr<cv::BackgroundSubtractor> bg = new cv::BackgroundSubtractorMOG();
  if (NULL == bg){
   JSTHROW_TYPE("OpenCV NULL from new cv::BackgroundSubtractorMOG()");
  }
#endif
  BackgroundSubtractorWrap *pt = new BackgroundSubtractorWrap(bg);

  pt->Wrap(n);
  info.GetReturnValue().Set( n );
}

NAN_METHOD(BackgroundSubtractorWrap::CreateGMG) {
  Nan::HandleScope scope;

  // int history = 200;
  // int nmixtures = 5;
  // double backgroundRatio = 0.7;
  // double noiseSigma = 0;
  //
  // if(info.Length() > 1){
  //   INT_FROM_ARGS(history, 0)
  //   INT_FROM_ARGS(nmixtures, 1)
  //   DOUBLE_FROM_ARGS(backgroundRatio, 2)
  //   DOUBLE_FROM_ARGS(noiseSigma, 3)
  // }

  Local<Object> n = Nan::NewInstance(Nan::GetFunction(Nan::New(BackgroundSubtractorWrap::constructor)).ToLocalChecked()).ToLocalChecked();

#if CV_MAJOR_VERSION >= 3
#ifdef HAVE_OPENCV_BGSEGM
  cv::Ptr<cv::BackgroundSubtractor> bg = cv::bgsegm::createBackgroundSubtractorGMG();
  if (NULL == bg){
   JSTHROW_TYPE("OpenCV NULL from cv::bgsegm::createBackgroundSubtractorGMG()");
  }
  BackgroundSubtractorWrap *pt = new BackgroundSubtractorWrap(bg);

  pt->Wrap(n);
  info.GetReturnValue().Set( n );
#else
  JSTHROW_TYPE("OpenCV built without bgsem (opencv_contrib) - use MOG2")
#endif
#else
  cv::Ptr<cv::BackgroundSubtractor> bg = new cv::BackgroundSubtractorMOG();
  if (NULL == bg){
   JSTHROW_TYPE("OpenCV NULL from new cv::BackgroundSubtractorMOG()");
  }
  BackgroundSubtractorWrap *pt = new BackgroundSubtractorWrap(bg);

  pt->Wrap(n);
  info.GetReturnValue().Set( n );
#endif
}


// Fetch foreground mask
NAN_METHOD(BackgroundSubtractorWrap::ApplyMOG) {
  SETUP_FUNCTION(BackgroundSubtractorWrap);
  REQ_FUN_ARG(1, cb);

  Local<Value> argv[2];
  if (info.Length() == 0) {
    argv[0] = Nan::New("Input image missing").ToLocalChecked();
    argv[1] = Nan::Null();
    cb->Call(Nan::GetCurrentContext()->Global(), 2, argv);
    return;
  }

  if (NULL == self->subtractor){
    argv[0] = Nan::New("BackgroundSubtractor not created").ToLocalChecked();
    argv[1] = Nan::Null();
    cb->Call(Nan::GetCurrentContext()->Global(), 2, argv);
    return;
  }

  
  try {
    cv::Mat mat;
    if (Buffer::HasInstance(info[0])) {
      uint8_t *buf = (uint8_t *) Buffer::Data(info[0]->ToObject());
      unsigned len = Buffer::Length(info[0]->ToObject());
      cv::Mat *mbuf = new cv::Mat(len, 1, CV_64FC1, buf);
      mat = cv::imdecode(*mbuf, -1);
      //mbuf->release();
    } else {
      Matrix *_img = Nan::ObjectWrap::Unwrap<Matrix>(info[0]->ToObject());
      mat = (_img->mat).clone();
    }

    if (mat.empty()) {
      return Nan::ThrowTypeError("Error loading file");
    }

    
    cv::Mat _fgMask;
    {
    // wait here if already in apply - auto-release on scope exit
    BGAutoMutex(self->applymutex);
#if CV_MAJOR_VERSION >= 3
    self->subtractor->apply(mat, _fgMask);
#else
    self->subtractor->operator()(mat, _fgMask);
#endif
    }
    
    Local<Object> fgMask = Matrix::CreateWrappedFromMat(_fgMask.clone());
    mat.release();

    argv[0] = Nan::Null();
    argv[1] = fgMask;

    Nan::TryCatch try_catch;
    cb->Call(Nan::GetCurrentContext()->Global(), 2, argv);

    if (try_catch.HasCaught()) {
      Nan::FatalException(try_catch);
    }
    return;
  } catch (cv::Exception& e) {
    const char* err_msg = e.what();
    Nan::ThrowError(err_msg);
    return;
  }
}


class AsyncBackgroundSubtractorWorker: public Nan::AsyncWorker {
public:
  AsyncBackgroundSubtractorWorker( 
        Nan::Callback *callback, 
        BackgroundSubtractorWrap *bg, 
        Matrix *matrix_in):
      Nan::AsyncWorker(callback),
      bg(bg),
      matrix(new Matrix(matrix_in)) {
    
  }

  ~AsyncBackgroundSubtractorWorker() {

  }

  // Executed inside the worker-thread.
  // It is not safe to access V8, or V8 data structures
  // here, so everything we need for input and output
  // should go on `this`.
  void Execute() {
    // wait here if already in apply - auto-release on scope exit
    BGAutoMutex(bg->applymutex);
#if CV_MAJOR_VERSION >= 3
    bg->subtractor->apply(matrix->mat, _fgMask);
#else
    bg->subtractor->operator()(matrix->mat, _fgMask);
#endif
  }

  // Executed when the async work is complete
  // this function will be run inside the main event loop
  // so it is safe to use V8 again
  void HandleOKCallback() {
    Nan::HandleScope scope;

    delete matrix;
    matrix = NULL;

    Local<Object> im_to_return = Matrix::CreateWrappedFromMat(_fgMask.clone());

    Local<Value> argv[] = {
      Nan::Null()
      , im_to_return
    };

    Nan::TryCatch try_catch;
    callback->Call(2, argv);
    if (try_catch.HasCaught()) {
      Nan::FatalException(try_catch);
    }
  }

private:
  BackgroundSubtractorWrap *bg;
  Matrix *matrix;
  cv::Mat _fgMask;
};


// Fetch foreground mask
NAN_METHOD(BackgroundSubtractorWrap::Apply) {
  SETUP_FUNCTION(BackgroundSubtractorWrap);
  int callback_arg = -1;
  int numargs = info.Length();
  
  Local<Function> cb;

  if (info[numargs-1]->IsFunction()){
      callback_arg = numargs-1;
      cb = Local<Function>::Cast(info[callback_arg]);
  }

  
  
  // if async
  if (callback_arg > 0){
    Local<Value> argv[2];

    if (info.Length() == 0) {
      argv[0] = Nan::New("Input image missing").ToLocalChecked();
      argv[1] = Nan::Null();
      cb->Call(Nan::GetCurrentContext()->Global(), 2, argv);
      return;
    }
    if (NULL == self->subtractor){
      argv[0] = Nan::New("BackgroundSubtractor not created").ToLocalChecked();
      argv[1] = Nan::Null();
      cb->Call(Nan::GetCurrentContext()->Global(), 2, argv);
      return;
    }
    
    Nan::Callback *callback = new Nan::Callback(cb.As<Function>());
    Matrix *_img = Nan::ObjectWrap::Unwrap<Matrix>(info[0]->ToObject());      
    Nan::AsyncQueueWorker(new AsyncBackgroundSubtractorWorker( callback, self, _img));
    return;
  } else { //synchronous - return the image

    try {
      Local<Object> fgMask;
      cv::Mat mat;
      if (Buffer::HasInstance(info[0])) {
        uint8_t *buf = (uint8_t *) Buffer::Data(info[0]->ToObject());
        unsigned len = Buffer::Length(info[0]->ToObject());
        cv::Mat *mbuf = new cv::Mat(len, 1, CV_64FC1, buf);
        mat = cv::imdecode(*mbuf, -1);
        //mbuf->release();
      } else {
        Matrix *_img = Nan::ObjectWrap::Unwrap<Matrix>(info[0]->ToObject());
        mat = (_img->mat).clone();
      }

      if (mat.empty()) {
        return Nan::ThrowTypeError("Empty matrix?");
      }

      {
      // wait here if already in apply - auto-release on scope exit
      BGAutoMutex(self->applymutex);
      cv::Mat _fgMask;
  #if CV_MAJOR_VERSION >= 3
      self->subtractor->apply(mat, _fgMask);
  #else
      self->subtractor->operator()(mat, _fgMask);
  #endif
      fgMask = Matrix::CreateWrappedFromMat(_fgMask.clone());
      }
      
      mat.release();

      info.GetReturnValue().Set(fgMask);
      return;
      
    } catch (cv::Exception& e) {
      const char* err_msg = e.what();
      Nan::ThrowError(err_msg);
      return;
    }
      
  }
}


NAN_METHOD(BackgroundSubtractorWrap::History) {
  SETUP_FUNCTION(BackgroundSubtractorWrap);
  auto mog = getMOG(self);
  if (!mog) {
    Nan::ThrowError("Not using a BackgroundSubtractorMOG");
  }
// only support  for V3+ with opencv-contrib
#ifdef HAVE_OPENCV_BGSEGM
  if (info.Length() > 0) {
    mog->setHistory(info[0]->NumberValue());
  }
  info.GetReturnValue().Set(mog->getHistory());
#else
  info.GetReturnValue().Set(Nan::Null());
#endif    
}

NAN_METHOD(BackgroundSubtractorWrap::BackgroundRatio) {
  SETUP_FUNCTION(BackgroundSubtractorWrap);
  auto mog = getMOG(self);
  if (!mog) {
    Nan::ThrowError("Not using a BackgroundSubtractorMOG");
  }
// only support  for V3+ with opencv-contrib
#ifdef HAVE_OPENCV_BGSEGM
  if (info.Length() > 0) {
    mog->setBackgroundRatio(info[0]->NumberValue());
  }
  info.GetReturnValue().Set(mog->getBackgroundRatio());
#else
  info.GetReturnValue().Set(Nan::Null());
#endif    
}

NAN_METHOD(BackgroundSubtractorWrap::NoiseSigma) {
  SETUP_FUNCTION(BackgroundSubtractorWrap);
  auto mog = getMOG(self);
  if (!mog) {
    Nan::ThrowError("Not using a BackgroundSubtractorMOG");
  }
// only support  for V3+ with opencv-contrib
#ifdef HAVE_OPENCV_BGSEGM
  if (info.Length() > 0) {
    mog->setNoiseSigma(info[0]->NumberValue());
  }
  info.GetReturnValue().Set(mog->getNoiseSigma());
#else
  info.GetReturnValue().Set(Nan::Null());
#endif    
}

NAN_METHOD(BackgroundSubtractorWrap::Mixtures) {
  SETUP_FUNCTION(BackgroundSubtractorWrap);
  auto mog = getMOG(self);
  if (!mog) {
    Nan::ThrowError("Not using a BackgroundSubtractorMOG");
  }
// only support  for V3+ with opencv-contrib
#ifdef HAVE_OPENCV_BGSEGM
  if (info.Length() > 0) {
    mog->setNMixtures(info[0]->NumberValue());
  }
  info.GetReturnValue().Set(mog->getNMixtures());
#else
  info.GetReturnValue().Set(Nan::Null());
#endif    
}

BackgroundSubtractorWrap::BackgroundSubtractorWrap(
    cv::Ptr<cv::BackgroundSubtractor> _subtractor) {
  subtractor = _subtractor;
}

#endif