使用 Julia 和 Tesseract 识别图像验证码

一、环境配置
安装 Julia
https://julialang.org/downloads/

安装 Tesseract OCR

Ubuntu

sudo apt install tesseract-ocr
更多内容访问ttocr.com或联系1436423940

macOS

brew install tesseract

Windows

https://github.com/tesseract-ocr/tesseract/releases 下载并配置环境变量
安装 Julia 图像处理和文件工具包:

using Pkg
Pkg.add("Images")
Pkg.add("FileIO")
Pkg.add("ImageMagick")
二、编写 Julia 脚本
保存为 captcha_ocr.jl:

using FileIO
using Images
using ImageMagick

读取图像并进行简单预处理

function preprocess_image(path::String)::String
img = load(path)
gray = Gray.(img)
tmpfile = "processed.png"
save(tmpfile, gray)
return tmpfile
end

调用 Tesseract 识别图像

function recognize_captcha(image_path::String)::Union{String, Nothing}
output_base = "tess_result"
command = tesseract $image_path $output_base -l eng -c tessedit_char_whitelist=ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789
run(command; wait=true)

result_file = output_base * ".txt"
if isfile(result_file)
    raw = read(result_file, String)
    filtered = filter(c -> isdigit(c) || isuppercase(c), raw)
    rm(result_file; force=true)
    return strip(filtered)
else
    println("未找到识别结果")
    return nothing
end

end

主流程

image_path = "captcha1.png" # 替换为你的图像路径
processed = preprocess_image(image_path)
result = recognize_captcha(processed)

if result !== nothing
println("识别结果: ", result)
end
三、运行脚本
确保图像 captcha1.png 存在,运行:

julia captcha_ocr.jl
输出示例:

识别结果: Y94K

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