在自动化测试、数据爬取等场景中,验证码(CAPTCHA)经常用于防止机器人操作。但在某些合法场景下,如自动化测试,我们需要识别验证码。本篇文章介绍如何使用 Python + Tesseract OCR 解析验证码,并优化识别准确度。
环境准备
1.1 安装 Tesseract OCR
Windows 用户
从 Tesseract OCR GitHub 下载并安装。
记下安装路径(例如 C:\Program Files\Tesseract-OCR\)。
将其添加到 环境变量 PATH。
Linux/macOS 用户
bash
Ubuntu
sudo apt update && sudo apt install tesseract-ocr
macOS(使用 Homebrew)
brew install tesseract
安装完成后,检查是否成功:
bash
tesseract --version
1.2 安装 Python 依赖
我们需要安装 pytesseract(Tesseract OCR 的 Python 封装库)以及 Pillow(Python 图像处理库)。
bash
pip install pytesseract pillow opencv-python numpy
2. 代码实现:识别验证码
下面是一个 Python 示例,展示如何加载验证码图像、进行预处理,并使用 Tesseract OCR 解析验证码。
2.1 代码示例
python
import cv2
import pytesseract
import numpy as np
from PIL import Image
指定 Tesseract 安装路径(Windows 用户需要配置)
pytesseract.pytesseract.tesseract_cmd = r"C:\Program Files\Tesseract-OCR\tesseract.exe"
def preprocess_image(image_path):
""" 预处理验证码,提高 OCR 识别率 """
# 读取图像
image = cv2.imread(image_path)
# 转换为灰度图像
gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
# 二值化处理(阈值设定)
_, binary = cv2.threshold(gray, 128, 255, cv2.THRESH_BINARY)
# 去噪(可选)
denoised = cv2.medianBlur(binary, 3)
# 保存处理后的图片(可选)
cv2.imwrite("processed_captcha.png", denoised)
return denoised
def recognize_captcha(image):
""" 识别验证码 """
# 配置 OCR 选项
custom_config = r'--oem 3 --psm 6 -c tessedit_char_whitelist=0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ'
# 使用 Tesseract 识别
text = pytesseract.image_to_string(image, config=custom_config).strip()
return text
if name == "main":
image_path = "captcha.png" # 替换为你的验证码图片路径
processed_image = preprocess_image(image_path)
result = recognize_captcha(processed_image)
print(f"识别出的验证码: {result}")
3. 代码解析
3.1 图像预处理
为了提高 OCR 识别率,代码对图像进行了以下优化:
灰度化:去除颜色干扰,保留亮度信息。
二值化:转换为黑白图像,提高字符对比度。
去噪处理(可选):使用 中值滤波 去除背景噪点。
python
_, binary = cv2.threshold(gray, 128, 255, cv2.THRESH_BINARY)
denoised = cv2.medianBlur(binary, 3)
3.2 OCR 解析
使用 Tesseract 解析验证码文本,并通过 -c 参数设定 只识别数字和大写字母,避免误识别。
python
custom_config = r'--oem 3 --psm 6 -c tessedit_char_whitelist=0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ'
text = pytesseract.image_to_string(image, config=custom_config).strip()
4. 运行程序
确保 captcha.png 存在于代码目录中,然后执行:
bash
python captcha_reader.py
程序会加载验证码图像,进行预处理并输出识别出的文本。
提高 OCR 识别准确率
5.1 选择合适的 PSM 模式
Tesseract 提供多种 页面分割模式(PSM),验证码通常使用 PSM 6 或 7:
python
custom_config = r'--psm 6'
常见 PSM 模式:
模式编号 适用场景
3 默认模式
6 适用于单行文本(推荐)
7 纯文本,无特殊布局
8 单个字符(适用于分割验证码)
5.2 进一步图像优化
去除噪点:可以使用 形态学处理 进一步去除干扰像素。
字符分割:对于粘连字符,可使用 轮廓检测 + 投影分割。
5.3 采用深度学习 OCR
如果 Tesseract 识别率不高,可使用 深度学习 OCR,如:
EasyOCR(Python)
PaddleOCR(Python)
Google Vision API(云端 OCR)
例如,使用 EasyOCR:
python
更多内容访问ttocr.com或联系1436423940
import easyocr
reader = easyocr.Reader(['en'])
result = reader.readtext('captcha.png')
print(result)