一、引言
验证码是网站常用的安全机制,用于防止自动化操作。然而在自动化测试和数据处理任务中,我们需要识别验证码。Python 结合 Tesseract OCR 提供了一种便捷的解决方案。
本文将带你一步步搭建 Python 环境,使用 Tesseract 进行验证码识别,并通过图像预处理提升识别准确率。
二、环境准备
2.1 安装 Python
更多内容访问ttocr.com或联系1436423940
Python 是跨平台的开发语言,推荐使用 Python 3.x 版本。
下载地址:Python 官方网站
安装完成后验证安装:
python --version
2.2 安装 Tesseract OCR
Windows:
前往 Tesseract GitHub 页面
下载适用于 Windows 的安装包。
安装完成后将其添加到环境变量中。
Linux (Ubuntu):
sudo apt update
sudo apt install tesseract-ocr
macOS:
brew install tesseract
验证安装:
tesseract --version
2.3 安装所需 Python 库
使用 pip 安装 OCR 和图像处理库:
pip install pytesseract opencv-python Pillow
三、验证码识别代码实现
3.1 代码结构
加载验证码图像
图像预处理(灰度化、二值化、去噪)
OCR 识别验证码
打印识别结果
3.2 代码示例
import cv2
import pytesseract
from PIL import Image
配置 Tesseract 路径(仅 Windows 需要)
pytesseract.pytesseract.tesseract_cmd = r'C:\Program Files\Tesseract-OCR\tesseract.exe'
def preprocess_image(image_path):
# 加载图像
img = cv2.imread(image_path)
# 转为灰度图像
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
# 二值化处理
_, binary = cv2.threshold(gray, 128, 255, cv2.THRESH_BINARY)
# 去噪(可选)
denoised = cv2.medianBlur(binary, 3)
return denoised
def ocr_recognition(image):
# OCR 识别
text = pytesseract.image_to_string(image, config='--psm 6')
return text
if name == "main":
# 输入验证码图片路径
image_path = "captcha.png"
processed_image = preprocess_image(image_path)
cv2.imwrite("processed.png", processed_image) # 保存处理后的图像
# 识别验证码
result = ocr_recognition(processed_image)
print(f"识别出的验证码: {result}")
四、提升识别准确率的方法
4.1 页面分割模式(PSM)调整
Tesseract 提供多种页面分割模式(PSM),针对验证码的单行文本,推荐使用 --psm 6:
text = pytesseract.image_to_string(image, config='--psm 6')
4.2 自定义语言训练数据
如果验证码包含非英文字符,可以使用自定义语言包,如中文或数字:
text = pytesseract.image_to_string(image, lang='eng+chi_sim')
4.3 图像预处理技巧
去噪处理:使用中值滤波去除噪点。
二值化增强:通过不同阈值调整,提升字符对比度。
字符分割:对粘连字符进行切分,逐一识别。
五、运行代码
确保验证码图片 (captcha.png) 存在于代码同一目录下,运行脚本:
python captcha_reader.py