@kubohiroya/turbowarp-camera-calibration 0.4.0 → 0.6.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/README.ja.md CHANGED
@@ -101,7 +101,7 @@ bundleは約11 MBあります。
101
101
  検証済みのversionをexact pinします。
102
102
 
103
103
  ```bash
104
- pnpm add --save-exact @kubohiroya/turbowarp-camera-calibration@0.4.0
104
+ pnpm add --save-exact @kubohiroya/turbowarp-camera-calibration@0.6.0
105
105
  ```
106
106
 
107
107
  standalone bundle:
@@ -113,7 +113,7 @@ node_modules/@kubohiroya/turbowarp-camera-calibration/dist/camera-calibration.js
113
113
  version固定CDN URL:
114
114
 
115
115
  ```text
116
- https://cdn.jsdelivr.net/npm/@kubohiroya/turbowarp-camera-calibration@0.4.0/dist/camera-calibration.js
116
+ https://cdn.jsdelivr.net/npm/@kubohiroya/turbowarp-camera-calibration@0.6.0/dist/camera-calibration.js
117
117
  ```
118
118
 
119
119
  ## クイックスタート
package/README.md CHANGED
@@ -102,7 +102,7 @@ therefore about 11 MB.
102
102
  Install an exact version that you have reviewed:
103
103
 
104
104
  ```bash
105
- pnpm add --save-exact @kubohiroya/turbowarp-camera-calibration@0.4.0
105
+ pnpm add --save-exact @kubohiroya/turbowarp-camera-calibration@0.6.0
106
106
  ```
107
107
 
108
108
  Load the standalone bundle from:
@@ -114,7 +114,7 @@ node_modules/@kubohiroya/turbowarp-camera-calibration/dist/camera-calibration.js
114
114
  A version-pinned CDN URL is:
115
115
 
116
116
  ```text
117
- https://cdn.jsdelivr.net/npm/@kubohiroya/turbowarp-camera-calibration@0.4.0/dist/camera-calibration.js
117
+ https://cdn.jsdelivr.net/npm/@kubohiroya/turbowarp-camera-calibration@0.6.0/dist/camera-calibration.js
118
118
  ```
119
119
 
120
120
  ## Quick start
@@ -182,9 +182,9 @@ generated section manually.
182
182
 
183
183
  <!-- BEGIN GENERATED BLOCKS -->
184
184
 
185
- ### `start camera [CAMERA_ID] calibration [CALIBRATION_ID] board [COLUMNS] by [ROWS] square [SQUARE_METERS] m max error [MAX_ERROR_PX] px`
185
+ ### `start camera [CAMERA_ID] calibration [CALIBRATION_ID] board [COLUMNS] by [ROWS] square [SQUARE_METERS] m marker [MARKER_METERS] m max error [MAX_ERROR_PX] px`
186
186
 
187
- Leases one shared Camera Source camera and fixes its real capture resolution for a chessboard calibration session. The board is measured in inner corners, not printed squares.
187
+ Leases one shared Camera Source camera and fixes its real capture resolution for a chessboard calibration session. The board is a ChArUco target: a chessboard with an ArUco marker inside each light square, so a view that runs off the frame still contributes the corners it shows. The board is measured in inner corners, not printed squares.
188
188
 
189
189
  | Property | Value |
190
190
  |---|---|
@@ -195,6 +195,7 @@ Leases one shared Camera Source camera and fixes its real capture resolution for
195
195
  | `COLUMNS` | Number, default: `9` |
196
196
  | `ROWS` | Number, default: `6` |
197
197
  | `SQUARE_METERS` | Number, default: `0.025` |
198
+ | `MARKER_METERS` | Number, default: `0.018` |
198
199
  | `MAX_ERROR_PX` | Number, default: `1.5` |
199
200
 
200
201
  ### `add calibration sample for camera [CAMERA_ID]`
@@ -328,6 +329,36 @@ Returns the RMS reprojection error in pixels for the latest solve or imported pr
328
329
  | Opcode | `cameraCalibrationReprojectionError` |
329
330
  | `CAMERA_ID` | String, default: `default` |
330
331
 
332
+ ### `camera [CAMERA_ID] calibration pose spread`
333
+
334
+ Returns how varied the angles of the collected samples are. Zero means every sample was taken from the same direction, which cannot be solved from: focal length and distance stay inseparable. Solving is refused below the required spread.
335
+
336
+ | Property | Value |
337
+ |---|---|
338
+ | Type | Reporter |
339
+ | Opcode | `cameraCalibrationPoseSpread` |
340
+ | `CAMERA_ID` | String, default: `default` |
341
+
342
+ ### `camera [CAMERA_ID] calibration holdout error px`
343
+
344
+ Returns the RMS reprojection error over the samples the solve was not fitted to. Compare it with the reprojection error: the two agreeing is the evidence that the calibration generalizes, and the two disagreeing says the set was too small or too alike.
345
+
346
+ | Property | Value |
347
+ |---|---|
348
+ | Type | Reporter |
349
+ | Opcode | `cameraCalibrationHoldoutErrorPx` |
350
+ | `CAMERA_ID` | String, default: `default` |
351
+
352
+ ### `camera [CAMERA_ID] calibration holdout sample count`
353
+
354
+ Returns how many samples were held back from the solve. Zero means nothing was validated, so the holdout error says nothing.
355
+
356
+ | Property | Value |
357
+ |---|---|
358
+ | Type | Reporter |
359
+ | Opcode | `cameraCalibrationHoldoutSampleCount` |
360
+ | `CAMERA_ID` | String, default: `default` |
361
+
331
362
  ### `camera [CAMERA_ID] calibration error code`
