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

一、准备工作
安装 D 编译器
使用 D 官方工具链 DMD:
更多内容访问ttocr.com或联系1436423940

Linux / macOS

curl -fsS https://dlang.org/install.sh | bash
source ~/dlang/dmd-*/activate
安装 Tesseract OCR

macOS

brew install tesseract

Ubuntu

sudo apt install tesseract-ocr
二、创建项目文件
创建一个名为 captcha_ocr.d 的文件:

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

string cleanText(string input) {
auto re = regex("[A-Z0-9]");
return input.matchAll(re).map!(m => m.hit).joiner("").join();
}

string recognizeCaptcha(string imagePath) {
string outputBase = "ocr_result";
string whitelist = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
string cmd = format("tesseract %s %s -l eng -c tessedit_char_whitelist=%s",
imagePath, outputBase, whitelist);

auto result = executeShell(cmd);
if (result.status != 0) {
    writeln("Tesseract 执行失败:", result.output);
    return "";
}

string outputFile = outputBase ~ ".txt";
if (!exists(outputFile)) {
    writeln("识别失败:输出文件未生成");
    return "";
}

string content = readText(outputFile);
std.file.remove(outputFile); // 删除临时文件
return cleanText(content);

}

void main() {
string path = "captcha1.png"; // 替换为你的验证码图片路径
string result = recognizeCaptcha(path);
writeln("识别结果: ", result);
}
三、编译与运行
使用 dmd 编译器:

dmd captcha_ocr.d
./captcha_ocr
示例输出:

识别结果: 9A2G
四、扩展能力
批量处理文件夹中的验证码图像

import std.file : dirEntries;

foreach (entry; dirEntries("captchas", "*.png")) {
auto res = recognizeCaptcha(entry.name);
writeln(entry.name, " -> ", res);
}
写入识别结果到 CSV 文件

import std.csv;
auto file = File("results.csv", "w");
file.writeln("filename,text");
foreach (entry; dirEntries("captchas", "*.png")) {
string res = recognizeCaptcha(entry.name);
file.writeln(format("%s,%s", entry.name, res));
}
file.close();

posted @ 2025-06-30 13:47  ttocr、com  阅读(4)  评论(0)    收藏  举报