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

一、安装依赖
安装 Elixir:

macOS

brew install elixir
更多内容访问ttocr.com或联系1436423940

Ubuntu

sudo apt install elixir
安装 Tesseract:

macOS

brew install tesseract

Ubuntu

sudo apt install tesseract-ocr
二、新建项目(可选)

mix new captcha_ocr
cd captcha_ocr
三、编写识别逻辑(lib/captcha_ocr.ex)

defmodule CaptchaOCR do
def recognize(image_path) do
output_base = "tess_output"
whitelist = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"

# 构造命令
cmd = "tesseract"
args = [
  image_path,
  output_base,
  "-l", "eng",
  "-c", "tessedit_char_whitelist=#{whitelist}"
]

# 执行 Tesseract 命令
case System.cmd(cmd, args) do
  {_, 0} ->
    result_file = output_base <> ".txt"
    case File.read(result_file) do
      {:ok, content} ->
        result = content
                 |> String.replace(~r/[^A-Z0-9]/, "")
                 |> String.trim()
        File.rm(result_file)
        IO.puts("识别结果: #{result}")
      {:error, _} ->
        IO.puts("无法读取识别结果文件")
    end
  {error, _} ->
    IO.puts("Tesseract 执行失败: #{error}")
end

end
end
四、运行脚本
在 mix.exs 旁创建一个简单脚本 run.exs:

Code.compile_file("lib/captcha_ocr.ex")
CaptchaOCR.recognize("captcha1.png")
运行:

elixir run.exs
输出示例:

识别结果: 5C7H
五、功能拓展建议
遍历图像文件夹批量识别

与 Phoenix 框架结合,提供 HTTP API 接口

添加图像预处理功能(需借助 imagemagick 或通过 Port 调用脚本)

将识别结果写入数据库或导出为 CSV

posted @ 2025-06-29 17:41  ttocr、com  阅读(6)  评论(0)    收藏  举报