332
363
 
333
364
  Returns a stable code for dependency, board, camera, sample, solve, reprojection, profile, or publication errors, or an empty string.
@@ -48,8 +48,8 @@
48
48
  {
49
49
  "opcode": "startCameraCalibration",
50
50
  "blockType": "COMMAND",
51
- "text": "start camera [CAMERA_ID] calibration [CALIBRATION_ID] board [COLUMNS] by [ROWS] square [SQUARE_METERS] m max error [MAX_ERROR_PX] px",
52
- "description": "Leases one shared Camera Source camera and fixes its real capture resolution for a chessboard calibration session. The board is measured in inner corners, not printed squares.",
51
+ "text": "start camera [CAMERA_ID] calibration [CALIBRATION_ID] board [COLUMNS] by [ROWS] square [SQUARE_METERS] m marker [MARKER_METERS] m max error [MAX_ERROR_PX] px",
52
+ "description": "Leases one shared Camera Source camera and fixes its real capture resolution for a chessboard calibration session. The board is a ChArUco target: a chessboard with an ArUco marker inside each light square, so a view that runs off the frame still contributes the corners it shows. The board is measured in inner corners, not printed squares.",
53
53
  "arguments": {
54
54
  "CAMERA_ID": {
55
55
  "type": "STRING",
@@ -71,6 +71,10 @@
71
71
  "type": "NUMBER",
72
72
  "defaultValue": .025
73
73
  },
74
+ "MARKER_METERS": {
75
+ "type": "NUMBER",
76
+ "defaultValue": .018
77
+ },
74
78
  "MAX_ERROR_PX": {
75
79
  "type": "NUMBER",
76
80
  "defaultValue": 1.5
@@ -216,6 +220,36 @@
216
220
  "defaultValue": "default"
217
221
  } }
218
222
  },
223
+ {
224
+ "opcode": "cameraCalibrationPoseSpread",
225
+ "blockType": "REPORTER",
226
+ "text": "camera [CAMERA_ID] calibration pose spread",
227
+ "description": "Returns how varied the angles of the collected samples are. Zero means every sample was taken from the same direction, which cannot be solved from: focal length and distance stay inseparable. Solving is refused below the required spread.",
228
+ "arguments": { "CAMERA_ID": {
229
+ "type": "STRING",
230
+ "defaultValue": "default"
231
+ } }
232
+ },
233
+ {
234
+ "opcode": "cameraCalibrationHoldoutErrorPx",
235
+ "blockType": "REPORTER",
236
+ "text": "camera [CAMERA_ID] calibration holdout error px",
237
+ "description": "Returns the RMS reprojection error over the samples the solve was not fitted to. Compare it with the reprojection error: the two agreeing is the evidence that the calibration generalizes, and the two disagreeing says the set was too small or too alike.",
238
+ "arguments": { "CAMERA_ID": {
239
+ "type": "STRING",
240
+ "defaultValue": "default"
241
+ } }
242
+ },
243
+ {
244
+ "opcode": "cameraCalibrationHoldoutSampleCount",
245
+ "blockType": "REPORTER",
246
+ "text": "camera [CAMERA_ID] calibration holdout sample count",
247
+ "description": "Returns how many samples were held back from the solve. Zero means nothing was validated, so the holdout error says nothing.",
248
+ "arguments": { "CAMERA_ID": {
249
+ "type": "STRING",
250
+ "defaultValue": "default"
251
+ } }
252
+ },
219
253
  {
220
254
  "opcode": "cameraCalibrationErrorCode",
221
255
  "blockType": "REPORTER",
@@ -636,11 +670,93 @@
636
670
  return value;
637
671
  }
638
672
  //#endregion
