@vitavision/overlays 0.2.1 → 0.4.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/dist/index.js CHANGED
@@ -50,21 +50,46 @@ const directed = {
50
50
  const CIRCLE_RADIUS = 5.5;
51
51
  /** Radius of the centre mark of a black circle, screen pixels; stroked, it reads as a filled dot. */
52
52
  const CENTRE_RADIUS = .8;
53
+ /** A white circle of a marker board: a hollow ring of radius 5.5 px. */
54
+ const circleWhite = {
55
+ paint: "line",
56
+ size: CIRCLE_RADIUS,
57
+ path: (x, y, unit) => circlePath(x, y, CIRCLE_RADIUS * unit)
58
+ };
59
+ /** A black circle: the same ring with a dot at its centre, so polarity is a shape and not a colour. */
60
+ const circleBlack = {
61
+ paint: "line",
62
+ size: CIRCLE_RADIUS,
63
+ path: (x, y, unit) => circlePath(x, y, CIRCLE_RADIUS * unit) + circlePath(x, y, CENTRE_RADIUS * unit)
64
+ };
65
+ /** Half-length of an excluded feature's strike-through cross, screen pixels. */
66
+ const EXCLUDED_REACH = 6;
67
+ /** Radius of a flagged feature's ring, screen pixels: outside the selection ring (about 9 px). */
68
+ const FLAG_RADIUS = 12;
53
69
  /** The marker names `TargetOverlay` uses, to pass to `PointSet`'s `markers`. */
54
70
  const TARGET_MARKERS = {
55
71
  /** Edge directions of a corner, from `angle` and `angle2`. */
56
72
  directed,
57
73
  /** A white matched circle. */
58
- "circle-white": {
74
+ "circle-white": circleWhite,
75
+ /** A black matched circle. */
76
+ "circle-black": circleBlack,
77
+ /** The cross through an excluded feature. */
78
+ excluded: {
59
79
  paint: "line",
60
- size: CIRCLE_RADIUS,
61
- path: (x, y, unit) => circlePath(x, y, CIRCLE_RADIUS * unit)
80
+ size: EXCLUDED_REACH,
81
+ role: "label",
82
+ path: (x, y, unit) => {
83
+ const a = EXCLUDED_REACH * unit;
84
+ return `M${round(x - a)} ${round(y - a)}l${round(2 * a)} ${round(2 * a)}M${round(x - a)} ${round(y + a)}l${round(2 * a)} ${round(-2 * a)}`;
85
+ }
62
86
  },
63
- /** A black matched circle. */
64
- "circle-black": {
87
+ /** The ring around a flagged feature. */
88
+ flagged: {
65
89
  paint: "line",
66
- size: CIRCLE_RADIUS,
67
- path: (x, y, unit) => circlePath(x, y, CIRCLE_RADIUS * unit) + circlePath(x, y, CENTRE_RADIUS * unit)
90
+ size: FLAG_RADIUS,
91
+ role: "label",
92
+ path: (x, y, unit) => circlePath(x, y, FLAG_RADIUS * unit)
68
93
  }
69
94
  };
70
95
  //#endregion
@@ -393,6 +418,95 @@ function edgeBitEllipses(bits) {
393
418
  opacity: BIT_OPACITY_MIN + .65 * Math.min(1, Math.max(0, bit.confidence))
394
419
  }));
395
420
  }
