用 Rust 进行英文数字验证码识别

验证码识别是 OCR 技术的典型应用之一。本文将介绍如何用 Rust 调用 Tesseract OCR 引擎实现英文数字验证码的识别。你将了解 Rust 中如何处理图像、调用外部命令以及构建一个基础的识别程序。

一、环境准备

  1. 安装 Rust 和 Tesseract
    安装 Rust(建议使用 rustup)

curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | sh
安装 Tesseract OCR:

Ubuntu / Debian:

sudo apt install tesseract-ocr
macOS:

brew install tesseract
Windows:
下载 Tesseract 安装包

确保 tesseract 命令可在终端中调用。

二、新建 Rust 项目

cargo new captcha_ocr
cd captcha_ocr
三、添加依赖
在 Cargo.toml 中添加:

[dependencies]
image = "0.25"
我们使用 image crate 来处理图像文件(灰度处理等)。

四、Rust 代码实现
编辑 src/main.rs:

use std::process::Command;
use std::fs::File;
use std::path::Path;
use image::{DynamicImage, GenericImageView, GrayImage, ImageBuffer, Luma, io::Reader as ImageReader};

fn convert_to_grayscale(input_path: &str, output_path: &str) -> Result<(), Box> {
let img = ImageReader::open(input_path)?.decode()?;
let gray = img.to_luma8();
gray.save(output_path)?;
Ok(())
}

fn run_tesseract(image_path: &str) -> Result<String, Box> {
let output = Command::new("tesseract")
.arg(image_path)
.arg("stdout")
.arg("-l")
.arg("eng")
.arg("--psm")
.arg("7") // 单行识别模式,适合验证码
.output()?;

if output.status.success() {
    Ok(String::from_utf8_lossy(&output.stdout).trim().to_string())
} else {
    Err("Tesseract 执行失败".into())
}

}

fn main() {
let input_img = "captcha.png";
let gray_img = "gray_captcha.png";

println!("处理图像...");
if let Err(e) = convert_to_grayscale(input_img, gray_img) {
    eprintln!("图像处理失败: {}", e);
    return;
}

println!("识别验证码...");
match run_tesseract(gray_img) {
    Ok(text) => println!("识别结果: {}", text),
    Err(e) => eprintln!("识别失败: {}", e),
}

}
五、运行程序
确保当前目录有一张 captcha.png 验证码图像:

cargo run
输出示例:

处理图像...
识别验证码...
识别结果: 7G9D2

posted @ 2025-06-07 20:54  ttocr、com  阅读(18)  评论(0)    收藏  举报