基于 Elixir 与 Tesseract 的验证码识别工具构建
一、项目简介
Elixir 是一门基于 Erlang 虚拟机(BEAM)的函数式编程语言,以高并发著称。虽然其在图像处理领域并不常见,但通过调用外部工具(如 Tesseract OCR),我们同样可以实现高效稳定的验证码识别流程。
二、项目环境配置
- 安装 Elixir
macOS: brew install elixir
Ubuntu: sudo apt install elixir
更多内容访问ttocr.com或联系1436423940
Windows: 使用 Elixir Installer
验证安装:
elixir -v
2. 安装 Tesseract OCR
macOS: brew install tesseract
Ubuntu: sudo apt install tesseract-ocr
Windows: 下载并添加 tesseract 到系统 PATH
三、新建 Mix 项目
mix new captcha_ocr
cd captcha_ocr
编辑 mix.exs 添加依赖:
defp deps do
[
{:porcelain, "~> 2.0"}
]
end
安装依赖:
mix deps.get
四、识别逻辑实现
创建文件 lib/captcha_ocr.ex,实现 Tesseract 调用逻辑:
defmodule CaptchaOCR do
use Porcelain
def recognize(image_path) do
cmd = "tesseract"
args = [image_path, "stdout", "-l", "eng", "--psm", "7"]
case Porcelain.exec(cmd, args) do
%Porcelain.Result{out: text, status: 0} ->
IO.puts("识别结果:#{String.trim(text)}")
%Porcelain.Result{status: code, err: error} ->
IO.puts("识别失败 (状态码 #{code}):#{error}")
end
end
end
五、运行识别任务
创建脚本 lib/run.exs:
CaptchaOCR.recognize("captcha.png")
执行识别:
elixir lib/run.exs
示例输出:
识别结果:7W3G
六、可选:图像预处理(通过调用 ImageMagick)
如果验证码图像背景复杂,可通过系统命令调用 ImageMagick 进行预处理:
def preprocess(input_path, output_path) do
Porcelain.shell("convert #{input_path} -colorspace Gray -threshold 50% #{output_path}")
end
然后在识别前调用:
preprocess("captcha.png", "processed.png")
CaptchaOCR.recognize("processed.png")
浙公网安备 33010602011771号