简介:本文围绕崔庆才的Python3爬虫教程,详细解析OCR技术在图形验证码识别中的应用,包括常用库介绍、代码实现、优化策略及实战案例,助力开发者高效突破验证码限制。
在Web爬虫开发中,图形验证码是常见的反爬机制之一。其通过生成包含字符、数字或干扰元素的图片,要求用户手动输入以验证人机身份。传统破解方式(如手动输入)效率低下,而自动化识别需依赖OCR(Optical Character Recognition,光学字符识别)技术。OCR的核心是将图像中的文字转换为可编辑的文本格式,其准确性直接影响验证码识别的成功率。
Python生态中,Tesseract OCR(由Google开发)和Pillow(图像处理库)是处理图形验证码的两大核心工具。Tesseract支持多语言识别,但需结合图像预处理优化效果;Pillow则用于调整图像的对比度、二值化等操作,降低干扰因素。本教程将基于Python3环境,结合这两款工具实现高效验证码识别。
首先需安装必要的Python库:
pip install pillow pytesseract
同时需下载Tesseract OCR引擎(官网下载链接),并配置系统环境变量(Windows需将Tesseract安装路径添加至PATH,Linux/macOS可通过包管理器安装)。
原始验证码图像可能存在噪声、低对比度或变形等问题,需通过以下步骤优化:
from PIL import Imageimg = Image.open("captcha.png").convert("L") # "L"模式表示灰度
threshold = 140 # 阈值需根据图像调整binary_img = img.point(lambda x: 0 if x < threshold else 255)
from PIL import ImageFilterdenoised_img = binary_img.filter(ImageFilter.MedianFilter(size=3))
配置Tesseract路径后,直接调用image_to_string方法:
import pytesseract# 指定Tesseract路径(Windows示例)pytesseract.pytesseract.tesseract_cmd = r"C:\Program Files\Tesseract-OCR\tesseract.exe"text = pytesseract.image_to_string(denoised_img, config="--psm 7") # --psm 7表示单行文本模式print("识别结果:", text.strip())
config参数中的--psm用于指定页面分割模式(如7为单行文本,6为块状文本),需根据验证码布局调整。
某网站验证码为4位数字,背景含干扰线,字符间距较小。直接识别准确率仅30%,需通过预处理优化。
from PIL import Image, ImageFilterimport pytesseractdef preprocess_captcha(img_path):# 打开图像并转为灰度img = Image.open(img_path).convert("L")# 二值化threshold = 150binary_img = img.point(lambda x: 0 if x < threshold else 255)# 降噪denoised_img = binary_img.filter(ImageFilter.MedianFilter(size=3))# 膨胀操作(可选,用于连接断裂字符)# from PIL import ImageOps# expanded_img = ImageOps.expand(denoised_img, border=1, fill=255)return denoised_imgdef recognize_captcha(img_path):processed_img = preprocess_captcha(img_path)text = pytesseract.image_to_string(processed_img,config="--psm 7 -c tessedit_char_whitelist=0123456789" # 限制识别字符集)return text.strip()# 测试result = recognize_captcha("example_captcha.png")print("识别结果:", result)
tessedit_char_whitelist参数限制识别范围(如仅数字),可提升准确率20%以上。Tesseract识别乱码
chi_sim.traineddata)。--psm参数或使用--oem 3(默认OCR引擎模式)。预处理后字符断裂
ImageOps.expand进行膨胀操作,连接断裂部分。cv2.adaptiveThreshold)。验证码含干扰线/点
cv2.inpaint(需OpenCV)修复干扰区域。本教程通过Python3的Pillow和Tesseract OCR库,实现了图形验证码的自动化识别。关键点在于:
--psm和字符集限制可显著优化结果。进阶方向:
EasyOCR或PaddleOCR等现代OCR库,支持更复杂的验证码场景。