pytesseract能识别什么样的py模拟登录验证码网站

博客分类:
首先我得承认,关注tesseract-ocr, 是冲着下面这篇文章的噱头去的,26行groovy代码破解网站验证码
当然,看了之后才知道,原来是调用了三方库tesseract-ocr……
尽管如此,本着邓爷爷的“不管白猫黑猫,能抓住老鼠的就是好猫”的原则,趁着假期也开始了“文字识别”的初级研究
HP的tesseract最近被Google支持并开支持英文字母和数字,据说辨识程度是世界排名第三的;更难能可贵的是,提供多国语言包下载(包括中文,精度不咋的倒是真的……),并自带训练工具。
安装完并跑过自带例子之后,首先想到的应用自然是用于验证码分析
按照说明,送入tesseract的图片的质量直接影响识别的效果,因此,简单的预处理是不可或缺的
1.首先灰度化,灰度值=0.3R+0.59G+0.11B:
for (int y = minY; y & y++) {
for (int x = minX; x & x++) {
int rgb = srcImg.getRGB(x, y);
Color color = new Color(rgb); // 根据rgb的int值分别取得r,g,b颜色。
int gray = (int) (0.3 * color.getRed() + 0.59
* color.getGreen() + 0.11 * color.getBlue());
Color newColor = new Color(gray, gray, gray);
srcImg.setRGB(x, y, newColor.getRGB());
}
结果如图:
2.其次是灰度反转:
for (int y = minY; y & y++) {
for (int x = minX; x & x++) {
int rgb = buffImg.getRGB(x, y);
Color color = new Color(rgb); // 根据rgb的int值分别取得r,g,b颜色。
Color newColor = new Color(255 - color.getRed(), 255 - color
.getGreen(), 255 - color.getBlue());
buffImg.setRGB(x, y, newColor.getRGB());
结果如图:
3.再次是二值化,取图片的平均灰度作为阈值,低于该值的全都为0,高于该值的全都为255:
for (int y = minY; y & y++) {
for (int x = minX; x & x++) {
int rgb = buffImg.getRGB(x, y);
Color color = new Color(rgb); // 根据rgb的int值分别取得r,g,b颜色。
int value = 255 - color.getBlue();
if (value & average) {
Color newColor = new Color(0, 0, 0);
buffImg.setRGB(x, y, newColor.getRGB());
Color newColor = new Color(255, 255, 255);
buffImg.setRGB(x, y, newColor.getRGB());
结果如图:
看看效果还凑合,就省却尺寸调整、中值滤波以及噪点去除等步骤了。
以上完成图片预处理工作;Tesseract没有开放api,纯命令行调用:
List&String& cmd = new ArrayList&String&(); // 存放命令行参数的数组
cmd.add(tessPath + "\\tesseract");
cmd.add("");
cmd.add(outputFile.getName()); // 输出文件位置
cmd.add(LANG_OPTION); // 字符类别
cmd.add("eng"); // 英文,找到tessdata里对应的字典文件。
ProcessBuilder pb = new ProcessBuilder();
pb.directory(imageFile.getParentFile());
cmd.set(1, tempImage.getName()); // 把图片文件位置放在第一个位置
pb.command(cmd); // 执行命令行
pb.redirectErrorStream(true); // 通知进程生成器是否合并标准错误和标准输出,把进程错误保存起来。
Process process = pb.start(); // 开始执行进程
int w = process.waitFor(); // 当前进程停止,直到process停止执行,返回执行结果.
结果输出表示一切正常
当然,真正要用好tesseract-ocr,还需用到其强大地训练工具,就是后话了……
另外,关于文字识别,除去作为破解验证码的反制手段之外,我们是否也有相关的应用呢?
浏览 36327
浏览: 305078 次
来自: 杭州
博主您好 ,能否求一份该博文对应源码,在下学生狗一枚,非常感谢 ...
博主,能不能发一份完整代码给我啊,我现在正在学习这个,邮箱:3 ...
soledad1030 写道[size=x-large][si ...
u 写道博主,求发 一份代码给我,学生党毕设 ...
博主,求发 一份代码给我,学生党毕设急用。。。
(window.slotbydup=window.slotbydup || []).push({
id: '4773203',
container: s,
size: '200,200',
display: 'inlay-fix'Python-tesseract是一款用于光学字符识别(OCR)的python工具,即从图片中识别出其中嵌入的文字。Python-tesseract是对Google Tesseract-OCR的一层封装。它也同时可以单独作为对tesseract引擎的调用脚本,支持使用PIL库(Python Imaging Library)读取的各种图片文件类型,包括jpeg、png、gif、bmp、tiff和其他格式,。作为脚本使用它将打印出识别出的文字而非写入到文件。所以安装pytesseract前要先安装PIL和tesseract-orc这俩依赖库
PIL 下载地址:
tesseract-ocr下载地址:https://sourceforge.net/projects/tesseract-ocr-alt/files/
然后在cmd 中安装pytesseract
cd C:\Python27\Scripts
pip install pytesseract
&3.用pytesseract识别验证码
import requests
import pytesseract
from PIL import Image
5 except ImportError:
raise SystemExit('cuole');
7 addr = raw_input()
8 image = Image.open(addr)
9 vcode = pytesseract.image_to_string(image)
<span style="color: # print vcode
4.PIL的Image模块
本文是节选自
并做了一些简单的翻译
只能保证自己看懂,不保证翻译质量。欢迎各位给出意见。
------------------------------------------------------
& & Image 模块提供了一个同名类(Image),也提供了一些工厂函数,包括从文件中载入图片和创建新图片。例如,以下的脚本先载入一幅图片,将它旋转 45 度角,并显示出来:
<span style="color: # &&&from PIL import Image<span style="color: # &&&&im = Image.open("j.jpg")<span style="color: # &&&&im.rotate(<span style="color: #).show()
& & 下面这个脚本则创建了当前目录下所有以 .jpg 结尾的图片的缩略图。
from PIL import Image
import glob, os
size = 128, 128
for infile in glob.glob("*.jpg"):
file, ext = os.path.splitext(infile)
im = Image.open(infile)
im.thumbnail(size, Image.ANTIALIAS)
im.save(file + ".thumbnail", "JPEG")
& & Image 类中的函数。
0. & &new :&这个函数创建一幅给定模式(mode)和尺寸(size)的图片。如果省略 color 参数,则创建的图片被黑色填充满,如果 color 参数是 None 值,则图片还没初始化。
<span style="color: # Image.new( mode, size ) =& image
<span style="color: # Image.new( mode, size, color ) =& image
1. & &open : 打开并识别所提供的图像文件。不过,使用这函数的时候,真正的图像数据在你进行数据处理之前并没有被读取出来。可使用 load 函数进行强制加载。 mode 参数可以省略,但它只能是 "r" 值。
<span style="color: # Image.open( infile ) =& image
<span style="color: # Image.open( infile, mode ) =& image
2. & &blend : 使用两幅给出的图片和一个常量 alpha 创建新的图片。两幅图片必须是同样的 size 和 mode 。
<span style="color: #
Image.blend( image1, image2, alpha ) =& image
<span style="color: #
# 结果 与 运算过程
<span style="color: #
# out = image1 * ( 1.0 - alpha ) + image2 * alpha
3. & &composite : 使用两幅给出的图片和一个与 alpha 参数相似用法的 mask 参数,其值可为:"1", "L", "RGBA" 。两幅图片的 size 必须相同。
<posite( image1, image2, mask ) =& image
4. & &eval : 使用带一个参数的函数作用于给定图片的每一个像素。如果给定的图片有超过一个的 频段(band),则该函数也会作用于每一个频段。注意,该函数是每一个像素计算一次,所以不能使用一些随机组件或其他的生成器。
<span style="color: # Image.eval( image, function ) =& image
5. & &frombuffer : (PIL 1.1.4 中新添加的)使用标准 "raw" 解码器在像素数据或是对象缓存中创建一个图像副本。不是所有的模式都支持这种用法。支持的 mode 有"L", "RGBX", "RGBA", "CMYK"。
<span style="color: # Image.frombuffer( mode, size, data ) =& image
6. & &fromstring : 注意,这个函数只对像素数据进行解码,而不是一整张图片。如果你有一整张字符串格式的图片,使用 StringIO 对其进行包装并用 open 函数载入它。
<span style="color: #
# 使用字符串类型的像素数据和标准解码器 "raw" 来创建图像
<span style="color: #
Image.fromstring( mode, size, data ) =& image
<span style="color: #
# 同上。不过允许你使用其他 PIL 支持的像素解码器。
<span style="color: #
Image.fromstring( mode, size, data, decoder, parameters ) =& image
7. & &merge : 使用一系列单一频段(band)的图像来创建新的一幅图像。频段是以一些图像组成的元组或列表,所有的 band 必须有相同大小的 size 。
<span style="color: # Image.merge( mode, bands ) =&image
& & Image 类中的方法:
0. & &convert : 返回一个转换后的图像的副本。
<span style="color: # convert
<span style="color: # # If mode is omitted, a mode is chosed so that all information in the image and the palette can be representedwithout a palette .
<span style="color: # # when from a colour image to black and white, the library uses the ITU-R 601-2 luma transfrom:
<span style="color: # # L = R * 299/1000 + G * 587/1000 + B * 114/1000
<span style="color: #
im.convert( mode ) =& image
<span style="color: #
<span style="color: #
# Converts an "RGB" image to "L" or "RGB" using a conversion matrix. The matrix is 4- or 16-tuple.
<span style="color: #
im.convert( mode, matrix ) =& image
& & 下面是一个例子:转换 RGB 为 XYZ 。
<span style="color: # rgb2xyz = (
<span style="color: #
0...180423, 0,
<span style="color: #
0...072169, 0,
<span style="color: #
0...950227, 0 )
<span style="color: # out = im.convert("RGB", rgb2xyz)
1. & &copy : 复制图像。如果你希望粘贴一些东西进图像里面的话可以使用这个方法,但仍然会保留原图像。
<span style="color: # im.copy() =& image
2. & &crop : 返回图像某个给定区域。box 是一个 4 元素元组,定义了 left, upper, right, lower 像素坐标。使用这个方法的时候,如果改变原始图像,可能会,也可能不会改变裁剪生成的图像。创建一个完全的复制,裁剪复制的时候使用 load 方法。
<span style="color: # im.crop( box ) =& image
3. & &draft : 按给出的 mode 和 size 进行配置。可以使用这个方法将彩色JPEG图片转为灰度图。
<span style="color: # im.draft(mode, size)
4. & &filter : 返回图像使用滤波器后的副本。可以看
获取更多有用的滤波器。
<span style="color: # im.filter( filter ) =& image
5. & &fromstring : 和前面的函数是一样的功能,不过这个方法是将数据载入到当前图像。
<span style="color: # im.fromstring( data )
<span style="color: # im.fromstring( data, decoder, parameters )
6. & &getbands : 返回一个元组,包含每一个 band 的名字,比如,在一幅 RGB 格式的图像上使用 getbands 则返回("R", "G", "B")。
<span style="color: # im.getbands(
) =& tuple of strings
7. & &getbbox : 计算图像边框值,返回一个 4-元组 ,值为(左,上,右,下)。
<span style="color: # im.getbbox()
=& 4-tuple or None
8. & &getcolors : 在 1.1.5 版本中新添加的。返回一个未排序列表,其元素是元组(count, color)。the count is the number of times the corresponding color occurs in the image 。If the maxcolors value is exceeded, the method stops counting and returns None。
<span style="color: # im.getcolors() =& a list of (count, color) tuples or None
<span style="color: # im.getcolors( maxcolors ) =& a list of (count, color) tuples or None
9. & &getdata : 返回一个图像内容的像素值序列。不过,这个返回值是 PIL 内部的数据类型,只支持确切的序列操作符,包括迭代器和基本序列方法。我们可以通过 list(im.getdata()) &为其生成普通的序列。
<span style="color: # im.getdata() =& sequence
10. & &getextrema : 返回一个 2-元组 ,值为图像的最小最大值。在当前PIL版本中,仅支持单一频段(single-band)的图像。
<span style="color: # im.getextrema() =& 2-tuple
11. & &getpixel : 返回指定位置的像素,如果所打开的图像是多层次的图片,那这个方法就返回一个元组。
<span style="color: # im.getpixel( xy ) =& value or tuple
12. & &histogram : 返回图像直方图,值为像素计数组成的列表。如果有参数 mask ,则返回图像所有部分的直方图。
<span style="color: # im.histogram() =& list
<span style="color: # im.histogram( mask ) =& list
13. & &load : 版本 1.1.6 新添加的。load 返回对象的像素值,可以用来修改像素值。
<span style="color: # im.load()
<span style="color: # pix = im.load()
<span style="color: # print pix[x, y]
<span style="color: # pix[x, y] = value
14. & &paste : 1). 粘贴新图片至图片中,box 参数可以为 2-元组(upper, left)或是 4-元组(left, upper, right, lower),或者是 None(0, 0)。2). 功能同上。不过是将指定位置填充为某种颜色。
<span style="color: # im.paste( image, box )
<span style="color: #
<span style="color: # im.paste( colour, box )
<span style="color: #
<span style="color: # im.paste( image, box, mask )
<span style="color: #
<span style="color: # im.paste( colour, box, mask )
15. & &point :&
<span style="color: # im.point( bable ) =& image
<span style="color: # im.point( function ) =& image
阅读(...) 评论()python+tesseract验证码识别的一点小心得
时间: 11:46:25
&&&& 阅读:171
&&&& 评论:
&&&& 收藏:0
标签:&&&&&&&&&&&&&&&&&&&&&&&&&&&由于公司需要,最近开始学习验证码的识别
我选用的是tesseract-ocr进行识别,据说以前是惠普公司开发的排名前三的,现在开源了。到目前为止已经出到3.0.2了
当然了,前期我们还是需要对验证码进行一些操作,让他对机器更友好,这样才能提高识别率。
步骤基本上是这样的
第一步对验证码进行灰度图以及二值化
需要用到pil库可以pip下载
def binarization(image):
#转成灰度图
imgry = image.convert(‘L‘)
#二值化,阈值可以根据情况修改
threshold = 128
table = []
for i in range(256):
if i & threshold:
table.append(0)
table.append(1)
out = imgry.point(table, ‘<span style="color: #‘)
return out
接着是去噪,因为我研究的验证码基本不需要去噪,所以省略,需要去噪的小伙伴们,请自行谷歌。
还有倾斜度调整,推荐使用旋转卡壳算法
原理是对图片进行-30度到30度的旋转,宽度最大的一般就是正的了。(网上这样说的,我试过了,对大部分是可以,小部分如c啥的貌似效果不好)
可以用腐蚀算法对验证码进行细化
腐蚀算法请自行谷歌。
第二步对验证码进行切割
对不同的验证码有不同的算法
目前我只研究了这几种
垂直像素直方图
原理是根据每个x的黑块数量进行切割,黑块数量大于某个值开始切割,小于某个值结束切割。适用于验证码之间有间隔或者间隔较大的,对那种粘连在一起的验证码效果不好。
平均分割法
原理是找到黑块开始出现的x,y轴和黑块不出现的x,y轴,切割。然后平均分割成n等分。适用于验证码大小比较固定的,对粘连在一起的验证码效果比上一种方法要好一点。
波谷分割法
原理和垂直像素直方图类似,记录每个x的黑块数量,找到局部的极小值,切割。适用于验证码之间有间隔或者间隔较大的,对那种粘连在一起的验证码效果比垂直像素直方图要好。
原理是模拟水滴的流动,记录水滴的流动路径,然后进行切割。要注意的是,起始点的确定很重要,对那种粘连在一起的验证码效果很好。
以上的四种算法以后我会将代码贴在另一个随笔里
第三步对验证码进行识别
终于到了重头戏了
需要导入pytesser,调用image_to_string(image)即可识别。
不过识别率实在是低的可怜。
所以需要我们对机器进行训练。
下面简要介绍下如果对机器进行训练。
首先下载tesseract-ocr,必须的没有怎么识别对吧。
找尽量多的验证码,最好是二值化后的或者按照上面的步骤切割下来的。
以下摘自/wolfray/p/5547267.html
为了方便 ,将tif命名格式设为[lang].[fontname].exp[num].tif&lang是语言&fontname是字体&比如我们要训练自定义字库 ec 字体名:unfont&那么我们把tif文件重命名 ec.ufont.exp0.tif
生成 .box文件&tesseract ec.ufont.exp0.tif ec.ufont.exp0 batch.nochop makebox&使用训练过的字库生成.box文件&tesseract ec.ufont.exp0.tif ec.ufont.exp0 -l ufont batch.nochop makebox
1. 产生字符特征文件 .tr
tesseract ec.ufont.exp0.tif ec.ufont.exp0 nobatch box.train&这一步将会产生 ec.ufont.exp0.tr文件和一个 ec.ufont.exp0.txt文件,txt文件貌似没什么用,看看而以。
2.计算字符集(生成unicharset文件)&unicharset_extractor ec.ufont.exp0.box
3.定义字体特征文件&—Tesseract-OCR3.01以上的版本在训练之前需要创建一个名称为font_properties.txt的字体特征文件&手工建立一个文件font_properties.txt&内容如:ufont 0 0 0 0 0&注意:这里 必须与训练名中的名称保持一致,填入下面内容 ,这里全取值为0,表示字体不是粗体、斜体等等。
4.聚集字符特征&1) shapeclustering -F font_properties.txt -U unicharset ec.ufont.exp0.tr&注意:如果font_properties不加扩展名.txt,可能会报错&2) mftraining -F font_properties.txt -U unicharset -O ufont.unicharset ec.ufont.exp0.tr&使用上一步产生的字符集文件unicharset,来生成当前新语言的字符集文件ec.unicharset。同时还会产生图形原型文件inttemp和每个字符所对应的字符&特征数文件pffmtable。最重要的就是这个inttemp文件了,他包含了所有需要产生的字的图形原型。&3)cntraining ec.ufont.exp0.tr&这一步产生字符形状正常化特征文件normproto。&shapeclustering 操作不是必须的,若没有进行此步,在mftraining的时候 会自动进行。&5.改名字&把目录下的unicharset、inttemp、pffmtable、shapetable、normproto这五个文件前面都加上ufont.
6.执行combine_tessdata ufont.&然后把ufont.traineddata放到tessdata目录
7.测试&必须确定的是第type 1、3、4、5的数据不是-1,那么一个新的字典就算生成了。&tesseract ec.ufont.exp0.tif papapa -l ufont
tesseract也提出,通过使用多个语言训练库联合使用。如此,新的字体训练库也可以与原有的数据训练库联合使用。如参数 -l 之后 tesseract input.tif output -l eng+newfont。
cntraining和mftraining只能最多采用32个.tr文件,因此,对于相同的字体,你必须从多种语言中,以字体独立的方式,将所有的文件cat到一起来让32种语言结合在一起。cntraining/mftraining以及unicharset_extractor命令行工具必须各自由给定的.tr和.box文件,以相同的顺序,为不同的字体进行不同的过滤。可以提供一个程序来完成以上的事情,并在字符集表中挑出相同字符集。这样会将事情更简单些。&写批处理bat命令的时候,要灵活使用excel里面的填充功能。
在这里感谢下很多大神在网站的解答和记录,对我的学习起了很大的作用。谢谢。标签:&&&&&&&&&&&&&&&&&&&&&&&&&&&
&&国之画&&&& &&&&chrome插件&&
版权所有 京ICP备号-2
迷上了代码!2010年9月 挨踢职涯大版内专家分月排行榜第一
2010年12月 .NET技术大版内专家分月排行榜第二2010年10月 挨踢职涯大版内专家分月排行榜第二2010年8月 挨踢职涯大版内专家分月排行榜第二
2013年 总版技术专家分年内排行榜第一
2014年 总版技术专家分年内排行榜第三
本帖子已过去太久远了,不再提供回复功能。python下调用pytesseract识别某网站验证码的实现方法
投稿:jingxian
字体:[ ] 类型:转载 时间:
下面小编就为大家带来一篇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
( /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 /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使用
& 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 htmltool
from pytesseract import *
from PIL import Image
from PIL import ImageEnhance
class orclnypcg:
def __init__(self):
self.baseUrl='http://jbywcg.****.'
self.ht=htmltool.htmltool()
self.curPath=self.ht.getPyFileDir()
self.authCode=''
def initUrllib2(self):
cookie = cookielib.CookieJar()
cookieHandLer = urllib2.HTTPCookieProcessor(cookie)
httpHandLer=urllib2.HTTPHandler(debuglevel=0)
httpsHandLer=urllib2.HTTPSHandler(debuglevel=0)
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"多次尝试仍无法链接网络,程序终止"
if (data=={}):
req = urllib2.Request(url)
req = urllib2.Request(url,urllib.urlencode(data))
response =urllib2.urlopen(req)
bodydata = response.read()
headerdata = ()
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"连接失败,尝试重新连接"
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.****./CommonPage/Code.aspx&#63;0.3862
while ( i&=100):
#拼接验证码Url
randomUrlNew='%s/CommonPage/Code.aspx&#63;%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
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
为了方便初学者,把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
( /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.
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 /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 :madmaze/pytesseract.git
$& sudo python setup.py install
Python-tesseract is released under the GPL v3.
CONTRIBUTERS:
- Originally written by [Samuel Hoffstaetter](/hoffstaetter)
- [Juarez Bochi](/jbochi)
- [Matthias Lee](/madmaze)
- [Lars Kistner](/Sr4l)
# CHANGE THIS IF TESSERACT IS NOT IN YOUR PATH, OR IS NAMED DIFFERENTLY
tesseract_cmd = 'tesseract'
import Image
except ImportError:
from PIL import Image
import subprocess
import sys
import tempfile
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]
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 '''
os.remove(filename)
except OSError:
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)
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
output_file_name = '%s.box' % output_file_name_base
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)
return f.read().strip()
cleanup(input_file_name)
cleanup(output_file_name)
def main():
if len(sys.argv) == 2:
filename = sys.argv[1]
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)
print(image_to_string(image))
elif len(sys.argv) == 4 and sys.argv[1] == '-l':
lang = sys.argv[2]
filename = sys.argv[3]
image = Image.open(filename)
except IOError:
sys.stderr.write('ERROR: Could not open file "%s"\n' % filename)
print(image_to_string(image, lang=lang))
sys.stderr.write('Usage: python pytesseract.py [-l language] input_file\n')
if __name__ == '__main__':
以上这篇python下调用pytesseract识别某网站验证码的实现方法就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持脚本之家。
您可能感兴趣的文章:
大家感兴趣的内容
12345678910
最近更新的内容
常用在线小工具}

我要回帖

更多关于 pytesseract 安装 的文章

更多推荐

版权声明:文章内容来源于网络,版权归原作者所有,如有侵权请点击这里与我们联系,我们将及时删除。

点击添加站长微信