识别图形验证码 (Elixir 示例)

ocr1 / 2024-10-21 / 原文

安装所需依赖
在你的 mix.exs 文件中添加以下依赖:

elixir

defp deps do
[
{:httpoison, "~> 1.8"},
{:mogrify, "~> 0.7"},
{:tesseract, "~> 0.1"}
]更多内容联系1436423940
end
然后运行 mix deps.get 来安装这些库。

下载并保存验证码图片
使用 HTTPoison 下载验证码图片并保存到本地:

elixir

defmodule CaptchaDownloader do
require Logger

def download_captcha(url, save_path) do
case HTTPoison.get(url) do
{:ok, %HTTPoison.Response{body: body}} ->
File.write!(save_path, body)
Logger.info("验证码图片已保存为 #{save_path}")

  {:error, %HTTPoison.Error{reason: reason}} ->
    Logger.error("下载验证码失败: #{reason}")
end

end
end

captcha_url = "https://captcha7.scrape.center/captcha.png"
save_path = "captcha.png"
CaptchaDownloader.download_captcha(captcha_url, save_path)
图像处理和 OCR 识别
使用 Mogrify 进行图像处理,并使用 Tesseract 进行验证码识别:

elixir

defmodule CaptchaProcessor do
def preprocess_image(input_path, output_path) do
input_path
|> Mogrify.open()
|> Mogrify.custom("colorspace", "Gray")
|> Mogrify.custom("threshold", "50%")
|> Mogrify.save(path: output_path)

IO.puts("处理后的验证码图片已保存为 #{output_path}")

end

def recognize_captcha(image_path) do
Tesseract.OCR.ocr(image_path)
end
end

processed_path = "captcha_processed.png"
CaptchaProcessor.preprocess_image(save_path, processed_path)
captcha_text = CaptchaProcessor.recognize_captcha(processed_path)
IO.puts("识别结果: #{captcha_text}")
自动化登录
使用 HTTPoison 发送登录请求,携带识别到的验证码进行自动化登录:

elixir

defmodule CaptchaLogin do
def login(username, password, captcha) do
body = %{
"username" => username,
"password" => password,
"captcha" => captcha
}

case HTTPoison.post("https://captcha7.scrape.center/login", Poison.encode!(body), [{"Content-Type", "application/json"}]) do
  {:ok, %HTTPoison.Response{status_code: 200}} ->
    IO.puts("登录成功")

  {:ok, %HTTPoison.Response{status_code: _}} ->
    IO.puts("登录失败")

  {:error, %HTTPoison.Error{reason: reason}} ->
    IO.puts("请求失败: #{reason}")
end

end
end

CaptchaLogin.login("admin", "admin", captcha_text)