Python3使用Pytesseract库识别验证码

识别验证码使用库: 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、

    165824_JpcB_2823264.png

4、Pycharm修改文件pytesseract.py

    tesseract_cmd = {tesseract安装目录}

165737_zVtP_2823264.png

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')

 结果为: 

170542_zI9p_2823264.png

 

 

转载于:https://my.oschina.net/xxWang/blog/1535993

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值