@kubohiroya/turbowarp-camera-calibration 0.3.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.
@@ -42,19 +42,14 @@
42
42
  docsURI: "https://kubohiroya.github.io/turbowarp-camera-calibration/",
43
43
  blockIconURI: "data:image/svg+xml;base64,PHN2ZyB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIHZpZXdCb3g9IjAgMCA0OCA0OCI+PHJlY3QgeD0iNCIgeT0iNCIgd2lkdGg9IjQwIiBoZWlnaHQ9IjQwIiByeD0iNCIgZmlsbD0iI2ZmZmZmZiIgc3Ryb2tlPSIjNEM5N0ZGIiBzdHJva2Utd2lkdGg9IjIiLz48ZyBmaWxsPSIjNEM5N0ZGIj48cmVjdCB4PSI2IiB5PSI2IiB3aWR0aD0iOSIgaGVpZ2h0PSI5Ii8+PHJlY3QgeD0iMjQiIHk9IjYiIHdpZHRoPSI5IiBoZWlnaHQ9IjkiLz48cmVjdCB4PSIxNSIgeT0iMTUiIHdpZHRoPSI5IiBoZWlnaHQ9IjkiLz48cmVjdCB4PSIzMyIgeT0iMTUiIHdpZHRoPSI5IiBoZWlnaHQ9IjkiLz48cmVjdCB4PSI2IiB5PSIyNCIgd2lkdGg9IjkiIGhlaWdodD0iOSIvPjxyZWN0IHg9IjI0IiB5PSIyNCIgd2lkdGg9IjkiIGhlaWdodD0iOSIvPjxyZWN0IHg9IjE1IiB5PSIzMyIgd2lkdGg9IjkiIGhlaWdodD0iOSIvPjxyZWN0IHg9IjMzIiB5PSIzMyIgd2lkdGg9IjkiIGhlaWdodD0iOSIvPjwvZz48L3N2Zz4="
44
44
  };
