使用 Rust + Tesseract OCR 实现验证码识别

一、准备工作

安装 Rust 如果尚未安装 Rust,请使用官方推荐的方式安装:
curl --proto '=https' --tlsv1.2 -sSf  https://sh.rustup.rs | sh 2. 安装 Tesseract OCR 确保你已在系统中安装了 Tesseract OCR:

macOS: brew install tesseract

Ubuntu: sudo apt install tesseract-ocr

Windows: 安装包下载

二、创建项目

cargo new captcha_ocr cd captcha_ocr 三、添加依赖 编辑 Cargo.toml,添加:

[dependencies] tesseract = "0.8" image = "0.24" 四、识别验证码代码示例 编辑 src/main.rs:

use tesseract::Tesseract; use std::path::Path;

fn main() { // 需要识别的图像路径 let image_path = "captcha.png";

复制
// 初始化 Tesseract OCR 引擎
let mut tess = Tesseract::new(None, Some("eng"))
.expect("初始化 Tesseract 引擎失败");

// 加载图像
tess.set_image(Path::new(image_path))
.expect("加载图像失败");

// 可选:限制识别字符集
tess.set_variable("tessedit_char_whitelist", "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789")
.expect("设置字符集失败");

// 执行识别
let text = tess.get_text()
.expect("识别失败");

println!("识别的验证码是: {}", text.trim());
1.
2.
3.
4.
5.
6.
7.
8.
9.
10.
11.
12.
13.
14.
15.
16.
17.
} 五、运行程序 确保 captcha.png 存在于项目根目录下:

cargo run 示例输出:

识别的验证码是: G7TK9

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