673
+ //#region src/calibration/pose.ts
674
+ var NO_TILT = Object.freeze({
675
+ x: 0,
676
+ y: 0
677
+ });
678
+ /**
679
+ * The minimum spread of tilts a solve is allowed to proceed from.
680
+ *
681
+ * A board half as wide as its distance, tilted thirty degrees, gives an edge
682
+ * ratio near 1.35 and so a component near 0.30. This floor is a quarter of
683
+ * that: enough to refuse a set collected without tilting, or tilted the same
684
+ * way every time, without refusing a cautious operator who varied it a little.
685
+ */
686
+ var MINIMUM_POSE_SPREAD = .08;
687
+ function tiltOf(sample, board) {
688
+ const { columns, rows } = board;
689
+ const at = /* @__PURE__ */ new Map();
690
+ sample.ids.forEach((id, index) => {
691
+ const corner = sample.corners[index];
692
+ if (corner) at.set(id, corner);
693
+ });
694
+ if (at.size < 4) return NO_TILT;
695
+ const acrossNear = [];
696
+ const acrossFar = [];
697
+ const downNear = [];
698
+ const downFar = [];
699
+ for (const [id, corner] of at) {
700
+ const column = id % columns;
701
+ const row = Math.floor(id / columns);
702
+ const right = column + 1 < columns ? at.get(id + 1) : void 0;
703
+ if (right) (row * 2 < rows - 1 ? acrossNear : acrossFar).push(distance(corner, right));
704
+ const below = row + 1 < rows ? at.get(id + columns) : void 0;
705
+ if (below) (column * 2 < columns - 1 ? downNear : downFar).push(distance(corner, below));
706
+ }
707
+ return {
708
+ x: logRatio(mean(acrossNear), mean(acrossFar)),
709
+ y: logRatio(mean(downNear), mean(downFar))
710
+ };
711
+ }
712
+ /**
713
+ * How varied the collected tilts are: the RMS distance from their mean.
714
+ *
715
+ * One number covers both ways a set goes wrong. Every sample square on puts
716
+ * every tilt near the origin; every sample tilted the same way puts them all in
717
+ * one place. Either way they sit together, and this is near zero.
718
+ */
719
+ function poseSpread(samples, board) {
720
+ if (samples.length < 2) return 0;
721
+ const tilts = samples.map((sample) => tiltOf(sample, board));
722
+ const mean = {
723
+ x: tilts.reduce((total, tilt) => total + tilt.x, 0) / tilts.length,
724
+ y: tilts.reduce((total, tilt) => total + tilt.y, 0) / tilts.length
725
+ };
726
+ const squared = tilts.reduce((total, tilt) => total + (tilt.x - mean.x) ** 2 + (tilt.y - mean.y) ** 2, 0) / tilts.length;
727
+ return Math.sqrt(squared);
728
+ }
729
+ function mean(values) {
730
+ if (values.length === 0) return 0;
731
+ return values.reduce((total, value) => total + value, 0) / values.length;
732
+ }
733
+ function logRatio(first, second) {
734
+ if (!(first > 0) || !(second > 0)) return 0;
735
+ return Math.log(first / second);
736
+ }
737
+ function distance(from, to) {
738
+ return Math.hypot(from.x - to.x, from.y - to.y);
739
+ }
740
+ //#endregion
639
741
  //#region src/calibration/controller.ts
640
742
  var MINIMUM_SAMPLES = 8;
641
743
  var MAXIMUM_SAMPLES = 40;
642
744
  var MINIMUM_SAMPLE_QUALITY = .2;
643
745
  var MINIMUM_NORMALIZED_NOVELTY = .015;
746
+ /**
747
+ * The share of samples held back from the fit, to be reprojected afterwards.
748
+ *
749
+ * A solve's own reprojection error says how well the answer reproduces the
750
+ * samples that produced it. With few samples for the number of parameters an
751
+ * overfitted answer scores well on exactly that, so some views are kept out of
752
+ * the fit and scored separately. The two agreeing is the evidence; the two
753
+ * disagreeing says the set was too small or too alike.
754
+ *
755
+ * Never at the cost of the minimum: if holding views back would leave fewer
756
+ * than MINIMUM_SAMPLES to fit, fewer are held back, and none at all rather than
757
+ * a fit that is weaker than the one the operator was promised.
758
+ */
759
+ var HOLDOUT_FRACTION = .2;
644
760
  /** Codes a profile validation can produce, and therefore can clear. */