421
+ /**
422
+ * The ellipse of a 2×2 position covariance: `scale` standard deviations along each principal
423
+ * axis.
424
+ *
425
+ * The semi-axes are `scale · √λ` for the matrix's two eigenvalues `λ₁ ≥ λ₂`, and `angle` is the
426
+ * direction of the eigenvector of `λ₁` (radians, clockwise on screen, in `(-π/2, π/2]`). At
427
+ * `scale = 1` this is the 1σ ellipse: the curve `dᵀ Σ⁻¹ d = 1`.
428
+ *
429
+ * @param cov - The covariance `[xx, xy, yy]`, image pixels squared.
430
+ * @param scale - The gain applied to both semi-axes. Defaults to 1.
431
+ * @returns The ellipse, or `null` when the matrix is not finite and positive definite, or the
432
+ * scale is not a finite positive number: there is no ellipse to draw.
433
+ */
434
+ function covarianceEllipse(cov, scale = 1) {
435
+ const [xx, xy, yy] = cov;
436
+ if (!Number.isFinite(xx + xy + yy) || !(Number.isFinite(scale) && scale > 0)) return null;
437
+ const det = xx * yy - xy * xy;
438
+ if (!(xx > 0 && yy > 0 && det > 0)) return null;
439
+ const major = .5 * (xx + yy) + Math.hypot(.5 * (xx - yy), xy);
440
+ const minor = det / major;
441
+ const half = .5 * Math.atan2(2 * xy, xx - yy);
442
+ const angle = half <= -Math.PI / 2 ? half + Math.PI : half;
443
+ return {
444
+ rx: scale * Math.sqrt(major),
445
+ ry: scale * Math.sqrt(minor),
446
+ angle
447
+ };
448
+ }
449
+ /**
450
+ * The ellipses of the uncertainty layer: each corner's position covariance as a 1σ ellipse,
451
+ * both semi-axes multiplied by `scale`, centred on the corner and sharing its id, in the `model`
452
+ * role. A corner with no covariance, or one that is not positive definite, has none.
453
+ *
454
+ * @param corners - The corners.
455
+ * @param scale - The gain on the semi-axes. A detector's σ is a fraction of a pixel, so it is
456
+ * drawn magnified; print the gain beside the image ("ellipses ×40").
457
+ * @returns One ellipse per corner with a drawable covariance, in order.
458
+ */
459
+ function uncertaintyEllipses(corners, scale) {
460
+ const out = [];
461
+ for (const corner of corners) {
462
+ if (!corner.cov) continue;
463
+ const ellipse = covarianceEllipse(corner.cov, scale);
464
+ if (ellipse) out.push({
465
+ id: corner.id,
466
+ x: corner.x,
467
+ y: corner.y,
468
+ ...ellipse,
469
+ role: "model"
470
+ });
471
+ }
472
+ return out;
473
+ }
474
+ /** The feature points of a detection (corners, circles, ring centres) that carry `flag`, as one point each of `kind`. */
475
+ function markedPoints(detection, flag, kind) {
476
+ const out = [];
477
+ const add = (items) => {
478
+ for (const item of items ?? []) if (item[flag] === true) out.push({
479
+ id: item.id,
480
+ x: item.x,
481
+ y: item.y,
482
+ kind
483
+ });
484
+ };
485
+ add(detection.corners);
486
+ add(detection.circles);
487
+ add(detection.rings);
488
+ return out;
489
+ }
490
+ /**
491
+ * The strike-through points of the excluded features: a corner, circle or ring with
492
+ * `excluded` set gets one `excluded` glyph at its position. Markers carry no flags.
493
+ *
494
+ * @param detection - The detection.
495
+ * @returns One point per excluded feature, corners first, then circles, then rings.
496
+ */
497
+ function excludedPoints(detection) {
498
+ return markedPoints(detection, "excluded", "excluded");
499
+ }
500
+ /**
501
+ * The ring points of the flagged features: a corner, circle or ring with `flagged` set gets one
502
+ * `flagged` glyph at its position.
503
+ *
504
+ * @param detection - The detection.
505
+ * @returns One point per flagged feature, corners first, then circles, then rings.
506
+ */
507
+ function flaggedPoints(detection) {
508
+ return markedPoints(detection, "flagged", "flagged");
509
+ }
396
510
  //#endregion
397
511
  //#region src/TargetOverlay.tsx
398
512
  /**
@@ -412,6 +526,9 @@ function edgeBitEllipses(bits) {
412
526
  * | `circles` | `PointSet` | ring; a centre dot marks black |
413
527
  * | `rings` | `PointSet` + `EllipseSet` | fitted outer and inner ellipse, plus at the centre |
414
528
  * | `edgeBits` | `EllipseSet` | dot on the edge: solid for 1, dashed for 0, opacity from confidence |
529
+ * | corners' `cov` | `EllipseSet` | with `uncertainty`: the 1σ ellipse × the scale, in `model` |
530
+ * | `excluded` features | `PointSet` | the feature dimmed, a small cross through it |
531
+ * | `flagged` features | `PointSet` | a thin ring around the feature |
415
532
  */
416
533
  /** The ids of each part, to route a hovered or selected id to the layers that have it. */
