下载的paddleocr的2.3版本。地址是paddleocr
检测模块用的是
det模块跑的慢,所以训练了一下rec模块。
默认的字典在ppocr_keys_v1.txt文件里面,6000多个符号。有些字识别的不是很好。从中挑选了60个字符,以同样的格式保存了一个txt文件(UTF-8格式)。在配置文件中把字典换为保存的txt文件名。
这里为了方便生成训练图片只挑选了60个字。只在这里改字典好像在识别时是不起作用的,还是会用ppocr_keys_v1.txt文件识别,需要在paddleocr.py文件中做修改如下(或许有其它修改方法):
把
for action in parser._actions:
if action.dest in ['rec_char_dict_path', 'table_char_dict_path']:
action.default = None
修改为:
for action in parser._actions:
if action.dest in ['table_char_dict_path']:
action.default = None
训练的步骤如下:
1.生成了包含文字的图片和标注文件(dec的标注文件。其中约750幅图片,这里用matlab生成,每幅图片包含20个字,从60个字的字典里面随机选取,字体5种,每种字体重复这20个字一次,但是顺序随机,字体大小没变化,背景基本没变,字体颜色固定),图片本身比字体大。
2.用paddleorc的det模块进行切割把切割后的图片作为rec模块训练用的图片。切割后的文件须检查一下,可能带标点符号的图片会被切割成两幅图,和标注文件对不上。
3.测试时用同样的方式生成了750个包含文字的图片,把paddleocr的训练模型转为推理模型,进行识别,统计了一下,准确率还是挺高的,约99.8%。估计主要是字体大小、种类、和颜色等没怎么变化影响也较大的缘故。
3.下面是一个简单的训练图片例子:
下面附一个matlab生成图片和相应的rec标注文件的小程序。需要说明的是,txt文件需utf-8格式,字典字符个数这里是20的整数倍,好多字体插入到图片的时候不支持一些符号,会出现警告的提示,图片中文字的相应位置为空。下面的几种字体大多数字符都支持。图片插入文字速度不太快。
% generate image and label file for paddle ocr rec train with 20 word a
% line with a dict contains 60 words.
clear all;
close all;
lastwarn('');
fileName='part60WordDict.txt';
textFileId=fopen(fileName,'r','n','UTF-8');
outFile='outPart60DictLabel20.txt';
outLabelId=fopen(outFile,'w','n','UTF-8');
outImagePath='./selfPart60DictRec20/images/'; %folder for out image
if exist(outImagePath,'dir')==0
mkdir(outImagePath);
end
ziTi={'STKaiti','STFangsong','STSong','STXihei','STZhongsong'}; % almost support font
ziNum=size(ziTi,2);
wordNum=60;
oneLineWord=20; % word number per line, wordNum should be N*oneLineWord
m1=60; % image height
m2=660; % image width
num=1;
sep=sprintf('%s\t','');
wordAll=[];
while(~feof(textFileId))
for k=1:oneLineWord
if(~feof(textFileId))
temp=textscan(textFileId,'%s',1,'Delimiter','\n');
textDisp=temp{1}{1};
if(size(textDisp)~=1)
t=1;
end
wordAll=[wordAll textDisp];
end
end
end
for k=1:70
wordOrder=randperm(wordNum,wordNum);
wordTemp=wordAll(wordOrder);
for s=1:oneLineWord:wordNum
wordOutTemp=wordTemp(s:s+oneLineWord-1);
for t=1:ziNum
randWord=randperm(oneLineWord,oneLineWord);
wordOut=wordOutTemp(randWord);
randColor=randperm(55,1);
A = ones(m1,m2,3,'uint8')*(200+randColor); %generate image with viarable background
imFileName=['im' num2str(num) '.jpg'];
A=insertText(A,[m2/2,m1/2],wordOut,'TextColor','black','FontSize',32,'Font',ziTi{t},'BoxColor' ,'white','AnchorPoint' ,'Center'); %
textOut=['train_data/selfPart60DictRec20' imFileName sep wordOut];
fprintf(outLabelId,'%s\n',textOut);
imwrite(A,[outImagePath imFileName]);
num=num+1;
end
end
end
fclose(textFileId);
fclose(outLabelId);