Python 自动化之图片验证码识别——Pillow + OCR 实战
·
验证码识别是爬虫自动化的常见需求,在很多场景下也很实用——批量识别发票、处理验证码、提取图片中的文字。
一、安装
pip install pytesseract Pillow
# 还需要安装 Tesseract-OCR 引擎
# Windows 下载地址:https://github.com/UB-Mannheim/tesseract/wiki
二、基础图片处理
1. 灰度化与二值化
from PIL import Image, ImageFilter, ImageEnhance
def preprocess_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(lambda x: 255 if x > 127 else 0)
# 去噪
img = img.filter(ImageFilter.MedianFilter(size=3))
return img
2. 简单验证码识别
import pytesseract
def recognize_captcha(image_path):
img = preprocess_image(image_path)
text = pytesseract.image_to_string(img, config='--psm 7')
return text.strip()
💡 觉得有用的话,点赞 + 关注【张老师技术栈】吧!每周更新 Java/Python/爬虫 实战干货,不让你白来。
更多推荐
所有评论(0)