417
534
  function idsByPart(detection) {
@@ -443,10 +560,16 @@ function dimPredicate(dimmed) {
443
560
  * - **Callbacks** report `{ id, part }` with the id from the detection. A press and a hover move
444
561
  * between layers (a corner, then the marker under it) without a flicker: the change is reported
445
562
  * once.
563
+ * - **Excluded and flagged features**: a corner, circle or ring with `excluded` is drawn dimmed
564
+ * with a small cross through it (a state, not a rejection); one with `flagged` has a thin ring
565
+ * around it (a mismatch with the master pattern, say). Both are drawn in the `label` role on a
566
+ * halo, compose with hover, selection and each other, and are not picked themselves.
567
+ * - **Uncertainty** (opt-in, `uncertainty`): each corner's covariance as a 1σ ellipse × the
568
+ * given scale, under the corners.
446
569
  *
447
570
  * The layers it renders carry their own accessible names ("Corners: 54 points, 0 selected").
448
571
  */
449
- function TargetOverlay({ detection, showEdges = true, showLabels = true, hoveredId, selectedIds, onHoverChange, onItemPress, dimmed, layerIdPrefix }) {
572
+ function TargetOverlay({ detection, showEdges = true, showLabels = true, hoveredId, selectedIds, onHoverChange, onItemPress, dimmed, uncertainty, layerIdPrefix }) {
450
573
  const nodes = useMemo(() => cornerNodes(detection), [detection]);
451
574
  const areas = useMemo(() => markerAreas(detection), [detection]);
452
575
  const circles = useMemo(() => circlePoints(detection), [detection]);
@@ -454,6 +577,8 @@ function TargetOverlay({ detection, showEdges = true, showLabels = true, hovered
454
577
  const ringPoints = useMemo(() => ringCentres(rings ?? []), [rings]);
455
578
  const ringShapes = useMemo(() => ringEllipses(rings ?? []), [rings]);
456
579
  const bits = useMemo(() => edgeBitEllipses(detection.edgeBits ?? []), [detection.edgeBits]);
580
+ const uncertaintyScale = uncertainty?.scale;
581
+ const covEllipses = useMemo(() => uncertaintyScale === void 0 ? [] : uncertaintyEllipses(detection.corners ?? [], uncertaintyScale), [detection.corners, uncertaintyScale]);
457
582
  const ids = useMemo(() => idsByPart(detection), [detection]);
458
583
  const selectedSet = useMemo(() => new Set(selectedIds ?? []), [selectedIds]);
459
584
  const selected = useMemo(() => {
@@ -465,7 +590,14 @@ function TargetOverlay({ detection, showEdges = true, showLabels = true, hovered
465
590
  ring: pick("ring")
466
591
  };
467
592
  }, [selectedSet, ids]);
468
- const isDimmed = useMemo(() => dimPredicate(dimmed), [dimmed]);
593
+ const userDimmed = useMemo(() => dimPredicate(dimmed), [dimmed]);
594
+ const excluded = useMemo(() => excludedPoints(detection), [detection]);
595
+ const flagged = useMemo(() => flaggedPoints(detection), [detection]);
596
+ const isDimmed = useMemo(() => {
597
+ if (excluded.length === 0) return userDimmed;
598
+ const ids = new Set(excluded.map((item) => item.id));
599
+ return (id) => ids.has(id) || (userDimmed?.(id) ?? false);
600
+ }, [excluded, userDimmed]);
469
601
  const [ownHover, setOwnHover] = useState(null);
470
602
  const hoverRef = useRef(null);
471
603
  const reportedRef = useRef(null);
@@ -555,6 +687,15 @@ function TargetOverlay({ detection, showEdges = true, showLabels = true, hovered
555
687
  label: "Rings"
556
688
  })
557
689
  ] }),
690
+ covEllipses.length > 0 && /* @__PURE__ */ jsx(EllipseSet$1, {
691
+ items: covEllipses,
692
+ role: "model",
693
+ hoveredId: hoverOf("corner"),
694
+ selectedIds: selected.corner,
695
+ dimmed: isDimmed,
696
+ pickable: false,
697
+ label: `Position uncertainty: 1σ ellipses ×${uncertaintyScale}`
698
+ }),
558
699
  hasCorners && /* @__PURE__ */ jsx(GridLayer, {
559
700
  nodes,
560
701
  markers: TARGET_MARKERS,
@@ -585,6 +726,24 @@ function TargetOverlay({ detection, showEdges = true, showLabels = true, hovered
585
726
  onItemPress: pressFrom("circle"),
586
727
  layerId: layerId("circles"),
587
728
  label: "Circles"
729
+ }),
730
+ excluded.length > 0 && /* @__PURE__ */ jsx(PointSet, {
731
+ items: excluded,
732
+ markers: TARGET_MARKERS,
733
+ labels: false,
734
+ dimmed: userDimmed,
735
+ pickable: false,
736
+ layerId: layerId("excluded"),
737
+ label: "Excluded features"
738
+ }),
739
+ flagged.length > 0 && /* @__PURE__ */ jsx(PointSet, {
740
+ items: flagged,
741
+ markers: TARGET_MARKERS,
742
+ labels: false,
743
+ dimmed: userDimmed,
744
+ pickable: false,
745
+ layerId: layerId("flagged"),
746
+ label: "Flagged features"
588
747
  })
589
748
  ] });
590
749
  }
@@ -646,6 +805,165 @@ function edgeBitsFromPuzzleboard(edges, corners, alignment, period = 501) {
646
805
  return out;
647
806
  }
648
807
  //#endregion
649
- export { EllipseSet, PUZZLEBOARD_PERIOD, TARGET_KINDS, TARGET_MARKERS, TargetOverlay, circlePoints, cornerGrid, cornerNodes, edgeBitEllipses, edgeBitsFromPuzzleboard, ellipsePath, gridEdges, gridKey, idByGrid, isLatticeKind, markerAreas, markerPolygons, ringCentres, ringEllipses };
808
+ //#region src/calibTargets.ts
809
+ /** The overlay kind of each calib-targets result kind. */
810
+ const OVERLAY_KIND = {
811
+ corners: "corners",
812
+ chessboard: "chessboard",
813
+ charuco: "charuco",
814
+ markerboard: "markerboard",
815
+ puzzleboard: "puzzleboard",
816
+ puzzlepole: "puzzleboard"
817
+ };
818
+ /** A covariance as `TargetCorner.cov`, or `undefined` when there is none or it is not finite. */
819
+ function covOf(cov) {
820
+ if (!cov) return void 0;
821
+ const { xx, xy, yy } = cov;
822
+ return Number.isFinite(xx + xy + yy) ? [
823
+ xx,
824
+ xy,
825
+ yy
826
+ ] : void 0;
827
+ }
828
+ /** A labelled corner as a `TargetCorner`, id `corner-<index>`; `(u, v)` becomes `(i, j)`. */
829
+ function labeledCorner(corner, index) {
830
+ const out = {
831
+ id: `corner-${index}`,
832
+ x: corner.position[0],
833
+ y: corner.position[1],
834
+ score: corner.score
835
+ };
836
+ if (corner.grid) {
837
+ out.i = corner.grid.u;
838
+ out.j = corner.grid.v;
839
+ }
840
+ const cov = covOf(corner.position_covariance);
841
+ if (cov) out.cov = cov;
842
+ return out;
843
+ }
844
+ /** A raw corner as a `TargetCorner` with both axis directions, id `corner-<index>`, labelled with its index. */
845
+ function rawCorner(corner, index) {
846
+ const out = {
847
+ id: `corner-${index}`,
848
+ x: corner.position[0],
849
+ y: corner.position[1],
850
+ score: corner.strength,
851
+ angle: corner.axes[0].angle,
852
+ angle2: corner.axes[1].angle,
853
+ label: String(index)
854
+ };
855
+ const cov = covOf(corner.position_covariance);
856
+ if (cov) out.cov = cov;
857
+ return out;
858
+ }
859
+ /** The markers with a projected quad, id `marker-<index>`, labelled with the dictionary id. */
860
+ function markersOf(markers) {
861
+ const out = [];
862
+ markers.forEach((marker, index) => {
863
+ if (!marker.corners_img) return;
864
+ out.push({
865
+ id: `marker-${index}`,
866
+ corners: marker.corners_img.flatMap(([x, y]) => [x, y]),
867
+ label: String(marker.id)
868
+ });
869
+ });
870
+ return out;
871
+ }
872
+ /**
873
+ * The matched circles of a marker board, id `circle-<index>` (index into `circle_matches`): at
874
+ * the matched candidate's centre, with the board's cell and printed polarity. An unmatched board
875
+ * circle is not drawn, nor is a candidate no board circle matched.
876
+ */
877
+ function circlesOf(diagnostics) {
878
+ const out = [];
879
+ diagnostics.circle_matches.forEach((match, index) => {
880
+ const candidate = match.matched_index === null ? void 0 : diagnostics.circle_candidates[match.matched_index];
881
+ if (!candidate) return;
882
+ out.push({
883
+ id: `circle-${index}`,
884
+ x: candidate.center_img[0],
885
+ y: candidate.center_img[1],
886
+ polarity: match.expected.polarity,
887
+ i: match.expected.cell.i,
888
+ j: match.expected.cell.j
889
+ });
890
+ });
891
+ return out;
892
+ }
893
+ /** The observed edges as `edgeBitsFromPuzzleboard` takes them: a nonzero bit is 1. */
894
+ function edgesOf(edges) {
895
+ return edges.map((edge) => ({
896
+ row: edge.row,
897
+ col: edge.col,
898
+ orientation: edge.orientation,
899
+ bit: edge.bit === 0 ? 0 : 1,
900
+ confidence: edge.confidence
901
+ }));
902
+ }
903
+ /**
904
+ * The `TargetDetection` of a calib-targets result.
905
+ *
906
+ * - **Kinds.** `chessboard`, `charuco`, `markerboard`, `puzzleboard` and raw `corners` map to the
907
+ * overlay kind of the same name; a `puzzlepole` is drawn as a `puzzleboard` lattice.
908
+ * - **Corners.** Positions pass through unchanged (calib-targets reports the centre of pixel `i`
909
+ * at `i`, as the overlay expects). A labelled corner's grid `(u, v)` becomes `(i, j)`, so a
910
+ * board draws its lattice and labels corners `i,j`. A raw corner draws its two axes (`angle`,
911
+ * `angle2`) and is labelled with its index; its `strength` is the `score`.
912
+ * - **Covariance.** A corner's `position_covariance`, when present and finite, becomes `cov`;
913
+ * `TargetOverlay` draws it with `uncertainty`.
914
+ * - **Markers** (ChArUco) are the quads of `corners_img`, labelled with the dictionary id; a
915
+ * marker without a projected quad is left out.
916
+ * - **Circles** (marker board, from `diagnostics`) are the board circles a candidate matched,
917
+ * at the candidate's centre with the board's cell and polarity.
918
+ * - **Edge bits** (PuzzleBoard, from `diagnostics`) are the observed edges placed through the
919
+ * alignment with `edgeBitsFromPuzzleboard`.
920
+ *
921
+ * Ids are `corner-<n>`, `marker-<n>` and `circle-<n>`, where `n` is the index into the result's
922
+ * `corners`, `markers` or `circle_matches`, so a hover or a press maps straight back to it.
923
+ *
924
+ * @param result - The result, tagged with its kind.
925
+ * @returns The detection for `TargetOverlay`. Parts with no items are left out.
926
+ */
927
+ function fromCalibTargets(result) {
928
+ const detection = { kind: OVERLAY_KIND[result.kind] };
929
+ if (result.kind === "corners") {
930
+ if (result.corners.length > 0) detection.corners = result.corners.map(rawCorner);
931
+ return detection;
932
+ }
933
+ if (!result.detection) return detection;
934
+ const corners = result.detection.corners.map(labeledCorner);
935
+ if (corners.length > 0) detection.corners = corners;
936
+ switch (result.kind) {
937
+ case "charuco": {
938
+ const markers = markersOf(result.detection.markers);
939
+ if (markers.length > 0) detection.markers = markers;
940
+ break;
941
+ }
942
+ case "markerboard": {
943
+ const circles = result.diagnostics ? circlesOf(result.diagnostics) : [];
944
+ if (circles.length > 0) detection.circles = circles;
945
+ break;
946
+ }
947
+ case "puzzleboard": {
948
+ if (!result.diagnostics) break;
949
+ const { matrix, translation } = result.detection.alignment;
950
+ const alignment = {
951
+ transform: {
952
+ a: matrix[0][0],
953
+ b: matrix[0][1],
954
+ c: matrix[1][0],
955
+ d: matrix[1][1]
956
+ },
957
+ translation: [translation[0], translation[1]]
958
+ };
959
+ const edgeBits = edgeBitsFromPuzzleboard(edgesOf(result.diagnostics.observed_edges), corners, alignment);
960
+ if (edgeBits.length > 0) detection.edgeBits = edgeBits;
961
+ break;
962
+ }
963
+ }
964
+ return detection;
965
+ }
966
+ //#endregion
967
+ export { EllipseSet, PUZZLEBOARD_PERIOD, TARGET_KINDS, TARGET_MARKERS, TargetOverlay, circlePoints, cornerGrid, cornerNodes, covarianceEllipse, edgeBitEllipses, edgeBitsFromPuzzleboard, ellipsePath, excludedPoints, flaggedPoints, fromCalibTargets, gridEdges, gridKey, idByGrid, isLatticeKind, markerAreas, markerPolygons, ringCentres, ringEllipses, uncertaintyEllipses };
650
968
 
651
969
  //# sourceMappingURL=index.js.map