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

一、准备环境
安装 Lua(建议使用 Lua 5.3 或 5.4)

macOS

brew install lua

Ubuntu

sudo apt install lua5.3

Windows

可从 Lua 官网或 LuaBinaries 下载
安装 Tesseract OCR
更多内容访问ttocr.com或联系1436423940

macOS

brew install tesseract

Ubuntu

sudo apt install tesseract-ocr
二、Lua 脚本实现(captcha.lua)

-- 清洗文本,只保留大写字母和数字
function clean_text(s)
return s:gsub("[^A-Z0-9]", "")
end

-- 调用 tesseract 进行识别
function recognize_captcha(image_path)
local output_base = "tess_output"
local whitelist = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"

local cmd = string.format(
'tesseract %s %s -l eng -c tessedit_char_whitelist=%s',
image_path, output_base, whitelist
)
os.execute(cmd)

local f = io.open(output_base .. ".txt", "r")
if not f then
print("识别失败:未找到输出文件")
return
end

local content = f:read("*a")
f:close()
os.remove(output_base .. ".txt")

local cleaned = clean_text(content)
print("识别结果: " .. cleaned)
end

-- 示例调用
recognize_captcha("captcha1.png") -- 请替换为你的验证码图片路径
三、运行脚本
确保 captcha1.png 存在,然后运行:

lua captcha.lua
示例输出:

识别结果: B8F7
四、功能扩展建议
遍历目录中所有验证码图像:

for file in io.popen('ls captcha_folder/*.png'):lines() do
recognize_captcha(file)
end
输出结果到 CSV:

local csv = io.open("result.csv", "a")
csv:write(file .. "," .. cleaned .. "\n")
csv:close()
使用 ImageMagick 对图像做预处理(如灰度化、锐化):

convert captcha1.png -colorspace Gray -sharpen 0x1 captcha1_gray.png
在 Lua 中调用:

os.execute('convert ' .. path .. ' -colorspace Gray -sharpen 0x1 temp.png')
recognize_captcha('temp.png')
os.remove('temp.png')

posted @ 2025-06-29 18:25  ttocr、com  阅读(15)  评论(0)    收藏  举报