使用 TypeScript 和 Tesseract.js 实现验证码图像识别
一、项目介绍
Tesseract.js 是 Tesseract OCR 的 WebAssembly 封装,支持在 Node.js 和浏览器中运行。本项目将使用 TypeScript 构建一个命令行工具,加载验证码图像,识别其中的英文和数字内容。
二、环境准备
安装 Node.js 和 TypeScript
建议使用最新版 Node.js 和 npm:
更多内容访问ttocr.com或联系1436423940
npm install -g typescript
创建项目目录
mkdir captcha-ts-ocr
cd captcha-ts-ocr
npm init -y
安装依赖
npm install tesseract.js @types/node
npm install --save-dev typescript ts-node
创建 tsconfig.json:
{
"compilerOptions": {
"target": "ES2020",
"module": "commonjs",
"esModuleInterop": true,
"strict": true
}
}
三、添加验证码识别代码
创建 index.ts:
import * as Tesseract from 'tesseract.js';
import * as path from 'path';
const imagePath = path.resolve(__dirname, 'captcha.png');
(async () => {
console.log('开始识别验证码...');
const { data: { text } } = await Tesseract.recognize(
imagePath,
'eng',
{
tessedit_char_whitelist: 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789',
logger: m => console.log(m.status, m.progress)
}
);
const cleaned = text.replace(/[^A-Za-z0-9]/g, '').trim();
console.log(识别结果为: ${cleaned});
})();
四、准备验证码图像
将验证码图像命名为 captcha.png 并放在项目根目录。
图像建议为清晰的 PNG 或 JPEG 格式(不包含复杂干扰线)。
五、运行程序
在命令行中运行:
npx ts-node index.ts
输出示例:
识别结果为: K39AB
六、进阶功能建议
图像预处理:使用 sharp 模块对图像进行灰度化或放大:
npm install sharp
预处理代码示例:
import sharp from 'sharp';
await sharp('captcha.png')
.grayscale()
.threshold(120)
.toFile('processed.png');
然后再识别 processed.png。
批量识别多个图像
前端版本:Tesseract.js 支持在浏览器中直接使用,非常适合无后端的 Web 应用。
浙公网安备 33010602011771号