tinkercalib 0.2.1 → 0.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/binding.gyp CHANGED
@@ -1,15 +1,23 @@
1
1
  {
2
2
  "targets": [{
3
- "target_name": "tinkercalib",
4
- "sources": ["src/tinkerCalib.cc", "src/calibration.cpp", "src/posConverter.cpp"],
3
+ "target_name": "tinkercalib",
4
+ "sources": ["src/tinkerCalib.cc", "src/calibration.cpp", "src/posConverter.cpp"],
5
5
  "include_dirs": [
6
- '/usr/local/include'
6
+ "<!(node -p \"require('node-addon-api').include_dir\")",
7
+ "<!@(node utils/find-opencv.js --include)"
7
8
  ],
8
- "libraries": [
9
- '<!@(pkg-config --libs opencv)'
10
- ],
11
- "cflags_cc!": ['-fno-rtti', '-fno-exceptions'
9
+ "libraries": [
10
+ "<!@(node utils/find-opencv.js --libs)"
12
11
  ],
13
- 'cflags!': ['-fno-exceptions'],
14
- }],
12
+ "defines": ["NAPI_VERSION=8", "NAPI_CPP_EXCEPTIONS"],
13
+ "cflags!": ["-fno-exceptions"],
14
+ "cflags_cc!": ["-fno-exceptions", "-fno-rtti"],
15
+ "cflags_cc": ["-std=c++17"],
16
+ "xcode_settings": {
17
+ "GCC_ENABLE_CPP_EXCEPTIONS": "YES",
18
+ "GCC_ENABLE_CPP_RTTI": "YES",
19
+ "CLANG_CXX_LANGUAGE_STANDARD": "c++17",
20
+ "MACOSX_DEPLOYMENT_TARGET": "11.0"
21
+ }
22
+ }]
15
23
  }
package/package.json CHANGED
@@ -1,12 +1,28 @@
1
1
  {
2
2
  "name": "tinkercalib",
3
- "version": "0.2.1",
3
+ "version": "0.3.0",
4
4
  "description": "A wrapper around several openCV calibration functions.",
5
5
  "main": "build/Release/tinkercalib.node",
6
6
  "scripts": {
7
- "test": "echo \"Error: no test specified\" && exit 1"
7
+ "install": "node-gyp rebuild",
8
+ "test": "node --test test/"
8
9
  },
9
- "repository": "",
10
+ "dependencies": {
11
+ "node-addon-api": "^8.3.0"
12
+ },
13
+ "engines": {
14
+ "node": ">=18"
15
+ },
16
+ "files": [
17
+ "binding.gyp",
18
+ "src/*.cc",
19
+ "src/*.cpp",
20
+ "src/*.h",
21
+ "utils/",
22
+ "test/",
23
+ "testData/"
24
+ ],
25
+ "repository": "github:GuillaumeZuff/tinkerCalib",
10
26
  "author": "",
11
27
  "license": "BSD"
12
28
  }
@@ -197,8 +197,8 @@ void Calibration::setDistortionMatrix(const std::vector<float> &distortion) {
197
197
 
198
198
  bool Calibration::findChessboard(const cv::Mat &frame) {
199
199
  return findChessboardCorners(frame, m_calibData.chessboardSize, m_camPxPoints,
200
- CV_CALIB_CB_ADAPTIVE_THRESH + CV_CALIB_CB_FILTER_QUADS
201
- + CV_CALIB_CB_FAST_CHECK);
200
+ cv::CALIB_CB_ADAPTIVE_THRESH + cv::CALIB_CB_FILTER_QUADS
201
+ + cv::CALIB_CB_FAST_CHECK);
202
202
  }
203
203
 
