美文网首页
Python+OCR图片文字识别,验证码识别,银行卡识别

Python+OCR图片文字识别,验证码识别,银行卡识别

作者: 来杯牛奶呗 | 来源:发表于2019-05-15 09:03 被阅读0次

    Python+OCR图片文字识别,验证码识别,银行卡识别

    利用测试如下:

    1.识别文字

    2.识别简单的验证码

    3.识别银行卡

    准备工作

    1.安装pytesseract库:pytesseract是Tesseract关于Python的接口,在cmd中可以直接使用pip install pytesseract安装

    2.用电脑下载安装tesseract,下载地址 http://digi.bib.unimannheim.de/tesseract/tesseract-ocr-setup-4.00.00dev.exe 

    一直点确定后完成安装,并配置环境变量,

    在CMD中输入tesseract -v, 如显示以下界面,则表示Tesseract安装完成且添加到系统变量中。

    3.下载tesseract的简体中文语言包,下载地址为:https://github.com/tesseract-ocr/tessdata/find/master/chi_sim.traineddata ,再将chi_sim.traineddata放在C:\Program Files (x86)\Tesseract-OCR\tessdata目录下。

    做好准备工作就可以实现OCR文字识别了,代码非常简单:

    importpytesseractfromPILimportImageimportcv2img=Image.open('0.jpg')#text = pytesseract.image_to_string(img,lang='chi_sim')pytesseract.pytesseract.tesseract_cmd='C://Program Files (x86)/Tesseract-OCR/tesseract.exe'text=pytesseract.image_to_string(img,lang='chi_sim')print(text)

    0.jpg 如下:

    运行结果如下

    如果出现报错:

    pytesseract.pytesseract.TesseractError: (1, ‘Error opening data file \Program Files (x86)\Tesseract-OCR\chi_sim.traineddata Please make sure the TESSDATA_PREFIX environment variable is set to your “tessdata” directory. Failed loading language ‘chi_sim’ Tesseract couldn’t load any languages! Could not initialize tesseract.’)

    请移步这篇文章:https://blog.csdn.net/weixin_43746433/article/details/89922155

    2.笔者突然想到,利用Ocr 能不能识别简单的验证码呢?

    于是在网上随便找了个验证码,如图:6.png:

    运行结果并不是让人满意,

    为了更好的处理图片,可以将图片转为灰度图片,再去掉黑点,进行二值化降噪,

    代码如下:

    importpytesseractfromPILimportImage,ImageEnhance,ImageFilterimportcv2img=Image.open('6.png')text=pytesseract.image_to_string(img,lang='chi_sim')print(text)# 将图片变成灰色img_gray=img.convert('L')img_gray.save('./tmp/ode_gray.png')# 转成黑白图片img_black_white=img_gray.point(lambdax:0ifx>200else255)pic1='./tmp/code_black_white.png'img_black_white.save(pic1)#要去掉黑点,就是一个二值化降噪的过程。可以用PIL(Python Image Library)试试im=Image.open(pic1)im=im.filter(ImageFilter.MedianFilter())enhancer=ImageEnhance.Contrast(im)im=enhancer.enhance(2)im=im.convert('1')im.save('./tmp/jiangzao.png')#im.show()pytesseract.pytesseract.tesseract_cmd='C://Program Files (x86)/Tesseract-OCR/tesseract.exe'#text = pytesseract.image_to_string(Image.open('./tmp/jiangzao.png'),lang='chi_sim')##,lang='eng 数字text=pytesseract.image_to_string(im,lang='chi_sim')print(text)

    运行结果如下,成功!

    3.如果利用ocr识别银行卡呢?

    修改图片如下

    运行结果如下:

    银行卡的识别结果却差强人意,这涉及到更深层次的opencv知识,笔者会在下篇详细的讲述如何使用OpenCV和python进行信用卡识别

    相关文章

      网友评论

          本文标题:Python+OCR图片文字识别,验证码识别,银行卡识别

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