使用 Elixir 调用 Tesseract 实现图像验证码识别
一、项目简介
Elixir 是一门构建在 Erlang 虚拟机(BEAM)上的函数式编程语言,以高并发和容错机制著称。尽管 Elixir 不是图像处理的主流语言,但它能通过系统调用等方式集成强大的工具,如 Tesseract OCR,实现验证码图像的字符识别。
二、开发环境准备
- 安装 Elixir
macOS:
更多内容访问ttocr.com或联系1436423940
brew install elixir
Ubuntu:
sudo apt-get install elixir
Windows: 使用 Elixir Installer
- 安装 Tesseract
确保安装并添加至环境变量:
sudo apt install tesseract-ocr
或在 Windows 中手动添加 tesseract.exe 路径。
三、新建 Elixir 项目
mix new captcha_ocr
cd captcha_ocr
修改 mix.exs 添加依赖:
defp deps do
[
{:mogrify, "~> 0.9.1"} # 图像处理库
]
end
安装依赖:
mix deps.get
四、OCR 脚本实现
编辑 lib/captcha_ocr.ex:
defmodule CaptchaOCR do
def recognize(image_path) do
# 调用 tesseract 命令
output_path = Path.rootname(image_path) <> "_out"
System.cmd("tesseract", [image_path, output_path, "-l", "eng"], stderr_to_stdout: true)
# 读取结果
text_path = output_path <> ".txt"
case File.read(text_path) do
{:ok, content} ->
String.trim(content)
{:error, reason} ->
"识别失败: #{inspect(reason)}"
end
end
end
五、测试识别
在 lib/captcha_ocr.ex 最后加上:
def test do
result = recognize("captcha.png")
IO.puts("识别结果: #{result}")
end
执行:
iex -S mix
在 IEx 中运行:
CaptchaOCR.test()
输出示例:
识别结果: W5RT
六、可选图像预处理(用 Mogrify)
alias Mogrify
def preprocess(image_path) do
Mogrify.open(image_path)
|> Mogrify.custom("colorspace", "Gray")
|> Mogrify.custom("threshold", "50%")
|> Mogrify.save(path: "processed.png")
end
再识别:
preprocess("captcha.png")
recognize("processed.png")
七、批量识别验证码图像
def batch_recognize(folder) do
File.ls!(folder)
|> Enum.filter(&String.ends_with?(&1, ".png"))
|> Enum.each(fn file ->
path = Path.join(folder, file)
text = recognize(path)
IO.puts("#{file} => #{text}")
end)
end
浙公网安备 33010602011771号