Documentation
¶
Overview ¶
Digit classification against canonical-size templates.
This file exists because the same mistake was made twice in two different readers, and the second time it cost a live battle.
The mistake: compare a glyph crop against a digit template resized to fit *that crop's* box. The correlation is then dominated by how much of the box is background rather than by the shape of the digit, so on the game's real font a CORRECT digit scored 0.05-0.45 and the winner was essentially always `digit_1` — the narrowest template, which resizes to the least background.
One reader hid the problem behind a special case (a thin bright blob with >0.65 fill is called a `1`, no template needed), which is why a damage panel reading "16%" came back as "1": the `1` was accepted by the shortcut, the `6` scored under the floor and was dropped. That read is the destruction percentage, and it is what left the bot's end-of-battle wait stuck on 0% while it watched the damage panel.
The fix, measured on real 720p frames with an army loaded: crop each glyph and each template to its own ink, resize both to one canonical box, and compare shapes with TM_CCOEFF_NORMED. Correct digits then score 0.54-0.72 and junk 0.12-0.45, so a confidence floor plus a confidence *margin* over the runner-up separates "this is a 6" from "this is a glyph I cannot name".
On-screen text recognition with bounding boxes.
The heavy lifting is done by tools/ocr.swift, which uses Apple's Vision framework: no tesseract, no network, and — critically — it returns pixel bounding boxes. A recognised string plus its rectangle is what lets a report say "the button at (400,640) reads RETURN HOME" instead of just "somewhere on screen it says RETURN HOME", which is the difference between a debugging aid and a decoration.
Screenshot -> text rendering, built for a debugging loop where the reader is an agent that cannot decode a PNG.
cmd/screendump already prints a coarse colour-letter map of a frame. That answers "roughly what is on screen"; it cannot answer "which button is lit", "did the popup close", "does the deploy line sit on the village or on the grass", because it has no coordinate frame and only one glyph of detail per cell. This file provides the primitives for a denser, ruler-annotated view:
Render the frame as text on a Grid, one character per cell, with the
screenshot pixel coordinates of every row and column labelled
so a glyph can be converted straight back into a tap
RenderColor the same geometry in 24-bit ANSI half blocks (two pixels per
character cell) for a human terminal
ChangeMap what differs between two frames, drawn on the same Grid so the
change map lines up with the frame render
Diff the numbers behind ChangeMap: percent changed, bounding box,
largest channel delta
Everything here works on Frame, a plain BGR byte view of a gocv.Mat, so the renderers are byte arithmetic over a slice: no OpenCV calls, and testable without a screen.
A rolling frame store: the memory of the seeing system.
One screenshot answers "what is on screen now". Debugging a bot that runs for minutes needs "what happened, in order" — which popup appeared when, whether a tap changed anything, what the screen looked like at the moment a state went wrong. The store keeps captured frames on disk beside a JSON-lines index recording, per frame, the classifier's verdict, a caller-supplied label, and how much the frame changed from its predecessor. That last number is the cheapest possible answer to "did my tap land": if a tap was supposed to dismiss a dialog, the frame changes; if it silently missed, the next frame is near-identical.
Index ¶
- Constants
- Variables
- func CanonicalGlyph(glyph gocv.Mat) gocv.Mat
- func CanonicalScores(canon gocv.Mat, templates []gocv.Mat) []float64
- func ChangeMap(a, b Frame, opts RenderOptions, threshold int) (string, Grid, DiffResult)
- func ChangedPercent(prev, cur gocv.Mat, perChannelDelta float64) float64
- func CloseTemplateCache()
- func ClosingKernelWidth(regionWidth int) int
- func ColourPixels(img gocv.Mat, region image.Rectangle, lower, upper gocv.Scalar) (pixels int, fraction float64)
- func DiskFreeBytes(dir string) (uint64, error)
- func EmptyMask() gocv.Mat
- func FacePixels(img gocv.Mat, region image.Rectangle) int
- func FractionRect(w, h int, fx0, fy0, fx1, fy1 float64) image.Rectangle
- func GetMat(rows, cols int, matType gocv.MatType) gocv.Mat
- func GetMatFrom(src gocv.Mat) gocv.Mat
- func GetScaledTemplates(name string, template gocv.Mat, minScale, maxScale float64, steps int) []gocv.Mat
- func HueClass(r, g, b int) (byte, bool)
- func MarkLegend(marks []Mark) string
- func MatchCanonical(canon gocv.Mat, templates []gocv.Mat) (int, float64, float64)
- func MatchTemplateBest(screen, template gocv.Mat, threshold float32) (image.Point, float64, error)
- func MatchTemplateRegion(screen, template gocv.Mat, rect image.Rectangle, threshold float32) (image.Point, float64, error)
- func OCRHelperBinary() (string, error)
- func ParseRect(spec string, w, h int) (image.Rectangle, error)
- func PickBest(scores []float64) (int, float64, float64)
- func PixelSearch(screen gocv.Mat, rect image.Rectangle, r, g, b int, tolerance int) (image.Point, error)
- func PutMat(mat gocv.Mat)
- func ResizeToHeight(src gocv.Mat, targetHeight int) gocv.Mat
- func Signature(src gocv.Mat) gocv.Mat
- func Timeline(entries []FrameEntry) string
- func WritePNG(path string, f Frame) error
- type ActionButton
- type ActionButtonConfig
- type ButtonColor
- type DiffResult
- type Frame
- type FrameEntry
- type FrameMeta
- type FrameStore
- func (s *FrameStore) Add(f Frame, meta FrameMeta) (FrameEntry, error)
- func (s *FrameStore) ByID(id int) (*FrameEntry, error)
- func (s *FrameStore) Dir() string
- func (s *FrameStore) Entries() ([]FrameEntry, error)
- func (s *FrameStore) FreeBytes() (uint64, error)
- func (s *FrameStore) Last() (*FrameEntry, error)
- func (s *FrameStore) Load(e FrameEntry) (Frame, error)
- func (s *FrameStore) MinFreeBytes() uint64
- func (s *FrameStore) Prune(keep int) (int, error)
- func (s *FrameStore) Recent(n int) ([]FrameEntry, error)
- func (s *FrameStore) SetMinFreeBytes(n uint64)
- type Grid
- type Mark
- type MatPool
- type Match
- func MatchMultiScale(screen, template gocv.Mat, minScale, maxScale float64, steps int, ...) ([]Match, error)
- func MatchMultiScaleAllROICached(screen, template gocv.Mat, templateName string, minScale, maxScale float64, ...) ([]Match, error)
- func MatchMultiScaleROI(screen, template gocv.Mat, minScale, maxScale float64, steps int, ...) ([]Match, error)
- func MatchMultiScaleROICached(screen, template gocv.Mat, templateName string, minScale, maxScale float64, ...) ([]Match, error)
- func MatchTemplate(screen, template gocv.Mat, threshold float32) ([]Match, error)
- type RenderOptions
- type ScaledTemplateCache
- type TextRegion
Constants ¶
const ( // SignatureHeight is the thumbnail height. 90 rows keeps a 16:9 frame at // 160x90 and the 860x732 reference at 106x90: small enough that resizing // and comparing cost well under a millisecond together, large enough that a // 90x90 px button still covers a 7x7 block of thumbnail pixels. SignatureHeight = 90 // DefaultChangeDelta is the per-channel difference at which a thumbnail // pixel counts as changed. It deliberately reuses the frame store's noise // floor (DefaultDiffThreshold) rather than inventing a second one: the // artifact tooling and the bot must agree on what "changed" means. DefaultChangeDelta = DefaultDiffThreshold )
const ( DigitCanonW = 24 DigitCanonH = 32 )
DigitCanonW and DigitCanonH are the canonical comparison box. It is the shape of a digit at roughly 1.5x its 720p size: big enough that the resize keeps the stroke topology that distinguishes 6/8/9 and 5/3, small enough that the whole match is a few hundred comparisons.
const ( MaxCols = 320 MaxRows = 200 )
Hard caps so a mistyped -cell cannot print megabytes of text.
const DefaultCols = 120
DefaultCols is the render width when the caller does not choose one. At 1280x720 it yields ~32 text lines, which fits a terminal pane and still resolves UI elements tens of pixels wide.
const DefaultDiffThreshold = 12
DefaultDiffThreshold is the per-channel delta at which a pixel counts as changed. Above video-compression noise, below a real UI change.
const DefaultMinFreeBytes = 2 << 30
DefaultMinFreeBytes is the free-space floor a recording insists on leaving on its volume. 2 GiB is comfortably more than a full default ring (400 frames at ~1.4 MB/frame from a 720p emulator is ~560 MB), so crossing it means something is writing far more than a review store should ever hold.
const DefaultStoreDir = "tmp/see"
DefaultStoreDir is where recordings live unless the caller says otherwise. Project-local and disposable: recordings are debugging output, not data.
Variables ¶
var ErrLowDisk = errors.New("low disk space: refusing to record another frame")
ErrLowDisk is returned instead of writing when the volume holding the recording directory is below its free-space floor.
Why this exists: ad-hoc `adb exec-out screencap` shell loops once wrote ~120,000 frames (~167 GB) into tmp/ over a weekend, taking this machine's disk to 99% and breaking `go build` with "no space left on device" linker errors. Frame recording is the one part of this project that can write an unbounded amount of data, so the recorder checks headroom itself instead of trusting every caller (and every one-off shell loop) to have capped its run.
var Ramp = []byte(" .:-=+*#%@")
Ramp maps brightness (dark -> bright) onto characters, so bright game pixels — label text, button faces, health bars — come out as dense glyphs and dark scenery and panels fade to whitespace. The report prints the convention, but the short version is: ink where the game draws, blanks where it does not.
var UnusableScore = math.Inf(-1)
UnusableScore is the score CanonicalScores records for a template it could not compare (empty, or a different canonical size). It is used instead of zero because TM_CCOEFF_NORMED can return negative values, so a zero could otherwise beat every real candidate on a glyph that matches nothing.
Functions ¶
func CanonicalGlyph ¶
CanonicalGlyph resizes one glyph (or template) crop into the canonical comparison box. The caller owns the returned Mat and must Close it.
func CanonicalScores ¶
CanonicalScores scores one canonical glyph against every template, in template order, and returns the raw scores. A caller that can rule digits out before comparing — the count reader rules out every digit whose ink is far wider than the glyph it is looking at — can set those entries to UnusableScore and hand the slice to PickBest, which is how a 3px-wide stroke stops being compared against digits drawn 8px wide.
func ChangeMap ¶
func ChangeMap(a, b Frame, opts RenderOptions, threshold int) (string, Grid, DiffResult)
ChangeMap draws which cells of the frame differ, on the same Grid a Render of b would use, so the two pictures line up. '#' marks a cell whose pixels changed by more than threshold, '.' a cell that differs at all, and ' ' a cell that is identical. Marks are drawn over the top.
func ChangedPercent ¶
ChangedPercent reports the percentage of thumbnail pixels that moved by more than perChannelDelta between two signatures.
Fail-safe by construction: anything it cannot compare — an empty or differently shaped signature, an OpenCV error — reports 100 (changed), so a caller that gates work on "under threshold" can only ever do MORE work than it needed, never less.
func CloseTemplateCache ¶
func CloseTemplateCache()
func ClosingKernelWidth ¶
ClosingKernelWidth returns the closing kernel used to bridge a button label's glyph gaps. It is exported for tests and diagnostics that need to reason about the same scale.
The width is a hundredth of the searched region, which is the window that separates the two scales involved. Measured on live frames: the gap between glyphs inside a label is ~0.5% of the frame width, while neighbouring buttons (the army sheet's two Boost chips) sit ~1.5% apart. A kernel in between — 1% — bridges the letters of a label without fusing two buttons into one blob, which would hand the bot a tap point in the gap between them.
func ColourPixels ¶
func ColourPixels(img gocv.Mat, region image.Rectangle, lower, upper gocv.Scalar) (pixels int, fraction float64)
ColourPixels counts the pixels in region whose BGR channels fall inside [lower, upper] (gocv.InRangeWithScalar's order, so the scalars are B,G,R) and returns the count together with its share of the region.
Two reasons this sits beside FacePixels instead of at the call site. The count is one vectorised InRange over the region rather than a per-pixel cgo GetVecbAt walk — measured 71 µs against 4.2 ms for a 16k-pixel region, so a caller that probes on every captured frame can afford it. And a colour test whose verdict is a fraction of a control's own face is only meaningful against a region of known size: returning both numbers lets a threshold read as "a tenth of this box is the button's orange" rather than as a raw pixel count that silently changes meaning when the box changes.
Returns (0, 0) for an empty or fully out-of-frame region.
func DiskFreeBytes ¶
DiskFreeBytes reports the space available to the current user on the filesystem holding dir. An empty dir means the working directory.
func EmptyMask ¶
EmptyMask returns a shared valid (non-nil) empty cv::Mat for use as the mask argument of cv::matchTemplate. Never close the returned Mat.
func FacePixels ¶
FacePixels counts the pixels in region that are "bright and strongly saturated" — the same mask FindActionButton locates button faces with, exposed so a caller can measure whether an already-known rect holds a painted control or merely text over artwork.
The distinction is the point. CoC prints its menu labels in near-white on a dark panel: bright (over the 170 floor) but with saturation ~0, so a label scores zero on this mask while a button face — gold (247,177,54) or green (200,237,98) — scores most of its area. A wall-upgrade tray chip is a painted face; the builder-menu row drawn in the same place is a glyph, so this is what separates "the tray is on screen" from "the assets point at a menu list".
Returns 0 for an empty or fully out-of-frame region.
func FractionRect ¶
FractionRect returns the sub-rectangle of a w-by-h frame covering [fx0,fx1) x [fy0,fy1) in fractional coordinates. Panel buttons are located by fraction rather than by a reference-frame ROI precisely because the panels reflow; a fraction of the frame is the one description that survives that.
func GetScaledTemplates ¶
func HueClass ¶
HueClass names a saturated colour with one letter: R red, O orange/gold, Y yellow, G green, C cyan, B blue, P magenta/purple, W white. It returns false when the pixel is too grey to name, which is the caller's cue to fall back to a brightness ramp. Seven buckets is deliberately coarser than a colour wheel: the letters have to stay readable in a wall of text.
func MarkLegend ¶
MarkLegend renders every mark's description, one per line, so a reader can map the digits in the picture back to what was detected.
func MatchCanonical ¶
MatchCanonical scores one canonical glyph against a set of canonical digit templates and returns the winning digit with its confidence and its margin over the runner-up.
Returns (-1, 0, 0) when the glyph is empty or no template is usable.
func MatchTemplateBest ¶
func MatchTemplateRegion ¶
func OCRHelperBinary ¶
OCRHelperBinary compiles tools/ocr.swift (once, into the temp dir) and returns the binary path. It rebuilds when the source is newer than the binary so an edit to the helper takes effect on the next run.
func ParseRect ¶
ParseRect reads an x,y,w,h region spec and clamps it to a w x h frame. An empty spec means the whole frame. A spec that would select nothing is an error rather than a silent empty render, because these flags are typed by hand.
func PickBest ¶
PickBest returns the winner of a score slice with its confidence and its margin over the runner-up. Scores equal to UnusableScore are skipped.
The margin is returned rather than folded into the score because the two answer different questions: a high confidence says "this matches a digit well", a high margin says "and it is not nearly the same shape as another digit". An 11-13 px `6` is genuinely ambiguous with `8` and `9`, and a reader that reports confident-but-ambiguous damage percentages is worse than one that reports it could not read the panel.
Returns (-1, 0, 0) when no template has a usable score.
func PixelSearch ¶
func Signature ¶
Signature reduces a frame to a small BGR thumbnail for change detection. The returned Mat comes from the shared Mat pool — release it with PutMat. An unusable input (too small to compare) returns an empty Mat, which makes ChangedPercent report "changed" rather than silently claiming stability.
func Timeline ¶
func Timeline(entries []FrameEntry) string
Timeline renders a table of recorded frames, oldest first.
Types ¶
type ActionButton ¶
type ActionButton struct {
// Rect is the button face's bounding box in frame coordinates.
Rect image.Rectangle
// Color is which palette family the face matched.
Color ButtonColor
// Fill is the fraction of the bounding box covered by the button colour,
// after bridging the label glyphs. A solid button face sits high; a
// decorated or hollow overlay (a badge, a banner, an army card) is low.
Fill float64
// Pixels is the masked pixel count inside Rect.
Pixels int
}
ActionButton is a primary button located in a live frame.
func FindActionButton ¶
func FindActionButton(img gocv.Mat, region image.Rectangle, cfg ActionButtonConfig) (ActionButton, bool)
FindActionButton locates the primary action button inside region: the widest bright saturated gold-or-green blob whose bounding box lies fully inside the region.
This exists because overlay panels do NOT follow a geometry law. Clash of Clans scales and anchors the village HUD predictably (internal/game's calibration models that, and it holds), but it *reflows* panels and dialogs by content and by aspect ratio. The army sheet is the case that broke the bot live: its Attack! button is the widest green blob at (727,536) on the 860x732 reference and at (1130,641) on 1280x720 — 180 px away in y, and no per-axis anchor reproduces both, because the panel around it is laid out differently at 16:9. Locating the button in the frame instead of predicting its coordinates works at both, from one rule.
The caller passes the window it expects the button in: a fraction of the frame for a panel whose place is stable (the sheet's action button is always bottom-right), or the box of a dialog it has already detected (see FindPanel). Widest-wins is what picks the primary button: on the sheet that is the 238 px Attack! face, not the 110 px Boost chips beside it.
func (ActionButton) Centre ¶
func (b ActionButton) Centre() image.Point
Centre is the tap point for the button: the centre of its face.
func (ActionButton) Describe ¶
func (b ActionButton) Describe() string
Describe renders a located button for logs.
type ActionButtonConfig ¶
type ActionButtonConfig struct {
// MinFrameWidthFrac rejects components narrower than this fraction of the
// whole frame's width. A primary button is a substantial object on screen;
// icons, badges, Boost chips, unit cards and the village's own SHOP button
// are all under it. Bounds are frame-relative, not region-relative, so the
// verdict does not change with the window the caller searched through — the
// window only decides *where* to look.
MinFrameWidthFrac float64
// MinFill rejects hollow or heavily decorated components. A button face is
// solid; chained scenery is not.
MinFill float64
// MinAspect and MaxAspect bound width/height. Button faces are wider than
// tall; the bounds keep ribbons, banners and tall blobs out.
MinAspect float64
MaxAspect float64
// MaxFrameWidthFrac and MaxFrameHeightFrac are upper bounds measured
// against the whole frame, not the searched region, because a button face
// is a small object on screen whatever window it was found through. They
// are what rejects scenery: the closing pass chains bright saturated grass,
// walls and storage roofs into one sprawling component, and without a
// ceiling that component passes every lower bound there is (measured on a
// live 1280x720 village: 1261x720, fill 0.59).
MaxFrameWidthFrac float64
MaxFrameHeightFrac float64
}
ActionButtonConfig bounds what counts as a primary action button. The defaults are measured on live frames from both geometries: the army sheet's Attack! face is 238x47 at 1280x720 and 144x27 at the 860x732 reference (aspect ~5), the gold Attack! face on the village is 124x59 (aspect 2.1), and the reward dialog's Okay is 238x96 (aspect 2.5). Shape alone cannot separate those, so the region the caller searches is what keeps village chrome out; these bounds only reject what is clearly not a button face.
func DefaultActionButtonConfig ¶
func DefaultActionButtonConfig() ActionButtonConfig
DefaultActionButtonConfig returns the bounds measured to hold on both the reference geometry and 1280x720.
type ButtonColor ¶
type ButtonColor uint8
ButtonColor names the palette family of a located action button. Clash of Clans paints primary buttons in three families, all measured on live frames: warm gold (247,177,54) for village chrome and the menu's Find a Match, green (200,237,98) for commit actions (the army sheet's Attack!, TRY AGAIN, the reward dialog's Okay), and blue (66,156,218) for the secondary panel actions such as Join Tournament.
const ( // ButtonGold is the warm gold button face. ButtonGold ButtonColor = iota // ButtonGreen is the saturated green button face. ButtonGreen // ButtonBlue is the blue secondary button face. ButtonBlue )
func (ButtonColor) String ¶
func (c ButtonColor) String() string
type DiffResult ¶
type DiffResult struct {
Comparable bool
W, H int
Changed int
Total int
Pct float64
BBox image.Rectangle
MaxDelta int
}
DiffResult is the quantitative outcome of comparing two frames.
func Diff ¶
func Diff(a, b Frame, threshold int) DiffResult
Diff compares two frames pixel by pixel. A pixel counts as changed when any colour channel differs by more than threshold, which keeps video noise and gradient dithering out of the change percentage.
func (DiffResult) Describe ¶
func (d DiffResult) Describe() string
Describe renders the one-line summary a report prints.
type Frame ¶
Frame is a read-only BGR view of a screenshot in OpenCV's pixel layout: CV_8UC3, three bytes per pixel, Stride bytes per row (Stride >= W*3).
func FrameFromMat ¶
FrameFromMat copies an OpenCV Mat into a Frame. Mat.ToBytes() returns the flattened pixel data, so the Frame owns its bytes and stays valid after the Mat is closed. A Mat whose row stride carries padding is only trusted when the flattened buffer is actually long enough for it; otherwise the frame is treated as contiguous, which is what every Mat this project creates is.
func (Frame) At ¶
At returns the colour at (x, y) in red, green, blue order. Out-of-bounds reads return black rather than panicking, because callers routinely probe mapped coordinates that a smaller screen pushed off-frame.
func (Frame) Avg ¶
Avg averages a rectangle of the frame, sampling at most `step` pixels apart so box-averaging a 10x20 cell stays cheap.
func (Frame) Copy ¶
Copy repacks a frame into a contiguous buffer, dropping any row padding. It is what makes a Frame safe to keep after its Mat is released, and what PNG writing needs.
type FrameEntry ¶
type FrameEntry struct {
ID int `json:"id"`
Time string `json:"ts"`
File string `json:"file"`
W int `json:"w"`
H int `json:"h"`
State string `json:"state"`
Score int `json:"score"`
Label string `json:"label"`
Note string `json:"note,omitempty"`
ChangedPct float64 `json:"changed_pct"`
}
FrameEntry is one recorded frame as stored in the index.
func SortEntries ¶
func SortEntries(entries []FrameEntry) []FrameEntry
SortEntries orders entries by ID ascending (the index is append-ordered, but a hand-edited file should not confuse the reader).
func (FrameEntry) Line ¶
func (e FrameEntry) Line() string
Line renders the one-line timeline row for this frame.
type FrameStore ¶
type FrameStore struct {
// contains filtered or unexported fields
}
FrameStore is an append-only recording directory.
func OpenFrameStore ¶
func OpenFrameStore(dir string) (*FrameStore, error)
OpenFrameStore prepares a recording directory (creating it if needed).
func (*FrameStore) Add ¶
func (s *FrameStore) Add(f Frame, meta FrameMeta) (FrameEntry, error)
Add writes a frame and appends its index entry, computing the change percentage against the previous frame. It returns the stored entry.
It fails with ErrLowDisk (writing nothing) when the volume is at or below the store's free-space floor: a recorder that keeps writing on a filling disk is how a review store turns into a machine-wide outage.
func (*FrameStore) ByID ¶
func (s *FrameStore) ByID(id int) (*FrameEntry, error)
ByID looks up a single recorded frame.
func (*FrameStore) Entries ¶
func (s *FrameStore) Entries() ([]FrameEntry, error)
Entries reads the whole index, skipping malformed lines rather than failing: a half-written line from an interrupted run must not make the history unreadable.
func (*FrameStore) FreeBytes ¶
func (s *FrameStore) FreeBytes() (uint64, error)
FreeBytes reports the free space on the store's volume.
func (*FrameStore) Last ¶
func (s *FrameStore) Last() (*FrameEntry, error)
Last returns the most recent entry, or nil when the store is empty.
func (*FrameStore) Load ¶
func (s *FrameStore) Load(e FrameEntry) (Frame, error)
Load reads a recorded frame back into memory.
func (*FrameStore) MinFreeBytes ¶
func (s *FrameStore) MinFreeBytes() uint64
MinFreeBytes is the configured headroom floor.
func (*FrameStore) Prune ¶
func (s *FrameStore) Prune(keep int) (int, error)
Prune keeps only the newest `keep` frames, deleting the rest so a long recording session cannot fill the disk.
func (*FrameStore) Recent ¶
func (s *FrameStore) Recent(n int) ([]FrameEntry, error)
Recent returns the last n entries in chronological order (all of them when n <= 0).
func (*FrameStore) SetMinFreeBytes ¶
func (s *FrameStore) SetMinFreeBytes(n uint64)
SetMinFreeBytes sets the volume headroom the store insists on keeping. Zero disables the low-disk check; a recording tool should only do that when the operator explicitly asked for it.
type Grid ¶
type Grid struct {
Rect image.Rectangle
CellW, CellH int
Cols, Rows int
// Truncated is set when MaxCols/MaxRows cut the region short, so the
// render covers part of Rect rather than all of it.
Truncated bool
}
Grid is the mapping between frame pixels and text cells. The same Grid is used for a frame render and its change map so the two line up column for column.
func NewGrid ¶
func NewGrid(rect image.Rectangle, opts RenderOptions) Grid
NewGrid resolves the cell size and character grid for a region.
func Render ¶
func Render(f Frame, opts RenderOptions) (string, Grid)
Render draws a frame as text. It returns the picture and the Grid it used, so a caller can convert a cell back to coordinates.
type Mark ¶
Mark is an annotation drawn into the text render so the picture shows WHERE something was found, not merely that it was found. Either a rectangle (a detected element's bounds) or a single point (a planned tap).
type MatPool ¶
type MatPool struct {
// contains filtered or unexported fields
}
func NewMatPool ¶
func NewMatPool() *MatPool
type Match ¶
func MatchMultiScale ¶
func MatchMultiScaleROI ¶
type RenderOptions ¶
type RenderOptions struct {
// Rect is the region of the frame to render. The zero value renders the
// whole frame.
Rect image.Rectangle
// Cols is the target width in characters; ignored when Cell is set or
// when the region is too small to subdivide.
Cols int
// Cell is the number of source pixels covered by one character column.
// A character row always covers twice that, which keeps the picture's
// aspect ratio (terminal cells are about twice as tall as wide). Set it
// to zoom: Cell=1 is one pixel per column, the finest a text render can
// manage.
Cell int
// Marks are drawn into the render after the glyphs.
Marks []Mark
// Ruler labels the screenshot pixel coordinate of every rendered row and
// of periodic columns. Leave it on: it is what turns the picture into
// something whose coordinates can be tapped.
Ruler bool
// Color emits 24-bit ANSI half blocks, two source pixels per cell.
Color bool
}
RenderOptions controls the text render geometry and decoration.
type ScaledTemplateCache ¶
type ScaledTemplateCache struct {
// contains filtered or unexported fields
}
func NewScaledTemplateCache ¶
func NewScaledTemplateCache() *ScaledTemplateCache
func (*ScaledTemplateCache) Close ¶
func (c *ScaledTemplateCache) Close()
func (*ScaledTemplateCache) GetOrBuild ¶
type TextRegion ¶
type TextRegion struct {
X int `json:"x"`
Y int `json:"y"`
W int `json:"w"`
H int `json:"h"`
Text string `json:"text"`
}
TextRegion is one block of recognized text in screenshot pixel coordinates, origin top-left, matching the bot's tap coordinate space.
func OCRTextRegions ¶
func OCRTextRegions(imagePath string) ([]TextRegion, error)
OCRTextRegions recognizes text in an image file, returning every region top-to-bottom. It compiles the Swift helper on first use and reuses the binary afterwards; a missing helper is reported as an error so a caller never mistakes "no text" for "no OCR".
func ParseOCRRegions ¶
func ParseOCRRegions(out string) []TextRegion
ParseOCRRegions reads the helper's "x,y,w,h | text" line format.
func SortedRegions ¶
func SortedRegions(regions []TextRegion) []TextRegion
SortedRegions puts text regions in reading order (top to bottom, then left to right) so reports are stable between runs.
func (TextRegion) Center ¶
func (t TextRegion) Center() image.Point
Center is the middle of the region, i.e. a coordinate that would tap the text if it sits on a button.
func (TextRegion) Describe ¶
func (t TextRegion) Describe() string
Describe renders one report line: box, centre, and the text.
func (TextRegion) Rect ¶
func (t TextRegion) Rect() image.Rectangle
Rect is the region's bounding box.