645
761
  var PROFILE_ERROR_CODES = /* @__PURE__ */ new Set([
646
762
  "invalid-calibration",
@@ -661,6 +777,8 @@
661
777
  this.sessionSampleCount = 0;
662
778
  this.sampleQuality = 0;
663
779
  this.reprojectionError = 0;
780
+ this.holdoutError = 0;
781
+ this.holdoutCount = 0;
664
782
  this.calibrationState = "idle";
665
783
  this.calibrationErrorCode = "";
666
784
  this.calibrationErrorMessage = "";
@@ -720,6 +838,8 @@
720
838
  this.sessionSampleCount = 0;
721
839
  this.sampleQuality = 0;
722
840
  this.reprojectionError = 0;
841
+ this.holdoutError = 0;
842
+ this.holdoutCount = 0;
723
843
  this.calibrationState = "ready";
724
844
  }
725
845
  addSample() {
@@ -737,6 +857,8 @@
737
857
  if (this.solving) return this.solving;
738
858
  if (!this.session || !this.lease || this.calibrationState !== "ready") throw new Error(`Camera ${this.cameraId} calibration is not ready to solve.`);
739
859
  if (this.samples.length < MINIMUM_SAMPLES) this.reject("sample-insufficient", `At least ${MINIMUM_SAMPLES} accepted samples are required.`);
860
+ const spread = poseSpread(this.samples, this.session.board);
861
+ if (spread < .08) this.reject("sample-poses-degenerate", `The board was held at nearly the same angle throughout (spread ${spread.toFixed(3)}, at least ${MINIMUM_POSE_SPREAD} is required). Tilt it between samples; moving it sideways does not separate focal length from distance.`);
740
862
  const solving = this.solveSession(this.operation);
741
863
  this.solving = solving;
742
864
  const clear = () => {
@@ -762,6 +884,8 @@
762
884
  this.sessionSampleCount = 0;
763
885
  this.sampleQuality = 0;
764
886
  this.reprojectionError = 0;
887
+ this.holdoutError = 0;
888
+ this.holdoutCount = 0;
765
889
  this.calibrationState = "idle";
766
890
  this.clearError();
767
891
  }
@@ -835,6 +959,19 @@
835
959
  latestReprojectionError() {
836
960
  return this.reprojectionError;
837
961
  }
962
+ /** RMS reprojection over views the fit never saw. Zero when none were held. */
963
+ latestHoldoutError() {
964
+ return this.holdoutError;
965
+ }
966
+ /** How many views were held back. Zero means nothing was validated. */
967
+ holdoutSampleCount() {
968
+ return this.holdoutCount;
969
+ }
970
+ /** How varied the collected tilts are. Zero until a second sample lands. */
971
+ poseSpread() {
972
+ const session = this.session;
973
+ return session ? poseSpread(this.samples, session.board) : 0;
974
+ }
838
975
  errorCode() {
839
976
  return this.calibrationErrorCode;
840
977
  }
@@ -871,8 +1008,7 @@
871
1008
  }
872
1009
  if (operation !== this.operation) return;
873
1010
  if (!sample) this.reject("board-not-found", "The complete chessboard was not found.");
874
- const expectedCorners = session.board.columns * session.board.rows;
875
- if (sample.corners.length !== expectedCorners || !Number.isFinite(sample.quality) || sample.quality < MINIMUM_SAMPLE_QUALITY) this.reject("sample-low-quality", `Sample quality must be at least ${MINIMUM_SAMPLE_QUALITY}.`);
1011
+ if (sample.corners.length !== sample.ids.length || !Number.isFinite(sample.quality) || sample.quality < MINIMUM_SAMPLE_QUALITY) this.reject("sample-low-quality", `Sample quality must be at least ${MINIMUM_SAMPLE_QUALITY}.`);
876
1012
  const accepted = sample;
877
1013
  if (this.samples.some((previous) => normalizedCornerDistance(previous, accepted, session.imageWidth, session.imageHeight) < MINIMUM_NORMALIZED_NOVELTY)) this.reject("sample-too-similar", "Move or tilt the board before capturing another sample.");
878
1014
  this.samples.push(accepted);
@@ -886,14 +1022,20 @@
886
1022
  const lease = this.lease;
887
1023
  if (!session || !lease) return;
888
1024
  this.calibrationState = "solving";
1025
+ const { fitted, heldOut } = splitForValidation(this.samples);
889
1026
  let solution;
1027
+ let holdoutError = 0;
890
1028
  try {
891
- solution = await (await this.resolveBackend()).solve([...this.samples], session.board, session.imageWidth, session.imageHeight);
1029
+ const backend = await this.resolveBackend();
1030
+ solution = await backend.solve(fitted, session.board, session.imageWidth, session.imageHeight);
1031
+ holdoutError = await backend.validate(heldOut, session.board, solution);
892
1032
  } catch (error) {
893
1033
  this.fail("solve-failed", error);
894
1034
  }
895
1035
  if (operation !== this.operation) return;
896
1036
  this.reprojectionError = solution.reprojectionErrorPx;
1037
+ this.holdoutError = holdoutError;
1038
+ this.holdoutCount = heldOut.length;
897
1039
  if (!Number.isFinite(this.reprojectionError) || this.reprojectionError > session.maximumReprojectionErrorPx) {
898
1040
  this.calibrationState = "ready";
899
1041
  this.reject("reprojection-too-high", `Reprojection RMS ${this.reprojectionError} px exceeds ${session.maximumReprojectionErrorPx} px.`);
@@ -1035,6 +1177,15 @@
1035
1177
  latestReprojectionError(cameraId) {
1036
1178
  return this.existing(cameraId)?.latestReprojectionError() ?? 0;
1037
1179
  }
1180
+ poseSpread(cameraId) {
1181
+ return this.existing(cameraId)?.poseSpread() ?? 0;
1182
+ }
1183
+ latestHoldoutError(cameraId) {
1184
+ return this.existing(cameraId)?.latestHoldoutError() ?? 0;
1185
+ }
1186
+ holdoutSampleCount(cameraId) {
1187
+ return this.existing(cameraId)?.holdoutSampleCount() ?? 0;
1188
+ }
1038
1189
  errorCode(cameraId) {
1039
1190
  return this.existing(cameraId)?.errorCode() ?? "";
1040
1191
  }
@@ -1082,6 +1233,7 @@
1082
1233
  const columns = integerInRange(options.board.columns, 3, 20, "columns");
1083
1234
  const rows = integerInRange(options.board.rows, 3, 20, "rows");
1084
1235
  if (!Number.isFinite(options.board.squareSizeMeters) || options.board.squareSizeMeters <= 0 || options.board.squareSizeMeters > 1) throw new Error("square size must be within (0, 1] meter.");
1236
+ if (!Number.isFinite(options.board.markerSizeMeters) || options.board.markerSizeMeters <= 0 || options.board.markerSizeMeters >= options.board.squareSizeMeters) throw new Error("marker size must be greater than zero and smaller than the square size.");
1085
1237
  if (!Number.isFinite(options.maximumReprojectionErrorPx) || options.maximumReprojectionErrorPx <= 0 || options.maximumReprojectionErrorPx > 100) throw new Error("maximum reprojection error must be within (0, 100] px.");
1086
1238
  return {
1087
1239
  cameraId: identifier(options.cameraId, "camera ID"),
@@ -1089,7 +1241,8 @@
1089
1241
  board: {
1090
1242
  columns,
1091
1243
  rows,
1092
- squareSizeMeters: options.board.squareSizeMeters
1244
+ squareSizeMeters: options.board.squareSizeMeters,
1245
+ markerSizeMeters: options.board.markerSizeMeters
1093
1246
  },
1094
1247
  maximumReprojectionErrorPx: options.maximumReprojectionErrorPx
1095
1248
  };
@@ -1113,6 +1266,32 @@
1113
1266
  if (!Number.isInteger(value) || value < minimum || value > maximum) throw new Error(`${label} must be an integer from ${minimum} to ${maximum}.`);
1114
1267
  return value;
1115
1268
  }
1269
+ /**
1270
+ * Divides the samples into the ones fitted and the ones kept back.
1271
+ *
1272
+ * Spread evenly through the order they were captured rather than taken from
1273
+ * the end. Samples near each other in time are the ones most likely to share a
1274
+ * position, so a hold-out cut from the tail can be the least independent part
1275
+ * of the set -- which would make the check read better than it should.
1276
+ */
1277
+ function splitForValidation(samples) {
1278
+ const holdOut = Math.min(Math.floor(samples.length * HOLDOUT_FRACTION), samples.length - MINIMUM_SAMPLES);
1279
+ if (holdOut < 1) return {
1280
+ fitted: [...samples],
1281
+ heldOut: []
1282
+ };
1283
+ const step = samples.length / holdOut;
1284
+ const chosen = new Set(Array.from({ length: holdOut }, (_, index) => Math.min(samples.length - 1, Math.floor(index * step + step / 2))));
1285
+ const fitted = [];
1286
+ const heldOut = [];
1287
+ samples.forEach((sample, index) => {
1288
+ (chosen.has(index) ? heldOut : fitted).push(sample);
1289
+ });
1290
+ return {
1291
+ fitted,
1292
+ heldOut
1293
+ };
1294
+ }
1116
1295
  function isPromise(value) {
1117
1296
  return value !== void 0;
1118
1297
  }
@@ -8501,7 +8680,15 @@
8501
8680
  * The single pinned production solver. The version is part of the identifier so
8502
8681
  * that a project can record which build produced a profile.
8503
8682
  */
8504
- var OPENCV_BACKEND_NAME = "opencv-js-wasm-4.12.0";
8683
+ var OPENCV_BACKEND_NAME = "opencv-js-wasm-4.12.0-charuco";
8684
+ /**
8685
+ * The fewest corners a view has to show to be worth keeping.
8686
+ *
8687
+ * A ChArUco view need not show the whole board -- that is the point of the
8688
+ * markers -- but a handful of corners constrains almost nothing and drags the
8689
+ * solve out for no gain. Six is two markers' worth.
8690
+ */
8691
+ var MINIMUM_CORNERS = 6;
8505
8692
  var openCvPromise;
8506
8693
  /**
8507
8694
  * Detects the chessboard and solves the camera intrinsics with OpenCV.
@@ -8513,6 +8700,38 @@
8513
8700
  var OpenCvChessboardCalibrationBackend = class {
8514
8701
  constructor() {
8515
8702
  this.name = OPENCV_BACKEND_NAME;
8703
+ this.detectors = /* @__PURE__ */ new Map();
8704
+ }
8705
+ detectorFor(cv, board) {
8706
+ return this.entryFor(cv, board).detector;
8707
+ }
8708
+ entryFor(cv, board) {
8709
+ const key = `${board.columns}x${board.rows}:${board.squareSizeMeters}:${board.markerSizeMeters}`;
8710
+ const existing = this.detectors.get(key);
8711
+ if (existing) return existing;
8712
+ const dictionary = cv.getPredefinedDictionary(cv.DICT_4X4_50);
8713
+ const ids = new cv.Mat();
8714
+ const charuco = new cv.aruco_CharucoBoard(new cv.Size(board.columns + 1, board.rows + 1), board.squareSizeMeters, board.markerSizeMeters, dictionary, ids);
8715
+ const entry = {
8716
+ board: charuco,
8717
+ detector: new cv.aruco_CharucoDetector(charuco, new cv.aruco_CharucoParameters(), new cv.aruco_DetectorParameters(), new cv.aruco_RefineParameters(10, 3, true))
8718
+ };
8719
+ this.detectors.set(key, entry);
8720
+ return entry;
8721
+ }
8722
+ /** Where each inner corner sits on the board, in metres. */
8723
+ worldPointsFor(cv, board) {
8724
+ const corners = this.entryFor(cv, board).board.getChessboardCorners();
8725
+ const points = [];
8726
+ for (let index = 0; index < corners.size(); index += 1) {
8727
+ const point = corners.get(index);
8728
+ points.push([
8729
+ point.x,
8730
+ point.y,
8731
+ point.z ?? 0
8732
+ ]);
8733
+ }
8734
+ return points;
8516
8735
  }
