使用 Rust 和 Tesseract OCR 解析验证码


1. 环境准备
1.1 安装 Rust
如果你还没有安装 Rust,可以使用官方推荐的 rustup 进行安装:


curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | sh
安装完成后,使用以下命令检查:

更多内容访问ttocr.com或联系1436423940
rustc --version
1.2 安装 Tesseract OCR
在不同的操作系统上安装 Tesseract:

Windows
使用 Tesseract 官方安装包 进行安装,并配置环境变量。

Linux (Ubuntu)

sudo apt update
sudo apt install tesseract-ocr
macOS

brew install tesseract
安装完成后,检查是否可用:

tesseract --version
1.3 创建 Rust 项目
使用 cargo 创建 Rust 项目:

cargo new rust_ocr
cd rust_ocr
然后,在 Cargo.toml 文件中添加 Tesseract 绑定:

[dependencies]
tesseract = "0.14.0"
image = "0.24"
2. 代码实现
编辑 src/main.rs,添加以下代码:

use std::process::Command;
use image::{DynamicImage, GrayImage, Luma, imageops};
use tesseract::Tesseract;

/// 预处理图像(灰度化 + 二值化)
fn preprocess_image(image_path: &str, output_path: &str) -> Result<(), Box<dyn std::error::Error>> {
    let img = image::open(image_path)?;

    // 转换为灰度图像
    let gray_img: GrayImage = img.to_luma8();

    // 二值化处理,提高 OCR 识别率
    let binary_img = imageops::map_pixels(&gray_img, |_, _, p| {
        if p[0] > 128 { Luma([255]) } else { Luma([0]) }
    });

    // 保存处理后的图像
    binary_img.save(output_path)?;

    Ok(())
}

/// OCR 识别
fn recognize_text(image_path: &str) -> Result<String, Box<dyn std::error::Error>> {
    let text = Tesseract::new(None, "eng")?
        .set_image(image_path)?
        .get_text()?;
    Ok(text.trim().to_string())
}

fn main() {
    let input_image = "captcha.png";  // 请输入你的验证码图片路径
    let processed_image = "processed_captcha.png";

    println!("正在处理图像...");
    if let Err(e) = preprocess_image(input_image, processed_image) {
        eprintln!("图像处理失败: {}", e);
        return;
    }

    println!("执行 OCR 识别...");
    match recognize_text(processed_image) {
        Ok(text) => println!("识别出的验证码: {}", text),
        Err(e) => eprintln!("OCR 失败: {}", e),
    }
}
3. 代码解析
3.1 预处理图像
转换为灰度图像

二值化处理(黑白化),以提高 OCR 识别率:


let binary_img = imageops::map_pixels(&gray_img, |_, _, p| {
    if p[0] > 128 { Luma([255]) } else { Luma([0]) }
});
3.2 OCR 解析

let text = Tesseract::new(None, "eng")?
    .set_image(image_path)?
    .get_text()?;
Tesseract 解析验证码

返回解析文本

4. 运行程序
编译并运行:


cargo run
程序会加载验证码图片,进行处理并输出识别结果。

5. 提高 OCR 识别率
5.1 选择合适的 PSM 模式
可尝试 PSM 6(假设单行文本):


let text = Tesseract::new(None, "eng")?
    .set_image(image_path)?
    .set_variable("tessedit_pageseg_mode", "6")?
    .get_text()?;
5.2 进一步图像优化
降噪

字符分割

猜你喜欢

转载自blog.csdn.net/asfdsgdf/article/details/146444758
今日推荐