最近打算写一个自动登陆百度的脚本,但是验证码始终无法绕过,于是打算自己来试着识别,下面的文章
工具:tesseract 和jTessBoxEditor ,python image lib
首先预处理:
import Image
def ImageBinaryzation(threshold, im):
im = im.convert('L')
table = []
for i in range(256):
if i < threshold:
table.append(0)
else:
table.append(1)
out = im.point(table,'1')
# out.show();
infile = 'C:/Users/chenchen/Desktop/validImage/14.gif'
pathList = infile.split('.')
print(pathList[0])
print(pathList[1])
outfile = pathList[0] + '.tif'
im = Image.open(infile)
ImageBinaryzation(160, im)
im.save(outfile)
然后进行训练:
1 打开jTessBoxEditor,合并训练文件(tif),tool-》merge tiff,保存成 [lang].[fontname].exp[num].tif ,注意这里的fontname后面要用
2 执行命令 tesseract [lang].[fontname].exp[num].tif [lang].[fontname].exp[num] batch.nochop makebox
生成box文件(tif的坐标文件),在同一级目录下即可
3 用jTessBoxEditor的box editor编辑[lang].[fontname].exp[num].tif 文件,调整坐标,保存
4 新建一个font_properties文件,内容是fontname 0 0 0 0 0 0,保存在同一级目录,fontname是上面的文件名中的name
5 创建如下脚本,执行
rem 执行改批处理前先要目录下创建font_properties文件
echo Run Tesseract for Training..
tesseract.exe eng.baidu.exp0.tif eng.baidu.exp0 nobatch box.train
echo Compute the Character Set..
unicharset_extractor.exe eng.baidu.exp0.box
mftraining -F font_properties -U unicharset -O baidu.unicharset eng.baidu.exp0.tr
echo Clustering..
cntraining.exe eng.baidu.exp0.tr
echo Rename Files..
rename normproto baidu.normproto
rename inttemp baidu.inttemp
rename pffmtable baidu.pffmtable
rename shapetable baidu.shapetable
echo Create Tessdata..
combine_tessdata.exe baidu.
6
会显示一个结果如:
Combining tessdata files
TessdataManager combined tesseract data files.
Offset for type 0 is -1
Offset for type 1 is 108
Offset for type 2 is -1
Offset for type 3 is 1660
Offset for type 4 is 327545
Offset for type 5 is 327781
Offset for type 6 is -1
Offset for type 7 is -1
Offset for type 8 is -1
Offset for type 9 is -1
Offset for type 10 is -1
Offset for type 11 is -1
Offset for type 12 is –1
必须确定的是第2、4、5、6行的数据不是-1,那么一个新的字典就算生成了。
此时目录下“baidu.traineddata”的文件拷贝到tesseract程序目录下的“tessdata”目录。
7 现在就可以使用来识别了
tesseract.exe test.jpg result –l 【fontname】