-
Notifications
You must be signed in to change notification settings - Fork 0
/
3_recognizeCaptcha.ts
71 lines (50 loc) · 1.74 KB
/
3_recognizeCaptcha.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
import * as path from "https://deno.land/[email protected]/path/mod.ts";
import jimp from 'npm:jimp';
import { processAndSplitDigits } from './utils.ts';
const __dirname = path.dirname(path.fromFileUrl(import.meta.url));
async function loadTemplates(): Promise<jimp[]> {
const templates: jimp[] = [];
for (let i = 0; i <= 9; i++) {
const template = await jimp.read(path.join(__dirname, `./templates/${i}.jpg`));
templates.push(template);
}
return templates;
}
function calculateMSE(image1: jimp, image2: jimp): number {
let mse = 0;
const width = image1.bitmap.width;
const height = image1.bitmap.height;
for (let y = 0; y < height; y++) {
for (let x = 0; x < width; x++) {
const idx = (y * width + x) * 4;
const diff = image1.bitmap.data[idx] - image2.bitmap.data[idx];
mse += diff * diff;
}
}
return mse / (width * height);
}
async function recognizeCaptcha(imagePath: string, templates: jimp[]): Promise<string> {
const digits = await processAndSplitDigits(imagePath);
let recognizedDigits = '';
for (let i = 0; i < 4; i++) {
const digitImage = await jimp.read(digits[i]);
let minMSE = Infinity;
let bestMatch = -1;
for (let t = 0; t < templates.length; t++) {
const template = templates[t];
const mse = calculateMSE(digitImage, template);
if (mse < minMSE) {
minMSE = mse;
bestMatch = t;
}
}
recognizedDigits += bestMatch;
}
return recognizedDigits;
}
const templates = await loadTemplates();
for (let i = 1; i <= 20; i++) {
const imagePath = path.join(__dirname, `./images/captcha_${i}.jpg`);
const recognizedCaptcha = await recognizeCaptcha(imagePath, templates);
console.log(`Recognized captcha: ${recognizedCaptcha}`);
}