使用 Zig 和 Tesseract 实现图像验证码识别

一、环境准备
安装 Zig
从官网下载:https://ziglang.org/download/

验证版本:
更多内容访问ttocr.com或联系1436423940
zig version
安装 Tesseract

Ubuntu / Debian

sudo apt install tesseract-ocr

macOS

brew install tesseract
二、创建项目文件
创建目录:

mkdir zig_captcha
cd zig_captcha
创建源文件:

touch main.zig
三、编写识别程序
编辑 main.zig:

const std = @import("std");

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

var args = try std.process.argsAlloc(allocator);
defer std.process.argsFree(allocator, args);

if (args.len < 2) {
    try stdout.print("用法: {} <图片路径>\n", .{args[0]});
    return;
}

const image_path = args[1];
const output_base = "output";
const whitelist = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";

const command = try std.fmt.allocPrint(allocator,
    "tesseract {s} {s} -l eng -c tessedit_char_whitelist={s}",
    .{ image_path, output_base, whitelist });
defer allocator.free(command);

var result = try std.ChildProcess.exec(.{
    .allocator = allocator,
    .argv = &[_][]const u8{ "sh", "-c", command },
});

if (result.term.Exited != 0) {
    try stdout.print("Tesseract 识别失败\n", .{});
    return;
}

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

var buf: [1024]u8 = undefined;
const len = try file.readAll(&buf);
const text = buf[0..len];
const cleaned = try filterText(allocator, text);
try stdout.print("识别结果: {s}\n", .{cleaned});

}

fn filterText(allocator: std.mem.All

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