45
- //#endregion
46
- //#region config/feature-flags.ts
47
- var overrides = globalThis.__TWCC_FEATURE_FLAGS__;
48
- var featureFlags = Object.freeze({ cameraCalibrationV1: overrides?.cameraCalibrationV1 === true });
49
45
  var block_definitions_default = {
50
46
  extensionName: "TurboWarp-Camera-Calibration",
51
47
  blocks: [
52
48
  {
53
49
  "opcode": "startCameraCalibration",
54
- "feature": "cameraCalibrationV1",
55
50
  "blockType": "COMMAND",
56
- "text": "start camera [CAMERA_ID] calibration [CALIBRATION_ID] board [COLUMNS] by [ROWS] square [SQUARE_METERS] m max error [MAX_ERROR_PX] px",
57
- "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.",
58
53
  "arguments": {
59
54
  "CAMERA_ID": {
60
55
  "type": "STRING",
@@ -76,6 +71,10 @@
76
71
  "type": "NUMBER",
77
72
  "defaultValue": .025
78
73
  },
74
+ "MARKER_METERS": {
75
+ "type": "NUMBER",
76
+ "defaultValue": .018
77
+ },
79
78
  "MAX_ERROR_PX": {
80
79
  "type": "NUMBER",
81
80
  "defaultValue": 1.5
@@ -84,7 +83,6 @@
84
83
  },
85
84
  {
86
85
  "opcode": "addCameraCalibrationSample",
87
- "feature": "cameraCalibrationV1",
88
86
  "blockType": "COMMAND",
89
87
  "text": "add calibration sample for camera [CAMERA_ID]",
90
88
  "description": "Detects the complete board in the current shared frame and retains it when its quality and its novelty against the retained samples both pass.",
@@ -95,7 +93,6 @@
95
93
  },
96
94
  {
97
95
  "opcode": "solveCameraCalibration",
98
- "feature": "cameraCalibrationV1",
99
96
  "blockType": "COMMAND",
100
97
  "text": "solve calibration for camera [CAMERA_ID]",
101
98
  "description": "Solves the intrinsic matrix and distortion coefficients from at least eight accepted samples, then releases the camera lease. No external pose is produced.",
@@ -106,7 +103,6 @@
106
103
  },
107
104
  {
108
105
  "opcode": "cancelCameraCalibration",
109
- "feature": "cameraCalibrationV1",
110
106
  "blockType": "COMMAND",
111
107
  "text": "cancel calibration for camera [CAMERA_ID]",
112
108
  "description": "Releases the camera lease and the retained samples while preserving the last validated profile.",
@@ -117,7 +113,6 @@
117
113
  },
118
114
  {
119
115
  "opcode": "cleanupCameraCalibration",
120
- "feature": "cameraCalibrationV1",
121
116
  "blockType": "COMMAND",
122
117
  "text": "cleanup calibration for camera [CAMERA_ID]",
123
118
  "description": "Releases the session and also clears the in-memory calibration profile for that camera.",
@@ -128,7 +123,6 @@
128
123
  },
129
124
  {
130
125
  "opcode": "publishCameraCalibration",
131
- "feature": "cameraCalibrationV1",
132
126
  "blockType": "COMMAND",
133
127
  "text": "publish calibration profile for camera [CAMERA_ID]",
134
128
  "description": "Registers the solved profile with Camera Source, which owns the profile contract. Reports an explicit error when Camera Source is absent, speaks another contract version, or has no profile to publish.",
@@ -139,7 +133,6 @@
139
133
  },
140
134
  {
141
135
  "opcode": "importCameraCalibration",
142
- "feature": "cameraCalibrationV1",
143
136
  "blockType": "COMMAND",
144
137
  "text": "import calibration profile [JSON] for camera [CAMERA_ID]",
145
138
  "description": "Imports a calibration profile after schema, credential, and applicability checks. Pre-migration profiles are accepted and their world pose is dropped rather than reinterpreted.",
@@ -156,7 +149,6 @@
156
149
  },
157
150
  {
158
151
  "opcode": "cameraCalibrationJsonValid",
159
- "feature": "cameraCalibrationV1",
160
152
  "blockType": "BOOLEAN",
161
153
  "text": "calibration profile [JSON] valid for camera [CAMERA_ID]?",
162
154
  "description": "Validates a profile and records why it failed, without replacing the stored profile.",
@@ -173,7 +165,6 @@
173
165
  },
174
166
  {
175
167
  "opcode": "cameraCalibrationReady",
176
- "feature": "cameraCalibrationV1",
177
168
  "blockType": "BOOLEAN",
178
169
  "text": "camera [CAMERA_ID] calibration ready?",
179
170
  "description": "Reports whether a fixed-resolution session for that camera can accept a sample or solve.",
@@ -184,7 +175,6 @@
184
175
  },
185
176
  {
186
177
  "opcode": "cameraCalibrationState",
187
- "feature": "always",
188
178
  "blockType": "REPORTER",
189
179
  "text": "camera calibration state [CAMERA_ID]",
190
180
  "description": "Returns the calibration session state for one shared Camera Source camera: idle, acquiring-camera, sampling, ready, solving, solved, cancelling, or error. A camera that has never been calibrated reports idle.",
@@ -195,7 +185,6 @@
195
185
  },
196
186
  {
197
187
  "opcode": "cameraCalibrationBackend",
198
- "feature": "cameraCalibrationV1",
199
188
  "blockType": "REPORTER",
200
189
  "text": "camera calibration backend",
201
190
  "description": "Returns the pinned solver identifier. Reading it does not load the solver.",
@@ -203,7 +192,6 @@
203
192
  },
204
193
  {
205
194
  "opcode": "cameraCalibrationSampleCount",
206
- "feature": "cameraCalibrationV1",
207
195
  "blockType": "REPORTER",
208
196
  "text": "camera [CAMERA_ID] calibration sample count",
209
197
  "description": "Returns the accepted sample count for the current or last solved session.",
@@ -214,7 +202,6 @@
214
202
  },
215
203
  {
216
204
  "opcode": "cameraCalibrationSampleQuality",
217
- "feature": "cameraCalibrationV1",
218
205
  "blockType": "REPORTER",
219
206
  "text": "camera [CAMERA_ID] calibration sample quality",
220
207
  "description": "Returns the latest accepted sample's combined board coverage and sharpness score, from zero to one.",
@@ -225,7 +212,6 @@
225
212
  },
226
213
  {
227
214
  "opcode": "cameraCalibrationReprojectionError",
228
- "feature": "cameraCalibrationV1",
229
215
  "blockType": "REPORTER",
230
216
  "text": "camera [CAMERA_ID] calibration reprojection error px",
231
217
  "description": "Returns the RMS reprojection error in pixels for the latest solve or imported profile.",
@@ -234,9 +220,38 @@
234
220
  "defaultValue": "default"
235
221
  } }
236
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
+ },
237
253
  {
238
254
  "opcode": "cameraCalibrationErrorCode",
239
- "feature": "cameraCalibrationV1",
240
255
  "blockType": "REPORTER",
241
256
  "text": "camera [CAMERA_ID] calibration error code",
242
257
  "description": "Returns a stable code for dependency, board, camera, sample, solve, reprojection, profile, or publication errors, or an empty string.",
@@ -247,7 +262,6 @@
247
262
  },
248
263
  {
249
264
  "opcode": "cameraCalibrationError",
250
- "feature": "cameraCalibrationV1",
251
265
  "blockType": "REPORTER",
252
266
  "text": "camera [CAMERA_ID] calibration error",
253
267
  "description": "Returns the detailed calibration diagnostic for that camera.",
@@ -258,7 +272,6 @@
258
272
  },
259
273
  {
260
274
  "opcode": "cameraCalibrationJson",
261
- "feature": "cameraCalibrationV1",
262
275
  "blockType": "REPORTER",
263
276
  "text": "camera [CAMERA_ID] calibration profile JSON",
264
277
  "description": "Exports the stored intrinsic profile for that camera, or an empty string when none exists.",
@@ -657,11 +670,93 @@
657
670
  return value;
658
671
  }
659
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
660
741
  //#region src/calibration/controller.ts
661
742
  var MINIMUM_SAMPLES = 8;
662
743
  var MAXIMUM_SAMPLES = 40;
663
744
  var MINIMUM_SAMPLE_QUALITY = .2;
664
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;
665
760
  /** Codes a profile validation can produce, and therefore can clear. */
666
761
  var PROFILE_ERROR_CODES = /* @__PURE__ */ new Set([
667
762
  "invalid-calibration",
@@ -682,6 +777,8 @@
682
777
  this.sessionSampleCount = 0;
683
778
  this.sampleQuality = 0;
684
779
  this.reprojectionError = 0;
780
+ this.holdoutError = 0;
781
+ this.holdoutCount = 0;
685
782
  this.calibrationState = "idle";
686
783
  this.calibrationErrorCode = "";
687
784
  this.calibrationErrorMessage = "";
@@ -741,6 +838,8 @@
741
838
  this.sessionSampleCount = 0;
742
839
  this.sampleQuality = 0;
743
840
  this.reprojectionError = 0;
841
+ this.holdoutError = 0;
842
+ this.holdoutCount = 0;
744
843
  this.calibrationState = "ready";
745
844
  }
746
845
  addSample() {
@@ -758,6 +857,8 @@
758
857
  if (this.solving) return this.solving;
759
858
  if (!this.session || !this.lease || this.calibrationState !== "ready") throw new Error(`Camera ${this.cameraId} calibration is not ready to solve.`);
760
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.`);
761
862
  const solving = this.solveSession(this.operation);
762
863
  this.solving = solving;
763
864
  const clear = () => {
@@ -783,6 +884,8 @@
783
884
  this.sessionSampleCount = 0;
784
885
  this.sampleQuality = 0;
785
886
  this.reprojectionError = 0;
887
+ this.holdoutError = 0;
888
+ this.holdoutCount = 0;
786
889
  this.calibrationState = "idle";
787
890
  this.clearError();
788
891
  }
@@ -856,6 +959,19 @@
856
959
  latestReprojectionError() {
857
960
  return this.reprojectionError;
858
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
+ }
859
975
  errorCode() {
860
976
  return this.calibrationErrorCode;
861
977
  }
@@ -892,8 +1008,7 @@
892
1008
  }
893
1009
  if (operation !== this.operation) return;
894
1010
  if (!sample) this.reject("board-not-found", "The complete chessboard was not found.");
895
- const expectedCorners = session.board.columns * session.board.rows;
896
- 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}.`);
897
1012
  const accepted = sample;
898
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.");
899
1014
  this.samples.push(accepted);
@@ -907,14 +1022,20 @@
907
1022
  const lease = this.lease;
908
1023
  if (!session || !lease) return;
909
1024
  this.calibrationState = "solving";
1025
+ const { fitted, heldOut } = splitForValidation(this.samples);
910
1026
  let solution;
1027
+ let holdoutError = 0;
911
1028
  try {
912
- 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);
913
1032
  } catch (error) {
914
1033
  this.fail("solve-failed", error);
915
1034
  }
916
1035
  if (operation !== this.operation) return;
917
1036
  this.reprojectionError = solution.reprojectionErrorPx;
1037
+ this.holdoutError = holdoutError;
1038
+ this.holdoutCount = heldOut.length;
918
1039
  if (!Number.isFinite(this.reprojectionError) || this.reprojectionError > session.maximumReprojectionErrorPx) {
919
1040
  this.calibrationState = "ready";
920
1041
  this.reject("reprojection-too-high", `Reprojection RMS ${this.reprojectionError} px exceeds ${session.maximumReprojectionErrorPx} px.`);
@@ -1056,6 +1177,15 @@
1056
1177
  latestReprojectionError(cameraId) {
1057
1178
  return this.existing(cameraId)?.latestReprojectionError() ?? 0;
1058
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
+ }
1059
1189
  errorCode(cameraId) {
1060
1190
  return this.existing(cameraId)?.errorCode() ?? "";
1061
1191
  }
@@ -1103,6 +1233,7 @@
1103
1233
  const columns = integerInRange(options.board.columns, 3, 20, "columns");
1104
1234
  const rows = integerInRange(options.board.rows, 3, 20, "rows");
1105
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.");
1106
1237
  if (!Number.isFinite(options.maximumReprojectionErrorPx) || options.maximumReprojectionErrorPx <= 0 || options.maximumReprojectionErrorPx > 100) throw new Error("maximum reprojection error must be within (0, 100] px.");
1107
1238
  return {
1108
1239
  cameraId: identifier(options.cameraId, "camera ID"),
@@ -1110,7 +1241,8 @@
1110
1241
  board: {
1111
1242
  columns,
1112
1243
  rows,
1113
- squareSizeMeters: options.board.squareSizeMeters
1244
+ squareSizeMeters: options.board.squareSizeMeters,
1245
+ markerSizeMeters: options.board.markerSizeMeters
1114
1246
  },
1115
1247
  maximumReprojectionErrorPx: options.maximumReprojectionErrorPx
1116
1248
  };
@@ -1134,6 +1266,32 @@
1134
1266
  if (!Number.isInteger(value) || value < minimum || value > maximum) throw new Error(`${label} must be an integer from ${minimum} to ${maximum}.`);
1135
1267
  return value;
1136
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
+ }
1137
1295
  function isPromise(value) {
1138
1296
  return value !== void 0;
1139
1297
  }
@@ -8522,7 +8680,15 @@
8522
8680
  * The single pinned production solver. The version is part of the identifier so
8523
8681
  * that a project can record which build produced a profile.
8524
8682
  */
8525
- 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;
8526
8692
  var openCvPromise;
8527
8693
  /**
8528
8694
  * Detects the chessboard and solves the camera intrinsics with OpenCV.
@@ -8534,6 +8700,38 @@
8534
8700
  var OpenCvChessboardCalibrationBackend = class {
8535
8701
  constructor() {
8536
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;
8537
8735
  }
8538
8736
  async captureSample(frame, board) {
8539
8737
  const cv = await getOpenCv();
@@ -8546,21 +8744,25 @@
8546
8744
  const source = cv.imread(canvas);
8547
8745
  const gray = new cv.Mat();
8548
8746
  const corners = new cv.Mat();
8747
+ const ids = new cv.Mat();
8549
8748
  const laplacian = new cv.Mat();
8550
8749
  const mean = new cv.Mat();
8551
8750
  const standardDeviation = new cv.Mat();
8552
8751
  try {
8553
8752
  cv.cvtColor(source, gray, cv.COLOR_RGBA2GRAY);
8554
- 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;
8555
- 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;
8556
8755
  const points = readPointPairs(corners.data32F);
8756
+ const identifiers = Array.from(ids.data32S);
8557
8757
  cv.Laplacian(gray, laplacian, cv.CV_64F);
8558
8758
  cv.meanStdDev(laplacian, mean, standardDeviation);
8559
8759
  const sharpness = standardDeviation.doubleAt(0, 0) ** 2;
8560
8760
  const coverage = boardCoverage(points, frame.width, frame.height);
8761
+ const completeness = identifiers.length / (board.columns * board.rows);
8561
8762
  return {
8562
8763
  corners: points,
8563
- 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),
8564
8766
  coverage,
8565
8767
  sharpness
8566
8768
  };
@@ -8568,6 +8770,7 @@
8568
8770
  standardDeviation.delete();
8569
8771
  mean.delete();
8570
8772
  laplacian.delete();
8773
+ ids.delete();
8571
8774
  corners.delete();
8572
8775
  gray.delete();
8573
8776
  source.delete();
@@ -8583,17 +8786,24 @@
8583
8786
  const translationVectors = new cv.MatVector();
8584
8787
  const cameraMatrix = cv.Mat.eye(3, 3, cv.CV_64F);
8585
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();
8586
8792
  const retainedMats = [];
8587
8793
  try {
8588
- const worldPoints = chessboardWorldPoints(board);
8794
+ const worldPoints = this.worldPointsFor(cv, board);
8589
8795
  for (const sample of samples) {
8590
- 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
+ ]));
8591
8801
  const imagePoint = cv.matFromArray(sample.corners.length, 1, cv.CV_32FC2, sample.corners.flatMap(({ x, y }) => [x, y]));
8592
8802
  retainedMats.push(objectPoint, imagePoint);
8593
8803
  objectPoints.push_back(objectPoint);
8594
8804
  imagePoints.push_back(imagePoint);
8595
8805
  }
8596
- 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);
8597
8807
  const coefficientCount = distortionCoefficients.rows * distortionCoefficients.cols;
8598
8808
  return {
8599
8809
  intrinsicMatrix: readMatrix(cameraMatrix, 9),
@@ -8603,6 +8813,9 @@
8603
8813
  };
8604
8814
  } finally {
8605
8815
  for (const matrix of retainedMats) matrix.delete();
8816
+ perViewErrors.delete();
8817
+ standardDeviationsExtrinsics.delete();
8818
+ standardDeviationsIntrinsics.delete();
8606
8819
  distortionCoefficients.delete();
8607
8820
  cameraMatrix.delete();
8608
8821
  translationVectors.delete();
@@ -8611,7 +8824,62 @@
8611
8824
  objectPoints.delete();
8612
8825
  }
8613
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
+ }
8614
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
+ }
8615
8883
  /**
8616
8884
  * Names the solver without constructing it, so that reading the backend
8617
8885
  * reporter — or loading the extension at all — never initializes the OpenCV
@@ -8653,19 +8921,6 @@
8653
8921
  const ys = points.map(({ y }) => y);
8654
8922
  return (Math.max(...xs) - Math.min(...xs)) * (Math.max(...ys) - Math.min(...ys)) / (width * height);
8655
8923
  }
8656
- function chessboardWorldPoints(board) {
8657
- const points = [];
8658
- 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);
8659
- return points;
8660
- }
8661
- function readMatrix(matrix, expected) {
8662
- const values = Array.from(matrix.data64F.slice(0, expected));
8663
- if (values.length !== expected || values.some((value) => !Number.isFinite(value))) throw new Error(`OpenCV returned an invalid ${expected}-element matrix.`);
8664
- return values;
8665
- }
8666
- function clamp01(value) {
8667
- return Math.min(1, Math.max(0, value));
8668
- }
8669
8924
  //#endregion
8670
8925
  //#region src/runtime-capability.ts
8671
8926
  var runtimeCapabilityKey = "kubohiroyaCameraCalibrationCapability";
@@ -8690,6 +8945,9 @@
8690
8945
  sampleCount: (cameraId) => host.sampleCount(cameraId),
8691
8946
  sampleQuality: (cameraId) => host.sampleQuality(cameraId),
8692
8947
  reprojectionErrorPx: (cameraId) => host.reprojectionErrorPx(cameraId),
8948
+ poseSpread: (cameraId) => host.poseSpread(cameraId),
8949
+ holdoutErrorPx: (cameraId) => host.holdoutErrorPx(cameraId),
8950
+ holdoutSampleCount: (cameraId) => host.holdoutSampleCount(cameraId),
8693
8951
  errorCode: (cameraId) => host.errorCode(cameraId),
8694
8952
  errorMessage: (cameraId) => host.errorMessage(cameraId),
8695
8953
  profileJson: (cameraId) => host.profileJson(cameraId)
@@ -8700,8 +8958,6 @@
8700
8958
  //#region src/extension.ts
8701
8959
  var blockDefinitions = block_definitions_default.blocks;
8702
8960
  var defaultCameraId = "default";
8703
- /** The state reported for a camera that has no calibration session. */
8704
- var IDLE_CALIBRATION_STATE = "idle";
8705
8961
  function normalizeId(value, fallback = defaultCameraId) {
8706
8962
  return String(value ?? "").trim() || fallback;
8707
8963
  }
@@ -8718,14 +8974,13 @@
8718
8974
  this.controller.cleanupAll();
8719
8975
  };
8720
8976
  this.runtime = options.runtime ?? Scratch.vm.runtime;
8721
- this.enabled = options.enabled ?? featureFlags.cameraCalibrationV1;
8722
8977
  const nowMilliseconds = options.nowMilliseconds;
8723
8978
  this.controller = new CameraCalibrationController({
8724
8979
  runtime: this.runtime,
8725
8980
  backend: options.backend ?? openCvBackendFactory,
8726
8981
  ...nowMilliseconds ? { nowMilliseconds } : {}
8727
8982
  });
8728
- if (this.enabled) this.runtime[runtimeCapabilityKey] = this.createCapability();
8983
+ this.runtime[runtimeCapabilityKey] = this.createCapability();
8729
8984
  this.runtime.on?.("PROJECT_STOP_ALL", this.handleProjectBoundary);
8730
8985
  this.runtime.on?.("PROJECT_LOADED", this.handleProjectBoundary);
8731
8986
  this.runtime.on?.("RUNTIME_DISPOSED", this.handleDisposed);
@@ -8736,28 +8991,26 @@
8736
8991
  name: Scratch.translate(block_definitions_default.extensionName),
8737
8992
  docsURI: extensionConfig.docsURI,
8738
8993
  blockIconURI: extensionConfig.blockIconURI,
8739
- blocks: blockDefinitions.filter((block) => this.blockEnabled(block.feature)).map((block) => this.toScratchBlock(block))
8994
+ blocks: blockDefinitions.map((block) => this.toScratchBlock(block))
8740
8995
  };
