欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

python下調(diào)用pytesseract識(shí)別某網(wǎng)站驗(yàn)證碼的實(shí)現(xiàn)方法

 更新時(shí)間:2016年06月06日 16:10:45   投稿:jingxian  
下面小編就為大家?guī)硪黄猵ython下調(diào)用pytesseract識(shí)別某網(wǎng)站驗(yàn)證碼的實(shí)現(xiàn)方法。小編覺得挺不錯(cuò)的,現(xiàn)在就分享給大家,也給大家做個(gè)參考。一起跟隨小編過來看看吧

一、pytesseract介紹

1、pytesseract說明

pytesseract最新版本0.1.6,網(wǎng)址: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是一個(gè)基于google's Tesseract-OCR的獨(dú)立封裝包;

b、Python-tesseract功能是識(shí)別圖片文件中文字,并作為返回參數(shù)返回識(shí)別結(jié)果;

c、Python-tesseract默認(rèn)支持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、上一篇博文中提到,執(zhí)行命令行 tesseract.exe 1.png output -l eng ,可以識(shí)別1.png中文字,并把識(shí)別結(jié)果輸出到output.txt中;

2、Pytesseract對(duì)上述過程進(jìn)行了二次封裝,自動(dòng)調(diào)用tesseract.exe,并讀取output.txt文件的內(nèi)容,作為函數(shù)的返回值進(jìn)行返回。

二、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函數(shù),該函數(shù)還支持-l eng 參數(shù),支持-psm 參數(shù)。

用法:

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

2、pytesseract里調(diào)用了image,所以才需要PIL,其實(shí)tesseract.exe本身是支持jpeg、png等圖片格式的。

實(shí)例代碼,識(shí)別某公共網(wǎng)站的驗(yàn)證碼(大家千萬別干壞事啊,思慮再三,最后還是隱掉網(wǎng)站域名,大家去找別的網(wǎng)站試試吧……):

#-*-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={}):      #定義連接函數(shù),有超時(shí)重連功能
    tryTimes = 0
    while True:
      if (tryTimes>20):
        print u"多次嘗試仍無法鏈接網(wǎng)絡(luò),程序終止"
        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可以增強(qiáng)圖片的識(shí)別率
    #enhancer = ImageEnhance.Contrast(image)
    #enhancer = enhancer.enhance(4)
    image = image.convert('L')
    ltext = ''
    ltext= image_to_string(image)
    #去掉非法字符,只保留字母數(shù)字
    ltext=re.sub("\W", "", ltext)
    print u'[%s]識(shí)別到驗(yàn)證碼:[%s]!!!' %(filename,ltext)
    image.save(filename)
    #print ltext
    return ltext

  def getRandomCode(self):
    #開始獲取驗(yàn)證碼
    #http://jbywcg.****.com.cn/CommonPage/Code.aspx?0.9409255818463862
    i = 0 
    while ( i<=100):
      i += 1 
      #拼接驗(yàn)證碼Url
      randomUrlNew='%s/CommonPage/Code.aspx?%s' %(self.baseUrl,random.random())
      #拼接驗(yàn)證碼本地文件名
      filename= '%s.png' %(i)
      filename= os.path.join(self.curPath,filename)
      jpgdata,jpgheader = self.urllib2Navigate(randomUrlNew)
      if len(jpgdata)<= 0 :
        print u'獲取驗(yàn)證碼出錯(cuò)!\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代碼優(yōu)化

上述程序在windows平臺(tái)運(yùn)行時(shí),會(huì)發(fā)現(xiàn)有黑色的控制臺(tái)窗口一閃而過的畫面,不太友好。

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

# 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

為了方便初學(xué)者,把pytesseract.py也貼出來,高手自行忽略。

