Home > Backend Development > Python Tutorial > Call pytesseract under python to identify a website verification code

Call pytesseract under python to identify a website verification code

高洛峰
Release: 2018-05-15 09:26:38
Original
3327 people have browsed it

1. Introduction to pytesseract

1. Description of pytesseract

pytesseract latest version 0.1.6

Python-tesseract is a wrapper for google's 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.

Translate the general idea:

a. Python-tesseract is an independent package based on google's Tesseract-OCR;

b . The function of Python-tesseract is to recognize text in image files and return the recognition result as a return parameter;

c. Python-tesseract supports tiff and bmp format images by default. Only after installing PIL can it support jpeg and gif. , png and other image formats;

2. pytesseract installation

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
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]
```
$> sudo pip install pytesseract

Translation:

a, Python-tesseract supports python2.5 and higher versions ;

b. Python-tesseract needs to install PIL (Python Imaging Library) to support more image formats;

c. Python-tesseract needs to install the tesseract-ocr installation package.

In summary, Pytesseract principle:

1. As mentioned in the previous blog post, executing the command line tesseract.exe 1.png output -l eng can recognize Chinese characters in 1.png. And output the recognition results to output.txt;

2. Pytesseract re-encapsulates the above process, automatically calls tesseract.exe, and reads the contents of the output.txt file as the return value of the function Make a return.

2. Use 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'),))

You can see:

1. The core code is the image_to_string function. This function also supports the -l eng parameter and the -psm parameter.

Usage:

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

2. In pytesseract Image is called, so PIL is needed. In fact, tesseract.exe itself supports jpeg, png and other image formats.

Example code to identify the verification code of a public website (please don’t do bad things. After thinking about it again and again, you finally hide the domain name of the website. Let’s try to find other websites...):

#-*-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=&#39;%s/CommonPage/Code.aspx?%s&#39; %(self.baseUrl,random.random())
      #拼接验证码本地文件名
      filename= &#39;%s.png&#39; %(i)
      filename= os.path.join(self.curPath,filename)
      jpgdata,jpgheader = self.urllib2Navigate(randomUrlNew)
      if len(jpgdata)<= 0 :
        print u&#39;获取验证码出错!\n&#39;
        return False
      f = open(filename, &#39;wb&#39;)
      f.write(jpgdata)
      #print u"保存图片:",fileName
      f.close()
      self.authCode = self.randomCodeOcr(filename)
 
 
#主程序开始
orcln=orclnypcg()
orcln.initUrllib2()
orcln.getRandomCode()
Copy after login

3. pytesseract code optimization

When the above program is run on the windows platform, you will find a black console window flashing by, which is not very friendly.

Slightly modified pytesseract.py (under the C:\Python27\Lib\site-packages\pytesseract directory) to hide the above process.

# 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

For For the convenience of beginners, pytesseract.py is also posted, and experts can ignore it.

#!/usr/bin/env python
&#39;&#39;&#39;
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&#39;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(&#39;test.png&#39;)))
 > print(pytesseract.image_to_string(Image.open(&#39;test-european.jpg&#39;),))
```
 
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&#39;t the case, for example because tesseract isn&#39;t in your PATH, you will
 have to change the "tesseract_cmd" variable at the top of &#39;tesseract.py&#39;.
 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)
 
&#39;&#39;&#39;
 
# CHANGE THIS IF TESSERACT IS NOT IN YOUR PATH, OR IS NAMED DIFFERENTLY
tesseract_cmd = &#39;tesseract&#39;
 
try:
  import Image
except ImportError:
  from PIL import Image
import subprocess
import sys
import tempfile
import os
import shlex
 
__all__ = [&#39;image_to_string&#39;]
 
def run_tesseract(input_filename, output_filename_base,, boxes=False, config=None):
  &#39;&#39;&#39;
  runs the command:
    `tesseract_cmd` `input_filename` `output_filename_base`
   
  returns the exit status of tesseract, as well as tesseract&#39;s stderr output
 
  &#39;&#39;&#39;
  command = [tesseract_cmd, input_filename, output_filename_base]
   
  if lang is not None:
    command += [&#39;-l&#39;, lang]
 
  if boxes:
    command += [&#39;batch.nochop&#39;, &#39;makebox&#39;]
     
  if config:
    command += shlex.split(config)
     
  # modified by zhongtang hide console window
  # new code
  IS_WIN32 = &#39;win32&#39; 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)
  &#39;&#39;&#39;
  # old code
  proc = subprocess.Popen(command,
      stderr=subprocess.PIPE)
  &#39;&#39;&#39;
  # modified end
   
  return (proc.wait(), proc.stderr.read())
 
def cleanup(filename):
  &#39;&#39;&#39; tries to remove the given filename. Ignores non-existent files &#39;&#39;&#39;
  try:
    os.remove(filename)
  except OSError:
    pass
 
def get_errors(error_string):
  &#39;&#39;&#39;
  returns all lines in the error_string that start with the string "error"
 
  &#39;&#39;&#39;
 
  lines = error_string.splitlines()
  error_lines = tuple(line for line in lines if line.find(&#39;Error&#39;) >= 0)
  if len(error_lines) > 0:
    return &#39;\n&#39;.join(error_lines)
  else:
    return error_string.strip()
 
def tempnam():
  &#39;&#39;&#39; returns a temporary file-name &#39;&#39;&#39;
  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,, boxes=False, config=None):
  &#39;&#39;&#39;
  Runs tesseract on the specified image. First, the image is written to disk,
  and then the tesseract command is run on the image. Resseract&#39;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"
 
  &#39;&#39;&#39;
 
  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 = &#39;%s.bmp&#39; % tempnam()
  output_file_name_base = tempnam()
  if not boxes:
    output_file_name = &#39;%s.txt&#39; % output_file_name_base
  else:
    output_file_name = &#39;%s.box&#39; % 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 &#39;test&#39; , 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(&#39;ERROR: Could not open file "%s"\n&#39; % filename)
      exit(1)
    print(image_to_string(image))
  elif len(sys.argv) == 4 and sys.argv[1] == &#39;-l&#39;:
   .argv[2]
    filename = sys.argv[3]
    try:
      image = Image.open(filename)
    except IOError:
      sys.stderr.write(&#39;ERROR: Could not open file "%s"\n&#39; % filename)
      exit(1)
    print(image_to_string(image,))
  else:
    sys.stderr.write(&#39;Usage: python pytesseract.py [-l language] input_file\n&#39;)
    exit(2)
 
if __name__ == &#39;__main__&#39;:
  main()
Copy after login

The above...

The above method of calling pytesseract to identify the verification code of a website under python is all the content shared by the editor. I hope it can give you a reference, and I hope everyone will support the PHP Chinese website.

For more articles related to calling pytesseract to identify a website verification code under Python, please pay attention to the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template