使用 Rust + Tesseract CLI 实现英文数字验证码识别

在本教程中,我们将:

用 image 库处理验证码图像(灰度化)

使用命令行方式调用 Tesseract OCR

识别英文数字验证码并输出结果

一、准备工作
安装依赖
先确保你安装了:

Rust 开发环境:https://www.rust-lang.org/zh-CN/tools/install

Tesseract OCR:

macOS

brew install tesseract

Ubuntu/Debian

sudo apt install tesseract-ocr
二、创建项目并添加依赖
初始化项目:

cargo new captcha_ocr
cd captcha_ocr
编辑 Cargo.toml:

[dependencies]
image = "0.24"
三、编写识别代码
修改 src/main.rs:

use std::process::Command;
use std::path::Path;
use image::{GenericImageView, ImageBuffer, Luma};

fn main() {
let input_path = "captcha.png";
let output_path = "gray_captcha.png";

// 加载图像并转换为灰度
let img = image::open(&input_path).expect("无法打开图像");
let gray = img.to_luma8();

// 保存灰度图
gray.save(&output_path).expect("保存失败");

// 调用 Tesseract 进行 OCR
let output = Command::new("tesseract")
    .arg(&output_path)
    .arg("stdout")
    .arg("-l")
    .arg("eng")
    .arg("--psm")
    .arg("8")
    .arg("tessedit_char_whitelist=ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789")
    .output()
    .expect("无法执行 tesseract");

let text = String::from_utf8_lossy(&output.stdout);
println!("识别的验证码是: {}", text.trim());

}
四、准备验证码图像
命名为 captcha.png

图片放入项目根目录

推荐为 4~6 位英数字符,清晰可读

五、运行程序
在项目根目录下运行:

cargo run
输出类似:

识别的验证码是: F9KX2
六、可选优化建议
使用 imageproc 进行二值化、腐蚀、去噪等处理

将此程序封装为 CLI 工具或服务 API

支持识别多个图像,适用于验证码批量识别任务

posted @ 2025-04-11 18:59  ttocr、com  阅读(11)  评论(0)    收藏  举报