Previous Project
This Android app grew out of an older hobby project, scrabble-opencv, which I started around 2013 using Python, OpenCV, and a Logitech C920 webcam mounted above family Scrabble games. Looking at how that classical vision pipeline worked explains why this app moved to YOLO convolutional neural networks.
How the Classical OpenCV Pipeline Worked
- Corner detection with ArUco markers or red borders: The easiest and most reliable way to locate the board in
scrabble-opencvwas printing out four ArUco fiducial markers and sticking them onto the corners of the board. An alternative mode segmented the red board border or red circular stickers using HSV color thresholds, with manual corner offsets tuned per setup. - Letter detection with adaptive thresholding: After performing a perspective warp to get an undistorted image of the board, adaptive binary thresholding on the V channel of HSV isolated dark letter ink. Contours were filtered by aspect ratio, area, and distance from each grid square.
- Letter classification with k-NN: Each surviving binary character contour was scaled to an
18×18square, flattened into a 1D vector, and fed into a simple K-Nearest Neighbors classifier averaged across recent frames. - Blank detection with variance and Z-scores: Because blank tiles have no printed ink, unclassified squares were checked for a low coefficient of variance (smooth color, ruling out printed bonus text). Remaining smooth patches were compared against their empty neighbors by Z-score, flagging brightness outliers as blank tiles.
If you want to learn more about the classical OpenCV methodology, the scrabble-opencv README walks through every step in detail.
2013 OpenCV
2013 OpenCV
2013 OpenCV
Why We Moved to YOLO
The classical OpenCV approach worked fine on my home board once tuned, though it always needed manual configuration edits for different cameras, lighting, or board editions. For a standalone phone app, asking people to print ArUco stickers or adjust HSV thresholds by hand is a non-starter.
Switching to YOLO (You Only Look Once) convolutional neural networks replaces those fragile color thresholds and fiducial markers with learned models that work out of the box across different boards, lighting, angles, and phone cameras.
| Vision Task | scrabble-opencv (Classical OpenCV) |
Scrabble Scorekeeper (YOLO CNNs) |
|---|---|---|
| Board Corners | ArUco corner markers, red stickers, or HSV red-border thresholding + manual offsets | yolo26s-seg instance segmentation mask + Huber line intersection (no markers needed) |
| Tile & Letter Reading | HSV adaptive threshold + contour filters + 18×18 binary k-NN |
yolo26s object detector on a flattened 800×800 color board |
| Blank Tiles | Patch variance & neighbor Z-score brightness outliers | Dedicated _ class in the tile detector + offline 196k dictionary solver |
| Lighting & Board Editions | Per-room manual tuning; sensitive to shadows and fonts | Trained across multiple board editions, fonts, shadows, hand occlusions, and phone cameras |
How the YOLO Models Work
YOLO (You Only Look Once) is a family of fast object detection and instance segmentation algorithms built on Convolutional Neural Networks (CNNs). Rather than running hand-crafted color filters and contour heuristics, a YOLO CNN takes an RGB image scaled to [0, 1] (using the same 1/255.0 scaling as OpenCV's cv.dnn.blobFromImage) and predicts bounding boxes, class confidence scores, or pixel masks in a single forward pass.
When you photograph a Scrabble board from a stand or by hand, the 15×15 grid sits at an angle and each tile may only be 25 to 40 pixels wide. Trying to classify small, tilted letters directly in the raw camera frame makes look-alike characters such as I/L or O/Q easy to confuse. To avoid that, we split the vision task into two separate YOLO models:
- Corner detection model (
yolo26s-seg): Finds the playable 15×15 board region in the wide camera frame, extracts its four corners, and applies a perspective warp to produce a flat800×800top-down image. - Letter detection model (
yolo26s): Runs on that flat800×800board image to locate and classify every tile (AthroughZ, plus_for blank tiles).
Both models are fine-tuned from pretrained Ultralytics YOLO26 small checkpoints and exported to ONNX so they run locally on-device via ONNX Runtime with the XNNPACK backend. To keep the app download small and on-device inference fast, the bundled models are quantized to static 8-bit integers (32.3 MB total), with optional full 32-bit floating-point models (76.4 MB) available inside Settings.
Training Dataset (Synthetic & Real)
Before looking at how each YOLO model behaves and scores, it helps to understand what they are trained on. Photographing and hand-labeling thousands of real Scrabble boards across every board edition, lighting condition, camera angle, hand occlusion, and rare letter combination takes a massive amount of manual effort. At the same time, training purely on computer-generated renders does not generalize well enough to real phone lenses, wood grain, and cluttered tables.
Our v4 dataset combines both: 525 Blender-rendered synthetic boards (350 clean + 175 hand-occluded) and 90 real smartphone photos (80 clean + 10 hand-occluded), totaling 615 unique boards and 33,771 labeled tiles.
Generating Synthetic Boards in Blender
To generate synthetic boards with zero manual labeling, an automated pipeline builds 3D scenes in Blender so every render automatically yields exact 3D-to-2D projected board corners and tile bounding boxes:
A few details in the synthetic generator are especially important for getting models that transfer well to real phone cameras:
- Realistic tile geometry and shadows: Each tile is a beveled 3D block with darker wood on its angled sides so adjacent tiles cast authentic dark hairline seams between letters. Half the scenes also place a camera-invisible shadow plane overhead to cast soft shadows from lamps, hands, or the phone itself.
- Procedural 3D hands and sleeves (175 renders): During real games, people constantly reach over the board to place or nudge tiles. Earlier models trained only on unobstructed boards lost corner lock whenever an arm crossed the border and occasionally fired false letter detections on fingers or sleeves. To fix that, one third of the synthetic set adds a procedural articulated 3D hand, wrist, flat-cuff sleeve, optional watch, and optional mid-air held tile covering 4% to 20% of the board (and at most one corner). The corner model receives the complete amodal board polygon behind the hand so it learns to trace the true outline straight through an arm. For the letter model, post-processing runs a
3×3raycast visibility check on every tile, keeping labels only for tiles that are at least 60% visible and excluding buried or mid-air tiles so the letter detector stays quiet over skin and sleeves. - Simulating imperfect board corners: Before warping a synthetic render to
800×800, post-processing adds random Gaussian jitter (σ=2.5 px, capped at 10 px) to the ground-truth corners and transforms both the image and the tile boxes by that slightly imperfect warp matrix. That teaches the letter model to tolerate small live corner errors. - Rare-letter enrichment: In normal Scrabble games,
Eappears twelve times as often asQ,X,Z, orJ. By enriching 20% of synthetic layouts with high-value letters and blanks, even our rarest class (Q) has 548 unique labeled instances across the 615 boards,Zhas 586,Jhas 593,Xhas 622,Khas 646, and blank tiles (_) have 803 instances (compared to 3,622 forE).
Real Photos, Scene-Group Splitting & Balancing
The 90 real photos cover multiple board editions, wooden and plastic tiles, warm indoor lamps, sharp angles, and 10 hand-occluded board shots labeled in Label Studio (using the same 60% tile visibility rule as the synthetic data).
Real games are often photographed multiple times from slightly different angles. If you split individual photos randomly into training and validation sets, one angle of a game ends up in training and another angle of the exact same board ends up in validation, which artificially inflates validation accuracy. Before splitting, the dataset builder downscales every real board to a 32×32 thumbnail and clusters visually similar photos into 28 distinct scene groups (keeping clean and hand-occluded captures stratified). Every photo in a group goes strictly into either training or validation, and both YOLO models share the exact same split.
After checking accuracy on that 85/15 held-out split, the final release models are retrained on all 615 boards. To keep a single multi-photo game session from dominating training, real photos are balanced per scene group (targeting 12 frames per group, capped at 10× repeats per photo). Large sessions appear once per epoch, medium sessions repeat 4×, and single-photo or hand-occluded captures repeat up to 10×. That yields 324 balanced real frames alongside 525 synthetic frames (849 frames/epoch, roughly 38% real).
| Dataset Source | Unique Boards | Validation Split (85 / 15) | Unique Labeled Tiles | Final v4 Retrain (100% Data) / Epoch |
|---|---|---|---|---|
| Synthetic Clean (Blender 3D) | 350 | 296 train / 54 val | 19,561 (55.9/board) | 350 frames (41%) |
| Synthetic Hand-Occluded (Blender 3D) | 175 | 150 train / 25 val | 9,737 (55.6/board) | 175 frames (21%) |
| Real Phone Photos (28 scene groups: 80 clean + 10 occluded) | 90 | 76 train / 14 val | 4,473 (49.7/board) | 324 balanced frames (38%) |
| Total | 615 | 522 train / 93 val | 33,771 | 849 frames / epoch |
Real Board Samples
Click any photo below to view it full resolution. Real captures span different board editions, tile fonts, room lighting, and camera angles:
Real
Real
scrabble-opencv ArUco stickers, which the YOLO model ignores), and a blank tile in JA_BONED.
Real
Synthetic Board Samples (Blender 3D + Post-Processed Crop)
Compare the Blender renders below with the real photos above. The generator varies board editions, camera roll and tilt, lighting temperature, tabletop clutter, and rare-letter density, then warps each render into a camera-degraded 800×800 crop for the letter model:
Synthetic • Hasbro
Synthetic • Green
Synthetic • Rare Enriched
Q, Z, X, J, V, W, K) and multiple blanks substituted under steep perspective.
Warped Letter Input
Hand-Occluded Samples (Real & Synthetic)
To keep board corners steady and avoid false tile readings when hands cross the board, v4 pairs real hand-occluded captures with procedural 3D Blender hand renders:
Real • Occluded
Synthetic • Occluded
Corner Detection Model
As a first step at runtime, we need the exact location of the playable 15×15 grid inside the camera frame. Stage 1 letterboxes the camera frame into a 640×640 RGB input tensor (pixel values scaled by 1/255.0, padded with gray 114/255) and runs a yolo26s-seg instance segmentation CNN.
Rather than regressing four corner coordinates directly or detecting each corner as its own small box, yolo26s-seg outputs a 160×160 confidence mask covering the entire playable board. Because the board has four straight edges, the corner geometry extractor can reconstruct sharp corners from hundreds of boundary pixels even when a corner is blurred, shadowed, or hidden behind someone's hand.
Extracting Sub-Pixel Corners from the Mask
In the final step, we run an iterated Huber-weighted line fit. The first pass fits outlier-resistant lines along the middle 76% of each side to establish the rough borders. A refinement pass then re-assigns contour points using a tighter distance cutoff (3.2% of edge length, minimum 1.8 px) so diagonal pixels carved out by a hand or sleeve over one corner get thrown away. When both adjacent sides have strong inlier support (at least 10 contour points each), the line intersection is allowed to reconstruct a covered corner up to 22% of the mask diagonal away from the raw hull vertex.
Corners are ordered clockwise (top-left, top-right, bottom-right, bottom-left). If the player rotates the board view in the app (0°, 90°, 180°, or 270°), we simply cycle that corner list before warping.
Perspective Warp & the Half-Cell Margin
With the four corners located, Android's perspective transform (Matrix.setPolyToPoly) warps the skewed board into an undistorted 800×800 top-down image for the letter model. We also save the inverse matrix so detected letter boxes can be projected back onto the live camera preview.
Rather than stretching the 15×15 grid all the way to the image edges (0 to 800), the warp layout leaves a half-cell margin on all four sides. That divides the 800×800 image into 16×16 units (15 playable squares plus 0.5 on each side), making every square an exact 50×50 pixel cell inside the [25, 775] core.
Tiles played along rows 1 and 15 or columns A and O often hang slightly past the printed grid line. The 25-pixel margin keeps those outer tiles uncropped for the letter detector. When snapping detections to the grid, an 11-pixel (0.22-cell) tolerance band clamps slightly overhanging border tiles onto their outer square and ignores clutter farther out on the table.
Camera Input
Warped 800×800
RULE, ID) intact, and every tile is now upright and roughly 50 px wide.
Move your pointer or tap anywhere on the square to see how tile bounding-box centers snap to Scrabble coordinates.
[25, 775] playable grid. Each cell is 50×50 px. The amber border is the 25 px (half-cell) margin, and the dashed line marks the 11 px edge-rescue band.
Training Setup & Validation Results
Because a board polygon stays geometrically valid under rotations and mirroring, the corner model trains for 29 epochs with aggressive geometry augmentations (±45° rotation, 50% horizontal and vertical flips, ±35% scale, perspective skew, and 12% random erasing alongside the hand-occluded dataset). Ultralytics transforms the exact polygon vertices along with each augmented image.
During development we tested three different YOLO corner approaches on our held-out real and synthetic benchmark: a keypoint pose model (yolo11s-pose), a local corner box detector (yolo11s), and board instance segmentation (yolo26s-seg) with Huber line fitting:
| Corner Approach Tested | Input Size | Missed Real Boards | Median Corner Error (Unseen Real, 1080p) | Main Limitation |
|---|---|---|---|---|
Keypoint Pose (yolo11s-pose) |
800×800 | 0 / 18 | 27.7 px (worst 181 px) | Regressed corners drift too far for clean 15×15 grid alignment |
Local Corner Boxes (yolo11s) |
800×800 | 10 / 18 | 6.0 px (when all 4 found) | One shadowed or covered corner drops the entire frame |
Board Mask + Huber Line Fit (yolo26s-seg, v4) Shipped |
640×640 | 0 / 14 | 4.2 px occluded / 7.3 px clean (3.2 px overall) | Reconstructs covered corners by intersecting straight edges |
Adding amodal hand-occluded training data and the iterated Huber corner fit cut mean corner error on our 5 unseen real hand-occluded photos from 28.8 px in v3 down to 8.3 px in v4, and cut 95th-percentile error from 160.6 px to 19.9 px (0.995 mask mAP@50-95), with no regression on clean boards (2.96 px mean on clean synthetic boards). Static 8-bit quantization shrinks the board model from 39.8 MB to 17.8 MB with only 0.72 px mean corner difference from FP32 across 12 real test boards.
Letter Detection Model
Once the corner model has warped the board flat into an 800×800 square, Stage 2 scales the RGB pixels by 1/255.0 into a 4D NCHW input tensor and runs a yolo26s object detection CNN. In a single forward pass, it predicts bounding boxes and class confidence scores across 27 classes: uppercase letters A through Z plus _ for blank wood tiles.
Detections with confidence at or above 0.28 pass through class-agnostic Non-Maximum Suppression (NMS) with an IoU threshold of 0.45 so one physical tile cannot produce overlapping labels like both O and Q. Each surviving box center maps into its nearest (row, col) square using the coordinate grid from Section 2.2, keeping the highest-confidence box if two land in the same cell.
Live App Overlay
The four fitted corners draw the green board outline. Every tile bounding box found by the letter model is projected back through the inverse perspective matrix onto the live camera feed and mirrored on the virtual board below.
- Green outlines mark already-committed tiles; highlighted badges mark newly placed candidate letters for the current turn.
- Between YOLO passes, optical flow updates these overlay positions at 30 FPS (covered in Section 3.2).
Standard letter tiles have thick black ink across the center, giving high contrast against the board. A blank tile is a plain wooden square sitting on top of a tan cardboard grid square, so from raw brightness alone it looks very close to an empty square. Even with a YOLO CNN that picks up subtle cues like beveled edges, dark shadow seams, and wood grain, blank tiles remain the trickiest class under uneven lighting. And detecting a blank as _ only tells us where it sits; figuring out which letter it represents happens separately via the offline dictionary (Section 3.3).
Reusing the Letter Model for Endgame Racks
At the end of a game, any unplayed tiles left on each player's rack need to be counted with no 15×15 board in view. Holding a phone close to a rack makes each tile roughly 110 to 180 pixels tall, which is 2 to 3 times larger than the ~50 pixel tiles the letter model sees on a warped board.
Rather than bundling an extra model, the endgame rack scanner runs the same letter detector at native 1.0× scale (for tiles spread across a table) and on a 0.48× zoomed-out pass padded onto an 800×800 canvas (bringing close-up rack tiles back down to ~50 pixels). Boxes from both passes are mapped back to original image coordinates, deduplicated with NMS, capped at 7 tiles, grouped into horizontal rows, and sorted left to right.
1.0× and 0.48× handles close-up racks and tabletop clusters without shipping an extra model.
Training Setup, Quantization & Model Specifications
Unlike the corner model, the letter model disables horizontal flips, vertical flips, and mosaic stitching completely: flipping M upside down turns it into W, mirroring reverses asymmetric characters like S, Z, P, and R, and mosaic cropping breaks the regular 15×15 grid spacing. Instead, it trains for 42 epochs with mild rotation (±5°), slight shear (1.5°), 8% random erasing, strong hue/saturation/brightness shifts, and the simulated corner jitter baked into our warped training crops.
| Specification | Stage 1: Corner Model | Stage 2: Letter Model |
|---|---|---|
| Model Version | v4 |
v4 |
| YOLO Architecture | yolo26s-seg (instance segmentation CNN) |
yolo26s (object detection CNN) |
| Input Tensor | 640×640 RGB, gray-letterboxed (114/255), scaled 1/255 | 800×800 RGB, warped board, scaled 1/255 |
| Outputs | 1 class (board) + 32 mask prototypes (160×160) |
27 classes (A to Z + _ blank) |
| Final Retrain Schedule | 29 epochs on all 615 boards (849 balanced frames/epoch), cosine LR decay, mixed precision | 42 epochs on all 615 boards (849 balanced frames/epoch), cosine LR decay, mixed precision |
| Geometric Augmentations | ±45° rotation, 50% horizontal & vertical flips, scale (±35%), perspective, 12% random erasing | 0% flips, 0% mosaic; mild ±5° rotation, 1.5° shear, ±15% scale, 8% random erasing |
| Color Augmentations | Hue ±2%, saturation ±60%, brightness ±45% | Hue ±6%, saturation ±60%, brightness ±45% |
| ONNX Size (FP32 / INT8) | 39.8 MB → 17.8 MB | 36.5 MB → 14.5 MB |
To shrink both ONNX models from 76.4 MB down to 32.3 MB (a 58% reduction) without hurting accuracy, we apply static 8-bit quantization using 60 evenly spaced, deduplicated calibration images (30 real + 30 synthetic, clean and occluded) with exact runtime preprocessing and moving-average MinMax calibration. Convolution weights use per-channel signed 8-bit integers and activations use unsigned 8-bit integers for ARM XNNPACK kernels, leaving the input stem, attention block (including Softmax), and final detection and segmentation heads in FP32. Keeping those sensitive layers in FP32 adds only ~2% compute and yields 100.0% exact tile agreement (831/831 tiles, 2,700/2,700 grid cells) between INT8 and FP32 across 12 real test boards (8 clean + 4 hand-occluded).
On Android, ONNX Runtime's main scheduler runs single-threaded with busy-spinning disabled, handing parallel CNN convolutions to XNNPACK (default 4 threads, configurable between 2, 4, and 6 in Vision Settings) so worker threads sleep cleanly between frames. Both the bundled INT8 models and the full 76.4 MB FP32 models are hosted with SHA-256 checksums in models/manifest.json if you prefer to download FP32 precision inside Settings.
Held-Out Validation Results
Evaluated on the 93-board held-out validation set (5,339 visible tiles across 79 unseen synthetic renders and 14 unseen real photos from completely separate scene groups), the v4 letter detector performs consistently across both clean and hand-occluded boards:
| Held-Out Validation Slice | Boards (Tiles) | Precision | Recall | Detection Accuracy (mAP@50 / 50-95) |
|---|---|---|---|---|
| Combined Validation Set | 93 (5,339) | 99.8% | 99.7% | 99.5% / 94.4% |
| Unseen Real Boards (Clean) | 9 (721) | 98.9% | 98.7% | 98.7% / 91.0% |
| Unseen Real Boards (Hand-Occluded) | 5 (222) | 98.4% | 99.2% | 98.9% / 98.2% |
| Unseen Synthetic Boards (Clean) | 54 (2,999) | 99.9% | 99.9% | 99.5% / 94.6% |
| Unseen Synthetic Boards (Hand-Occluded) | 25 (1,397) | 99.7% | 99.3% | 99.4% / 95.2% |
- Real hand-occluded boards end-to-end: Running the full corner mask → Huber line fit → perspective warp → letter detector pipeline on all 5 unseen real hand-occluded photos (
222visible tiles) jumped from63.1%(140/222) inv3to97.8%(217/222) inv4, with 4 of the 5 unseen occluded boards reading at100.0%exact cell-and-letter accuracy (including the real hand-occluded photo shown in Section 2.1, which read 37/37 tiles within 7.3 px corner error and zero skin false positives). - Skin and hand false positives cut 11× to 18×: Across the 25 unseen hand-occluded synthetic boards (at runtime confidence
0.28), false tile detections landing on skin, fingers, or sleeves dropped from11to18inv3down to1total (0.072%of predictions) inv4.
Other App Considerations
Running the YOLO models on a static photo is straightforward. Turning them into a comfortable tabletop Android app takes a few extra engineering layers on top: keeping battery use reasonable over an hour-long game, tracking handheld camera movement smoothly at 30 FPS, resolving blank tiles offline, and turning real games into training data for future releases.
Smart Power Management
A full Scrabble game easily lasts 45 to 90 minutes, and the board sits untouched for most of that time while players think about their next play. Keeping an OLED screen at full brightness and running two YOLO CNNs nonstop on 4 CPU threads would burn through a phone battery quickly.
We cut battery draw in two ways: letting the display dim automatically during idle thinking time, and pausing YOLO inference and optical flow whenever the board is still or the phone is laid face-down.
Screen-Dim Wake Lock
Instead of setting Android's FLAG_KEEP_SCREEN_ON (which locks the display at full brightness indefinitely), gameplay uses a SCREEN_DIM_WAKE_LOCK. The screen stays bright when you interact with the app, then dims down to low OLED power after your phone's normal screen timeout without locking the device or interrupting CameraX, voice commands, or the LAN web scoreboard.
Power Consumption Across States
The power manager watches a tiny 64×48 grayscale thumbnail (3 KB) sampled from the camera stream and moves the vision pipeline between active scanning and low-power sleep states based on what the camera sees:
| Power State | What Runs | CPU & Battery Impact | Overlay & Wake Behavior |
|---|---|---|---|
| Active Scanning | CameraX preview, 30 FPS Lucas-Kanade optical flow (~2 to 4 ms/frame), 4-thread YOLO CNN inference (~50 to 100 ms/pass) | Highest draw (sustained multi-core CPU + camera ISP). Used only when the camera or board is moving. | Live tracked overlay; enters sleep automatically after 5 s still or 300 ms covered. |
| Stationary Idle (board untouched ≥5 s) |
CameraX preview + 1 Hz 64×48 thumbnail diff (~0.15 ms once per second). YOLO and optical flow stopped. |
Low draw (~0% vision CPU; only camera ISP + dimmed OLED screen). Eliminates almost all compute drain between turns. | Last board overlay stays pinned. Wakes within 1 s on a moving hand or single placed tile, or immediately on Capture / voice. |
| Covered / Face-Down (lens dark/flat ≥300 ms) |
~2.5 Hz 64×48 brightness probe (~0.15 ms/probe). YOLO, optical flow, and overlay stopped. |
Lowest draw (~0% vision CPU and no overlay redraws). Ideal when setting the phone down between turns. | Overlay cleared; wakes immediately on the first bright or textured frame when lifted. |
In Stationary Idle, the 1 Hz check compensates for global brightness shifts from camera auto-exposure so passing clouds or lamp flicker do not wake the scanner, and compares against both the previous second and a frozen reference snapshot so slowly placing one tile still triggers a wake. Both power-saving modes and motion sensitivity (Low, Medium, or High) can be adjusted in Vision Settings.
Reusing Pixel Buffers
Allocating a fresh camera bitmap 30 times per second would churn through tens of megabytes of temporary heap memory every second and trigger constant garbage collection. Instead, the camera pipeline allocates reusable buffers once and overwrites them in place: a 64×48 grayscale thumbnail (3 KB) for power checks, a quarter-resolution grayscale buffer for optical flow, and one full camera bitmap copied only when the background YOLO worker is free.
Motion Tracking
Running locally on-device, a combined YOLO corner and letter pass takes roughly 50 to 150 ms. If the app simply drew the board outline and tile badges whenever YOLO finished, the overlay would stutter at a few frames per second and visibly lag behind a handheld phone.
Pipeline Threading & Alternating Letter Cadence
We separate camera tracking, YOLO inference, and turn scoring onto independent threads with non-blocking handoffs so slow model passes never stall the 30 FPS camera preview:
- Camera & Optical Flow Thread (30 FPS): Receives 4:3 frames from CameraX (requesting around
720×960, or the closest 4:3 resolution supported by the device) with a keep-latest policy so old frames are dropped instead of queuing up. It runs power checks, tracks frame-to-frame motion with optical flow, and draws the live overlay directly onto an AndroidCanvaswith zero UI recompositions. - Background YOLO Worker (4 to 12 FPS): Grabs the newest frame whenever it finishes the previous pass, runs Stage 1 and Stage 2 via ONNX Runtime, maps detections to the 15×15 grid, and feeds the temporal smoother. Because camera angle moves continuously and tiles only change every few seconds, the default setting runs only the corner model on every other pass and re-projects the cached tiles onto the fresh corners in under 0.1 ms, roughly halving CPU load.
- Game Engine & Capture Thread: Diffs the stabilized 15×15 grid against the committed game board, resolves blank tiles, scores cross-words, and optionally saves verified turns for future training.
| Pipeline Step | Run Rate | Working Resolution | Typical CPU Time (Modern Android Phone) |
|---|---|---|---|
| Power State Thumbnail Check | 4 Hz active / 1 Hz idle | 64×48 grayscale (3 KB) | ~0.15 ms |
| Lucas-Kanade Optical Flow | 30 FPS | 1/4 → 1/8 → 1/16 frame (e.g. 180×240) | ~2 to 4 ms |
| Stage 1: Corner Model | 4 to 12 FPS | 640×640 RGB → 160×160 mask | ~45 to 75 ms (INT8) |
| Stage 2: Letter Model | Every 2nd YOLO pass | 800×800 warped board | ~60 to 95 ms (INT8) |
| Cached Tile Re-Projection | Alternate YOLO passes | Cached boxes × new board corners | <0.1 ms |
Optical Flow & Homography Catch-Up
To keep the overlay locked onto the physical board between YOLO updates, the app runs pyramidal Lucas-Kanade optical flow on every 30 FPS camera frame (strictly for the visual overlay; it never affects game scoring). Because background inference finishes on an older frame (say frame 10) after the camera has already reached frame 13, a 48-frame circular history buffer (1.6 seconds at 30 FPS) stores each frame-to-frame homography. When frame 10's YOLO result arrives at frame 13, the buffer chains the recorded transforms from frame 10 to 13 so the fresh detection lands cleanly on the live frame without jumping backward.
Each 33 ms tracking step runs four stages:
- Pyramidal Lucas-Kanade tracking: The grayscale camera frame is downscaled into a multi-level pyramid (
1/4,1/8, and1/16of frame resolution, e.g.180×240down to45×60on a720×960stream). Coarse levels catch fast camera pans first, and finer levels refine each feature's sub-pixel position. - Grid-balanced feature selection: The board interior is divided into a 6×6 grid and the tracker picks one strong corner feature per cell (up to 36 points), reseeding automatically whenever fewer than 18 survive so one dense cluster of tiles cannot skew the motion fit.
- Forward-backward and occlusion checks: Each feature is tracked forward using a
5×5patch and then tracked back. If the round-trip error exceeds1.5pixels, or if local patch brightness jumps sharply (such as a hand passing over the tiles), the point is dropped. - Rigid vs. perspective motion fitting: Fitting a full perspective homography directly to noisy points can warp the board outline if a hand covers half the board. Instead, the motion estimator fits a rigid similarity transform (scale, rotation, and pan) first, and only upgrades to a full perspective homography when at least 12 points span 3 or more quadrants, the perspective fit cuts alignment error by over 22%, and the resulting quadrilateral stays convex and bounded.
Temporal Smoothing, Hand Pass-Throughs & Fresh Capture
To stop single-frame glitches or passing hands from flickering on the virtual board, a few lightweight temporal rules sit between YOLO outputs and the UI:
- Sliding-window tile voting: High-confidence letters (
≥ 0.52) appear immediately, and picked-up tiles clear after 2 consecutive empty frames. Borderline detections and blank tiles require consensus across recent frames (blanks need at least half the window unless confidence reaches0.65), reducing false blanks on empty squares. - Hand pass-through hold: During live preview, the detector holds the last good board corners for up to 4 missed frames so a quick hand wave does not flash the overlay off. When optical flow is turned off, corner smoothing also rejects sudden single-corner spikes (where three corners stay still and one jumps over 8% of the frame diagonal) until two consecutive frames agree.
- On-demand Fresh Capture: When a player taps Capture or triggers a voice command (such as “Scrabble Score”), the app bypasses idle sleep and temporal smoothing, grabs one fresh camera frame, and runs a direct Stage 1 + Stage 2 pass (with a 1.5-second timeout) so the scored play always reflects what is on the board right now.
Dictionary Integration
The app bundles the offline NWL2023 tournament dictionary (196,601 words packed into a compact word graph) directly inside the APK so word validation, manual dictionary lookups, and blank tile resolution all work with zero internet access.
When the letter model detects a blank wooden tile, it outputs _ because there is no printed ink on the square. Before asking the player to pick a letter by hand, the blank tile solver tests all 26 letters against the offline dictionary for every word passing through that blank. Each word produces a 26-bit mask of legal letters, and crossing words intersect their bitmasks to narrow the choices automatically:
Single Blank: Q_IZ Auto-Resolved: U
Testing A through Z in the offline dictionary yields only one valid match: QUIZ.The app assigns
U automatically with no manual picker.
Cross-Word Constraint: C_T × _N Narrowed to 2
Across C_T allows A, O, U (CAT, COT, CUT). Down _N allows A, E, I, O (AN, EN, IN, ON).Their intersection narrows the picker to just
A and O.
For rare turns that play both blank tiles at once, the solver intersects each blank's cross-word letters before checking valid pairs in the main word. If one blank only has a single valid letter across all legal combinations, it locks that blank automatically and only prompts for the remaining one.
Training Data Collection
Every confirmed turn gives us human-verified ground truth for the whole 15×15 board, including any misread letter a player corrected in the confirmation dialog. When opt-in training data collection is enabled in Settings, the app saves a compact subset of turns locally so they can be folded back into future training runs.
Rather than saving every turn (which would fill storage with nearly identical frames), the collector uses selective sampling: it saves 100% of turns where the player corrected a letter, rare letters and blanks spaced at least 3 turns apart, and board-density checkpoints (around 14, 38, and 68 tiles, plus game end). Saved frames are scaled to at most 1280 px on the long edge (JPEG quality 85) so an entire game session takes only a few megabytes.
All captured training data stays strictly on your device and is never uploaded automatically. It is completely up to you whether you want to enable collection or share anything, though if you are willing to export a ZIP bundle from Settings and email it to scrabble@jeffheidel.com to help development, I would really appreciate it.