Python 自动化之图片验证码识别——Pillow + OCR 实战

Python 自动化之图片验证码识别——Pillow + OCR 实战

验证码识别是爬虫自动化的常见需求,在很多场景下也很实用——批量识别发票、处理验证码、提取图片中的文字。

一、安装

pipinstallpytesseract Pillow# 还需要安装 Tesseract-OCR 引擎# Windows 下载地址:https://github.com/UB-Mannheim/tesseract/wiki

二、基础图片处理

1. 灰度化与二值化

fromPILimportImage,ImageFilter,ImageEnhancedefpreprocess_image(image_path):"""预处理验证码图片"""img=Image.open(image_path)# 灰度化img=img.convert('L')# 增强对比度enhancer=ImageEnhance.Contrast(img)img=enhancer.enhance(2.0)# 二值化(阈值 127)img=img.point(lambdax:255ifx>127else0)# 去噪img=img.filter(ImageFilter.MedianFilter(size=3))returnimg

2. 简单验证码识别

importpytesseractdefrecognize_captcha(image_path):img=preprocess_image(image_path)text=pytesseract.image_to_string(img,config='--psm 7')returntext.strip()

💡 觉得有用的话,点赞 + 关注【张老师技术栈】吧!每周更新 Java/Python/爬虫 实战干货,不让你白来。