8741
8996
  }
8742
8997
  async startCameraCalibration(args) {
8743
- this.requireEnabled();
8744
8998
  await this.controller.start({
8745
8999
  cameraId: normalizeId(args.CAMERA_ID),
8746
9000
  calibrationId: Scratch.Cast.toString(args.CALIBRATION_ID).trim(),
8747
9001
  board: {
8748
9002
  columns: Scratch.Cast.toNumber(args.COLUMNS),
8749
9003
  rows: Scratch.Cast.toNumber(args.ROWS),
8750
- squareSizeMeters: Scratch.Cast.toNumber(args.SQUARE_METERS)
9004
+ squareSizeMeters: Scratch.Cast.toNumber(args.SQUARE_METERS),
9005
+ markerSizeMeters: Scratch.Cast.toNumber(args.MARKER_METERS)
8751
9006
  },
8752
9007
  maximumReprojectionErrorPx: Scratch.Cast.toNumber(args.MAX_ERROR_PX)
8753
9008
  });
8754
9009
  }
8755
9010
  async addCameraCalibrationSample(args) {
8756
- this.requireEnabled();
8757
9011
  await this.controller.addSample(normalizeId(args.CAMERA_ID));
8758
9012
  }
8759
9013
  async solveCameraCalibration(args) {
8760
- this.requireEnabled();
8761
9014
  await this.controller.solve(normalizeId(args.CAMERA_ID));
8762
9015
  }
