Rust + Tesseract OCR 解析验证码


1. 环境准备
1.1 安装 Rust
Rust 采用 rustup 进行管理,使用以下命令安装:

bash

curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | sh
安装后,验证 Rust 是否安装成功:

bash

rustc --version
1.2 安装 Tesseract OCR
Linux/macOS
bash

sudo apt install tesseract-ocr  # Ubuntu
brew install tesseract          # macOS
Windows
使用 choco 安装:

powershell

choco install tesseract
然后检查 Tesseract 是否可用:

bash

tesseract --version
1.3 创建 Rust 项目
bash

cargo new captcha_ocr
cd captcha_ocr
1.4 添加 Tesseract 绑定
编辑 Cargo.toml,添加 leptess 依赖:

toml

[dependencies]
leptess = "0.13"
image = "0.24"
2. 代码实现
在 src/main.rs 中编写如下代码:

rust

use leptess::{LepTess, Variable};
use image::{GrayImage, Luma};
use std::path::Path;

/// 进行 OCR 识别
fn recognize_captcha(image_path: &str) -> Result<String, Box<dyn std::error::Error>> {
    // 加载 Tesseract OCR
    let mut ocr = LepTess::new(None, "eng")?;
    ocr.set_variable(Variable::TesseditPagesegMode, "6")?; // 设定页面分割模式

    // 预处理图像(转换为灰度)
    let img = image::open(image_path)?.into_luma8();
    let processed_path = "processed_captcha.png";
    img.save(processed_path)?;

    // 进行 OCR 识别
    ocr.set_image(processed_path);
    let text = ocr.get_utf8_text()?;
    
    Ok(text.trim().to_string())
}

fn main() {
    let image_path = "captcha.png"; // 你的验证码图片路径
    match recognize_captcha(image_path) {
        Ok(text) => println!("识别出的验证码: {}", text),
        Err(e) => eprintln!("OCR 识别失败: {}", e),
    }
}
3. 代码解析
3.1 加载 Tesseract
rust

let mut ocr = LepTess::new(None, "eng")?;
LepTess::new(None, "eng") 创建 OCR 实例,使用英语模型。

3.2 预处理图像
rust

let img = image::open(image_path)?.into_luma8();
img.save(processed_path)?;
使用 image 库将验证码转换为灰度图,提高 OCR 识别率。

3.3 OCR 解析

ocr.set_image(processed_path);
let text = ocr.get_utf8_text()?;
set_image(processed_path) 设置识别的验证码图像。

get_utf8_text() 获取识别结果。

4. 运行 OCR 识别
编译并运行:


cargo run
终端将输出识别的验证码内容。

5. 提高 OCR 识别率
5.1 设置合适的 PSM 模式

ocr.set_variable(Variable::TesseditPagesegMode, "6")?;
PSM 6 适用于单行验证码解析。

5.2 进一步图像优化
可以使用 OpenCV 进行二值化:

let binary_img = img.map(|p| if p[0] > 128 { Luma([255]) } else { Luma([0]) });
binary_img.save("binary_captcha.png")?;

猜你喜欢

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