python下調用pytesseract識別某網站驗證碼

一、pytesseract介紹

1、pytesseract說明

pytesseract最新版本0.1.6,網址:https://pypi.python.org/pypi/pytesseract

Python-tesseract is a wrapper for google's Tesseract-OCR
( http://code.google.com/p/tesseract-ocr/ ). It is also useful as a
stand-alone invocation script to tesseract, as it can read all image types
supported by the Python Imaging Library, including jpeg, png, gif, bmp, tiff,
and others, whereas tesseract-ocr by default only supports tiff and bmp.
Additionally, if used as a script, Python-tesseract will print the recognized
text in stead of writing it to a file. Support for confidence estimates and
bounding box data is planned for future releases.

翻譯一下大意:

a、Python-tesseract是一個基於google's Tesseract-OCR的獨立封裝包;

b、Python-tesseract功能是識別圖片文件中文字,並作爲返回參數返回識別結果;

c、Python-tesseract默認支持tiff、bmp格式圖片,只有在安裝PIL之後,才能支持jpeg、gif、png等其他圖片格式;

2、pytesseract安裝

INSTALLATION:

Prerequisites:
* Python-tesseract requires python 2.5 or later or python 3.
* You will need the Python Imaging Library (PIL). Under Debian/Ubuntu, this is
the package "python-imaging" or "python3-imaging" for python3.
* Install google tesseract-ocr from http://code.google.com/p/tesseract-ocr/ .
You must be able to invoke the tesseract command as "tesseract". If this
isn't the case, for example because tesseract isn't in your PATH, you will
have to change the "tesseract_cmd" variable at the top of 'tesseract.py'.
Under Debian/Ubuntu you can use the package "tesseract-ocr".

Installing via pip: 
See the [pytesseract package page](https://pypi.python.org/pypi/pytesseract) 
```
$> sudo pip install pytesseract 

 翻譯一下:

a、Python-tesseract支持python2.5及更高版本;

b、Python-tesseract需要安裝PIL(Python Imaging Library) ,來支持更多的圖片格式;

c、Python-tesseract需要安裝tesseract-ocr安裝包,具體參看上一篇博文

 

綜上,Pytesseract原理:

1、上一篇博文中提到,執行命令行 tesseract.exe 1.png output -l eng ,可以識別1.png中文字,並把識別結果輸出到output.txt中;

2、Pytesseract對上述過程進行了二次封裝,自動調用tesseract.exe,並讀取output.txt文件的內容,作爲函數的返回值進行返回。

二、pytesseract使用

 USAGE:
```
> try:
> import Image
> except ImportError:
> from PIL import Image
> import pytesseract
> print(pytesseract.image_to_string(Image.open('test.png')))
> print(pytesseract.image_to_string(Image.open('test-european.jpg'), lang='fra'))

 

可以看到:

1、核心代碼就是image_to_string函數,該函數還支持-l eng 參數,支持-psm 參數。

 

用法:
image_to_string(Image.open('test.png'),lang="eng" config="-psm 7")

2、pytesseract裏調用了image,所以才需要PIL,其實tesseract.exe本身是支持jpeg、png等圖片格式的。

 

實例代碼,識別某公共網站的驗證碼(大家千萬別幹壞事啊,思慮再三,最後還是隱掉網站域名,大家去找別的網站試試吧……):

#-*-coding=utf-8-*-
__author__='zhongtang'

import urllib
import urllib2
import cookielib
import math
import random
import time
import os
import htmltool
from pytesseract import *
from PIL import Image
from PIL import ImageEnhance
import re

class orclnypcg:
    def __init__(self):
        self.baseUrl='http://jbywcg.****.com.cn'
        self.ht=htmltool.htmltool()
        self.curPath=self.ht.getPyFileDir()
        self.authCode=''
        
    def initUrllib2(self):
        try:
            cookie = cookielib.CookieJar()
            cookieHandLer = urllib2.HTTPCookieProcessor(cookie)
            httpHandLer=urllib2.HTTPHandler(debuglevel=0)
            httpsHandLer=urllib2.HTTPSHandler(debuglevel=0)
        except:
            raise
        else:
             opener = urllib2.build_opener(cookieHandLer,httpHandLer,httpsHandLer)
             opener.addheaders = [('User-Agent','Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.11 (KHTML, like Gecko) Chrome/23.0.1271.64 Safari/537.11')]
             urllib2.install_opener(opener)
             
    def urllib2Navigate(self,url,data={}):           #定義連接函數,有超時重連功能
        tryTimes = 0
        while True:
            if (tryTimes>20):
                print u"多次嘗試仍無法鏈接網絡,程序終止"
                break
            try:
                if (data=={}):
                    req = urllib2.Request(url)
                else:
                    req = urllib2.Request(url,urllib.urlencode(data))
                response =urllib2.urlopen(req)
                bodydata = response.read()
                headerdata = response.info()
                if headerdata.get('Content-Encoding')=='gzip':
                    rdata = StringIO.StringIO(bodydata)
                    gz = gzip.GzipFile(fileobj=rdata)
                    bodydata = gz.read()
                    gz.close()
                tryTimes = tryTimes +1
            except urllib2.HTTPError, e:
              print 'HTTPError[%s]\n' %e.code                
            except urllib2.URLError, e:
              print 'URLError[%s]\n' %e.reason    
            except socket.error:
                print u"連接失敗,嘗試重新連接"
            else:
                break
        return bodydata,headerdata
    
    def randomCodeOcr(self,filename):
        image = Image.open(filename)
        #使用ImageEnhance可以增強圖片的識別率
        #enhancer = ImageEnhance.Contrast(image)
        #enhancer = enhancer.enhance(4)
        image = image.convert('L')
        ltext = ''
        ltext= image_to_string(image)
        #去掉非法字符,只保留字母數字
        ltext=re.sub("\W", "", ltext)
        print u'[%s]識別到驗證碼:[%s]!!!' %(filename,ltext)
        image.save(filename)
        #print ltext
        return ltext

    def getRandomCode(self):
        #開始獲取驗證碼
        #http://jbywcg.****.com.cn/CommonPage/Code.aspx?0.9409255818463862
        i = 0 
        while ( i<=100):
            i += 1 
            #拼接驗證碼Url
            randomUrlNew='%s/CommonPage/Code.aspx?%s' %(self.baseUrl,random.random())
            #拼接驗證碼本地文件名
            filename= '%s.png' %(i)
            filename=  os.path.join(self.curPath,filename)
            jpgdata,jpgheader = self.urllib2Navigate(randomUrlNew)
            if len(jpgdata)<= 0 :
                print u'獲取驗證碼出錯!\n'
                return False
            f = open(filename, 'wb')
            f.write(jpgdata)
            #print u"保存圖片:",fileName
            f.close()
            self.authCode = self.randomCodeOcr(filename)


#主程序開始
orcln=orclnypcg()
orcln.initUrllib2()
orcln.getRandomCode()

 

三、pytesseract代碼優化

上述程序在windows平臺運行時,會發現有黑色的控制檯窗口一閃而過的畫面,不太友好。

略微修改了pytesseract.py(C:\Python27\Lib\site-packages\pytesseract目錄下),把上述過程進行了隱藏。

# modified by zhongtang hide console window
# new code
IS_WIN32 = 'win32' in str(sys.platform).lower()
if IS_WIN32:
   startupinfo = subprocess.STARTUPINFO()
   startupinfo.dwFlags |= subprocess.STARTF_USESHOWWINDOW
   startupinfo.wShowWindow = subprocess.SW_HIDE
   proc = subprocess.Popen(command,
        stderr=subprocess.PIPE,startupinfo=startupinfo)
'''
# old code
proc = subprocess.Popen(command,
   stderr=subprocess.PIPE)
'''
# modified end

發佈了13 篇原創文章 · 獲贊 13 · 訪問量 5萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章