基于Tesseract-OCR识别简单验证码

Tesseract-OCR是谷歌的开源OCR库。使用Tesseract-OCR识别验证码的优点如下:

1、与调用网络API相比,本地调用速度更快;

2、对于识别简单的验证码,Tesseract-OCR显得更加简单高效。

缺点也是十分明显的,如下:

1、只调用Tesseract-OCR识别效果差,需要使用jTextBoxEditor进行人工手动训练数据,过程十分繁琐;

2、对于复杂验证码,比如存在字符粘连、字符扭曲等情况。Tesseract-OCR识别效果较差。

以Python+Tesseract-OCR识别验证码为例,介绍使用过程:

(1)获取安装Tesseract-OCR、Python及相应库。

(2)通过Python网络爬虫,获取大量验证码图片。

# 得到一定数目的验证码, 并保存到本地

def get_pic(num):

    url = 'http://yktapp.hebut.edu.cn:8088/Phone/GetValidateCode'

    for i in range(num):

        r = requests.get(url)

        r.raise_for_status()

        path = 'jpg/' + str(i) + '.jpg'

        with open(path, 'wb') as f:

            f.write(r.content)

(3)预处理。基于像素统计的方法,分析干扰点的像素值,来设置阈值,实现降噪的目的。

# 得到二值化图像

def get_image_binary(file_path):

    # 阈值

    threshold = 190

    # 二值化辅助数组

    table = [0] * threshold + [1] * (256 - threshold)

    # 转灰度图

    img_grey = Image.open(file_path).convert('L')

    # 二值化

    return img_grey.point(table, '1')

 

(4)通过jTextBoxEditor训练样本文件。

1、在jTextBoxEditor中,点击Merge TIFF按钮,生成TIFF文件。如下图:

1 生成TIFF文件

2、使用如下命令,生成Box文件

tesseract num.font.exp0.tif num.font.exp0 batch.nochop makebox

3、对于样本图片,使用jTextBoxEditor进行校正。

2 jTextBoxEditor编辑信息

4、生成font_properties文件。内容如下:

font 0 0 0 0 0

 

5、使用如下命令生成字符集文件、shape文件、聚集字符特征文件、正常化特征文件等等,并合并生成训练结果。

tesseract num.font.exp0.tif num.font.exp0 batch.nochop makebox



echo Run Tesseract for Training..

tesseract.exe num.font.exp0.tif num.font.exp0 -psm 7 nobatch box.train



echo Compute the Character Set..

unicharset_extractor.exe num.font.exp0.box

mftraining -F font_properties -U unicharset -O num.unicharset num.font.exp0.tr



echo Clustering..

cntraining.exe num.font.exp0.tr



echo Rename Files..

rename normproto num.normproto

rename inttemp num.inttemp

rename pffmtable num.pffmtable

rename shapetable num.shapetable 



echo Create Tessdata..

combine_tessdata.exe num.

echo. & pause

6、将生成data文件拷贝到tesseract-OCR安装目录下的tessdata文件夹内。

(5)调用Tesseract-OCR识别验证码。如下:

def get_yzm(img):

    yzm = pytesseract.image_to_string(img, lang='num', config='-psm 7')

    yzm = yzm.replace(' ', '')

    return yzm

参考文献

[1] 张柯. Python使用tesseract-ocr完成验证码识别(模型训练和使用部分). https://www.cnblogs.com/zhang-ke/p/7606572.html

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值