8517
8736
  async captureSample(frame, board) {
8518
8737
  const cv = await getOpenCv();
@@ -8525,21 +8744,25 @@
8525
8744
  const source = cv.imread(canvas);
8526
8745
  const gray = new cv.Mat();
8527
8746
  const corners = new cv.Mat();
8747
+ const ids = new cv.Mat();
8528
8748
  const laplacian = new cv.Mat();
8529
8749
  const mean = new cv.Mat();
8530
8750
  const standardDeviation = new cv.Mat();
8531
8751
  try {
8532
8752
  cv.cvtColor(source, gray, cv.COLOR_RGBA2GRAY);
8533
- if (!cv.findChessboardCorners(gray, new cv.Size(board.columns, board.rows), corners, cv.CALIB_CB_ADAPTIVE_THRESH | cv.CALIB_CB_NORMALIZE_IMAGE)) return void 0;
8534
- cv.cornerSubPix(gray, corners, new cv.Size(11, 11), new cv.Size(-1, -1), new cv.TermCriteria(cv.TermCriteria_EPS | cv.TermCriteria_MAX_ITER, 30, .01));
8753
+ this.detectorFor(cv, board).detectBoard(gray, corners, ids);
8754
+ if (ids.rows < MINIMUM_CORNERS) return void 0;
8535
8755
  const points = readPointPairs(corners.data32F);
8756
+ const identifiers = Array.from(ids.data32S);
8536
8757
  cv.Laplacian(gray, laplacian, cv.CV_64F);
8537
8758
  cv.meanStdDev(laplacian, mean, standardDeviation);
8538
8759
  const sharpness = standardDeviation.doubleAt(0, 0) ** 2;
8539
8760
  const coverage = boardCoverage(points, frame.width, frame.height);
8761
+ const completeness = identifiers.length / (board.columns * board.rows);
8540
8762
  return {
8541
8763
  corners: points,
8542
- quality: clamp01(.7 * Math.min(1, coverage / .25) + .3 * Math.min(1, sharpness / 100)),
8764
+ ids: identifiers,
8765
+ quality: clamp01(.5 * Math.min(1, coverage / .25) + .3 * Math.min(1, sharpness / 100) + .2 * completeness),
8543
8766
  coverage,
8544
8767
  sharpness
8545
8768
  };
@@ -8547,6 +8770,7 @@
8547
8770
  standardDeviation.delete();
8548
8771
  mean.delete();
8549
8772
  laplacian.delete();
8773
+ ids.delete();
8550
8774
  corners.delete();
8551
8775
  gray.delete();
8552
8776
  source.delete();
@@ -8562,17 +8786,24 @@
8562
8786
  const translationVectors = new cv.MatVector();
8563
8787
  const cameraMatrix = cv.Mat.eye(3, 3, cv.CV_64F);
8564
8788
  const distortionCoefficients = cv.Mat.zeros(8, 1, cv.CV_64F);
8789
+ const standardDeviationsIntrinsics = new cv.Mat();
8790
+ const standardDeviationsExtrinsics = new cv.Mat();
8791
+ const perViewErrors = new cv.Mat();
8565
8792
  const retainedMats = [];
8566
8793
  try {
8567
- const worldPoints = chessboardWorldPoints(board);
8794
+ const worldPoints = this.worldPointsFor(cv, board);
8568
8795
  for (const sample of samples) {
8569
- const objectPoint = cv.matFromArray(sample.corners.length, 1, cv.CV_32FC3, worldPoints);
8796
+ const objectPoint = cv.matFromArray(sample.ids.length, 1, cv.CV_32FC3, sample.ids.flatMap((id) => worldPoints[id] ?? [
8797
+ 0,
8798
+ 0,
8799
+ 0
8800
+ ]));
8570
8801
  const imagePoint = cv.matFromArray(sample.corners.length, 1, cv.CV_32FC2, sample.corners.flatMap(({ x, y }) => [x, y]));
8571
8802
  retainedMats.push(objectPoint, imagePoint);
8572
8803
  objectPoints.push_back(objectPoint);
8573
8804
  imagePoints.push_back(imagePoint);
8574
8805
  }
8575
- const reprojectionErrorPx = cv.calibrateCamera(objectPoints, imagePoints, new cv.Size(imageWidth, imageHeight), cameraMatrix, distortionCoefficients, rotationVectors, translationVectors);
8806
+ const reprojectionErrorPx = cv.calibrateCameraExtended(objectPoints, imagePoints, new cv.Size(imageWidth, imageHeight), cameraMatrix, distortionCoefficients, rotationVectors, translationVectors, standardDeviationsIntrinsics, standardDeviationsExtrinsics, perViewErrors);
8576
8807
  const coefficientCount = distortionCoefficients.rows * distortionCoefficients.cols;
8577
8808
  return {
8578
8809
  intrinsicMatrix: readMatrix(cameraMatrix, 9),
@@ -8582,6 +8813,9 @@
8582
8813
  };
8583
8814
  } finally {
8584
8815
  for (const matrix of retainedMats) matrix.delete();
8816
+ perViewErrors.delete();
8817
+ standardDeviationsExtrinsics.delete();
8818
+ standardDeviationsIntrinsics.delete();
8585
8819
  distortionCoefficients.delete();
8586
8820
  cameraMatrix.delete();
8587
8821
  translationVectors.delete();
@@ -8590,7 +8824,62 @@
8590
8824
  objectPoints.delete();
8591
8825
  }
8592
8826
  }
8827
+ /**
8828
+ * Reprojects held-out views with the solved intrinsics.
8829
+ *
8830
+ * Each view's pose is solved first, from those intrinsics. That is not
8831
+ * circular: the pose describes where the board happened to be, which the
8832
+ * calibration never claimed to know, and every view of a planar target needs
8833
+ * one before its corners can be predicted at all. What the residual then
8834
+ * measures is whether the intrinsics account for corners they were not
8835
+ * fitted to.
8836
+ */
8837
+ async validate(samples, board, solution) {
8838
+ if (samples.length === 0) return 0;
8839
+ const cv = await getOpenCv();
8840
+ const worldPoints = this.worldPointsFor(cv, board);
8841
+ const cameraMatrix = cv.matFromArray(3, 3, cv.CV_64F, solution.intrinsicMatrix);
8842
+ const distortion = cv.matFromArray(Math.max(1, solution.distortionCoefficients.length), 1, cv.CV_64F, solution.distortionCoefficients.length > 0 ? solution.distortionCoefficients : [0]);
8843
+ let squared = 0;
8844
+ let counted = 0;
8845
+ const scratch = [cameraMatrix, distortion];
8846
+ try {
8847
+ for (const sample of samples) {
8848
+ const objectPoint = cv.matFromArray(sample.ids.length, 1, cv.CV_32FC3, sample.ids.flatMap((id) => worldPoints[id] ?? [
8849
+ 0,
8850
+ 0,
8851
+ 0
8852
+ ]));
8853
+ const imagePoint = cv.matFromArray(sample.corners.length, 1, cv.CV_32FC2, sample.corners.flatMap(({ x, y }) => [x, y]));
8854
+ const rotation = new cv.Mat();
8855
+ const translation = new cv.Mat();
8856
+ const projected = new cv.Mat();
8857
+ scratch.push(objectPoint, imagePoint, rotation, translation, projected);
8858
+ if (!cv.solvePnP(objectPoint, imagePoint, cameraMatrix, distortion, rotation, translation)) continue;
8859
+ cv.projectPoints(objectPoint, rotation, translation, cameraMatrix, distortion, projected);
8860
+ const predicted = readPointPairs(projected.data32F);
8861
+ for (let index = 0; index < sample.corners.length; index += 1) {
8862
+ const observed = sample.corners[index];
8863
+ const expected = predicted[index];
8864
+ if (!observed || !expected) continue;
8865
+ squared += (observed.x - expected.x) ** 2 + (observed.y - expected.y) ** 2;
8866
+ counted += 1;
8867
+ }
8868
+ }
8869
+ } finally {
8870
+ for (const matrix of scratch) matrix.delete();
8871
+ }
8872
+ return counted > 0 ? Math.sqrt(squared / counted) : 0;
8873
+ }
8593
8874
  };
