@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.
@@ -37,6 +37,26 @@
37
37
  }
38
38
  ]
39
39
  },
40
+ {
41
+ "opcode": "cameraCalibrationHoldoutErrorPx",
42
+ "blockType": "REPORTER",
43
+ "arguments": [
44
+ {
45
+ "id": "CAMERA_ID",
46
+ "type": "STRING"
47
+ }
48
+ ]
49
+ },
50
+ {
51
+ "opcode": "cameraCalibrationHoldoutSampleCount",
52
+ "blockType": "REPORTER",
53
+ "arguments": [
54
+ {
55
+ "id": "CAMERA_ID",
56
+ "type": "STRING"
57
+ }
58
+ ]
59
+ },
40
60
  {
41
61
  "opcode": "cameraCalibrationJson",
42
62
  "blockType": "REPORTER",
@@ -61,6 +81,16 @@
61
81
  }
62
82
  ]
63
83
  },
84
+ {
85
+ "opcode": "cameraCalibrationPoseSpread",
86
+ "blockType": "REPORTER",
87
+ "arguments": [
88
+ {
89
+ "id": "CAMERA_ID",
90
+ "type": "STRING"
91
+ }
92
+ ]
93
+ },
64
94
  {
65
95
  "opcode": "cameraCalibrationReady",
66
96
  "blockType": "BOOLEAN",
@@ -181,6 +211,10 @@
181
211
  "id": "COLUMNS",
182
212
  "type": "NUMBER"
183
213
  },
