美文网首页
在Python中使用tesseract识别验证码

在Python中使用tesseract识别验证码

作者: 头顶一根发的程序猿 | 来源:发表于2019-07-19 13:36 被阅读0次

    前言

    在对网站数据进行爬取的过程中,由于访问过于频繁或是其他的原因,经常会出现输入验证码进行验证的情况,面对这种验证码验证的问题,一般有三种解决方法:

    第一种,最简单也是最费时的,手动输入验证码;

    第二种,使用一些公司的API接口对验证码进行判别和输入;

    第三种,使用tessract对验证码进行识别;

    在这里,我们使用tessract对验证码进行识别。

    Tesseract简介

    tesseract是谷歌开源的一个ORC组件,并支持语言的训练,支持中文的识别(需要下载语言包)

    Python中使用Tesseract

    在Python中安装Tesseract一共分为三步:

    1、pip安装pytesseract及其他依赖库

    pip pytesseract

    在使用pytesseract中需要读取图像,所以还需要安装Pillow

    2、安装tesseract

    下载并安装:https://tesseract-ocr.googlecode.com/files/tesseract-ocr-setup-3.02.02.exe

    3、修改tesseract.py文件

    防止提示没有匹配的文件

    # tesseract_cmd = 'tesseract'

    tesseract_cmd = "C:/Program Files (x86)/Tesseract-OCR/tesseract.exe" # tesseract的安装目录

    防止提示Unicode编码错误

    # f = open(output_file_name)

    f = open(output_file_name,encoding='utf-8')

    做完这三步,就可以使用tesseract基本的功能了。

    下面来看看在实际的代码中如何利用tesseract进行验证码识别:

    原始的验证码图像为:

    示例验证码为:

    #coding:utf-8

    '''

    验证码识别

    '''

    from PIL import Image,ImageFilter,ImageEnhance

    import pytesseract

    # 二值化

    threshold = 140

    table = []

    for i in range(256):

    if i < threshold:

    table.append(0)

    else:

    table.append(1)

    # 识别验证码

    def get_vcode():

    # 打开原始图像

    image = Image.open("getimgbysig.jpg")

    # image = Image.open("e:/a.jpg")

    # 将图像转为灰度,并另存为

    bimage = image.convert('L')

    bimage.save('g'+"getimgbysig.jpg")

    # 进行二值化处理,并另存为

    out = bimage.point(table,'1')

    out.save('b'+"getimgbysig.jpg")

    icode = pytesseract.image_to_string(image)

    bcode = pytesseract.image_to_string(bimage)

    vcode = pytesseract.image_to_string(out)

    print(icode,bcode,vcode)

    if __name__ == '__main__':

    get_vcode()

    结果输出为:7364,说明识别成功了。

    对于简单、清晰的数字,没有经过任何训练的Tesseract还是能够很精确地识别出来。而对于那些模糊、变形的数字、字母或是中文,就需要先对Tesseract进行训练了,暂且不表。

    觉得文章不错或者对你有用,可以关注小编,后面持续更新更多精彩内容哟~

    相关文章

      网友评论

          本文标题:在Python中使用tesseract识别验证码

          本文链接:https://www.haomeiwen.com/subject/vfwjlctx.html