在验证码识别场景中,Python + OpenCV + Tesseract OCR 是非常流行的组合。本文将介绍如何编写一个程序,对图像进行预处理,然后识别出其中的英文和数字字符。
一、环境准备
- 安装依赖库 确保你安装了以下组件:
Python 3.x
Tesseract OCR(系统级安装)
Python 库:opencv-python, pytesseract, Pillow
安装方式如下:
pip install opencv-python pytesseract pillow 系统中还需安装 Tesseract:
macOS:
brew install tesseract Ubuntu:
sudo apt-get install tesseract-ocr Windows:下载 Tesseract 安装包并配置 tesseract.exe 到环境变量中。
二、识别代码示例 创建一个 Python 文件 captcha_recognition.py:
import cv2 import pytesseract from PIL import Image
若在 Windows 上,需指定 tesseract 路径
pytesseract.pytesseract.tesseract_cmd = r'C:\Program Files\Tesseract-OCR\tesseract.exe'
def preprocess_image(path): img = cv2.imread(path)
# 转为灰度图
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
# 应用二值化处理
_, thresh = cv2.threshold(gray, 150, 255, cv2.THRESH_BINARY_INV)
# 可选:进行膨胀或腐蚀操作
kernel = cv2.getStructuringElement(cv2.MORPH_RECT, (2, 2))
processed = cv2.morphologyEx(thresh, cv2.MORPH_CLOSE, kernel)
# 保存中间处理图像(可调试查看)
cv2.imwrite('processed.png', processed)
return processed
def recognize_text(image): return pytesseract.image_to_string(image, config='--psm 8 -c tessedit_char_whitelist=ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789')
if name == "main": image = preprocess_image("captcha.png") result = recognize_text(image) print(f"识别的验证码是: {result.strip()}") 三、程序说明 灰度化:简化图像,去除颜色干扰;
二值化:增强文字与背景的对比;
形态学操作(可选):去除噪点、连接字符;
--psm 8:告诉 Tesseract 图像是一个单行的单词,有助于提高识别率;
白名单设置:限制识别范围为大写字母和数字,提高准确度。
四、运行程序 将验证码图像命名为 captcha.png,并运行程序:
python captcha_recognition.py 输出示例:
识别的验证码是: A9XK2