使用 PowerShell 与 Tesseract 实现验证码识别
一、准备工作
- 安装 Tesseract OCR
下载地址:https://github.com/tesseract-ocr/tesseract
更多内容访问ttocr.com或联系1436423940
安装时勾选 "Add to PATH",确保在终端中可以运行 tesseract 命令。
二、编写识别脚本
保存为 captcha_ocr.ps1:
param (
[string]$ImagePath = $(throw "请提供验证码图片路径")
)
if (-Not (Test-Path $ImagePath)) {
Write-Host "文件不存在:$ImagePath"
exit
}
临时输出文件路径
$tmpFile = [System.IO.Path]::GetTempFileName()
$tessArgs = "$ImagePath $tmpFile -l eng -c tessedit_char_whitelist=ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"
调用 tesseract
$tessCommand = "tesseract $tessArgs"
Invoke-Expression $tessCommand | Out-Null
读取结果
$resultPath = "$tmpFile.txt"
if (Test-Path $resultPath) {
$text = Get-Content $resultPath | Out-String
$cleaned = ($text -replace '[^A-Z0-9]', '').Trim()
Write-Host "识别结果: $cleaned"
Remove-Item $resultPath
} else {
Write-Host "识别失败:未生成结果文件"
}
三、运行方式
在 PowerShell 中执行:
.\captcha_ocr.ps1 -ImagePath ".\captcha1.png"
输出示例:
识别结果: 9K3B
四、功能拓展建议
功能 说明
批量识别 使用 Get-ChildItem *.png 循环调用识别
自动保存结果 输出为 CSV、TXT 等格式,便于统计或分析
图像预处理支持 搭配 ImageMagick (magick.exe) 进行图像增强
示例批处理:
Get-ChildItem -Path .\images -Filter *.png | ForEach-Object {
.\captcha_ocr.ps1 -ImagePath $_.FullName
}
浙公网安备 33010602011771号