214
+ {
215
+ "id": "MARKER_METERS",
216
+ "type": "NUMBER"
217
+ },
184
218
  {
185
219
  "id": "MAX_ERROR_PX",
186
220
  "type": "NUMBER"
@@ -9,7 +9,7 @@
9
9
  */
10
10
  import type { CalibrationBoard } from './types.js';
11
11
  export type CalibrationState = 'idle' | 'acquiring-camera' | 'sampling' | 'ready' | 'solving' | 'solved' | 'cancelling' | 'error';
12
- export type CalibrationErrorCode = '' | 'dependency-missing' | 'api-version-mismatch' | 'invalid-board' | 'camera-unavailable' | 'camera-ended' | 'resolution-mismatch' | 'capture-condition-mismatch' | 'board-not-found' | 'sample-low-quality' | 'sample-too-similar' | 'sample-limit' | 'sample-insufficient' | 'sample-failed' | 'solve-failed' | 'reprojection-too-high' | 'invalid-calibration' | 'credential-forbidden' | 'calibration-not-applicable' | 'not-calibrated' | 'publish-failed';
12
+ export type CalibrationErrorCode = '' | 'dependency-missing' | 'api-version-mismatch' | 'invalid-board' | 'camera-unavailable' | 'camera-ended' | 'resolution-mismatch' | 'capture-condition-mismatch' | 'board-not-found' | 'sample-low-quality' | 'sample-too-similar' | 'sample-limit' | 'sample-insufficient' | 'sample-poses-degenerate' | 'sample-failed' | 'solve-failed' | 'reprojection-too-high' | 'invalid-calibration' | 'credential-forbidden' | 'calibration-not-applicable' | 'not-calibrated' | 'publish-failed';
13
13
  export interface CalibrationStartOptions {
14
14
  cameraId: string;
15
15
  calibrationId: string;
@@ -1,8 +1,28 @@
1
- /** A printed chessboard target, measured by its inner corner grid. */
1
+ /**
2
+ * A ChArUco target: a chessboard with an ArUco marker in every light square.
3
+ *
4
+ * Measured by its inner corner grid, the same way a plain chessboard is, so
5
+ * `columns` and `rows` mean what they always meant. The board itself has one
6
+ * more square than that in each direction.
7
+ *
8
+ * The markers are what make a partly visible board usable. A plain chessboard
9
+ * has to be found whole, because nothing in it says which corner is which; here
10
+ * each marker names the corners around it, so a view that runs off the edge of
11
+ * the frame still contributes the corners it does show -- which are the ones
12
+ * near the edges, and those are what pin down the principal point and the
13
+ * distortion.
14
+ */
2
15
  export interface CalibrationBoard {
3
16
  columns: number;
4
17
  rows: number;
5
18
  squareSizeMeters: number;
19
+ /**
20
+ * The side of the marker printed inside a light square.
21
+ *
22
+ * Smaller than the square, so that white remains around it for the detector
23
+ * to separate it from the dark squares it touches.
24
+ */
25
+ markerSizeMeters: number;
6
26
  }
7
27
  /** One still image taken from the leased camera. */
8
28
  export interface CalibrationFrame {
@@ -14,9 +34,18 @@ export interface CalibrationCorner {
14
34
  x: number;
15
35
  y: number;
16
36
  }
17
- /** One accepted board view, kept until the session solves or is cancelled. */
37
+ /**
38
+ * One accepted board view, kept until the session solves or is cancelled.
39
+ *
40
+ * `corners` and `ids` are parallel: a view need not show the whole board, so
41
+ * the identity of each corner is carried rather than implied by its position in
42
+ * the array. An id is the corner's index in the board's own inner-corner grid,
43
+ * counted along the rows.
44
+ */
18
45
  export interface CalibrationSample {
19
46
  corners: CalibrationCorner[];
47
+ /** Which inner corner each entry of `corners` is. Same length as `corners`. */
48
+ ids: number[];
20
49
  quality: number;
21
50
  coverage: number;
22
51
  sharpness: number;
@@ -38,6 +67,21 @@ export interface CalibrationSolveResult {
38
67
  distortionCoefficients: number[];
39
68
  reprojectionErrorPx: number;
40
69
  }
70
+ /**
71
+ * How a solution fares on views it was not fitted to.
72
+ *
73
+ * `reprojectionErrorPx` from a solve measures how well the answer reproduces
74
+ * the very samples that produced it, which is a statement about fit and not
75
+ * about the camera. With few samples for the number of parameters, an
76
+ * overfitted solution scores well on exactly that measure. These are the views
77
+ * held back from the fit, so their error is the one that can disagree.
78
+ */
79
+ export interface CalibrationValidationResult {
80
+ /** RMS reprojection error over the held-out views, in pixels. */
81
+ reprojectionErrorPx: number;
82
+ /** How many views were held back. Zero means nothing was validated. */
83
+ sampleCount: number;
84
+ }
41
85
  /**
42
86
  * The solver seam. Everything above this interface is arithmetic-free control
43
87
  * flow, so tests drive the whole procedure without loading OpenCV.
@@ -46,6 +90,14 @@ export interface CalibrationBackendPort {
46
90
  readonly name: string;
47
91
  captureSample(frame: CalibrationFrame, board: CalibrationBoard): Promise<CalibrationSample | undefined>;
48
92
  solve(samples: readonly CalibrationSample[], board: CalibrationBoard, imageWidth: number, imageHeight: number): Promise<CalibrationSolveResult>;
93
+ /**
94
+ * Reprojects views the solve did not use, with the solution it produced.
95
+ *
96
+ * Each view needs its own pose, solved from the given intrinsics -- the pose
97
+ * is not what is being checked, so fitting it here is not circular. What is
98
+ * checked is whether the intrinsics predict corners they never saw.
99
+ */
100
+ validate(samples: readonly CalibrationSample[], board: CalibrationBoard, solution: CalibrationSolveResult): Promise<number>;
49
101
  }
50
102
  /**
51
103
  * Creates the solver on first use. The name is available without creating it so
@@ -56,6 +56,28 @@ export interface CameraCalibrationCapabilityV1 {
56
56
  * alone will report an uncalibrated camera as a flawless one.
57
57
  */
58
58
  reprojectionErrorPx(cameraId: string): number;
59
+ /**
60
+ * How varied the angles of the collected samples are.
61
+ *
62
+ * Zero means every sample was taken from the same direction, and a set like
63
+ * that cannot be solved from: focal length and distance stay inseparable,
64
+ * because a small board seen close and a large one seen far away make the
65
+ * same image. `solve` refuses below the required spread rather than
66
+ * returning a calibration whose reprojection error looks fine.
67
+ */
68
+ poseSpread(cameraId: string): number;
69
+ /**
70
+ * RMS reprojection over the views the solve was not fitted to.
71
+ *
72
+ * `reprojectionErrorPx` measures how well the answer reproduces the samples
73
+ * that produced it, which is a statement about fit. This one is the same
74
+ * measure over views held back, so the two disagreeing is the signal: the set
75
+ * was too small, or too alike, to support the answer. Meaningless when
76
+ * `holdoutSampleCount` is zero.
77
+ */
78
+ holdoutErrorPx(cameraId: string): number;
79
+ /** How many views were held back. Zero means nothing was validated. */
80
+ holdoutSampleCount(cameraId: string): number;
59
81
  errorCode(cameraId: string): CalibrationErrorCode;
60
82
  /** The refusal in full, including the detail behind the code. */
61
83
  errorMessage(cameraId: string): string;
@@ -23,6 +23,9 @@ export function createRuntimeCapability(host) {
23
23
  sampleCount: (cameraId) => host.sampleCount(cameraId),
24
24
  sampleQuality: (cameraId) => host.sampleQuality(cameraId),
25
25
  reprojectionErrorPx: (cameraId) => host.reprojectionErrorPx(cameraId),
26
+ poseSpread: (cameraId) => host.poseSpread(cameraId),
27
+ holdoutErrorPx: (cameraId) => host.holdoutErrorPx(cameraId),
28
+ holdoutSampleCount: (cameraId) => host.holdoutSampleCount(cameraId),
26
29
  errorCode: (cameraId) => host.errorCode(cameraId),
27
30
  errorMessage: (cameraId) => host.errorMessage(cameraId),
28
31
  profileJson: (cameraId) => host.profileJson(cameraId)
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@kubohiroya/turbowarp-camera-calibration",
3
- "version": "0.4.0",
3
+ "version": "0.6.0",
4
4
  "description": "A TurboWarp extension that calibrates a shared Camera Source camera and publishes its intrinsic calibration profile.",
5
5
  "author": "Hiroya Kubo <hiroya@cuc.ac.jp>",
6
6
  "license": "MPL-2.0",
@@ -4,8 +4,8 @@
4
4
  {
5
5
  "opcode": "startCameraCalibration",
6
6
  "blockType": "COMMAND",
7
- "text": "start camera [CAMERA_ID] calibration [CALIBRATION_ID] board [COLUMNS] by [ROWS] square [SQUARE_METERS] m max error [MAX_ERROR_PX] px",
8
- "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.",
7
+ "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",
8
+ "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.",
9
9
  "arguments": {
10
10
  "CAMERA_ID": {
11
11
  "type": "STRING",
@@ -27,6 +27,10 @@
27
27
  "type": "NUMBER",
28
28
  "defaultValue": 0.025
29
29
  },
30
+ "MARKER_METERS": {
31
+ "type": "NUMBER",
32
+ "defaultValue": 0.018
33
+ },
30
34
  "MAX_ERROR_PX": {
31
35
  "type": "NUMBER",
32
36
  "defaultValue": 1.5
@@ -192,6 +196,42 @@
192
196
  }
193
197
  }
194
198
  },
199
+ {
200
+ "opcode": "cameraCalibrationPoseSpread",
201
+ "blockType": "REPORTER",
202
+ "text": "camera [CAMERA_ID] calibration pose spread",
203
+ "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.",
204
+ "arguments": {
205
+ "CAMERA_ID": {
206
+ "type": "STRING",
207
+ "defaultValue": "default"
208
+ }
209
+ }
210
+ },
211
+ {
212
+ "opcode": "cameraCalibrationHoldoutErrorPx",
213
+ "blockType": "REPORTER",
214
+ "text": "camera [CAMERA_ID] calibration holdout error px",
215
+ "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.",
216
+ "arguments": {
217
+ "CAMERA_ID": {
218
+ "type": "STRING",
219
+ "defaultValue": "default"
220
+ }
221
+ }
222
+ },
223
+ {
224
+ "opcode": "cameraCalibrationHoldoutSampleCount",
225
+ "blockType": "REPORTER",
226
+ "text": "camera [CAMERA_ID] calibration holdout sample count",
227
+ "description": "Returns how many samples were held back from the solve. Zero means nothing was validated, so the holdout error says nothing.",
228
+ "arguments": {
229
+ "CAMERA_ID": {
230
+ "type": "STRING",
231
+ "defaultValue": "default"
232
+ }
233
+ }
234
+ },
195
235
  {
196
236
  "opcode": "cameraCalibrationErrorCode",
197
237
  "blockType": "REPORTER",
@@ -33,6 +33,7 @@ export type CalibrationErrorCode =
33
33
  | 'sample-too-similar'
34
34
  | 'sample-limit'
35
35
  | 'sample-insufficient'
36
+ | 'sample-poses-degenerate'
36
37
  | 'sample-failed'
37
38
  | 'solve-failed'
38
39
  | 'reprojection-too-high'
@@ -24,6 +24,7 @@ import type {
24
24
  CalibrationStartOptions,
25
25
  CalibrationState
26
26
  } from './contract.js';
27
+ import {MINIMUM_POSE_SPREAD, poseSpread} from './pose.js';
27
28
  import type {
28
29
  CalibrationBackendFactory,
29
30
  CalibrationBackendPort,
@@ -36,6 +37,21 @@ const MAXIMUM_SAMPLES = 40;
36
37
  const MINIMUM_SAMPLE_QUALITY = 0.2;
37
38
  const MINIMUM_NORMALIZED_NOVELTY = 0.015;
38
39
 
40
+ /**
41
+ * The share of samples held back from the fit, to be reprojected afterwards.
42
+ *
43
+ * A solve's own reprojection error says how well the answer reproduces the
44
+ * samples that produced it. With few samples for the number of parameters an
45
+ * overfitted answer scores well on exactly that, so some views are kept out of
46
+ * the fit and scored separately. The two agreeing is the evidence; the two
47
+ * disagreeing says the set was too small or too alike.
48
+ *
49
+ * Never at the cost of the minimum: if holding views back would leave fewer
50
+ * than MINIMUM_SAMPLES to fit, fewer are held back, and none at all rather than
51
+ * a fit that is weaker than the one the operator was promised.
52
+ */
53
+ const HOLDOUT_FRACTION = 0.2;
54
+
39
55
  /** Codes a profile validation can produce, and therefore can clear. */
40
56
  const PROFILE_ERROR_CODES: ReadonlySet<string> = new Set([
41
57
  'invalid-calibration',
@@ -74,6 +90,8 @@ class CameraCalibration {
74
90
  private sessionSampleCount = 0;
75
91
  private sampleQuality = 0;
76
92
  private reprojectionError = 0;
93
+ private holdoutError = 0;
94
+ private holdoutCount = 0;
77
95
  private calibrationState: CalibrationState = 'idle';
78
96
  private calibrationErrorCode: CalibrationErrorCode = '';
79
97
  private calibrationErrorMessage = '';
@@ -148,6 +166,8 @@ class CameraCalibration {
148
166
  this.sessionSampleCount = 0;
149
167
  this.sampleQuality = 0;
150
168
  this.reprojectionError = 0;
169
+ this.holdoutError = 0;
170
+ this.holdoutCount = 0;
151
171
  this.calibrationState = 'ready';
152
172
  }
153
173
 
@@ -173,6 +193,18 @@ class CameraCalibration {
173
193
  if (this.samples.length < MINIMUM_SAMPLES) {
174
194
  this.reject('sample-insufficient', `At least ${MINIMUM_SAMPLES} accepted samples are required.`);
175
195
  }
196
+ // Refused here rather than at capture time. A sample taken at a tilt some
197
+ // other sample already has is not a wasted sample -- it still constrains
198
+ // the principal point and the distortion. What cannot be solved from is a
199
+ // whole set that never varied, and that is only knowable once the set is
200
+ // complete.
201
+ const spread = poseSpread(this.samples, this.session.board);
202
+ if (spread < MINIMUM_POSE_SPREAD) {
203
+ this.reject(
204
+ 'sample-poses-degenerate',
205
+ `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.`
206
+ );
207
+ }
176
208
  const solving = this.solveSession(this.operation);
177
209
  this.solving = solving;
178
210
  const clear = () => {
@@ -199,6 +231,8 @@ class CameraCalibration {
199
231
  this.sessionSampleCount = 0;
200
232
  this.sampleQuality = 0;
201
233
  this.reprojectionError = 0;
234
+ this.holdoutError = 0;
235
+ this.holdoutCount = 0;
202
236
  this.calibrationState = 'idle';
203
237
  this.clearError();
204
238
  }
@@ -316,6 +350,22 @@ class CameraCalibration {
316
350
  return this.reprojectionError;
317
351
  }
318
352
 
353
+ /** RMS reprojection over views the fit never saw. Zero when none were held. */
354
+ public latestHoldoutError(): number {
355
+ return this.holdoutError;
356
+ }
357
+
358
+ /** How many views were held back. Zero means nothing was validated. */
359
+ public holdoutSampleCount(): number {
360
+ return this.holdoutCount;
361
+ }
362
+
363
+ /** How varied the collected tilts are. Zero until a second sample lands. */
364
+ public poseSpread(): number {
365
+ const session = this.session;
366
+ return session ? poseSpread(this.samples, session.board) : 0;
367
+ }
368
+
319
369
  public errorCode(): CalibrationErrorCode {
320
370
  return this.calibrationErrorCode;
321
371
  }
@@ -369,9 +419,12 @@ class CameraCalibration {
369
419
  }
370
420
  if (operation !== this.operation) return;
371
421
  if (!sample) this.reject('board-not-found', 'The complete chessboard was not found.');
372
- const expectedCorners = session.board.columns * session.board.rows;
422
+ // A view need not show the whole board. The markers name each corner, so a
423
+ // board running off the edge of the frame still contributes what it shows,
424
+ // and those corners are near the image border -- which is where the
425
+ // principal point and the distortion are decided.
373
426
  if (
374
- sample.corners.length !== expectedCorners ||
427
+ sample.corners.length !== sample.ids.length ||
375
428
  !Number.isFinite(sample.quality) ||
376
429
  sample.quality < MINIMUM_SAMPLE_QUALITY
377
430
  ) {
@@ -399,20 +452,25 @@ class CameraCalibration {
399
452
  const lease = this.lease;
400
453
  if (!session || !lease) return;
401
454
  this.calibrationState = 'solving';
455
+ const {fitted, heldOut} = splitForValidation(this.samples);
402
456
  let solution;
457
+ let holdoutError = 0;
403
458
  try {
404
459
  const backend = await this.resolveBackend();
405
460
  solution = await backend.solve(
406
- [...this.samples],
461
+ fitted,
407
462
  session.board,
408
463
  session.imageWidth,
409
464
  session.imageHeight
410
465
  );
466
+ holdoutError = await backend.validate(heldOut, session.board, solution);
411
467
  } catch (error) {
412
468
  this.fail('solve-failed', error);
413
469
  }
414
470
  if (operation !== this.operation) return;
415
471
  this.reprojectionError = solution.reprojectionErrorPx;
472
+ this.holdoutError = holdoutError;
473
+ this.holdoutCount = heldOut.length;
416
474
  if (
417
475
  !Number.isFinite(this.reprojectionError) ||
418
476
  this.reprojectionError > session.maximumReprojectionErrorPx
@@ -590,6 +648,18 @@ export class CameraCalibrationController {
590
648
  return this.existing(cameraId)?.latestReprojectionError() ?? 0;
591
649
  }
592
650
 
651
+ public poseSpread(cameraId: string): number {
652
+ return this.existing(cameraId)?.poseSpread() ?? 0;
653
+ }
654
+
655
+ public latestHoldoutError(cameraId: string): number {
656
+ return this.existing(cameraId)?.latestHoldoutError() ?? 0;
657
+ }
658
+
659
+ public holdoutSampleCount(cameraId: string): number {
660
+ return this.existing(cameraId)?.holdoutSampleCount() ?? 0;
661
+ }
662
+
593
663
  public errorCode(cameraId: string): CalibrationErrorCode {
594
664
  return this.existing(cameraId)?.errorCode() ?? '';
595
665
  }
@@ -658,6 +728,15 @@ function normalizeStartOptions(options: CalibrationStartOptions): CalibrationSta
658
728
  ) {
659
729
  throw new Error('square size must be within (0, 1] meter.');
660
730
  }
731
+ // The marker has to leave white around it inside its square, or the detector
732
+ // cannot separate it from the dark squares it touches.
733
+ if (
734
+ !Number.isFinite(options.board.markerSizeMeters) ||
735
+ options.board.markerSizeMeters <= 0 ||
736
+ options.board.markerSizeMeters >= options.board.squareSizeMeters
737
+ ) {
738
+ throw new Error('marker size must be greater than zero and smaller than the square size.');
739
+ }
661
740
  if (
662
741
  !Number.isFinite(options.maximumReprojectionErrorPx) ||
663
742
  options.maximumReprojectionErrorPx <= 0 ||
@@ -668,7 +747,12 @@ function normalizeStartOptions(options: CalibrationStartOptions): CalibrationSta
668
747
  return {
669
748
  cameraId: identifier(options.cameraId, 'camera ID'),
670
749
  calibrationId: identifier(options.calibrationId, 'calibration ID'),
671
- board: {columns, rows, squareSizeMeters: options.board.squareSizeMeters},
750
+ board: {
751
+ columns,
752
+ rows,
753
+ squareSizeMeters: options.board.squareSizeMeters,
754
+ markerSizeMeters: options.board.markerSizeMeters
755
+ },
672
756
  maximumReprojectionErrorPx: options.maximumReprojectionErrorPx
673
757
  };
674
758
  }
@@ -702,6 +786,37 @@ function integerInRange(value: number, minimum: number, maximum: number, label:
702
786
  return value;
703
787
  }
704
788
 
789
+ /**
790
+ * Divides the samples into the ones fitted and the ones kept back.
791
+ *
792
+ * Spread evenly through the order they were captured rather than taken from
793
+ * the end. Samples near each other in time are the ones most likely to share a
794
+ * position, so a hold-out cut from the tail can be the least independent part
795
+ * of the set -- which would make the check read better than it should.
796
+ */
797
+ function splitForValidation(samples: readonly CalibrationSample[]): {
798
+ fitted: CalibrationSample[];
799
+ heldOut: CalibrationSample[];
800
+ } {
801
+ const holdOut = Math.min(
802
+ Math.floor(samples.length * HOLDOUT_FRACTION),
803
+ samples.length - MINIMUM_SAMPLES
804
+ );
805
+ if (holdOut < 1) return {fitted: [...samples], heldOut: []};
806
+ const step = samples.length / holdOut;
807
+ const chosen = new Set(
808
+ Array.from({length: holdOut}, (_, index) =>
809
+ Math.min(samples.length - 1, Math.floor(index * step + step / 2))
810
+ )
811
+ );
812
+ const fitted: CalibrationSample[] = [];
813
+ const heldOut: CalibrationSample[] = [];
814
+ samples.forEach((sample, index) => {
815
+ (chosen.has(index) ? heldOut : fitted).push(sample);
816
+ });
817
+ return {fitted, heldOut};
818
+ }
819
+
705
820
  function isPromise(value: Promise<void> | undefined): value is Promise<void> {
706
821
  return value !== undefined;
707
822
  }