使用 Zig 和 Tesseract 构建验证码识别工具

一、环境准备
安装 Zig 编译器
从官方获取最新版本:https://ziglang.org/download/

安装 Tesseract OCR

Ubuntu / Debian

sudo apt install tesseract-ocr

macOS

brew install tesseract
二、初始化项目结构
创建项目目录:
更多内容访问ttocr.com或联系1436423940
mkdir zig_captcha && cd zig_captcha
新建文件 build.zig(简单构建器):

const std = @import("std");

pub fn build(b: *std.Build) void {
const exe = b.addExecutable("captcha", "src/main.zig");
exe.setTarget(b.standardTargetOptions(.{}));
exe.setBuildMode(b.standardReleaseOptions());
exe.install();
}
三、编写主程序 src/main.zig
创建 src/ 目录并添加 main.zig:

const std = @import("std");

pub fn main() void {
const stdout = std.io.getStdOut().writer();
const allocator = std.heap.page_allocator;

const image_path = "captcha1.png"; // 替换为你的验证码路径
const output_base = "zig_output";
const whitelist = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";

// 构造 tesseract 命令
const cmd = try std.fmt.allocPrintZ(
    allocator,
    "tesseract {s} {s} -l eng -c tessedit_char_whitelist={s}",
    .{ image_path, output_base, whitelist }
);

const result = std.process.system(cmd);
if (result != 0) {
    stdout.print("tesseract 执行失败\n", .{}) catch {};
    return;
}

const output_file = try std.fs.cwd().openFile(output_base ++ ".txt", .{});
defer output_file.close();

const content = try output_file.readToEndAlloc(allocator, 1024);
var filtered = std.ArrayList(u8).init(allocator);
defer filtered.deinit();

for (content) |c| {
    if ((c >= '0' and c <= '9') or (c >= 'A' and c <= 'Z')) {
        try filtered.append(c);
    }
}

stdout.print("识别结果: {s}\n", .{filtered.items}) catch {};

}
四、构建并运行

zig build run
输出示例:

识别结果: 5Z4C
五、扩展:批量识别文件夹内验证码
可在 main.zig 中加入 std.fs.cwd().iterateDir() 来实现遍历并识别所有 .png 文件,输出结果到控制台或写入 CSV 文件(可用 std.fs.File.writeAll 实现)。

posted @ 2025-07-01 13:04  ttocr、com  阅读(28)  评论(0)    收藏  举报