8763
9016
  async cancelCameraCalibration(args) {
@@ -8767,44 +9020,49 @@
8767
9020
  await this.controller.cleanup(normalizeId(args.CAMERA_ID));
8768
9021
  }
8769
9022
  async publishCameraCalibration(args) {
8770
- this.requireEnabled();
8771
9023
  await this.controller.publishProfile(normalizeId(args.CAMERA_ID));
8772
9024
  }
8773
9025
  async importCameraCalibration(args) {
8774
- this.requireEnabled();
8775
9026
  await this.controller.importProfile(normalizeId(args.CAMERA_ID), Scratch.Cast.toString(args.JSON));
8776
9027
  }
8777
9028
  cameraCalibrationJsonValid(args) {
8778
- if (!this.enabled) return false;
8779
9029
  return this.controller.validateProfile(normalizeId(args.CAMERA_ID), Scratch.Cast.toString(args.JSON));
8780
9030
  }
8781
9031
  cameraCalibrationReady(args) {
8782
- return this.enabled && this.controller.ready(normalizeId(args.CAMERA_ID));
9032
+ return this.controller.ready(normalizeId(args.CAMERA_ID));
8783
9033
  }
8784
9034
  cameraCalibrationState(args = {}) {
8785
- if (!this.enabled) return IDLE_CALIBRATION_STATE;
8786
9035
  return this.controller.state(normalizeId(args.CAMERA_ID));
8787
9036
  }