204
204
  std::vector<float> Calibration::getProjectionMatrix(bool isCamera) const {
@@ -1,319 +1,170 @@
1
- #include <node.h>
2
- #include <iostream>
3
- #include "calibration.h"
4
-
5
- using namespace std;
6
- using v8::FunctionCallbackInfo;
7
- using v8::Isolate;
8
- using v8::Local;
9
- using v8::Object;
10
- using v8::String;
11
- using v8::Value;
12
- using v8::Array;
13
- using v8::Number;
14
- using v8::Boolean;
15
-
16
- Isolate* isolate;
17
-
18
- //NAN_METHOD(Calibrate) {
19
- // NanScope();
20
- // Calibration calib;
21
- // string filename = "";
22
- //
23
- // if (args[0]->IsObject()) {
24
- // Local<Object> obj = Local<Object>::Cast(args[0]);
25
- // if (obj->Has(NanNew<String>("frameSize"))) {
26
- // std::vector<int> vect = getArray<int>(obj, "frameSize");
27
- // cv::Size frameSize = cv::Size(vect[0], vect[1]);
28
- // calib.setFrameSize(frameSize);
29
- // }
30
- // if (obj->Has(NanNew<String>("nearPlane"))) {
31
- // int nearPlane = getNumber<int>(obj, "nearPlane");
32
- // calib.setNearPlane(nearPlane);
33
- // }
34
- // if(obj->Has(NanNew<String>("farPlane"))) {
35
- // int farPlane = getNumber<int>(obj, "farPlane");
36
- // calib.setFarPlane(farPlane);
37
- // }
38
- // if(obj->Has(NanNew<String>("chessboardSize"))) {
39
- // std::vector<int> vect = getArray<int>(obj, "chessboardSize");
40
- // cv::Size chessboardSize = cv::Size(vect[0], vect[1]);
41
- // calib.setChessboardSize(chessboardSize);
42
- // }
43
- // if (obj->Has(NanNew<String>("chessboardCellSize"))) {
44
- // int cellSize = getNumber<int>(obj, "chessboardCellSize");
45
- // calib.setChessboardCellSize(cellSize);
46
- // }
47
- // if (obj->Has(NanNew<String>("intrinsic"))) {
48
- // vector<float> intrinsic = getArray<float>(obj, "intrinsic");
49
- // calib.setIntrinsicMatrix(intrinsic);
50
- // }
51
- // if (obj->Has(NanNew<String>("distortion"))) {
52
- // vector<float> distortion = getArray<float>(obj, "distortion");
53
- // calib.setDistortionMatrix(distortion);
54
- // }
55
- // if (obj->Has(NanNew<String>("filename"))) {
56
- // filename = getString(obj, "filename");
57
- // }
58
- // }
59
- //
60
- // Local<Object> result;
61
- // bool success = true;
62
- // bool isCamera = true;
63
- // if (calib.calibrate(filename,isCamera)) {
64
- // Handle<Object> camera = getCalibrationResult(calib,isCamera);
65
- // result->Set(NanNew<String>("camera"), camera);
66
- // } else {
67
- // success = false;
68
- // }
69
- //
70
- // isCamera = false;
71
- // if (success && calib.calibrate(filename,isCamera)) {
72
- // Handle<Object> renderer = getCalibrationResult(calib,isCamera);
73
- // result->Set(NanNew<String>("renderer"), renderer);
74
- // } else {
75
- // success = false;
76
- // }
77
- //
78
- // result->Set(NanNew<String>("success"), NanNew<Boolean>(success));
79
- // NanReturnValue(result);
80
- //}
1
+ // Node-API binding (node-addon-api) for the calibration code.
81
2
  //
82
- //NAN_METHOD(CalibrateFromPoints) {
83
- // NanScope();
84
- // Calibration calib;
85
- // vector<float> imagePoints, objectPoints;
3
+ // JS interface (unchanged since 0.2.x):
4
+ // calibrate(options) -> { camera?, renderer?, success }
5
+ // calibrateFromPoints(options) -> { camera?, renderer?, success }
6
+ // where camera/renderer are { projection: number[16], modelview: number[16] }.
86
7
  //
87
- // if (args[0]->IsObject()) {
88
- // Local<Object> obj = Local<Object>::Cast(args[0]);
89
- // if (obj->Has(NanNew<String>("frameSize"))) {
90
- // std::vector<int> vect = getArray<int>(obj, "frameSize");
91
- // cv::Size frameSize = cv::Size(vect[0], vect[1]);
92
- // calib.setFrameSize(frameSize);
93
- // }
94
- // if (obj->Has(NanNew<String>("nearPlane"))) {
95
- // int nearPlane = getNumber<int>(obj, "nearPlane");
96
- // calib.setNearPlane(nearPlane);
97
- // }
98
- // if(obj->Has(NanNew<String>("farPlane"))) {
99
- // int farPlane = getNumber<int>(obj, "farPlane");
100
- // calib.setFarPlane(farPlane);
101
- // }
102
- // if (obj->Has(NanNew<String>("intrinsic"))) {
103
- // vector<float> intrinsic = getArray<float>(obj, "intrinsic");
104
- // calib.setIntrinsicMatrix(intrinsic);
105
- // }
106
- // if (obj->Has(NanNew<String>("distortion"))) {
107
- // vector<float> distortion = getArray<float>(obj, "distortion");
108
- // calib.setDistortionMatrix(distortion);
109
- // }
110
- // if (obj->Has(NanNew<String>("imagePoints"))) {
111
- // imagePoints = getArray<float>(obj,"imagePoints");
112
- // }
113
- // if (obj->Has(NanNew<String>("objectPoints"))) {
114
- // objectPoints = getArray<float>(obj,"objectPoints");
115
- // }
116
- // }
8
+ // options: frameSize [w, h], nearPlane, farPlane, chessboardSize [w, h],
9
+ // chessboardCellSize, intrinsic number[9], distortion number[<=5],
10
+ // filename (calibrate), imagePoints / objectPoints (calibrateFromPoints,
11
+ // flat [x0, y0, x1, y1, ...] arrays of the same length).
117
12
  //
118
- // Local<Object> result;
119
- // bool success = true;
120
- // bool isCamera = true;
121
- // if (calib.calibrateFromPoints(imagePoints,objectPoints,isCamera)) {
122
- // Handle<Object> camera = getCalibrationResult(calib,isCamera);
123
- // result->Set(NanNew<String>("camera"), camera);
124
- // } else {
125
- // success = false;
126
- // }
127
- //
128
- // isCamera = false;
129
- // if (success && calib.calibrateFromPoints(imagePoints,objectPoints,isCamera)) {
130
- // Handle<Object> renderer = getCalibrationResult(calib,isCamera);
131
- // result->Set(NanNew<String>("renderer"), renderer);
132
- // } else {
133
- // success = false;
134
- // }
135
- //
136
- // result->Set(NanNew<String>("success"), NanNew<Boolean>(success));
137
- // NanReturnValue(result);
138
- //}
13
+ // Unlike 0.2.x, invalid input and OpenCV errors throw a JS Error instead of
14
+ // crashing the Node process.
15
+
16
+ #include <napi.h>
17
+ #include <exception>
18
+ #include <string>
19
+ #include <vector>
20
+ #include "calibration.h"
21
+
22
+ namespace {
139
23
 
140
24
  template<class T>
141
- std::vector<T> getArray(const Local<Object> &obj, const std::string &name) {
25
+ std::vector<T> getArray(const Napi::Object &obj, const char *name) {
26
+ Napi::Value val = obj.Get(name);
27
+ if (!val.IsArray()) {
28
+ throw Napi::TypeError::New(obj.Env(), std::string(name) + " must be an array of numbers");
29
+ }
30
+ Napi::Array array = val.As<Napi::Array>();
142
31
  std::vector<T> vect;
143
- //Local<Value> val = obj->Get(String::Cast(name.c_str()));
144
- Local<Value> val = obj->Get(String::NewFromUtf8(isolate, name.c_str()));
145
- Local<Array> array = Local<Array>::Cast(val);
146
- for (unsigned int i=0; i<array->Length(); ++i) {
147
- Local<Number> n = Local<Number>::Cast(array->Get(i));
148
- vect.push_back(n->Value());
32
+ vect.reserve(array.Length());
33
+ for (uint32_t i = 0; i < array.Length(); ++i) {
34
+ vect.push_back(static_cast<T>(array.Get(i).ToNumber().DoubleValue()));
149
35
  }
150
36
  return vect;
151
37
  }
152
38
 
153
39
  template<class T>
154
- T getNumber(const Local<Object> &obj, const std::string &name) {
155
- //Local<Value> val = obj->Get(NanNew<String>(name.c_str()));
156
- Local<Value> val = obj->Get(String::NewFromUtf8(isolate, name.c_str()));
157
- T number = Local<Number>::Cast(val)->NumberValue();
158
- return number;
40
+ std::vector<T> getSizedArray(const Napi::Object &obj, const char *name, size_t minSize, size_t maxSize) {
41
+ std::vector<T> vect = getArray<T>(obj, name);
42
+ if (vect.size() < minSize || vect.size() > maxSize) {
43
+ std::string msg = std::string(name) + " must have " + std::to_string(minSize);
44
+ if (maxSize != minSize) msg += " to " + std::to_string(maxSize);
45
+ throw Napi::TypeError::New(obj.Env(), msg + " entries");
46
+ }
47
+ return vect;
159
48
  }
160
49
 
161
- std::string getString(const Local<Object> &obj, const std::string &name) {
162
- //Local<Value> val = obj->Get(NanNew<String>(name.c_str()));
163
- Local<Value> val = obj->Get(String::NewFromUtf8(isolate, name.c_str()));
164
- String::Utf8Value str(val->ToString());
165
- return string(*str);
50
+ int getInt(const Napi::Object &obj, const char *name) {
51
+ return static_cast<int>(obj.Get(name).ToNumber().DoubleValue());
166
52
  }
167
53
 
168
- Local<Object> getCalibrationResult(Calibration &calib, bool isCamera) {
169
- // projection matrix
170
- vector<float> projVect = calib.getProjectionMatrix(isCamera);
171
- Local<Array> projection = Array::New(isolate, projVect.size());
172
- for (int i=0; i<(int)projVect.size(); ++i) {
173
- projection->Set(i, Number::New(isolate, projVect[i]));
174
- }
175
- // modelview matrix
176
- vector<float> mvVect = calib.getMvMatrix(isCamera);
177
- Local<Array> mv = Array::New(isolate, mvVect.size());
178
- for (int i=0; i<(int)mvVect.size(); i++) {
179
- mv->Set(i, Number::New(isolate, mvVect[i]));
54
+ Napi::Array toJsArray(Napi::Env env, const std::vector<float> &values) {
55
+ Napi::Array array = Napi::Array::New(env, values.size());
56
+ for (uint32_t i = 0; i < values.size(); ++i) {
57
+ array.Set(i, Napi::Number::New(env, values[i]));
180
58
  }
181
- // create result object
182
- Local<Object> result = Object::New(isolate);
183
- result->Set(String::NewFromUtf8(isolate, "projection"), projection);
184
- result->Set(String::NewFromUtf8(isolate, "modelview"), mv);
59
+ return array;
60
+ }
185
61
 
62
+ Napi::Object getCalibrationResult(Napi::Env env, const Calibration &calib, bool isCamera) {
63
+ Napi::Object result = Napi::Object::New(env);
64
+ result.Set("projection", toJsArray(env, calib.getProjectionMatrix(isCamera)));
65
+ result.Set("modelview", toJsArray(env, calib.getMvMatrix(isCamera)));
186
66
  return result;
187
67
  }
188
68
 
189
- void getCalibrationPoints(const FunctionCallbackInfo<Value>& args, vector<float>& imagePoints, vector<float>& objectPoints) {
190
- if (args[0]->IsObject()) {
191
- Local<Object> obj = Local<Object>::Cast(args[0]);
192
- Local<String> imageStr = String::NewFromUtf8(isolate, "imagePoints");
193
- Local<String> objectStr = String::NewFromUtf8(isolate, "objectPoints");
194
- if (obj->Has(imageStr)) {
195
- imagePoints = getArray<float>(obj, "imagePoints");
196
- }
197
- if (obj->Has(objectStr)) {
198
- objectPoints = getArray<float>(obj, "objectPoints");
199
- }
200
- }
201
- }
69
+ void configureCalibration(const Napi::CallbackInfo &info, Calibration &calib, std::string &filename) {
70
+ if (info.Length() < 1 || !info[0].IsObject()) return;
71
+ Napi::Object obj = info[0].As<Napi::Object>();
202
72
 
203
- void configureCalibration(const FunctionCallbackInfo<Value>& args, Calibration &calib, string &filename) {
204
- if (args[0]->IsObject()) {
205
- Local<Object> obj = Local<Object>::Cast(args[0]);
206
- Local<String> frameSize = String::NewFromUtf8(isolate, "frameSize");
207
- Local<String> nearPlane = String::NewFromUtf8(isolate, "nearPlane");
208
- Local<String> farPlane = String::NewFromUtf8(isolate, "farPlane");
209
- Local<String> chessboardSize = String::NewFromUtf8(isolate, "chessboardSize");
210
- Local<String> chessboardCellSize = String::NewFromUtf8(isolate, "chessboardCellSize");
211
- Local<String> intrinsic = String::NewFromUtf8(isolate, "intrinsic");
212
- Local<String> distortion = String::NewFromUtf8(isolate, "distortion");
213
- Local<String> filenameMember = String::NewFromUtf8(isolate, "filename");
214
- if (obj->Has(frameSize)) {
215
- std::vector<int> vect = getArray<int>(obj, "frameSize");
216
- cv::Size frameSize = cv::Size(vect[0], vect[1]);
217
- calib.setFrameSize(frameSize);
218
- }
219
- if (obj->Has(nearPlane)) {
220
- int nearPlane = getNumber<int>(obj, "nearPlane");
221
- calib.setNearPlane(nearPlane);
222
- }
223
- if(obj->Has(farPlane)) {
224
- int farPlane = getNumber<int>(obj, "farPlane");
225
- calib.setFarPlane(farPlane);
226
- }
227
- if(obj->Has(chessboardSize)) {
228
- std::vector<int> vect = getArray<int>(obj, "chessboardSize");
229
- cv::Size chessboardSize = cv::Size(vect[0], vect[1]);
230
- calib.setChessboardSize(chessboardSize);
231
- }
232
- if (obj->Has(chessboardCellSize)) {
233
- int cellSize = getNumber<int>(obj, "chessboardCellSize");
234
- calib.setChessboardCellSize(cellSize);
235
- }
236
- if (obj->Has(intrinsic)) {
237
- vector<float> intrinsic = getArray<float>(obj, "intrinsic");
238
- calib.setIntrinsicMatrix(intrinsic);
239
- }
240
- if (obj->Has(distortion)) {
241
- vector<float> distortion = getArray<float>(obj, "distortion");
242
- calib.setDistortionMatrix(distortion);
243
- }
244
- if (obj->Has(filenameMember)) {
245
- filename = getString(obj, "filename");
246
- }
73
+ if (obj.Has("frameSize")) {
74
+ std::vector<int> v = getSizedArray<int>(obj, "frameSize", 2, 2);
75
+ calib.setFrameSize(cv::Size(v[0], v[1]));
76
+ }
77
+ if (obj.Has("nearPlane")) {
78
+ calib.setNearPlane(getInt(obj, "nearPlane"));
79
+ }
80
+ if (obj.Has("farPlane")) {
81
+ calib.setFarPlane(getInt(obj, "farPlane"));
82
+ }
83
+ if (obj.Has("chessboardSize")) {
84
+ std::vector<int> v = getSizedArray<int>(obj, "chessboardSize", 2, 2);
85
+ calib.setChessboardSize(cv::Size(v[0], v[1]));
86
+ }
87
+ if (obj.Has("chessboardCellSize")) {
88
+ calib.setChessboardCellSize(getInt(obj, "chessboardCellSize"));
89
+ }
90
+ if (obj.Has("intrinsic")) {
91
+ calib.setIntrinsicMatrix(getSizedArray<float>(obj, "intrinsic", 9, 9));
92
+ }
93
+ if (obj.Has("distortion")) {
94
+ calib.setDistortionMatrix(getSizedArray<float>(obj, "distortion", 0, 5));
95
+ }
96
+ if (obj.Has("filename")) {
97
+ filename = obj.Get("filename").ToString().Utf8Value();
247
98
  }
248
99
  }
249
100
 
250
-
251
- void Calibrate(const FunctionCallbackInfo<Value>& args) {
252
- isolate = args.GetIsolate();
253
- Calibration calib;
254
- string filename = "";
255
- configureCalibration(args, calib, filename);
256
-
257
- Local<Object> result = Object::New(isolate);
258
- bool success = true;
259
- bool isCamera = true;
260
- if (calib.calibrate(filename,isCamera)) {
261
- Local<Object> camera = getCalibrationResult(calib,isCamera);
262
- result->Set(Local<String>(String::NewFromUtf8(isolate, "camera")), camera);
263
- } else {
264
- success = false;
101
+ void getCalibrationPoints(const Napi::CallbackInfo &info, std::vector<float> &imagePoints, std::vector<float> &objectPoints) {
102
+ if (info.Length() < 1 || !info[0].IsObject()) return;
103
+ Napi::Object obj = info[0].As<Napi::Object>();
104
+ if (obj.Has("imagePoints")) {
105
+ imagePoints = getArray<float>(obj, "imagePoints");
265
106
  }
266
-
267
- isCamera = false;
268
- if (success && calib.calibrate(filename,isCamera)) {
269
- Local<Object> renderer = getCalibrationResult(calib, isCamera);
270
- result->Set(String::NewFromUtf8(isolate,"renderer"), renderer);
271
- } else {
272
- success = false;
107
+ if (obj.Has("objectPoints")) {
108
+ objectPoints = getArray<float>(obj, "objectPoints");
109
+ }
110
+ if (imagePoints.size() % 2 != 0 || imagePoints.size() != objectPoints.size()) {
111
+ throw Napi::TypeError::New(info.Env(),
112
+ "imagePoints and objectPoints must be flat [x, y, ...] arrays of the same length");
273
113
  }
274
-
275
- Local<Boolean> successValue = Boolean::New(isolate,success);
276
- result->Set(String::NewFromUtf8(isolate,"success"), successValue);
277
- args.GetReturnValue().Set(result);
278
114
  }
279
115
 
280
-
281
- void CalibrateFromPoints(const FunctionCallbackInfo<Value>& args) {
282
- isolate = args.GetIsolate();
283
- Calibration calib;
284
- string filename = "";
285
- configureCalibration(args, calib, filename);
286
-
287
- vector<float> imagePoints, objectPoints;
288
- getCalibrationPoints(args, imagePoints, objectPoints);
289
-
290
-
291
- Local<Object> result = Object::New(isolate);
116
+ // Runs the camera then the renderer calibration, building the same result
117
+ // object as 0.2.x: {camera, renderer, success}, stopping at the first failure.
118
+ template<class F>
119
+ Napi::Value runCalibration(Napi::Env env, F calibrateOne, Calibration &calib) {
120
+ Napi::Object result = Napi::Object::New(env);
292
121
  bool success = true;
293
- bool isCamera = true;
294
- if (calib.calibrateFromPoints(imagePoints,objectPoints,isCamera)) {
295
- Local<Object> camera = getCalibrationResult(calib,isCamera);
296
- result->Set(String::NewFromUtf8(isolate,"camera"), camera);
297
- } else {
298
- success = false;
122
+ try {
123
+ if (calibrateOne(true)) {
124
+ result.Set("camera", getCalibrationResult(env, calib, true));
125
+ } else {
126
+ success = false;
127
+ }
128
+ if (success && calibrateOne(false)) {
129
+ result.Set("renderer", getCalibrationResult(env, calib, false));
130
+ } else {
131
+ success = false;
132
+ }
133
+ } catch (const Napi::Error &) {
134
+ throw;
135
+ } catch (const std::exception &e) {
136
+ throw Napi::Error::New(env, std::string("tinkercalib: ") + e.what());
299
137
  }
138
+ result.Set("success", Napi::Boolean::New(env, success));
139
+ return result;
140
+ }
300
141
 
301
- isCamera = false;
302
- if (success && calib.calibrateFromPoints(imagePoints,objectPoints,isCamera)) {
303
- Local<Object> renderer = getCalibrationResult(calib,isCamera);
304
- result->Set(String::NewFromUtf8(isolate, "renderer"), renderer);
305
- } else {
306
- success = false;
307
- }
142
+ Napi::Value Calibrate(const Napi::CallbackInfo &info) {
143
+ Calibration calib;
144
+ std::string filename;
145
+ configureCalibration(info, calib, filename);
146
+ return runCalibration(info.Env(), [&](bool isCamera) {
147
+ return calib.calibrate(filename, isCamera);
148
+ }, calib);
149
+ }
308
150
 
309
- result->Set(String::NewFromUtf8(isolate,"success"), Boolean::New(isolate, success));
310
- args.GetReturnValue().Set(result);
151
+ Napi::Value CalibrateFromPoints(const Napi::CallbackInfo &info) {
152
+ Calibration calib;
153
+ std::string filename;
154
+ configureCalibration(info, calib, filename);
155
+ std::vector<float> imagePoints, objectPoints;
156
+ getCalibrationPoints(info, imagePoints, objectPoints);
157
+ return runCalibration(info.Env(), [&](bool isCamera) {
158
+ return calib.calibrateFromPoints(imagePoints, objectPoints, isCamera);
159
+ }, calib);
311
160
  }
312
161
 
313
- void init(Local<Object> exports)
314
- {
315
- NODE_SET_METHOD(exports, "calibrate", Calibrate);
316
- NODE_SET_METHOD(exports, "calibrateFromPoints", CalibrateFromPoints);
162
+ Napi::Object Init(Napi::Env env, Napi::Object exports) {
163
+ exports.Set("calibrate", Napi::Function::New(env, Calibrate, "calibrate"));
164
+ exports.Set("calibrateFromPoints", Napi::Function::New(env, CalibrateFromPoints, "calibrateFromPoints"));
165
+ return exports;
317
166
  }
318
167
 
319
- NODE_MODULE(tinkercalib, init)
168
+ } // namespace
169
+
170
+ NODE_API_MODULE(tinkercalib, Init)
@@ -0,0 +1,114 @@
1
+ // Run with: npm test (needs a built addon: npm install / node-gyp rebuild)
2
+ //
3
+ // The reference values in fixtures/reference-0.2.1.json were produced by the
4
+ // original V8 binding (tinkercalib 0.2.1, Node 8, OpenCV 3.2) running on the
5
+ // old Tinkerlamp server, with exactly the input below (the same input the
6
+ // Meteor app sends from imports/api/tinker/calib/calibrations.js).
7
+ const test = require('node:test');
8
+ const assert = require('node:assert/strict');
9
+ const path = require('node:path');
10
+
11
+ const addon = require('..');
12
+ const reference = require('./fixtures/reference-0.2.1.json');
13
+
14
+ const pointsInput = () => ({
15
+ frameSize: [640, 480],
16
+ imagePoints: [
17
+ 489.51717499999995, 59.588125,
18
+ 327.63941666666665, 57.302975,
19
+ 165.40420833333337, 53.272125,
20
+ 481.890575, 162.326525,
21
+ 325.59499166666666, 159.64954999999998,
22
+ 169.28835833333338, 156.7088,
23
+ 475.0754, 258.10405000000003,
24
+ 323.73726666666664, 255.4805,
25
+ 172.2098333333334, 253.03025,
26
+ ],
27
+ objectPoints: [-125, -80, 0, -80, 125, -80, -125, 0, 0, 0, 125, 0, -125, 80, 0, 80, 125, 80],
28
+ intrinsic: [846.538, 0, 331.012, 0, 846.538, 228.192, 0, 0, 1],
29
+ distortion: [0, 0, 0, 0, 0],
30
+ nearPlane: 1,
31
+ farPlane: 12000,
32
+ chessboardSize: [10, 6],
33
+ chessboardCellSize: 25,
34
+ });
35
+
36
+ const fileInput = (filename) => ({
37
+ nearPlane: 100,
38
+ farPlane: 1200,
39
+ chessboardSize: [10, 6],
40
+ chessboardCellSize: 25,
41
+ filename,
42
+ intrinsic: [1061.64, 0.0, 449.264, 0.0, 1061.64, 361.303, 0.0, 0.0, 1.0],
43
+ distortion: [0.00436111, 1.4013e-45, 0.0, 7.54728e-34, 2.8026e-45],
44
+ });
45
+
46
+ function assertMatrixClose(actual, expected, tolerance, label) {
47
+ assert.ok(Array.isArray(actual), `${label} is an array`);
48
+ assert.equal(actual.length, 16, `${label} has 16 entries`);
49
+ actual.forEach((value, i) => {
50
+ assert.equal(typeof value, 'number', `${label}[${i}] is a number`);
51
+ const diff = Math.abs(value - expected[i]);
52
+ assert.ok(diff <= tolerance,
53
+ `${label}[${i}]: got ${value}, expected ${expected[i]} (diff ${diff} > ${tolerance})`);
54
+ });
55
+ }
56
+
57
+ test('exports calibrate and calibrateFromPoints', () => {
58
+ assert.equal(typeof addon.calibrate, 'function');
59
+ assert.equal(typeof addon.calibrateFromPoints, 'function');
60
+ });
61
+
62
+ test('calibrateFromPoints returns the same shape as 0.2.1', () => {
63
+ const result = addon.calibrateFromPoints(pointsInput());
64
+ assert.deepEqual(Object.keys(result).sort(), ['camera', 'renderer', 'success']);
65
+ assert.equal(result.success, true);
66
+ for (const part of ['camera', 'renderer']) {
67
+ assert.deepEqual(Object.keys(result[part]).sort(), ['modelview', 'projection']);
68
+ }
69
+ });
70
+
71
+ test('calibrateFromPoints matches the 0.2.1 values', () => {
72
+ const result = addon.calibrateFromPoints(pointsInput());
73
+ for (const part of ['camera', 'renderer']) {
74
+ // Projection only depends on the inputs: must match to float precision.
75
+ assertMatrixClose(result[part].projection, reference[part].projection, 1e-6, `${part}.projection`);
76
+ // Modelview comes from solvePnP; allow for OpenCV 3 -> 4 numeric drift:
77
+ // rotation entries within 1e-3, translation (mm) within 0.05 mm.
78
+ const mv = result[part].modelview;
79
+ const ref = reference[part].modelview;
80
+ assertMatrixClose(mv.slice(0, 12).concat([0, 0, 0, 1]), ref.slice(0, 12).concat([0, 0, 0, 1]), 1e-3, `${part}.modelview rotation`);
81
+ assertMatrixClose(mv.slice(12).concat(new Array(12).fill(0)), ref.slice(12).concat(new Array(12).fill(0)), 0.05, `${part}.modelview translation`);
82
+ }
83
+ });
84
+
85
+ test('calibrateFromPoints does not modify its argument', () => {
86
+ const input = pointsInput();
87
+ addon.calibrateFromPoints(input);
88
+ assert.deepEqual(input, pointsInput());
89
+ });
90
+
91
+ test('calibrate returns {success: false} when the file is missing', () => {
92
+ assert.deepEqual(addon.calibrate(fileInput('/nonexistent/calib.png')), { success: false });
93
+ });
94
+
95
+ test('calibrate on the test image returns a well-formed result', () => {
96
+ // 0.2.1 + OpenCV 3.2 did not find the chessboard in this image ({success: false});
97
+ // newer OpenCV versions may. Either way the shape must be the old one.
98
+ const result = addon.calibrate(fileInput(path.join(__dirname, '..', 'testData', 'calib.png')));
99
+ assert.equal(typeof result.success, 'boolean');
100
+ if (result.success) {
101
+ for (const part of ['camera', 'renderer']) {
102
+ assert.equal(result[part].projection.length, 16);
103
+ assert.equal(result[part].modelview.length, 16);
104
+ }
105
+ } else {
106
+ assert.deepEqual(result, { success: false });
107
+ }
108
+ });
109
+
110
+ test('invalid input throws a JS error instead of aborting the process', () => {
111
+ // 0.2.1 crashed Node with an uncaught cv::Exception here.
112
+ assert.throws(() => addon.calibrateFromPoints({}));
113
+ assert.throws(() => addon.calibrateFromPoints({ imagePoints: [1, 2, 3, 4], objectPoints: [1, 2] }));
114
+ });