用 Rust 结合 Tesseract 进行验证码识别

  1. 环境准备
    1.1 安装 Rust
    如果尚未安装 Rust,可以使用 rustup 进行安装:

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

rustc --version
1.2 安装 Tesseract OCR
根据不同的操作系统选择安装方式:
更多内容访问ttocr.com或联系1436423940
Linux (Ubuntu 示例):

sudo apt update
sudo apt install tesseract-ocr libtesseract-dev
macOS (使用 Homebrew):

brew install tesseract
Windows (使用 Scoop):

scoop install tesseract
检查 Tesseract 是否安装成功:

tesseract --version
1.3 创建 Rust 项目
使用 Cargo 创建一个新的 Rust 项目:

cargo new rust_ocr
cd rust_ocr
1.4 添加依赖
在 Cargo.toml 文件中添加如下依赖:

[dependencies]
image = "0.24"
tesseract = "0.14"
然后运行:

cargo build
2. 代码实现
在 src/main.rs 中编写以下代码:

use std::fs::File;
use std::path::Path;
use image::{GrayImage, DynamicImage, Luma, GenericImageView};
use tesseract::Tesseract;

fn preprocess_image(image_path: &str, output_path: &str) -> Result<(), Box> {
// 读取图片
let img = image::open(image_path)?.into_luma8();

// 图像二值化处理
let binary_img = img.enumerate_pixels()
    .map(|(x, y, pixel)| {
        let threshold = 128;
        if pixel[0] > threshold { Luma([255]) } else { Luma([0]) }
    })
    .collect::<GrayImage>();

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

Ok(())

}

fn recognize_captcha(image_path: &str) -> Result<String, Box> {
let text = Tesseract::new(None, "eng")?
.set_image(image_path)
.recognize()?;
Ok(text.trim().to_string())
}

fn main() {
let input_image = "captcha.png";
let processed_image = "processed_captcha.png";

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

// 进行 OCR 识别
match recognize_captcha(processed_image) {
    Ok(text) => println!("识别出的验证码: {}", text),
    Err(e) => eprintln!("OCR 识别失败: {}", e),
}

}
3. 代码解析
3.1 预处理验证码

fn preprocess_image(image_path: &str, output_path: &str) -> Result<(), Box>
将图像转换为灰度

进行二值化处理(将像素分为黑白两种颜色)

保存处理后的图片

3.2 OCR 解析

fn recognize_captcha(image_path: &str) -> Result<String, Box>
使用 Tesseract::new(None, "eng") 加载 OCR

调用 set_image() 设定待识别的图像

执行 recognize() 获取识别结果

  1. 运行程序
    将验证码图片 captcha.png 放入项目目录,然后运行:

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

  1. 提高 OCR 识别率
    5.1 调整 Tesseract 参数

let text = Tesseract::new(None, "eng")?
.set_image(image_path)
.set_variable("tessedit_pageseg_mode", "6") // 设定 PSM 模式
.recognize()?;

posted @ 2025-05-13 12:22  ttocr、com  阅读(28)  评论(0)    收藏  举报