使用 D 语言与 Tesseract 实现图像验证码识别

一、准备工作
安装 D 编译器
推荐使用 DMD 或 LDC 编译器。

安装 dub(D 的构建工具和包管理器):
更多内容访问ttocr.com或联系1436423940

安装 dmd 时通常已自带 dub,可通过以下命令确认:

dub --version
安装 Tesseract OCR

Ubuntu / Debian

sudo apt install tesseract-ocr

macOS

brew install tesseract
二、创建 D 项目

dub init d_captcha_app console
cd d_captcha_app
三、编辑 source/app.d

import std.stdio;
import std.process;
import std.string;
import std.file;
import std.regex;

string recognizeCaptcha(string imagePath) {
string outputBase = "d_output";
string whitelist = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";

auto command = format("tesseract %s %s -l eng -c tessedit_char_whitelist=%s", imagePath, outputBase, whitelist);

int result = system(command);
if (result != 0) {
    return "识别失败";
}

string outputFile = outputBase ~ ".txt";

if (!exists(outputFile)) {
    return "未找到输出文件";
}

string content = readText(outputFile);
std.file.remove(outputFile);

auto re = regex("[A-Z0-9]");
auto matches = matchAll(content.toUpper(), re);
return matches.map!(m => m.hit).joiner.array.join;

}

void main() {
string image = "captcha1.png"; // 替换为你的验证码图片路径
string result = recognizeCaptcha(image);
writeln("识别结果: ", result);
}
四、运行程序
确保有图片 captcha1.png 放在当前目录:

dub run
输出示例:

识别结果: 7KZ9
五、扩展功能:批量识别目录下验证码
修改 main 函数如下:

import std.algorithm;
import std.file;
import std.path;

void main() {
string folder = "captchas";
auto files = dirEntries(folder, "*.png");

foreach (entry; files) {
    string result = recognizeCaptcha(entry.name);
    writeln(entry.name.baseName, " -> ", result);
}

}

posted @ 2025-07-01 21:09  ttocr、com  阅读(12)  评论(0)    收藏  举报