#!/usr/bin/env python
'''
Python-tesseract is an optical character recognition (OCR) tool for python.
That is, it will recognize and "read" the text embedded in images.

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.


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

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  

Installing from source:  
$> git clone git@github.com:madmaze/pytesseract.git  
$> sudo python setup.py install  


LICENSE:
Python-tesseract is released under the GPL v3.

CONTRIBUTERS:
- Originally written by [Samuel Hoffstaetter](https://github.com/hoffstaetter) 
- [Juarez Bochi](https://github.com/jbochi)
- [Matthias Lee](https://github.com/madmaze)
- [Lars Kistner](https://github.com/Sr4l)

'''

# CHANGE THIS IF TESSERACT IS NOT IN YOUR PATH, OR IS NAMED DIFFERENTLY
tesseract_cmd = 'tesseract'

try:
  import Image
except ImportError:
  from PIL import Image
import subprocess
import sys
import tempfile
import os
import shlex

__all__ = ['image_to_string']

def run_tesseract(input_filename, output_filename_base, lang=None, boxes=False, config=None):
  '''
  runs the command:
    `tesseract_cmd` `input_filename` `output_filename_base`
  
  returns the exit status of tesseract, as well as tesseract's stderr output

  '''
  command = [tesseract_cmd, input_filename, output_filename_base]
  
  if lang is not None:
    command += ['-l', lang]

  if boxes:
    command += ['batch.nochop', 'makebox']
    
  if config:
    command += shlex.split(config)
    
  # 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
  
  return (proc.wait(), proc.stderr.read())

def cleanup(filename):
  ''' tries to remove the given filename. Ignores non-existent files '''
  try:
    os.remove(filename)
  except OSError:
    pass

def get_errors(error_string):
  '''
  returns all lines in the error_string that start with the string "error"

  '''

  lines = error_string.splitlines()
  error_lines = tuple(line for line in lines if line.find('Error') >= 0)
  if len(error_lines) > 0:
    return '\n'.join(error_lines)
  else:
    return error_string.strip()

def tempnam():
  ''' returns a temporary file-name '''
  tmpfile = tempfile.NamedTemporaryFile(prefix="tess_")
  return tmpfile.name

class TesseractError(Exception):
  def __init__(self, status, message):
    self.status = status
    self.message = message
    self.args = (status, message)

def image_to_string(image, lang=None, boxes=False, config=None):
  '''
  Runs tesseract on the specified image. First, the image is written to disk,
  and then the tesseract command is run on the image. Resseract's result is
  read, and the temporary files are erased.
  
  also supports boxes and config.
  
  if boxes=True
    "batch.nochop makebox" gets added to the tesseract call
  if config is set, the config gets appended to the command.
    ex: config="-psm 6"

  '''

  if len(image.split()) == 4:
    # In case we have 4 channels, lets discard the Alpha.
    # Kind of a hack, should fix in the future some time.
    r, g, b, a = image.split()
    image = Image.merge("RGB", (r, g, b))
  
  input_file_name = '%s.bmp' % tempnam()
  output_file_name_base = tempnam()
  if not boxes:
    output_file_name = '%s.txt' % output_file_name_base
  else:
    output_file_name = '%s.box' % output_file_name_base
  try:
    image.save(input_file_name)
    status, error_string = run_tesseract(input_file_name,
                       output_file_name_base,
                       lang=lang,
                       boxes=boxes,
                       config=config)
    if status:
      #print 'test' , status,error_string
      errors = get_errors(error_string)
      raise TesseractError(status, errors)
    f = open(output_file_name)
    try:
      return f.read().strip()
    finally:
      f.close()
  finally:
    cleanup(input_file_name)
    cleanup(output_file_name)

def main():
  if len(sys.argv) == 2:
    filename = sys.argv[1]
    try:
      image = Image.open(filename)
      if len(image.split()) == 4:
        # In case we have 4 channels, lets discard the Alpha.
        # Kind of a hack, should fix in the future some time.
        r, g, b, a = image.split()
        image = Image.merge("RGB", (r, g, b))
    except IOError:
      sys.stderr.write('ERROR: Could not open file "%s"\n' % filename)
      exit(1)
    print(image_to_string(image))
  elif len(sys.argv) == 4 and sys.argv[1] == '-l':
    lang = sys.argv[2]
    filename = sys.argv[3]
    try:
      image = Image.open(filename)
    except IOError:
      sys.stderr.write('ERROR: Could not open file "%s"\n' % filename)
      exit(1)
    print(image_to_string(image, lang=lang))
  else:
    sys.stderr.write('Usage: python pytesseract.py [-l language] input_file\n')
    exit(2)

