使用 Bash + Tesseract 实现验证码识别
一、准备环境
- 安装 Tesseract OCR
更多内容访问ttocr.com或联系1436423940
Ubuntu / Debian
sudo apt install tesseract-ocr
macOS(使用 Homebrew)
brew install tesseract
二、编写识别脚本
创建文件 captcha_ocr.sh:
!/bin/bash
检查参数
if [ $# -lt 1 ]; then
echo "用法: ./captcha_ocr.sh <验证码图片路径>"
exit 1
fi
image_path="$1"
whitelist="ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"
调用 tesseract 识别
output=$(tesseract "$image_path" stdout -l eng -c "tessedit_char_whitelist=$whitelist" 2>/dev/null)
过滤非字母数字字符
cleaned=$(echo "$output" | tr -cd 'A-Z0-9')
echo "识别结果: $cleaned"
赋予可执行权限:
chmod +x captcha_ocr.sh
三、运行脚本
./captcha_ocr.sh ./sample.png
示例输出:
识别结果: 8KJX
四、功能扩展建议
功能 说明
批量识别图像 用 for f in *.png; do ... 批量处理
文件名自动标注 将识别结果作为文件名后缀保存输出图像
图像预处理 搭配 convert(ImageMagick)进行灰度化
示例批量处理:
for f in images/*.png; do
./captcha_ocr.sh "$f"
done
浙公网安备 33010602011771号