Tesseract-OCR-v5.0中文識別,訓練自定義字庫,提高圖片的識別效果
1,下載安裝Tesseract-OCR 安裝,鏈接地址https://digi.bib.uni-mannheim.de/tesseract/
2,安裝成功 tesseract -v
注意:安裝后,要添加系統環境變量
3,cmd指定目錄到 cd C:\Work\BlogsTest\TestPic,要識別圖片的文件夾 識別:tesseract test.png result -l chi_sim
識別成功的效果,result.txt文件會自動生成
要注意:Tesseract-OCR的安裝目錄要包含識別中文的字符集chi_sim.traineddata,可以在GitHub下載https://github.com/tesseract-ocr/tessdata
4,可見第3步的識別效果不是很好,想到通過訓練自定義字庫,提高圖片的識別效果
(0)下載安裝jTessBoxEditor,https://sourceforge.net/projects/vietocr/files/jTessBoxEditor/
注意要安裝JavaRuntime
(1)打開jTessBoxEditor,選擇Tools->Merge TIFF,進入訓練樣本所在文件夾,選中要參與訓練的樣本圖片:
(2)點擊 “打開” 后彈出保存對話框,選擇保存在當前路徑下,文件命名為 “qq66.test.exp0.tif” ,格式只有一種 “TIFF” 可選。
tif文面命名格式[lang].[fontname].exp[num].tif
lang是語言,fontname是字體,num為自定義數字。
比如我們要訓練自定義字庫 qq66,字體名test,那么我們把圖片文件命名為 qq66.test.exp0.tif
(3)使用tesseract生成.box文件
tesseract qq66.test.exp0.tif qq66.test.exp0 -l chi_sim --psm 6 batch.nochop makebox
注意:--psm的語法,數字對應不同的 頁面分割模式。
(4)使用jTessBoxEditor矯正.box文件的錯誤
打開后矯正后,點擊 save
(5)生成font_properties文件:(該文件沒有后綴名)
執行命令,執行完之后,會在當前目錄生成font_properties文件
echo test 0 0 0 0 0 >font_properties
也可以手工新建一個名為font_properties的文本文件,輸入內容 “test 0 0 0 0 0” 表示字體test的粗體、傾斜等共計5個屬性。這里的“test”必須與“qq66.test.exp0.box”中的“test”名稱一致。
(6)使用tesseract生成.tr訓練文件
執行下面命令,執行完之后,會在當前目錄生成qq66.test.exp0.tr文件。
tesseract qq66.test.exp0.tif qq66.test.exp0 nobatch box.train
(7)生成字符集文件:
執行下面命令:執行完之后會在當前目錄生成一個名為“unicharset”的文件。
unicharset_extractor qq66.test.exp0.box
(8)生成shape文件:
執行下面命令,執行完之后,會生成 shapetable 和 zwp.unicharset 兩個文件。
shapeclustering -F font_properties -U unicharset -O qq66.unicharset qq66.test.exp0.tr
(8)生成聚字符特征文件
執行下面命令,會生成 inttemp、pffmtable、shapetable和zwp.unicharset四個文件。
mftraining -F font_properties -U unicharset -O qq66.unicharset qq66.test.exp0.tr
(9)生成字符正常化特征文件
執行下面命令,會生成 normproto 文件。
cntraining qq66.test.exp0.tr
(10)文件重命名
重新命名inttemp、pffmtable、shapetable和normproto這四個文件的名字為[lang].xxx。
這里修改為qq66.inttemp、qq66.pffmtable、qq66.shapetable和qq66.normproto
(11)合並訓練文件
執行下面命令,會生成qq66.traineddata文件。
combine_tessdata qq66.
最后文件目錄
5,用新生成的qq66.traineddata字符集,重新識別身份證
6,可以同時選擇多個不同的樣本生成box文件
7,在原有訓練數據的基礎上,加入新的字符訓練信息
經研究找到實用合並方法(紅色部分為示例,實際應為你自己生成的文件名):
在新的訓練數據生成.box 和.tr文件后,
生成字符集 unicharset_extractor add.font.exp0.box new.font.exp0.box
合並訓練數據(.tr)
mftraining -F font_properties -U unicharset -O added.unicharset add.font.exp0.tr new.font.exp0.tr
聚合所有的tr文件:
cntraining add.font.exp0.tr new.font.exp0.tr
8,設置圖片分割模式
Page segmentation modes:
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.
例如:
tesseract test.png result -l chi_sim -psm 7 nobatch