File: Calib3D.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 (561 lines) | stat: -rw-r--r-- 16,736 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
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
#include "Calib3D.h"
#include "Matrix.h"

#ifdef HAVE_OPENCV_CALIB3D

inline cv::Mat matFromMatrix(Local<Value> matrix) {
  Matrix* m = Nan::ObjectWrap::Unwrap<Matrix>(matrix->ToObject());
  return m->mat;
}

inline cv::Size sizeFromArray(Local<Value> jsArray) {
  cv::Size patternSize;

  if (jsArray->IsArray()) {
    Local<Object> v8sz = jsArray->ToObject();

    patternSize = cv::Size(v8sz->Get(0)->IntegerValue(),
        v8sz->Get(1)->IntegerValue());
  } else {
    JSTHROW_TYPE("Size is not a valid array");
  }

  return patternSize;
}

inline std::vector<cv::Point2f> points2fFromArray(Local<Value> array) {
  std::vector<cv::Point2f> points;
  if (array->IsArray()) {
    Local<Array> pointsArray = Local<Array>::Cast(array->ToObject());

    for (unsigned int i = 0; i < pointsArray->Length(); i++) {
      Local<Object> pt = Nan::Get(pointsArray, i).ToLocalChecked()->ToObject();
      points.push_back(
          cv::Point2f(
              Nan::To<double>(Nan::Get(pt, Nan::New<String>("x").ToLocalChecked()).ToLocalChecked()).FromJust(),
              Nan::To<double>(Nan::Get(pt, Nan::New<String>("y").ToLocalChecked()).ToLocalChecked()).FromJust()
          )
      );
    }
  } else {
    JSTHROW_TYPE("Points not a valid array");
  }

  return points;
}

inline std::vector<cv::Point3f> points3fFromArray(Local<Value> array) {
  std::vector<cv::Point3f> points;
  if (array->IsArray()) {
    Local<Array> pointsArray = Local<Array>::Cast(array->ToObject());

    for (unsigned int i = 0; i < pointsArray->Length(); i++) {
      Local<Object> pt = pointsArray->Get(i)->ToObject();
      points.push_back(
          cv::Point3f(
              Nan::To<double>(Nan::Get(pt, Nan::New<String>("x").ToLocalChecked()).ToLocalChecked()).FromJust(),
              Nan::To<double>(Nan::Get(pt, Nan::New<String>("y").ToLocalChecked()).ToLocalChecked()).FromJust(),
              Nan::To<double>(Nan::Get(pt, Nan::New<String>("z").ToLocalChecked()).ToLocalChecked()).FromJust()
        )
      );
    }
  } else {
    JSTHROW_TYPE("Must pass array of object points for each frame")
  }

  return points;
}

inline std::vector<std::vector<cv::Point2f> > points2fFromArrayOfArrays(
    Local<Value> array) {
  std::vector<std::vector<cv::Point2f> > points;
  if (array->IsArray()) {
    Local<Array> pointsArray = Local<Array>::Cast(array->ToObject());

    for (unsigned int i = 0; i < pointsArray->Length(); i++) {
      points.push_back(points2fFromArray(pointsArray->Get(i)));
    }
  } else {
    JSTHROW_TYPE("Must pass array of object points for each frame")
  }

  return points;
}

inline std::vector<std::vector<cv::Point3f> > points3fFromArrayOfArrays(
    Local<Value> array) {
  std::vector<std::vector<cv::Point3f> > points;
  if (array->IsArray()) {
    Local<Array> pointsArray = Local<Array>::Cast(array->ToObject());

    for (unsigned int i = 0; i < pointsArray->Length(); i++) {
      points.push_back(points3fFromArray(pointsArray->Get(i)));
    }
  } else {
    JSTHROW_TYPE("Must pass array of object points for each frame")
  }

  return points;
}

void Calib3D::Init(Local<Object> target) {
  Nan::Persistent<Object> inner;
  Local<Object> obj = Nan::New<Object>();
  inner.Reset(obj);

  Nan::SetMethod(obj, "findChessboardCorners", FindChessboardCorners);
  Nan::SetMethod(obj, "drawChessboardCorners", DrawChessboardCorners);
  Nan::SetMethod(obj, "calibrateCamera", CalibrateCamera);
  Nan::SetMethod(obj, "solvePnP", SolvePnP);
  Nan::SetMethod(obj, "getOptimalNewCameraMatrix", GetOptimalNewCameraMatrix);
  Nan::SetMethod(obj, "stereoCalibrate", StereoCalibrate);
  Nan::SetMethod(obj, "stereoRectify", StereoRectify);
  Nan::SetMethod(obj, "computeCorrespondEpilines", ComputeCorrespondEpilines);
  Nan::SetMethod(obj, "reprojectImageTo3d", ReprojectImageTo3D);

  target->Set(Nan::New("calib3d").ToLocalChecked(), obj);
}

