使用 Julia 和 Tesseract 实现验证码识别
一、环境准备
安装 Julia(建议版本 1.6 或更高)
访问官网 https://julialang.org/downloads/ 下载并安装
安装 Tesseract OCR
更多内容访问ttocr.com或联系1436423940
Ubuntu / Debian:
sudo apt install tesseract-ocr
macOS:
brew install tesseract
Windows:安装后将 tesseract.exe 添加到系统环境变量
安装 Julia 所需包
启动 Julia,安装如下包:
using Pkg
Pkg.add(["Images", "ImageIO"])
二、识别验证码的主程序 captcha_ocr.jl
using Images
using Printf
function file_exists(path::String)::Bool
return isfile(path)
end
function clean_text(s::String)::String
return replace(s, r"[^A-Z0-9]" => "")
end
function recognize_captcha(image_path::String)
if !file_exists(image_path)
println("文件不存在: $image_path")
return
end
output_base = "temp_result"
whitelist = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"
cmd = `tesseract $image_path $output_base -l eng -c tessedit_char_whitelist=$whitelist`
run(cmd)
txt_path = "$output_base.txt"
if !file_exists(txt_path)
println("输出文件不存在")
return
end
raw = read(txt_path, String)
cleaned = clean_text(raw)
println("识别结果: $cleaned")
rm(txt_path; force=true)
end
三、添加命令行参数支持
function main()
if length(ARGS) != 1
println("用法: julia captcha_ocr.jl <图像路径>")
return
end
recognize_captcha(ARGS[1])
end
main()
保存为 captcha_ocr.jl,运行:
julia captcha_ocr.jl ./test.png
示例输出:
识别结果: 7DXQ
四、批量识别图像文件夹(可选)
function batch_recognize(dir::String)
for (root, _, files) in walkdir(dir)
for file in files
if endswith(file, ".png")
path = joinpath(root, file)
println("识别中: $file")
recognize_captcha(path)
end
end
end
end
浙公网安备 33010602011771号