8788
9037
  cameraCalibrationBackend() {
8789
- return this.enabled ? this.controller.backend() : "";
9038
+ return this.controller.backend();
8790
9039
  }
8791
9040
  cameraCalibrationSampleCount(args) {
8792
- return this.enabled ? this.controller.sampleCount(normalizeId(args.CAMERA_ID)) : 0;
9041
+ return this.controller.sampleCount(normalizeId(args.CAMERA_ID));
8793
9042
  }
8794
9043
  cameraCalibrationSampleQuality(args) {
8795
- return this.enabled ? this.controller.latestSampleQuality(normalizeId(args.CAMERA_ID)) : 0;
9044
+ return this.controller.latestSampleQuality(normalizeId(args.CAMERA_ID));
8796
9045
  }
8797
9046
  cameraCalibrationReprojectionError(args) {
8798
- return this.enabled ? this.controller.latestReprojectionError(normalizeId(args.CAMERA_ID)) : 0;
9047
+ return this.controller.latestReprojectionError(normalizeId(args.CAMERA_ID));
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));
8799
9057
  }
8800
9058
  cameraCalibrationErrorCode(args) {
8801
- return this.enabled ? this.controller.errorCode(normalizeId(args.CAMERA_ID)) : "";
9059
+ return this.controller.errorCode(normalizeId(args.CAMERA_ID));
8802
9060
  }
