您的位置:首页 > 编程语言 > Python开发

Python3使用Pytesseract库识别验证码

2017-09-12 00:00 204 查看
识别验证码使用库: PIL(Python3安装Pillow)、pytesseract库

window使用pytesseract库:

1、Pycharm安装pytesseract

2、下载安装Tesseract-OCR:

tesseract-ocr-setup-3.05.01.exe (当前最新版本)

下载地址: https://github.com/tesseract-ocr/tesseract/wiki

3、配置环境变量

第一步:将tesseract安装目录添加到PATH中(本机为 【C:\Program Files (x86)\Tesseract-OCR】)

第二步:系统变量(添加) 将TESSDATA_PREFIX 设置为 C:\Program Files (x86)\Tesseract-OCR、



4、Pycharm修改文件pytesseract.py

tesseract_cmd = {tesseract安装目录}



5、Python处理验证码图片: 去干扰、去噪、处理识别结果操作

主要实现:

打开图片—返回识别结果—去除干扰—转化为灰度图—去噪—调用图像识别—处理识别结果

代码如下:

# -*- coding: utf8 -*-
import os

from PIL import Image
from pytesseract import image_to_string

def verify_yzm(filename):
f1, f2 = os.path.splitext(filename)

calc_result = None
try:
im = Image.open(filename)

# 切掉四周的黑边
width = im.size[0]
height = im.size[1]
left = 4
top = 4
right = width - 4
bottom = height - 4
box = (int(left), int(top), int(right), int(bottom))
im = im.crop(box)
im = im.resize((width * 4, height * 4), Image.BILINEAR)
im.save(f1 + '_step1' + f2)

# 转为灰度图
imgry = im.convert('L')
imgry.save(f1 + '_step2' + f2)

# 去噪
threshold = 140
table = []
for i in range(256):
if i < threshold:
table.append(0)
else:
table.append(1)
out = imgry.point(table, '1')
out.save(f1 + '_step3' + f2)

# 调用
text = image_to_string(out, config='-l eng')
print('text: ', text)

except Exception as e:
print(e)
return calc_result

if __name__ == '__main__':
verify_yzm('./yzm_test.jpg')

结果为:

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  PIL Pillow pytesseract