if __name__ == '__main__':
  main()

以上……

以上這篇python下調(diào)用pytesseract識(shí)別某網(wǎng)站驗(yàn)證碼的實(shí)現(xiàn)方法就是小編分享給大家的全部內(nèi)容了,希望能給大家一個(gè)參考,也希望大家多多支持腳本之家。

相關(guān)文章

  • python編程語言中pathlib模塊簡介及使用

    python編程語言中pathlib模塊簡介及使用

    pathlib模塊類似os模塊,包含了對(duì)創(chuàng)建和刪除目錄、讀寫文件、獲取文件所在目錄不同部分字段、判斷文件是否存在,是否為文件和文件夾、文件統(tǒng)計(jì)和匹配查找,這篇文章主要介紹了python編程語言中pathlib模塊簡介及使用,需要的朋友可以參考下
    2023-09-09
  • Python log模塊logging記錄打印用法解析

    Python log模塊logging記錄打印用法解析

    這篇文章主要介紹了Python log模塊logging記錄打印用法解析,文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友可以參考下
    2020-01-01
  • Pytorch訓(xùn)練過程出現(xiàn)nan的解決方式

    Pytorch訓(xùn)練過程出現(xiàn)nan的解決方式

    今天小編就為大家分享一篇Pytorch訓(xùn)練過程出現(xiàn)nan的解決方式,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過來看看吧
    2020-01-01
  • Python?多線程爬取案例

    Python?多線程爬取案例

    這篇文章主要介紹了Python?多線程爬取案例,爬蟲屬于I/O密集型的程序,所以使用多線程可以大大提高爬取效率,文章圍繞主題展開詳細(xì)的內(nèi)容介紹,具有一定的參考價(jià)值,需要的小伙伴可以參考一下
    2022-08-08
  • Python工廠函數(shù)用法實(shí)例分析

    Python工廠函數(shù)用法實(shí)例分析

    這篇文章主要介紹了Python工廠函數(shù)用法,結(jié)合實(shí)例形式分析了Python工廠函數(shù)的概念、功能、使用方法及相關(guān)注意事項(xiàng),需要的朋友可以參考下
    2018-05-05
  • python 人工智能算法之隨機(jī)森林流程詳解

    python 人工智能算法之隨機(jī)森林流程詳解

    這篇文章主要為大家介紹了python 人工智能算法之隨機(jī)森林流程詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪
    2023-03-03
  • PyQt5實(shí)現(xiàn)簡單的計(jì)算器

    PyQt5實(shí)現(xiàn)簡單的計(jì)算器

    這篇文章主要為大家詳細(xì)介紹了PyQt5實(shí)現(xiàn)簡單的計(jì)算器,文中示例代碼介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下
    2020-05-05
  • Python中os.path模塊的8個(gè)神奇函數(shù)分享

    Python中os.path模塊的8個(gè)神奇函數(shù)分享

    在Python編程中,os.path模塊是一個(gè)非常重要的模塊,它提供了用于處理文件路徑和目錄的函數(shù),本文將介紹os.path模塊中最常用的8個(gè)內(nèi)置函數(shù),需要的可以參考下
    2023-11-11
  • 利用setuptools打包python程序的方法步驟

    利用setuptools打包python程序的方法步驟

    這篇文章主要介紹了利用setuptools打包python程序的方法步驟,文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧
    2020-01-01
  • Python3進(jìn)制之間的轉(zhuǎn)換代碼實(shí)例

    Python3進(jìn)制之間的轉(zhuǎn)換代碼實(shí)例

    這篇文章主要介紹了Python3進(jìn)制之間的轉(zhuǎn)換代碼實(shí)例,文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友可以參考下
    2019-08-08

最新評(píng)論