一、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 astand-alone invocation script to tesseract, as it can read all image typessupported 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 recognizedtext in stead of writing it to a file. support for confidence estimates andbounding 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 isthe 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 thisisn’t the case, for example because tesseract isn’t in your path, you willhave 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’),))
可以看到:
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 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,, 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,, 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’:
.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,))
else:
sys.stderr.write(‘usage: python pytesseract.py [-l language] input_file\n’)
exit(2)
if __name__ == ‘__main__’:
main()
以上……
以上这篇python下调用pytesseract识别某网站验证码的实现方法就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持php中文网。
更多python下调用pytesseract识别某网站验证码相关文章请关注php中文网!