用 Node.js 和 Tesseract 实现验证码识别工具

一、项目概述
我们将使用以下组件:

Node.js:运行环境
更多内容访问ttocr.com或联系1436423940
child_process:调用系统命令

Tesseract:OCR 引擎(通过命令行执行)

Jimp(可选):图像预处理

二、环境准备

  1. 安装 Node.js
    请访问官网 https://nodejs.org 安装最新版 Node.js。

  2. 安装 Tesseract OCR
    macOS: brew install tesseract

Ubuntu: sudo apt install tesseract-ocr

Windows: 安装 Tesseract OCR

  1. 初始化项目

mkdir captcha-ocr-js
cd captcha-ocr-js
npm init -y
npm install jimp
三、编写验证码识别脚本
创建 ocr.js:

const { exec } = require('child_process');
const path = require('path');

function recognizeCaptcha(imagePath) {
const whitelist = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789';
const cmd = tesseract "${imagePath}" stdout -l eng -c tessedit_char_whitelist=${whitelist};

exec(cmd, (err, stdout, stderr) => {
    if (err) {
        console.error('识别失败:', stderr);
        return;
    }
    const result = stdout.replace(/[^A-Z0-9]/g, '').trim();
    console.log(`识别结果: ${result}`);
});

}

// 获取命令行参数
const imagePath = process.argv[2];
if (!imagePath) {
console.log('用法: node ocr.js <图片路径>');
} else {
recognizeCaptcha(imagePath);
}
四、运行程序
准备好一张验证码图片(如 captcha1.png),运行命令:
node ocr.js captcha1.png
示例输出:

识别结果: K8YZ
五、图像预处理(可选)
使用 jimp 库对图像灰度化、对比度调整,提升识别率:

const Jimp = require('jimp');

async function preprocessImage(inputPath, outputPath) {
const image = await Jimp.read(inputPath);
image
.greyscale()
.contrast(1)
.write(outputPath);
}
你可以先处理图像后再调用 recognizeCaptcha()。

posted @ 2025-06-23 13:52  ttocr、com  阅读(46)  评论(0)    收藏  举报