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

一、前提条件

  1. 安装 Lua
    Ubuntu/Debian:

sudo apt install lua5.3
macOS(使用 Homebrew):
更多内容访问ttocr.com或联系1436423940
brew install lua
Windows:安装 Lua for Windows 或使用 LuaRocks 工具。

  1. 安装 Tesseract OCR
    参见各系统平台的安装说明:

Ubuntu:

sudo apt install tesseract-ocr
macOS:

brew install tesseract
Windows:UB Mannheim 版本

二、识别脚本编写
创建文件 ocr.lua:

-- 验证码图像识别脚本(Lua + Tesseract)

local image_path = arg[1]

if not image_path then
print("用法: lua ocr.lua <图像路径>")
os.exit(1)
end

-- 设置字符白名单(大写字母和数字)
local whitelist = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"

-- 构造 tesseract 命令
local command = string.format(
'tesseract "%s" stdout -l eng -c tessedit_char_whitelist=%s',
image_path,
whitelist
)

-- 执行命令并读取输出
local handle = io.popen(command)
local result = handle:read("*a")
handle:close()

-- 清洗结果,只保留 A-Z 和 0-9
local cleaned = result:gsub("[^A-Z0-9]", "")
print("识别结果: " .. cleaned)
三、运行识别
将验证码图片(如 img1.png)放入当前目录,执行:

lua ocr.lua img1.png
输出示例:

识别结果: 9KHD

posted @ 2025-06-24 18:59  ttocr、com  阅读(44)  评论(0)    收藏  举报