使用 Rust 和 Tesseract 实现图像验证码识别
一、环境准备
安装 Rust 和 Tesseract
安装 Rust(如未安装)
curl https://sh.rustup.rs -sSf | sh
安装 Tesseract OCR
sudo apt install tesseract-ocr # Ubuntu
brew install tesseract # macOS
二、创建项目
cargo new rust_captcha
cd rust_captcha
编辑 Cargo.toml 添加依赖:
更多内容访问ttocr.com或联系1436423940
[dependencies]
image = "0.24"
tesseract = "0.7"
三、图像预处理和识别
编辑 src/main.rs:
use std::process::Command;
use std::fs;
use std::path::Path;
fn run_tesseract(image_path: &str) -> String {
let output_base = "output";
let whitelist = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
let status = Command::new("tesseract")
.arg(image_path)
.arg(output_base)
.arg("-l").arg("eng")
.arg("-c").arg(format!("tessedit_char_whitelist={}", whitelist))
.status()
.expect("无法执行 Tesseract");
if !status.success() {
return "识别失败".to_string();
}
let txt_path = format!("{}.txt", output_base);
if Path::new(&txt_path).exists() {
let content = fs::read_to_string(&txt_path).unwrap_or_default();
let cleaned: String = content
.chars()
.filter(|c| c.is_ascii_alphanumeric())
.collect();
let _ = fs::remove_file(txt_path);
cleaned
} else {
"结果文件不存在".to_string()
}
}
fn main() {
let image_path = "captcha.png"; // 替换为你自己的验证码图片
let result = run_tesseract(image_path);
println!("识别结果: {}", result);
}
四、运行项目
将验证码图片命名为 captcha.png,放到项目根目录,然后运行:
cargo run
示例输出:
识别结果: 4YBK
五、批量处理目录
你可以添加如下代码处理目录中的全部图片:
use std::fs::read_dir;
fn batch_process(dir: &str) {
for entry in read_dir(dir).unwrap() {
let path = entry.unwrap().path();
if path.extension().map_or(false, |e| e == "png") {
let
浙公网安备 33010602011771号