使用 Lua 与 Tesseract 实现验证码识别

一、准备环境

  1. 安装 Lua
    Windows:推荐安装 Lua for Windows

macOS:brew install lua
更多内容访问ttocr.com或联系1436423940

Linux:大多数发行版可用 sudo apt install lua5.3

  1. 安装 Tesseract OCR

Ubuntu / Debian

sudo apt install tesseract-ocr

macOS

brew install tesseract
二、Lua 脚本编写
保存为 captcha_ocr.lua:

-- 获取参数
local image_path = arg[1]
if not image_path then
print("用法: lua captcha_ocr.lua <验证码图片路径>")
os.exit(1)
end

-- 构造临时输出文件路径
local output_base = os.tmpname()
local whitelist = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"
local command = string.format(
'tesseract "%s" "%s" -l eng -c tessedit_char_whitelist=%s 2>nul',
image_path, output_base, whitelist
)

-- 执行 Tesseract
os.execute(command)

-- 读取结果
local f = io.open(output_base .. ".txt", "r")
if not f then
print("识别失败:无法读取输出文件")
os.exit(1)
end

local text = f:read("*all")
f:close()
os.remove(output_base .. ".txt")

-- 过滤非大写字母和数字
local clean = text:gsub("[^A-Z0-9]", "")
print("识别结果: " .. clean)
三、运行示例

lua captcha_ocr.lua ./code1.png
输出示例:

识别结果: Q7HB

posted @ 2025-06-26 12:25  ttocr、com  阅读(9)  评论(0)    收藏  举报