!752 static Map chars; static bool debug; !include #1000522 p { chars = loadGlyphSheet("#1004645"); Map words = loadGlyphSheet("#1004649"); chars = mapValues("unChar", chars); printStructure(values(words)); double score = 0, total = 0; for (BWImage img : keys(words)) { debug = false; S w; try { w = recognizeWord(img); } catch e { w = exceptionToStringShort(e); } S real = words.get(img); print(real + " => " + w); ++total; if (eq(real, w)) { ++score; print(" ok!"); } else { print(" oops..."); debug = true; try { recognizeWord(img); } catch {} } } print(); print("SCORE: " + formatDouble(score, 1) + "/" + formatDouble(total, 1)); } static S recognizeWord(BWImage iw) { int w = iw.getWidth(); new StringBuilder buf; xloop: for (int x = 0; x < w; x++) { if (debug) print("Best match at " + x + ": " + structure(bestMatch(iw, x))); for (BWImage ic : keys(chars)) { if (preciseMatch(ic, iw, x)) { buf.append(chars.get(ic)); x += ic.getWidth()-1; continue xloop; } } } ret str(buf); } sclass Lowest { A a; double score; void update(A x, double s) { if (a == null || s < score) { a = x; score = s; } } Pair getPair() { ret a == null ? null : pair(a, score); } } static Pair bestMatch(BWImage iw, int x) { new Lowest best; for (BWImage ic : keys(chars)) { double d = diff(ic, iw.clip(x, 0, ic.getWidth(), ic.getHeight())); best.update(chars.get(ic), d); } ret best.getPair(); } static bool preciseMatch(BWImage ic, BWImage iw, int x1) { int w = iw.getWidth(), h = iw.getHeight(); if (ic.getHeight() != h) false; int x2 = x1+ic.getWidth(); if (x2 > w) false; for (int x = x1; x < x2; x++) for (int y = 0; y < h; y++) if (ic.getPixel(x-x1, y) != iw.getPixel(x, y)) false; true; } static S unChar(S s) { try { int i = s.indexOf('-'); if (i > 0) s = substring(s, 0, i); ret str((char) hexToInt(s)); } catch { ret "[" + s + "]"; } }