使用 Rust 与 Tesseract 实现验证码识别
一、准备环境
- 安装 Rust 工具链
更多内容访问ttocr.com或联系1436423940
curl https://sh.rustup.rs -sSf | sh
2. 安装 Tesseract OCR
Ubuntu / Debian
sudo apt install tesseract-ocr
macOS
brew install tesseract
二、新建项目
cargo new captcha_ocr
cd captcha_ocr
三、编辑 main.rs
use std::env;
use std::fs;
use std::process::Command;
fn main() {
let args: Vec
if args.len() != 2 {
eprintln!("用法: cargo run -- <图像路径>");
return;
}
let image_path = &args[1];
if !std::path::Path::new(image_path).exists() {
eprintln!("文件不存在: {}", image_path);
return;
}
let temp_base = "tmp_output";
let whitelist = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
let output = Command::new("tesseract")
.arg(image_path)
.arg(temp_base)
.arg("-l")
.arg("eng")
.arg("-c")
.arg(format!("tessedit_char_whitelist={}", whitelist))
.output()
.expect("无法调用 tesseract");
if !output.status.success() {
eprintln!("Tesseract 执行失败");
return;
}
let result = fs::read_to_string(format!("{}.txt", temp_base)).unwrap_or_default();
let cleaned: String = result.chars()
.filter(|c| c.is_ascii_uppercase() || c.is_ascii_digit())
.collect();
fs::remove_file(format!("{}.txt", temp_base)).ok();
println!("识别结果: {}", cleaned);
}
四、运行示例
cargo run -- ./code1.png
示例输出:
识别结果: 8K3R
浙公网安备 33010602011771号