// cv::findChessboardCorners
NAN_METHOD(Calib3D::FindChessboardCorners) {
  Nan::EscapableHandleScope scope;

  try {
    // Get the arguments from javascript

    // Arg 0 is the image
    cv::Mat mat = matFromMatrix(info[0]);

    // Arg 1 is the pattern size
    cv::Size patternSize = sizeFromArray(info[1]);

    // Arg 2 would normally be the flags, ignoring this for now and using the
    // default flags

    // Find the corners
    std::vector<cv::Point2f> corners;
    bool found = cv::findChessboardCorners(mat, patternSize, corners);

    // Make the return value
    Local<Object> ret = Nan::New<Object>();
    ret->Set(Nan::New<String>("found").ToLocalChecked(), Nan::New<Boolean>(found));

    Local<Array> cornersArray = Nan::New<Array>(corners.size());
    for (unsigned int i = 0; i < corners.size(); i++) {
      Local<Object> point_data = Nan::New<Object>();
      point_data->Set(Nan::New<String>("x").ToLocalChecked(), Nan::New<Number>(corners[i].x));
      point_data->Set(Nan::New<String>("y").ToLocalChecked(), Nan::New<Number>(corners[i].y));

      cornersArray->Set(Nan::New<Number>(i), point_data);
    }

    ret->Set(Nan::New<String>("corners").ToLocalChecked(), cornersArray);

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

// cv::drawChessboardCorners
NAN_METHOD(Calib3D::DrawChessboardCorners) {
  Nan::EscapableHandleScope scope;

  try {
    // Get the arguments

    // Arg 0 is the image
    cv::Mat mat = matFromMatrix(info[0]);

    // Arg 1 is the pattern size
    cv::Size patternSize = sizeFromArray(info[1]);

    // Arg 2 is the corners array
    std::vector<cv::Point2f> corners = points2fFromArray(info[2]);

    // Arg 3, pattern found boolean
    bool patternWasFound = info[3]->ToBoolean()->Value();

    // Draw the corners
    cv::drawChessboardCorners(mat, patternSize, corners, patternWasFound);

    // Return the passed image, now with corners drawn on it
    info.GetReturnValue().Set(info[0]);

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

// cv::calibrateCamera
NAN_METHOD(Calib3D::CalibrateCamera) {
  Nan::EscapableHandleScope scope;

  try {
    // Get the arguments

    // Arg 0, the array of object points, an array of arrays
    std::vector<std::vector<cv::Point3f> > objectPoints =
        points3fFromArrayOfArrays(info[0]);

    // Arg 1, the image points, another array of arrays
    std::vector<std::vector<cv::Point2f> > imagePoints =
        points2fFromArrayOfArrays(info[1]);

    // Arg 2, the image size
    cv::Size imageSize = sizeFromArray(info[2]);

    // Arg 3, 4, input guesses for the camrea matrix and distortion coefficients,
    // skipping for now
    cv::Mat K, dist;

    // Arg 5, 6 flags and termination criteria, skipping for now

    // Calibrate the camera
    std::vector<cv::Mat> rvecs, tvecs;

    double error = cv::calibrateCamera(objectPoints, imagePoints, imageSize, K,
        dist, rvecs, tvecs);

    // make the return values
    Local<Object> ret = Nan::New<Object>();

    // Reprojection error
    ret->Set(Nan::New<String>("reprojectionError").ToLocalChecked(), Nan::New<Number>(error));

    // K
    Local<Object> KMatrixWrap = Matrix::CreateWrappedFromMat(K);
    ret->Set(Nan::New<String>("K").ToLocalChecked(), KMatrixWrap);

    // dist
    Local<Object> distMatrixWrap = Matrix::CreateWrappedFromMat(dist);
    ret->Set(Nan::New<String>("distortion").ToLocalChecked(), distMatrixWrap);

    // Per frame R and t, skiping for now

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

// cv::solvePnP
NAN_METHOD(Calib3D::SolvePnP) {
  Nan::EscapableHandleScope scope;

  try {
    // Get the arguments

    // Arg 0, the array of object points
    std::vector<cv::Point3f> objectPoints = points3fFromArray(info[0]);

    // Arg 1, the image points
    std::vector<cv::Point2f> imagePoints = points2fFromArray(info[1]);

    // Arg 2, the camera matrix
    cv::Mat K = matFromMatrix(info[2]);

    // Arg 3, the distortion coefficients
    cv::Mat dist = matFromMatrix(info[3]);

    // Arg 4, use extrinsic guess, skipped for now

    // Arg 5, flags, skip for now

    // solve for r and t
    cv::Mat rvec, tvec;

    cv::solvePnP(objectPoints, imagePoints, K, dist, rvec, tvec);

    // make the return values
    Local<Object> ret = Nan::New<Object>();

    // rvec
    Local<Object> rMatrixWrap = Matrix::CreateWrappedFromMat(rvec);
    ret->Set(Nan::New<String>("rvec").ToLocalChecked(), rMatrixWrap);

    // tvec
    Local<Object> tMatrixWrap = Matrix::CreateWrappedFromMat(tvec);
    ret->Set(Nan::New<String>("tvec").ToLocalChecked(), tMatrixWrap);

    // Return
    info.GetReturnValue().Set(ret);

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

// cv::getOptimalNewCameraMAtrix
NAN_METHOD(Calib3D::GetOptimalNewCameraMatrix) {
  Nan::EscapableHandleScope scope;

  try {
    // Get the arguments

    // Arg 0 is the original camera matrix
    cv::Mat Kin = matFromMatrix(info[0]);

    // Arg 1 is the distortion coefficients
    cv::Mat dist = matFromMatrix(info[1]);

    // Arg 2, the image size
    cv::Size imageSize = sizeFromArray(info[2]);

    // Arg 3 is the alpha free scaling parameter
    double alpha = Nan::To<double>(info[3]).FromJust();

    // Arg 4, the new image size
    cv::Size newImageSize = sizeFromArray(info[4]);

    // Arg 5, valid ROI, skip for now
    // Arg 6, center principal point, skip for now

    // Get the optimal new camera matrix
    cv::Mat Kout = cv::getOptimalNewCameraMatrix(Kin, dist, imageSize, alpha,
        newImageSize);

    // Wrap the output K
    Local<Object> KMatrixWrap = Matrix::CreateWrappedFromMat(Kout);

    // Return the new K matrix
    info.GetReturnValue().Set(KMatrixWrap);
  } catch (cv::Exception &e) {
    const char *err_msg = e.what();
    Nan::ThrowError(err_msg);
    return;
  }
}

// cv::stereoCalibrate
NAN_METHOD(Calib3D::StereoCalibrate) {
  Nan::EscapableHandleScope scope;

  try {
    // Get the arguments

    // Arg 0, the array of object points, an array of arrays
    std::vector<std::vector<cv::Point3f> > objectPoints =
        points3fFromArrayOfArrays(info[0]);

    // Arg 1, the image points1, another array of arrays
    std::vector<std::vector<cv::Point2f> > imagePoints1 =
        points2fFromArrayOfArrays(info[1]);

    // Arg 2, the image points2, another array of arrays =(
    std::vector<std::vector<cv::Point2f> > imagePoints2 =
        points2fFromArrayOfArrays(info[2]);

    // Arg 3 is the image size (follows the PYTHON api not the C++ api since all
    // following arguments are optional or outputs)
    cv::Size imageSize = sizeFromArray(info[3]);

    // Arg 4,5,6,7 is the camera matrix and distortion coefficients
    // (optional but must pass all 4 or none)
    cv::Mat k1, d1, k2, d2;
    if (info.Length() >= 8) {
      k1 = matFromMatrix(info[4]);
      d1 = matFromMatrix(info[5]);

      k2 = matFromMatrix(info[6]);
      d2 = matFromMatrix(info[7]);
    }

    // Last argument is flags, skipping for now

    // Output mats
    cv::Mat R, t, E, F;

    // Do the stereo calibration
    cv::stereoCalibrate(objectPoints, imagePoints1, imagePoints2, k1, d1, k2,
        d2, imageSize, R, t, E, F);

    // make the return value
    Local<Object> ret = Nan::New<Object>();

    // Make the output arguments

    // k1
    Local<Object> K1MatrixWrap = Matrix::CreateWrappedFromMat(k1);

    // d1
    Local<Object> d1MatrixWrap = Matrix::CreateWrappedFromMat(d1);

    // k2
    Local<Object> K2MatrixWrap = Matrix::CreateWrappedFromMat(k2);

    // d2
    Local<Object> d2MatrixWrap = Matrix::CreateWrappedFromMat(d2);

    // R
    Local<Object> RMatrixWrap = Matrix::CreateWrappedFromMat(R);

    // t
    Local<Object> tMatrixWrap = Matrix::CreateWrappedFromMat(t);

    // E
    Local<Object> EMatrixWrap = Matrix::CreateWrappedFromMat(E);

    // F
    Local<Object> FMatrixWrap = Matrix::CreateWrappedFromMat(F);

    // Add to return object
    ret->Set(Nan::New<String>("K1").ToLocalChecked(), K1MatrixWrap);
    ret->Set(Nan::New<String>("distortion1").ToLocalChecked(), d1MatrixWrap);
    ret->Set(Nan::New<String>("K2").ToLocalChecked(), K2MatrixWrap);
    ret->Set(Nan::New<String>("distortion2").ToLocalChecked(), d2MatrixWrap);
    ret->Set(Nan::New<String>("R").ToLocalChecked(), RMatrixWrap);
    ret->Set(Nan::New<String>("t").ToLocalChecked(), tMatrixWrap);
    ret->Set(Nan::New<String>("E").ToLocalChecked(), EMatrixWrap);
    ret->Set(Nan::New<String>("F").ToLocalChecked(), FMatrixWrap);

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

// cv::stereoRectify
NAN_METHOD(Calib3D::StereoRectify) {
  Nan::EscapableHandleScope scope;

  try {
    // Get the arguments

    // Arg0, the first camera matrix
    cv::Mat K1 = matFromMatrix(info[0]);

    // Arg1, the first distortion coefficients
    cv::Mat d1 = matFromMatrix(info[1]);

    // Arg2, the second camera matrix
    cv::Mat K2 = matFromMatrix(info[2]);

    // Arg3, the second distortion coefficients
    cv::Mat d2 = matFromMatrix(info[3]);

    // Arg4, the image size
    cv::Size imageSize = sizeFromArray(info[4]);

    // arg5, the intercamera rotation matrix
    cv::Mat R = matFromMatrix(info[5]);

    // Arg6, the intercamera translation vector
    cv::Mat t = matFromMatrix(info[6]);

    // Arg8, flags, skipping for now

    // Arg9, freescaling paremeter, skipping for now

    // Arg10, new image size, skipping for now to fix at original image size

    // Make output matrics
    cv::Mat R1, R2, P1, P2, Q;

    // Do the stereo rectification
    cv::stereoRectify(K1, d1, K2, d2, imageSize, R, t, R1, R2, P1, P2, Q);

    // Make the return object
    Local<Object> ret = Nan::New<Object>();

    ret->Set(Nan::New<String>("R1").ToLocalChecked(), Matrix::CreateWrappedFromMat(R1));
    ret->Set(Nan::New<String>("R2").ToLocalChecked(), Matrix::CreateWrappedFromMat(R2));
    ret->Set(Nan::New<String>("P1").ToLocalChecked(), Matrix::CreateWrappedFromMat(P1));
    ret->Set(Nan::New<String>("P2").ToLocalChecked(), Matrix::CreateWrappedFromMat(P2));
    ret->Set(Nan::New<String>("Q").ToLocalChecked(), Matrix::CreateWrappedFromMat(Q));

    // Return the rectification parameters
    info.GetReturnValue().Set(ret);
  } catch (cv::Exception &e) {
    const char *err_msg = e.what();
    Nan::ThrowError(err_msg);
    return;
  }
}

// cv::computeCorrespondEpilines
NAN_METHOD(Calib3D::ComputeCorrespondEpilines) {
  Nan::EscapableHandleScope scope;

  try {
    // Get the arguments

    // Arg0, the image points
    std::vector<cv::Point2f> points = points2fFromArray(info[0]);

    // Arg1, the image index (1 or 2)
    int whichImage = Nan::To<int>(info[1]).FromJust();

    // Arg2, the fundamental matrix
    cv::Mat F = matFromMatrix(info[2]);

    // compute the lines
    std::vector<cv::Vec3f> lines;
    cv::computeCorrespondEpilines(points, whichImage, F, lines);

    // Convert the lines to an array of objects (ax + by + c = 0)
    Local<Array> linesArray = Nan::New<Array>(lines.size());
    for(unsigned int i = 0; i < lines.size(); i++)
    {
      Local<Object> line_data = Nan::New<Object>();
      line_data->Set(Nan::New<String>("a").ToLocalChecked(), Nan::New<Number>(lines[i][0]));
      line_data->Set(Nan::New<String>("b").ToLocalChecked(), Nan::New<Number>(lines[i][1]));
      line_data->Set(Nan::New<String>("c").ToLocalChecked(), Nan::New<Number>(lines[i][2]));

      linesArray->Set(Nan::New<Number>(i), line_data);
    }

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

// cv::reprojectImageTo3D
NAN_METHOD(Calib3D::ReprojectImageTo3D) {
  Nan::EscapableHandleScope scope;

  try {
    // Get the arguments

    // Arg0, the disparity image
    cv::Mat disparity = matFromMatrix(info[0]);

    // Arg1, the depth-to-disparity transformation Q
    cv::Mat Q = matFromMatrix(info[1]);

    // Arg 2, handle missing values, skipped for now

    // Arg3, output bit depth, skipped for now

    // Compute the depth image
    cv::Mat depthImage;
    cv::reprojectImageTo3D(disparity, depthImage, Q);

    // Wrap the depth image
    Local<Object> depthImageMatrix = Matrix::CreateWrappedFromMat(depthImage);

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

#endif