Tesseract 是一个著名、开源、多平台的 OCR 引擎,最初由惠普公司开发,后来由 Google 维护,现在项目托管在 Github 上。到目前为止已经支持了数十种语言(包括中文)。在我看来它最吸引人的地方是开发者可以训练出自己的语言文件用来识别。
以自带语言库进行识别的方法不在本文范围之内.关于如何训练样本,Tesseract-OCR 官网有详细的介绍 http://code.google.com/p/tesseract-ocr/wiki/TrainingTesseract3 ,这里通过一个简单的例子来介绍一下如何进行样本训练。
环境: Windows 10 x64, JRE 8
训练工具 jTessBoxEditor,这个工具用来生成训练样本以及纠正监督,下载地址:http://sourceforge.net/projects/vietocr/files/jTessBoxEditor/。工具基于 Java 所以需要配置适当的运行环境。
准备样本
准备自己的样本图像(越多越好),比如我准备了若干 B 站抽瓜子的验证码。
因为 jTessBoxEditor 只接受 tiff 格式的图片,需要事先转换。可以使用 ImageMagick 等工具。
合并样本图像
运行 jTessBoxEditor ,菜单栏 Tools->Merge TIFF。在弹出的对话框中选择样本图像(按Shift选择多张),合并保存成 num.font.exp0.tif
文件。
生成 Box 文件
tesseract.exe [-psm 7] num.font.exp0.tif num.font.exp0 batch.nochop makebox
如果输出中含有 Empty page!!
可以添加 -psm 参数修正。
-psm N
Set Tesseract to only run a subset of layout analysis and assume a certain form of image. The options for N are:
0 = Orientation and script detection (OSD) only.
1 = Automatic page segmentation with OSD.
2 = Automatic page segmentation, but no OSD, or OCR.
3 = Fully automatic page segmentation, but no OSD. (Default)
4 = Assume a single column of text of variable sizes.
5 = Assume a single uniform block of vertically aligned text.
6 = Assume a single uniform block of text.
7 = Treat the image as a single text line.
8 = Treat the image as a single word.
9 = Treat the image as a single word in a circle.
10 = Treat the image as a single character.
生成的 Box 文件为 num.font.exp0.box
,Box 文件为 Tessercat 识别出的文字和其坐标。
makebox 命名格式
tesseract.exe [lang].[fontname].exp[num].tif [lang].[fontname].exp[num] batch.nochop makebox
校正
运行 jTessBoxEditor,打开 num.font.exp0.tif
文件(必须将上一步生成的 .box 和 .tif 样本文件放在同一目录),如下图所示。可以看出有些字符识别的不正确,可以通过该工具手动对每张图片中识别错误的字符进行校正。校正完成后保存即可。
一定要全部纠正,否则训练结果会出现偏差,影响最后成果。
定义字体特征文件
Tesseract-OCR3.01 以上的版本在训练之前需要创建一个名称为 font_properties
的字体特征文件。
font_properties
不含有 BOM 头,文件内容格式如下
<fontname> <italic> <bold> <fixed> <serif> <fraktur>
其中 fontname
为字体名称,必须与 [lang].[fontname].exp[num].box
中的名称保持一致。 <italic>、<bold> 、<fixed> 、<serif>、 <fraktur>
的取值为 1 或 0,表示字体是否具有这些属性。
我们直接使用
font 0 0 0 0 0
生成语言文件
在样本图片所在目录下创建一个批处理文件,输入如下内容
rem 执行改批处理前先要目录下创建 font_properties 文件
echo Run Tesseract for Training..
tesseract.exe num.font.exp0.tif num.font.exp0 nobatch box.train
echo Compute the Character Set..
unicharset_extractor.exe num.font.exp0.box
mftraining -F font_properties -U unicharset -O num.unicharset num.font.exp0.tr
echo Clustering..
cntraining.exe num.font.exp0.tr
echo Rename Files..
rename normproto num.normproto
rename inttemp num.inttemp
rename pffmtable num.pffmtable
rename shapetable num.shapetable
echo Create Tessdata..
combine_tessdata.exe num.
执行结果如下
需确认打印结果中的 Offset 1、3、4、5、13 这些项不是 -1。这样,一个新的语言文件就生成了。
num.traineddata
便是最终生成的语言文件,将生成的 num.traineddata
拷贝到 Tesseract-OCR->tessdata 目录下。可以用它来进行字符识别了。