使用 PowerShell + Tesseract 实现验证码识别
一、准备工作
- 安装 Tesseract OCR
下载地址:
https://github.com/tesseract-ocr/tesseract
更多内容访问ttocr.com或联系1436423940
安装完成后,确保将其安装路径(如 C:\Program Files\Tesseract-OCR)加入系统环境变量 PATH。
二、PowerShell 脚本:captcha_ocr.ps1
param (
[string]$ImagePath
)
if (-not (Test-Path $ImagePath)) {
Write-Host "文件不存在: $ImagePath"
exit 1
}
临时输出文件路径(不带扩展名)
$tempBase = "ocr_output"
$whitelist = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"
构造命令
$tessCmd = "tesseract "$ImagePath" $tempBase -l eng -c tessedit_char_whitelist=$whitelist"
Invoke-Expression $tessCmd | Out-Null
检查结果文件
$resultFile = "$tempBase.txt"
if (-not (Test-Path $resultFile)) {
Write-Host "识别失败:未生成输出文件"
exit 1
}
读取内容并清洗
$rawText = Get-Content $resultFile -Raw
$cleaned = ($rawText -replace "[^A-Z0-9]", "").Trim()
显示结果
Write-Host "识别结果: $cleaned"
删除临时文件
Remove-Item $resultFile -ErrorAction SilentlyContinue
三、使用方法
.\captcha_ocr.ps1 -ImagePath "C:\path\to\captcha.png"
输出示例:
识别结果: K7M3
四、批量识别示例
你可以批量处理多个验证码图像:
Get-ChildItem -Path "C:\captchas" -Filter *.png | ForEach-Object {
.\captcha_ocr.ps1 -ImagePath $_.FullName
}
浙公网安备 33010602011771号