@scoriiu/fenshot 0.1.4 → 0.1.6
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/LICENSE +1 -1
- package/README.md +2 -2
- package/dist/detect.d.ts +24 -0
- package/dist/detect.js +167 -0
- package/dist/index.d.ts +1 -1
- package/dist/index.js +1 -1
- package/dist/recognize.d.ts +23 -6
- package/dist/recognize.js +86 -29
- package/package.json +2 -2
package/LICENSE
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
MIT License
|
|
2
2
|
|
|
3
|
-
Copyright (c) 2026 SORTINO LABS S.R.L. (
|
|
3
|
+
Copyright (c) 2026 SORTINO LABS S.R.L. (kibitzo.com)
|
|
4
4
|
|
|
5
5
|
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
6
|
of this software and associated documentation files (the "Software"), to deal
|
package/README.md
CHANGED
|
@@ -10,7 +10,7 @@ Live demo: **[fenshot.com](https://fenshot.com/)**
|
|
|
10
10
|
|
|
11
11
|
Chessboard recognition that runs entirely in the browser: finds the board in any screenshot (chess.com, Lichess, book diagrams, reddit lightboxes), reads the position with a CNN tile classifier, and returns a FEN with per-tile confidence. No server, no account, nothing leaves the page.
|
|
12
12
|
|
|
13
|
-
Extracted from the position-import feature of [
|
|
13
|
+
Extracted from the position-import feature of [kibitzo.com](https://kibitzo.com?ref=fenshot-npm), where it runs in production.
|
|
14
14
|
|
|
15
15
|
## Install
|
|
16
16
|
|
|
@@ -108,7 +108,7 @@ The model is reproducible, not just downloadable: the full training pipeline (as
|
|
|
108
108
|
|
|
109
109
|
- Board detection algorithm: [Elucidation/tensorflow_chessbot](https://github.com/Elucidation/tensorflow_chessbot) (MIT).
|
|
110
110
|
- Piece set and board theme assets used as training input: lichess ([lila](https://github.com/lichess-org/lila), free licenses). The corpus also includes other sites' themes (including chess.com) so the recognizer reads their screenshots too; those assets are training input only and are never redistributed, only trained weights ship.
|
|
111
|
-
- Built and maintained by [
|
|
111
|
+
- Built and maintained by [kibitzo.com](https://kibitzo.com?ref=fenshot-npm).
|
|
112
112
|
|
|
113
113
|
## License
|
|
114
114
|
|
package/dist/detect.d.ts
CHANGED
|
@@ -44,4 +44,28 @@ export interface GrayImage {
|
|
|
44
44
|
* the alignment with higher mean confidence (recognize.ts).
|
|
45
45
|
*/
|
|
46
46
|
export declare function snapCorners(img: GrayImage, box: BoardCorners): BoardCorners;
|
|
47
|
+
/**
|
|
48
|
+
* How much a box looks like a chessboard, whatever stands on it: the
|
|
49
|
+
* Pearson correlation (-1..1) between the 64 tile backgrounds and the
|
|
50
|
+
* chessboard colouring. A box on a real board scores high in any theme;
|
|
51
|
+
* a box that hangs off the board, or sits at the wrong scale, mixes page
|
|
52
|
+
* background into the tiles and scores low. Patches average over a few
|
|
53
|
+
* pixels, so hatched dark squares read as their mean grey.
|
|
54
|
+
*/
|
|
55
|
+
export declare function boardness(img: GrayImage, box: BoardCorners): number;
|
|
56
|
+
/**
|
|
57
|
+
* Second look: boards the plain search misses or misplaces because the
|
|
58
|
+
* board itself is full of edges. Hatched dark squares (printed diagrams,
|
|
59
|
+
* chess.com's newspaper board) put more gradient energy inside the
|
|
60
|
+
* squares than on the grid lines, and marbled or low-contrast boards can
|
|
61
|
+
* slide the grid one tile diagonally, which keeps the colouring and so
|
|
62
|
+
* slips past repairParity. On a blurred copy the hatching melts to grey
|
|
63
|
+
* and the grid lines dominate again.
|
|
64
|
+
*
|
|
65
|
+
* Returns the boxes found on blurred copies, each with its grid-snapped
|
|
66
|
+
* variant, that are square and look like a board, without duplicates and
|
|
67
|
+
* without anything in `known`. They are CANDIDATES: the caller lets the
|
|
68
|
+
* tile classifier choose (recognize.ts).
|
|
69
|
+
*/
|
|
70
|
+
export declare function findBlurredBoardCandidates(img: GrayImage, known?: BoardCorners[]): BoardCorners[];
|
|
47
71
|
export declare function findChessboardCorners(img: GrayImage): BoardCorners | null;
|
package/dist/detect.js
CHANGED
|
@@ -376,6 +376,173 @@ function repairParity(img, box) {
|
|
|
376
376
|
}
|
|
377
377
|
return best;
|
|
378
378
|
}
|
|
379
|
+
/** Box blur (edges clamped), two separable passes. */
|
|
380
|
+
function boxBlur(img, radius) {
|
|
381
|
+
const { width: w, height: h, data } = img;
|
|
382
|
+
const span = 2 * radius + 1;
|
|
383
|
+
const tmp = new Float32Array(w * h);
|
|
384
|
+
const out = new Float32Array(w * h);
|
|
385
|
+
for (let y = 0; y < h; y++) {
|
|
386
|
+
const row = y * w;
|
|
387
|
+
let acc = 0;
|
|
388
|
+
for (let x = -radius; x <= radius; x++)
|
|
389
|
+
acc += data[row + Math.min(w - 1, Math.max(0, x))];
|
|
390
|
+
for (let x = 0; x < w; x++) {
|
|
391
|
+
tmp[row + x] = acc / span;
|
|
392
|
+
acc += data[row + Math.min(w - 1, x + radius + 1)] - data[row + Math.max(0, x - radius)];
|
|
393
|
+
}
|
|
394
|
+
}
|
|
395
|
+
for (let x = 0; x < w; x++) {
|
|
396
|
+
let acc = 0;
|
|
397
|
+
for (let y = -radius; y <= radius; y++)
|
|
398
|
+
acc += tmp[Math.min(h - 1, Math.max(0, y)) * w + x];
|
|
399
|
+
for (let y = 0; y < h; y++) {
|
|
400
|
+
out[y * w + x] = acc / span;
|
|
401
|
+
acc += tmp[Math.min(h - 1, y + radius + 1) * w + x] - tmp[Math.max(0, y - radius) * w + x];
|
|
402
|
+
}
|
|
403
|
+
}
|
|
404
|
+
return { data: out, width: w, height: h };
|
|
405
|
+
}
|
|
406
|
+
/** Where in a tile its background shows: near the four corners, which
|
|
407
|
+
* pieces (drawn centered) do not reach. */
|
|
408
|
+
const BACKGROUND_SAMPLES = [
|
|
409
|
+
[0.16, 0.16],
|
|
410
|
+
[0.84, 0.16],
|
|
411
|
+
[0.16, 0.84],
|
|
412
|
+
[0.84, 0.84],
|
|
413
|
+
];
|
|
414
|
+
/** Background brightness of one tile: the median of small patches at its
|
|
415
|
+
* corners. Null when the tile lies mostly outside the image. */
|
|
416
|
+
function tileBackground(img, x, y, tw, th, patch) {
|
|
417
|
+
const vals = [];
|
|
418
|
+
for (const [fx, fy] of BACKGROUND_SAMPLES) {
|
|
419
|
+
const cx = Math.round(x + fx * tw);
|
|
420
|
+
const cy = Math.round(y + fy * th);
|
|
421
|
+
let sum = 0;
|
|
422
|
+
let n = 0;
|
|
423
|
+
for (let py = Math.max(0, cy - patch); py <= Math.min(img.height - 1, cy + patch); py++) {
|
|
424
|
+
for (let px = Math.max(0, cx - patch); px <= Math.min(img.width - 1, cx + patch); px++) {
|
|
425
|
+
sum += img.data[py * img.width + px];
|
|
426
|
+
n++;
|
|
427
|
+
}
|
|
428
|
+
}
|
|
429
|
+
if (n)
|
|
430
|
+
vals.push(sum / n);
|
|
431
|
+
}
|
|
432
|
+
return vals.length < 2 ? null : median(vals);
|
|
433
|
+
}
|
|
434
|
+
/**
|
|
435
|
+
* How much a box looks like a chessboard, whatever stands on it: the
|
|
436
|
+
* Pearson correlation (-1..1) between the 64 tile backgrounds and the
|
|
437
|
+
* chessboard colouring. A box on a real board scores high in any theme;
|
|
438
|
+
* a box that hangs off the board, or sits at the wrong scale, mixes page
|
|
439
|
+
* background into the tiles and scores low. Patches average over a few
|
|
440
|
+
* pixels, so hatched dark squares read as their mean grey.
|
|
441
|
+
*/
|
|
442
|
+
export function boardness(img, box) {
|
|
443
|
+
const tw = (box.x1 - box.x0) / 8;
|
|
444
|
+
const th = (box.y1 - box.y0) / 8;
|
|
445
|
+
if (tw < 6 || th < 6)
|
|
446
|
+
return -1;
|
|
447
|
+
const patch = Math.max(1, Math.round(tw / 10));
|
|
448
|
+
const backgrounds = [];
|
|
449
|
+
const colours = [];
|
|
450
|
+
for (let r = 0; r < 8; r++) {
|
|
451
|
+
for (let c = 0; c < 8; c++) {
|
|
452
|
+
const bg = tileBackground(img, box.x0 + c * tw, box.y0 + r * th, tw, th, patch);
|
|
453
|
+
if (bg === null)
|
|
454
|
+
continue;
|
|
455
|
+
backgrounds.push(bg);
|
|
456
|
+
colours.push((r + c) % 2 === 0 ? 1 : -1);
|
|
457
|
+
}
|
|
458
|
+
}
|
|
459
|
+
if (backgrounds.length < 48)
|
|
460
|
+
return -1;
|
|
461
|
+
const meanBg = backgrounds.reduce((a, b) => a + b, 0) / backgrounds.length;
|
|
462
|
+
const meanCol = colours.reduce((a, b) => a + b, 0) / colours.length;
|
|
463
|
+
let cov = 0;
|
|
464
|
+
let varBg = 0;
|
|
465
|
+
let varCol = 0;
|
|
466
|
+
for (let i = 0; i < backgrounds.length; i++) {
|
|
467
|
+
cov += (backgrounds[i] - meanBg) * (colours[i] - meanCol);
|
|
468
|
+
varBg += (backgrounds[i] - meanBg) ** 2;
|
|
469
|
+
varCol += (colours[i] - meanCol) ** 2;
|
|
470
|
+
}
|
|
471
|
+
return varBg > 0 && varCol > 0 ? cov / Math.sqrt(varBg * varCol) : 0;
|
|
472
|
+
}
|
|
473
|
+
/** Blur radii for the second look. The right one depends on the hatch
|
|
474
|
+
* period, which depends on scale: measured on the benchmark, 1 to 4 px
|
|
475
|
+
* between them find hatched boards from 110 to 200 dpi and chess.com's
|
|
476
|
+
* newspaper board; 6 px added nothing. */
|
|
477
|
+
const BLUR_RADII = [1, 2, 3, 4];
|
|
478
|
+
/** Above this size the second look runs at half resolution: tiles are
|
|
479
|
+
* large enough to stand the coarser grid, and a page with no board on it
|
|
480
|
+
* (the extension's whole-tab scan) costs a quarter as much. Halving is
|
|
481
|
+
* itself a 2x2 blur, so the radii shrink with it. */
|
|
482
|
+
const HALF_RES_ABOVE = 1000;
|
|
483
|
+
const HALF_RES_BLUR_RADII = [0, 1, 2];
|
|
484
|
+
/** A second-look box must be square within this fraction... */
|
|
485
|
+
const MAX_ASPECT_ERROR = 0.08;
|
|
486
|
+
/** ...and look like a board at least this much (boardness). */
|
|
487
|
+
const MIN_BOARDNESS = 0.5;
|
|
488
|
+
function sameBox(a, b) {
|
|
489
|
+
return (Math.abs(a.x0 - b.x0) <= 1 && Math.abs(a.y0 - b.y0) <= 1 && Math.abs(a.x1 - b.x1) <= 1 && Math.abs(a.y1 - b.y1) <= 1);
|
|
490
|
+
}
|
|
491
|
+
/** Half-size copy, each pixel the mean of a 2x2 block. */
|
|
492
|
+
function halve(img) {
|
|
493
|
+
const w = img.width >> 1;
|
|
494
|
+
const h = img.height >> 1;
|
|
495
|
+
const out = new Float32Array(w * h);
|
|
496
|
+
for (let y = 0; y < h; y++) {
|
|
497
|
+
const top = 2 * y * img.width;
|
|
498
|
+
const bottom = top + img.width;
|
|
499
|
+
for (let x = 0; x < w; x++) {
|
|
500
|
+
out[y * w + x] = (img.data[top + 2 * x] + img.data[top + 2 * x + 1] + img.data[bottom + 2 * x] + img.data[bottom + 2 * x + 1]) / 4;
|
|
501
|
+
}
|
|
502
|
+
}
|
|
503
|
+
return { data: out, width: w, height: h };
|
|
504
|
+
}
|
|
505
|
+
/**
|
|
506
|
+
* Second look: boards the plain search misses or misplaces because the
|
|
507
|
+
* board itself is full of edges. Hatched dark squares (printed diagrams,
|
|
508
|
+
* chess.com's newspaper board) put more gradient energy inside the
|
|
509
|
+
* squares than on the grid lines, and marbled or low-contrast boards can
|
|
510
|
+
* slide the grid one tile diagonally, which keeps the colouring and so
|
|
511
|
+
* slips past repairParity. On a blurred copy the hatching melts to grey
|
|
512
|
+
* and the grid lines dominate again.
|
|
513
|
+
*
|
|
514
|
+
* Returns the boxes found on blurred copies, each with its grid-snapped
|
|
515
|
+
* variant, that are square and look like a board, without duplicates and
|
|
516
|
+
* without anything in `known`. They are CANDIDATES: the caller lets the
|
|
517
|
+
* tile classifier choose (recognize.ts).
|
|
518
|
+
*/
|
|
519
|
+
export function findBlurredBoardCandidates(img, known = []) {
|
|
520
|
+
const found = [];
|
|
521
|
+
const consider = (box) => {
|
|
522
|
+
const w = box.x1 - box.x0;
|
|
523
|
+
const h = box.y1 - box.y0;
|
|
524
|
+
if (w <= 0 || Math.abs(w - h) / w > MAX_ASPECT_ERROR)
|
|
525
|
+
return;
|
|
526
|
+
if (known.some((k) => sameBox(k, box)) || found.some((f) => sameBox(f, box)))
|
|
527
|
+
return;
|
|
528
|
+
if (boardness(img, box) < MIN_BOARDNESS)
|
|
529
|
+
return;
|
|
530
|
+
found.push(box);
|
|
531
|
+
};
|
|
532
|
+
const half = Math.max(img.width, img.height) > HALF_RES_ABOVE;
|
|
533
|
+
const base = half ? halve(img) : img;
|
|
534
|
+
const scale = half ? 2 : 1;
|
|
535
|
+
const up = (b) => ({ x0: b.x0 * scale, y0: b.y0 * scale, x1: b.x1 * scale, y1: b.y1 * scale });
|
|
536
|
+
for (const radius of half ? HALF_RES_BLUR_RADII : BLUR_RADII) {
|
|
537
|
+
const blurred = radius > 0 ? boxBlur(base, radius) : base;
|
|
538
|
+
const box = findChessboardCorners(blurred);
|
|
539
|
+
if (!box)
|
|
540
|
+
continue;
|
|
541
|
+
consider(up(box));
|
|
542
|
+
consider(up(snapCorners(blurred, box)));
|
|
543
|
+
}
|
|
544
|
+
return found;
|
|
545
|
+
}
|
|
379
546
|
export function findChessboardCorners(img) {
|
|
380
547
|
const gradY = gradientRows(img);
|
|
381
548
|
const gradX = gradientCols(img);
|
package/dist/index.d.ts
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
export { createRecognizer, recognizeGray, CONFIDENCE_FLOOR, type Recognizer, type RecognizerOptions, type BoardScanResult, type TileClassifier, } from "./recognize";
|
|
2
|
-
export { findChessboardCorners, snapCorners, type BoardCorners, type GrayImage, } from "./detect";
|
|
2
|
+
export { findChessboardCorners, findBlurredBoardCandidates, boardness, snapCorners, type BoardCorners, type GrayImage, } from "./detect";
|
|
3
3
|
export { extractBoardImage, boardToTiles, extractTiles, rgbaToGray } from "./tiles";
|
|
4
4
|
export { probsToPlacement, flipPlacement, resolveOrientation, type RecognitionResult, } from "./fen";
|
|
5
5
|
export { inferCastling, placementToFen } from "./compose";
|
package/dist/index.js
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
export { createRecognizer, recognizeGray, CONFIDENCE_FLOOR, } from "./recognize";
|
|
2
|
-
export { findChessboardCorners, snapCorners, } from "./detect";
|
|
2
|
+
export { findChessboardCorners, findBlurredBoardCandidates, boardness, snapCorners, } from "./detect";
|
|
3
3
|
export { extractBoardImage, boardToTiles, extractTiles, rgbaToGray } from "./tiles";
|
|
4
4
|
export { probsToPlacement, flipPlacement, resolveOrientation, } from "./fen";
|
|
5
5
|
export { inferCastling, placementToFen } from "./compose";
|
package/dist/recognize.d.ts
CHANGED
|
@@ -26,6 +26,20 @@ export declare const CONFIDENCE_FLOOR = 0.7;
|
|
|
26
26
|
export interface BoardScanResult extends RecognitionResult {
|
|
27
27
|
corners: BoardCorners;
|
|
28
28
|
reliable: boolean;
|
|
29
|
+
/** True when the read satisfies the one invariant every real chess
|
|
30
|
+
* position has: exactly one king per side. Detector false positives
|
|
31
|
+
* on board-free UI (settings pages, card grids) typically read as
|
|
32
|
+
* sparse kingless scatters; callers doing automatic whole-page scans
|
|
33
|
+
* should treat implausible reads as "no board found". */
|
|
34
|
+
plausible: boolean;
|
|
35
|
+
/** Size of the image `corners` are measured in. `recognize` scales large
|
|
36
|
+
* sources down before it looks for a board, so divide by this to place
|
|
37
|
+
* the box on the source (set by `recognize`; absent from recognizeGray,
|
|
38
|
+
* whose caller supplied the image). */
|
|
39
|
+
frame?: {
|
|
40
|
+
width: number;
|
|
41
|
+
height: number;
|
|
42
|
+
};
|
|
29
43
|
}
|
|
30
44
|
export interface RecognizerOptions {
|
|
31
45
|
/** URL of the tile classifier model (`chess-tiles-v2.onnx`, shipped
|
|
@@ -57,12 +71,15 @@ export type TileClassifier = (corners: BoardCorners) => Promise<RecognitionResul
|
|
|
57
71
|
* the classifier is injected. Exercised directly by the golden test
|
|
58
72
|
* suite and usable from Node with any rasterizer.
|
|
59
73
|
*
|
|
60
|
-
* An
|
|
61
|
-
* has no position to analyze, and
|
|
62
|
-
*
|
|
63
|
-
*
|
|
64
|
-
*
|
|
65
|
-
*
|
|
74
|
+
* An implausible read is unlikely to be the board the user means: an
|
|
75
|
+
* empty board has no position to analyze, and a kingless scatter is
|
|
76
|
+
* usually the detector locking onto board-free UI (whole-screen
|
|
77
|
+
* captures can include decorative boards, placeholder boards, and
|
|
78
|
+
* card grids that look like boards). When a pass reads implausible,
|
|
79
|
+
* the region is masked and the scan repeats, preferring a plausible
|
|
80
|
+
* board found later. The best implausible read is still returned when
|
|
81
|
+
* nothing better exists, preferring piece-bearing reads over empty
|
|
82
|
+
* ones; callers decide how much to trust it via `plausible`.
|
|
66
83
|
*/
|
|
67
84
|
export declare function recognizeGray(gray: GrayImage, classify: TileClassifier): Promise<BoardScanResult | null>;
|
|
68
85
|
export declare function createRecognizer(options: RecognizerOptions): Recognizer;
|
package/dist/recognize.js
CHANGED
|
@@ -20,7 +20,7 @@
|
|
|
20
20
|
* piece set, partial board) and the caller should route the user to
|
|
21
21
|
* an editor with a warning rather than trusting the result.
|
|
22
22
|
*/
|
|
23
|
-
import { findChessboardCorners, snapCorners } from "./detect";
|
|
23
|
+
import { boardness, findBlurredBoardCandidates, findChessboardCorners, snapCorners, } from "./detect";
|
|
24
24
|
import { extractTiles, rgbaToGray } from "./tiles";
|
|
25
25
|
import { probsToPlacement } from "./fen";
|
|
26
26
|
export const CONFIDENCE_FLOOR = 0.7;
|
|
@@ -44,34 +44,84 @@ function imageToGray(img) {
|
|
|
44
44
|
return rgbaToGray(data.data, cw, ch);
|
|
45
45
|
}
|
|
46
46
|
const EMPTY_PLACEMENT = "8/8/8/8/8/8/8/8";
|
|
47
|
+
function isPlausiblePosition(placement) {
|
|
48
|
+
let white = 0;
|
|
49
|
+
let black = 0;
|
|
50
|
+
for (const ch of placement) {
|
|
51
|
+
if (ch === "K")
|
|
52
|
+
white++;
|
|
53
|
+
else if (ch === "k")
|
|
54
|
+
black++;
|
|
55
|
+
}
|
|
56
|
+
return white === 1 && black === 1;
|
|
57
|
+
}
|
|
47
58
|
/** Detection passes per image: the first board found can be an empty
|
|
48
59
|
* decorative board (a page can contain several board-like regions,
|
|
49
60
|
* including this library's own UI); masking it and rescanning finds
|
|
50
61
|
* the board the user actually means. */
|
|
51
62
|
const MAX_SCAN_PASSES = 3;
|
|
52
|
-
|
|
63
|
+
/** A first-look read this good needs no second look: confident on every
|
|
64
|
+
* tile, a legal king count, and a box that looks like a board. Normal
|
|
65
|
+
* chess.com and Lichess screenshots stop here, at the cost they always
|
|
66
|
+
* had. */
|
|
67
|
+
const SETTLED_BOARDNESS = 0.8;
|
|
68
|
+
/** Picking the most confident of several alignments flatters the
|
|
69
|
+
* winner: the maximum of noisy confidences is biased upward, so a wrong
|
|
70
|
+
* read can clear CONFIDENCE_FLOOR by luck. When another alignment is
|
|
71
|
+
* nearly as confident (within this margin of the winner's mean) and
|
|
72
|
+
* reads a DIFFERENT position, the read is contested and not reliable.
|
|
73
|
+
* Measured on the benchmark and 488 Reddit screenshots: 0.03 removes
|
|
74
|
+
* every silent misread the second look would otherwise add. */
|
|
75
|
+
const CONTEST_MARGIN = 0.03;
|
|
76
|
+
async function readAll(boxes, classify) {
|
|
77
|
+
const reads = [];
|
|
78
|
+
for (const corners of boxes)
|
|
79
|
+
reads.push({ result: await classify(corners), corners });
|
|
80
|
+
return reads;
|
|
81
|
+
}
|
|
82
|
+
/** Highest mean confidence; the earlier box wins a tie. */
|
|
83
|
+
function mostConfident(reads) {
|
|
84
|
+
let best = null;
|
|
85
|
+
for (const r of reads) {
|
|
86
|
+
if (!best || r.result.meanConfidence > best.result.meanConfidence)
|
|
87
|
+
best = r;
|
|
88
|
+
}
|
|
89
|
+
return best;
|
|
90
|
+
}
|
|
91
|
+
function firstLookBoxes(gray) {
|
|
53
92
|
const corners = findChessboardCorners(gray);
|
|
54
93
|
if (!corners)
|
|
55
|
-
return
|
|
56
|
-
let bestCorners = corners;
|
|
57
|
-
let best = await classify(corners);
|
|
94
|
+
return [];
|
|
58
95
|
const snapped = snapCorners(gray, corners);
|
|
59
|
-
|
|
60
|
-
|
|
61
|
-
|
|
62
|
-
|
|
63
|
-
const snappedRead = await classify(snapped);
|
|
64
|
-
if (snappedRead.meanConfidence > best.meanConfidence) {
|
|
65
|
-
best = snappedRead;
|
|
66
|
-
bestCorners = snapped;
|
|
67
|
-
}
|
|
68
|
-
}
|
|
96
|
+
const same = snapped.x0 === corners.x0 && snapped.y0 === corners.y0 && snapped.x1 === corners.x1 && snapped.y1 === corners.y1;
|
|
97
|
+
return same ? [corners] : [corners, snapped];
|
|
98
|
+
}
|
|
99
|
+
function toScan(read, reliable) {
|
|
69
100
|
return {
|
|
70
|
-
...
|
|
71
|
-
corners:
|
|
72
|
-
reliable
|
|
101
|
+
...read.result,
|
|
102
|
+
corners: read.corners,
|
|
103
|
+
reliable,
|
|
104
|
+
plausible: isPlausiblePosition(read.result.placement),
|
|
73
105
|
};
|
|
74
106
|
}
|
|
107
|
+
async function scanOnce(gray, classify) {
|
|
108
|
+
const boxes = firstLookBoxes(gray);
|
|
109
|
+
const reads = await readAll(boxes, classify);
|
|
110
|
+
const first = mostConfident(reads);
|
|
111
|
+
if (first &&
|
|
112
|
+
first.result.minConfidence >= CONFIDENCE_FLOOR &&
|
|
113
|
+
isPlausiblePosition(first.result.placement) &&
|
|
114
|
+
boardness(gray, first.corners) >= SETTLED_BOARDNESS) {
|
|
115
|
+
return toScan(first, true);
|
|
116
|
+
}
|
|
117
|
+
reads.push(...(await readAll(findBlurredBoardCandidates(gray, boxes), classify)));
|
|
118
|
+
const best = mostConfident(reads);
|
|
119
|
+
if (!best)
|
|
120
|
+
return null;
|
|
121
|
+
const contested = reads.some((r) => r.result.placement !== best.result.placement &&
|
|
122
|
+
r.result.meanConfidence >= best.result.meanConfidence - CONTEST_MARGIN);
|
|
123
|
+
return toScan(best, best.result.minConfidence >= CONFIDENCE_FLOOR && !contested);
|
|
124
|
+
}
|
|
75
125
|
/** Flatten a region so its gradients vanish and the detector cannot
|
|
76
126
|
* lock onto it again on the next pass. */
|
|
77
127
|
function maskRegion(gray, box) {
|
|
@@ -91,26 +141,32 @@ function maskRegion(gray, box) {
|
|
|
91
141
|
* the classifier is injected. Exercised directly by the golden test
|
|
92
142
|
* suite and usable from Node with any rasterizer.
|
|
93
143
|
*
|
|
94
|
-
* An
|
|
95
|
-
* has no position to analyze, and
|
|
96
|
-
*
|
|
97
|
-
*
|
|
98
|
-
*
|
|
99
|
-
*
|
|
144
|
+
* An implausible read is unlikely to be the board the user means: an
|
|
145
|
+
* empty board has no position to analyze, and a kingless scatter is
|
|
146
|
+
* usually the detector locking onto board-free UI (whole-screen
|
|
147
|
+
* captures can include decorative boards, placeholder boards, and
|
|
148
|
+
* card grids that look like boards). When a pass reads implausible,
|
|
149
|
+
* the region is masked and the scan repeats, preferring a plausible
|
|
150
|
+
* board found later. The best implausible read is still returned when
|
|
151
|
+
* nothing better exists, preferring piece-bearing reads over empty
|
|
152
|
+
* ones; callers decide how much to trust it via `plausible`.
|
|
100
153
|
*/
|
|
101
154
|
export async function recognizeGray(gray, classify) {
|
|
102
155
|
let working = gray;
|
|
103
|
-
let
|
|
156
|
+
let fallback = null;
|
|
104
157
|
for (let pass = 0; pass < MAX_SCAN_PASSES; pass++) {
|
|
105
158
|
const result = await scanOnce(working, classify);
|
|
106
159
|
if (!result)
|
|
107
160
|
break;
|
|
108
|
-
if (result.
|
|
161
|
+
if (result.plausible)
|
|
109
162
|
return result;
|
|
110
|
-
|
|
163
|
+
const fallbackIsEmpty = !fallback || fallback.placement === EMPTY_PLACEMENT;
|
|
164
|
+
if (fallbackIsEmpty && (!fallback || result.placement !== EMPTY_PLACEMENT)) {
|
|
165
|
+
fallback = result;
|
|
166
|
+
}
|
|
111
167
|
working = maskRegion(working, result.corners);
|
|
112
168
|
}
|
|
113
|
-
return
|
|
169
|
+
return fallback;
|
|
114
170
|
}
|
|
115
171
|
export function createRecognizer(options) {
|
|
116
172
|
let ortPromise = null;
|
|
@@ -146,11 +202,12 @@ export function createRecognizer(options) {
|
|
|
146
202
|
const img = source instanceof File || source instanceof Blob ? await createImageBitmap(source) : source;
|
|
147
203
|
const gray = imageToGray(img);
|
|
148
204
|
const [ort, session] = await Promise.all([loadOrt(), getSession()]);
|
|
149
|
-
|
|
205
|
+
const scan = await recognizeGray(gray, async (c) => {
|
|
150
206
|
const tiles = extractTiles(gray, c);
|
|
151
207
|
const out = await session.run({ tiles: new ort.Tensor("float32", tiles, [64, 1024]) });
|
|
152
208
|
return probsToPlacement(out["probs"].data);
|
|
153
209
|
});
|
|
210
|
+
return scan && { ...scan, frame: { width: gray.width, height: gray.height } };
|
|
154
211
|
},
|
|
155
212
|
};
|
|
156
213
|
}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@scoriiu/fenshot",
|
|
3
|
-
"version": "0.1.
|
|
3
|
+
"version": "0.1.6",
|
|
4
4
|
"description": "Screenshot in, FEN out. Chessboard recognition in the browser: detects the board in any screenshot or book diagram and reads the position with a CNN tile classifier.",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"main": "./dist/index.js",
|
|
@@ -45,7 +45,7 @@
|
|
|
45
45
|
"onnx",
|
|
46
46
|
"lichess"
|
|
47
47
|
],
|
|
48
|
-
"author": "
|
|
48
|
+
"author": "Kibitzo (https://kibitzo.com)",
|
|
49
49
|
"license": "MIT",
|
|
50
50
|
"repository": {
|
|
51
51
|
"type": "git",
|