8803
9061
  cameraCalibrationError(args) {
8804
- return this.enabled ? this.controller.errorMessage(normalizeId(args.CAMERA_ID)) : "";
9062
+ return this.controller.errorMessage(normalizeId(args.CAMERA_ID));
8805
9063
  }
8806
9064
  cameraCalibrationJson(args) {
8807
- return this.enabled ? this.controller.profileJson(normalizeId(args.CAMERA_ID)) : "";
9065
+ return this.controller.profileJson(normalizeId(args.CAMERA_ID));
8808
9066
  }
8809
9067
  /**
8810
9068
  * The procedure, named rather than reached through opcodes.
@@ -8832,18 +9090,15 @@
8832
9090
  sampleCount: (cameraId) => this.controller.sampleCount(normalizeId(cameraId)),
8833
9091
  sampleQuality: (cameraId) => this.controller.latestSampleQuality(normalizeId(cameraId)),
8834
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)),
8835
9096
  errorCode: (cameraId) => this.controller.errorCode(normalizeId(cameraId)),
8836
9097
  errorMessage: (cameraId) => this.controller.errorMessage(normalizeId(cameraId)),
8837
9098
  profileJson: (cameraId) => this.controller.profileJson(normalizeId(cameraId))
8838
9099
  });
8839
9100
  return this.capability;
8840
9101
  }
8841
- blockEnabled(feature) {
8842
- return feature === "always" || this.enabled;
8843
- }
8844
- requireEnabled() {
8845
- if (!this.enabled) throw new Error("Camera calibration v1 is disabled. Enable it before the project starts.");
8846
- }
8847
9102
  toScratchBlock(block) {
8848
9103
  return {
8849
9104
  opcode: block.opcode,