8875
+ function readMatrix(matrix, expected) {
8876
+ const values = Array.from(matrix.data64F.slice(0, expected));
8877
+ if (values.length !== expected || values.some((value) => !Number.isFinite(value))) throw new Error(`OpenCV returned an invalid ${expected}-element matrix.`);
8878
+ return values;
8879
+ }
8880
+ function clamp01(value) {
8881
+ return Math.min(1, Math.max(0, value));
8882
+ }
8594
8883
  /**
8595
8884
  * Names the solver without constructing it, so that reading the backend
8596
8885
  * reporter — or loading the extension at all — never initializes the OpenCV
@@ -8632,19 +8921,6 @@
8632
8921
  const ys = points.map(({ y }) => y);
8633
8922
  return (Math.max(...xs) - Math.min(...xs)) * (Math.max(...ys) - Math.min(...ys)) / (width * height);
8634
8923
  }
8635
- function chessboardWorldPoints(board) {
8636
- const points = [];
8637
- for (let row = 0; row < board.rows; row += 1) for (let column = 0; column < board.columns; column += 1) points.push(column * board.squareSizeMeters, row * board.squareSizeMeters, 0);
8638
- return points;
8639
- }
8640
- function readMatrix(matrix, expected) {
8641
- const values = Array.from(matrix.data64F.slice(0, expected));
8642
- if (values.length !== expected || values.some((value) => !Number.isFinite(value))) throw new Error(`OpenCV returned an invalid ${expected}-element matrix.`);
8643
- return values;
8644
- }
8645
- function clamp01(value) {
8646
- return Math.min(1, Math.max(0, value));
8647
- }
8648
8924
  //#endregion
8649
8925
  //#region src/runtime-capability.ts
8650
8926
  var runtimeCapabilityKey = "kubohiroyaCameraCalibrationCapability";
@@ -8669,6 +8945,9 @@
8669
8945
  sampleCount: (cameraId) => host.sampleCount(cameraId),
8670
8946
  sampleQuality: (cameraId) => host.sampleQuality(cameraId),
8671
8947
  reprojectionErrorPx: (cameraId) => host.reprojectionErrorPx(cameraId),
8948
+ poseSpread: (cameraId) => host.poseSpread(cameraId),
8949
+ holdoutErrorPx: (cameraId) => host.holdoutErrorPx(cameraId),
8950
+ holdoutSampleCount: (cameraId) => host.holdoutSampleCount(cameraId),
8672
8951
  errorCode: (cameraId) => host.errorCode(cameraId),
8673
8952
  errorMessage: (cameraId) => host.errorMessage(cameraId),
8674
8953
  profileJson: (cameraId) => host.profileJson(cameraId)
@@ -8722,7 +9001,8 @@
8722
9001
  board: {
8723
9002
  columns: Scratch.Cast.toNumber(args.COLUMNS),
8724
9003
  rows: Scratch.Cast.toNumber(args.ROWS),
8725
- squareSizeMeters: Scratch.Cast.toNumber(args.SQUARE_METERS)
9004
+ squareSizeMeters: Scratch.Cast.toNumber(args.SQUARE_METERS),
9005
+ markerSizeMeters: Scratch.Cast.toNumber(args.MARKER_METERS)
8726
9006
  },
8727
9007
  maximumReprojectionErrorPx: Scratch.Cast.toNumber(args.MAX_ERROR_PX)
8728
9008
  });
@@ -8766,6 +9046,15 @@
8766
9046
  cameraCalibrationReprojectionError(args) {
8767
9047
  return this.controller.latestReprojectionError(normalizeId(args.CAMERA_ID));
8768
9048
  }
9049
+ cameraCalibrationPoseSpread(args) {
9050
+ return this.controller.poseSpread(normalizeId(args.CAMERA_ID));
9051
+ }
9052
+ cameraCalibrationHoldoutErrorPx(args) {
9053
+ return this.controller.latestHoldoutError(normalizeId(args.CAMERA_ID));
9054
+ }
9055
+ cameraCalibrationHoldoutSampleCount(args) {
9056
+ return this.controller.holdoutSampleCount(normalizeId(args.CAMERA_ID));
9057
+ }
8769
9058
  cameraCalibrationErrorCode(args) {
8770
9059
  return this.controller.errorCode(normalizeId(args.CAMERA_ID));
8771
9060
  }
@@ -8801,6 +9090,9 @@
8801
9090
  sampleCount: (cameraId) => this.controller.sampleCount(normalizeId(cameraId)),
8802
9091
  sampleQuality: (cameraId) => this.controller.latestSampleQuality(normalizeId(cameraId)),
8803
9092
  reprojectionErrorPx: (cameraId) => this.controller.latestReprojectionError(normalizeId(cameraId)),
9093
+ poseSpread: (cameraId) => this.controller.poseSpread(normalizeId(cameraId)),
9094
+ holdoutErrorPx: (cameraId) => this.controller.latestHoldoutError(normalizeId(cameraId)),
9095
+ holdoutSampleCount: (cameraId) => this.controller.holdoutSampleCount(normalizeId(cameraId)),
8804
9096
  errorCode: (cameraId) => this.controller.errorCode(normalizeId(cameraId)),
8805
9097
  errorMessage: (cameraId) => this.controller.errorMessage(normalizeId(cameraId)),
8806
9098
  profileJson: (cameraId) => this.controller.profileJson(normalizeId(cameraId))