2021AIWIN 手写体 OCR 识别竞赛总结(任务一)

本赛题共分成三个大阶段:

线上比赛(包含任务一和任务二) ———— 解决方案复审 ———— 终选答辩

赛程总览示意如下:

img

具体方案

===============================================================

通过在网上查阅资料,得知OCR比赛最常用的模型是CRNN+CTC。所以我最开始也是采用这个方案。

image-20220118133621906

上图是我找到的资料,有好多个版本。因为是第一次做OCR的项目,所以我优先选择有数据集的项目,这样可以快速的了解模型的输入输出。

所以我选择的第一个Attention_ocr.pytorch-master.zip,从名字上可以看出这个是加入注意力机制,感觉效果会好一些。

构建数据集


下图是Attention_ocr.pytorch-master.zip自带的数据集截图,从截图上可以看出,数据的格式:“图片路径+空格+标签”。我们也需要按照这样的格式构建数据集。

image-20220118134943952

新建makedata.py文件,插入下面的代码。

import os

import json

#官方给的数据集

image_path_amount = “./data/train/amount/images”

image_path_date = “./data/train/date/images”

#增强数据集

image_path_test=‘./data/gan_test_15000/images/0’

image_path_train=‘./data/gan_train_15500_0/images/0’

amount_list = os.listdir(image_path_amount)

amount_list = os.listdir(image_path_amount)

new_amount_list = []

for filename in amount_list:

new_amount_list.append(image_path_amount + “/” + filename)

date_list = os.listdir(image_path_date)

new_date_list = []

for filename in date_list:

new_date_list.append(image_path_date + “/” + filename)

new_test_list = []

for filename in amount_list:

new_test_list.append(image_path_amount + “/” + filename)

new_train_list = []

for filename in amount_list:

new_train_list.append(image_path_amount + “/” + filename)

image_path_amount和image_path_date是官方给定的数据集路径。

image_path_test和image_path_train是增强的数据集(在后面会讲如何做增强)

创建建立list,保存图片的路径。

amount_json = “./data/train/amount/gt.json”

date_json = “./data/train/date/gt.json”

train_json = “train_data.json”

test_json = “test_data.json”

with open(amount_json, “r”, encoding=‘utf-8’) as f:

load_dict_amount = json.load(f)

with open(date_json, “r”, encoding=‘utf-8’) as f:

load_dict_date = json.load(f)

with open(train_json, “r”, encoding=‘utf-8’) as f:

load_dict_train = json.load(f)

with open(test_json, “r”, encoding=‘utf-8’) as f:

load_dict_test = json.load(f)

四个json文件对应上面的四个list,json文件存储的是图片的名字和图片的标签,把json解析出来存到字典中。

#聚合list

all_list = new_amount_list + new_date_list+new_test_list+new_train_list

from sklearn.model_selection import train_test_split

#切分训练集合和验证集

train_list, test_list = train_test_split(all_list, test_size=0.15, random_state=42)

#聚合字典

all_dic = {}

all_dic.update(load_dict_amount)

all_dic.update(load_dict_date)

all_dic.update(load_dict_train)

all_dic.update(load_dict_test)

with open(‘train.txt’, ‘w’) as f:

for line in train_list:

f.write(line + " " + all_dic[line.split(‘/’)[-1]]+“\n”)

with open(‘val.txt’, ‘w’) as f:

for line in test_list:

f.write(line + " " + all_dic[line.split(‘/’)[-1]]+“\n”)

将四个list聚合为一个list。

使用train_test_split切分训练集和验证集。

聚合字典。

然后分别遍历trainlist和testlist,将其写入train.txt和val.txt。

到这里数据集就制作完成了。得到train.txt和val.txt

image-20220118145805987

查看train.txt

image-20220118145909198

数据集和自带的数据集格式一样了,然后我们就可以开始训练了。

获取class

==================================================================

新建getclass.py文件夹,加入以下代码:

import json

amount_json = “./data/train/amount/gt.json”

date_json = “./data/train/date/gt.json”

with open(amount_json, “r”, encoding=‘utf-8’) as f:

load_dict_amount = json.load(f)

with open(date_json, “r”, encoding=‘utf-8’) as f:

load_dict_date = json.load(f)

all_dic = {}

all_dic.update(load_dict_amount)

all_dic.update(load_dict_date)

list_key=[]

for keyline in all_dic.values():

for key in keyline:

if key not in list_key:

list_key.append(key)

with open(‘data/char_std_5990.txt’, ‘w’) as f:

for line in list_key:

f.write(line+“\n”)

执行完就可以得到存储class的txt文件。打开char_std_5990.txt,看到有21个类。

image-20220118152118479

改进模型

===============================================================

crnn的卷积部分类似VGG,我对模型的改进主要有一下几个方面:

1、加入激活函数Swish。

2、加入BatchNorm。

3、加入SE注意力机制。

4、适当加深模型。

代码如下:

self.cnn = nn.Sequential(

nn.Conv2d(nc, 64, 3, 1, 1), Swish(), nn.BatchNorm2d(64),

nn.MaxPool2d(2, 2), # 64x16x50

nn.Conv2d(64, 128, 3, 1, 1), Swish(), nn.BatchNorm2d(128),

nn.MaxPool2d(2, 2), # 128x8x25

nn.Conv2d(128, 256, 3, 1, 1), nn.BatchNorm2d(256), Swish(), # 256x8x25

nn.Conv2d(256, 256, 3, 1, 1), nn.BatchNorm2d(256), Swish(), # 256x8x25

SELayer(256, 16),

nn.MaxPool2d((2, 2), (2, 1), (0, 1)), # 256x4x25

nn.Conv2d(256, 512, 3, 1, 1), nn.BatchNorm2d(512), Swish(), # 512x4x25

nn.Conv2d(512, 512, 1), nn.BatchNorm2d(512), Swish(),

nn.Conv2d(512, 512, 3, 1, 1), nn.BatchNorm2d(512), Swish(), # 512x4x25

SELayer(512, 16),

nn.MaxPool2d((2, 2), (2, 1), (0, 1)), # 512x2x25

nn.Conv2d(512, 512, 2, 1, 0), nn.BatchNorm2d(512), Swish()) # 512x1x25

SE和Swish

class SELayer(nn.Module):

def init(self, channel, reduction=16):

super(SELayer, self).init()

self.avg_pool = nn.AdaptiveAvgPool2d(1)

self.fc = nn.Sequential(

nn.Linear(channel, channel // reduction, bias=True),

nn.LeakyReLU(inplace=True),

nn.Linear(channel // reduction, channel, bias=True),

nn.Sigmoid()

)

def forward(self, x):

b, c, _, _ = x.size()

y = self.avg_pool(x).view(b, c)

y = self.fc(y).view(b, c, 1, 1)

return x * y.expand_as(x)

class Swish(nn.Module):

def forward(self, x):

return x * torch.sigmoid(x)

训练


打开train.py ,在训练之前,我们还要调节一下参数。

parser = argparse.ArgumentParser()

parser.add_argument(‘–trainlist’, default=‘train.txt’)

parser.add_argument(‘–vallist’, default=‘val.txt’)

parser.add_argument(‘–workers’, type=int, help=‘number of data loading workers’, default=0)

parser.add_argument(‘–batchSize’, type=int, default=4, help=‘input batch size’)

parser.add_argument(‘–imgH’, type=int, default=32, help=‘the height of the input image to network’)

parser.add_argument(‘–imgW’, type=int, default=512, help=‘the width of the input image to network’)

parser.add_argument(‘–nh’, type=int, default=512, help=‘size of the lstm hidden state’)

parser.add_argument(‘–niter’, type=int, default=300, help=‘number of epochs to train for’)

parser.add_argument(‘–lr’, type=float, default=0.00005, help=‘learning rate for Critic, default=0.00005’)

parser.add_argument(‘–beta1’, type=float, default=0.5, help=‘beta1 for adam. default=0.5’)

parser.add_argument(‘–cuda’, action=‘store_true’, help=‘enables cuda’, default=True)

parser.add_argument(‘–ngpu’, type=int, default=1, help=‘number of GPUs to use’)

parser.add_argument(‘–encoder’, type=str, default=‘’, help=“path to encoder (to continue training)”)

parser.add_argument(‘–decoder’, type=str, default=‘’, help=‘path to decoder (to continue training)’)

parser.add_argument(‘–experiment’, default=‘./expr/attentioncnn’, help=‘Where to store samples and models’)

parser.add_argument(‘–displayInterval’, type=int, default=100, help=‘Interval to be displayed’)

parser.add_argument(‘–valInterval’, type=int, default=1, help=‘Interval to be displayed’)

parser.add_argument(‘–saveInterval’, type=int, default=1, help=‘Interval to be displayed’)

parser.add_argument(‘–adam’, default=True, action=‘store_true’, help=‘Whether to use adam (default is rmsprop)’)

parser.add_argument(‘–adadelta’, action=‘store_true’, help=‘Whether to use adadelta (default is rmsprop)’)

parser.add_argument(‘–keep_ratio’,default=True, action=‘store_true’, help=‘whether to keep ratio for image resize’)

parser.add_argument(‘–random_sample’, default=True, action=‘store_true’, help=‘whether to sample the dataset with random sampler’)

parser.add_argument(‘–teaching_forcing_prob’, type=float, default=0.5, help=‘where to use teach forcing’)

parser.add_argument(‘–max_width’, type=int, default=129, help=‘the width of the featuremap out from cnn’)

parser.add_argument(“–output_file”, default=‘deep_model.log’, type=str, required=False)

opt = parser.parse_args()

trainlist:训练集,默认是train.txt。

vallist:验证集路径,默认是val.txt。

batchSize:批大小,根据显存大小设置。

imgH:图片的高度,crnn模型默认为32,这里不需要修改。

imgW:图片宽度,我在这里设置为512。

keep_ratio:设置为True,设置为True后,程序会保持图片的比率,然后在一个batch内统一尺寸,这样训练的模型精度更高。

lr:学习率,设置为0.00005,这里要注意,不要太大,否则不收敛。

其他的参数就不一一介绍了,大家可以自行尝试。

运行结果:

image-20220118161714707

训练完成后,可以在expr文件夹下面找到模型。

image-20220118161851392

推理


在推理之前,我们还需要确认最长的字符串,新建getmax.py,添加如下代码:

import os

import json

image_path_amount = “./data/train/amount/images”

image_path_date = “./data/train/date/images”

amount_list = os.listdir(image_path_amount)

new_amount_list = []

for filename in amount_list:

new_amount_list.append(image_path_amount + “/” + filename)

date_list = os.listdir(image_path_date)

new_date_list = []

for filename in date_list:

new_date_list.append(image_path_date + “/” + filename)

amount_json = “./data/train/amount/gt.json”

date_json = “./data/train/date/gt.json”

with open(amount_json, “r”, encoding=‘utf-8’) as f:

load_dict_amount = json.load(f)

with open(date_json, “r”, encoding=‘utf-8’) as f:

load_dict_date = json.load(f)

all_list = new_amount_list + new_date_list

from sklearn.model_selection import train_test_split

all_dic = {}

all_dic.update(load_dict_amount)

all_dic.update(load_dict_date)

maxLen = 0

for i in all_dic.values():

if (len(i) > maxLen):

maxLen = len(i)

print(maxLen)

运行结果:28

将test.py中的max_length设置为28。

修改模型的路径,包括encoder_path和decoder_path。

encoder_path = ‘./expr/attentioncnn/encoder_22.pth’

decoder_path = ‘./expr/attentioncnn/decoder_22.pth’

修改测试集的路径:

for path in tqdm(glob.glob(‘./data/测试集/date/images/*.jpg’)):

text, prob = test(path)

if prob<0.8:

count+=1

result_dict[os.path.basename(path)] = {

‘result’: text,

‘confidence’: prob

}

for path in tqdm(glob.glob(‘./data/测试集/amount/images/*.jpg’)):

text, prob = test(path)

if prob<0.8:

count+=1

result_dict[os.path.basename(path)] = {

‘result’: text,

‘confidence’: prob

}

数据增强

===============================================================

前面提到了数据增强,增强用的百度的StyleText。下载地址:

PaddleOCR: PaddleOCR dome (gitee.com)

一、工具简介


3

1

Style-Text数据合成工具是基于百度和华科合作研发的文本编辑算法《Editing Text in the Wild》https://arxiv.org/abs/1908.03047

不同于常用的基于GAN的数据合成工具,Style-Text主要框架包括:1.文本前景风格迁移模块 2.背景抽取模块 3.融合模块。经过这样三步,就可以迅速实现图像文本风格迁移。下图是一些该数据合成工具效果图。

2

二、环境配置


  1. 安装PaddleOCR。

  2. 进入StyleText目录,下载模型,并解压:

cd StyleText

wget https://paddleocr.bj.bcebos.com/dygraph_v2.0/style_text/style_text_models.zip

unzip style_text_models.zip

如果您将模型保存再其他位置,请在configs/config.yml中修改模型文件的地址,修改时需要同时修改这三个配置:

bg_generator:

pretrain: style_text_models/bg_generator

text_generator:

pretrain: style_text_models/text_generator

fusion_generator:

pretrain: style_text_models/fusion_generator

三、快速上手


合成单张图


输入一张风格图和一段文字语料,运行tools/synth_image,合成单张图片,结果图像保存在当前目录下:

python3 tools/synth_image.py -c configs/config.yml --style_image examples/style_images/2.jpg --text_corpus PaddleOCR --language en

  • 注1:语言选项和语料相对应,目前支持英文(en)、简体中文(ch)和韩语(ko)。

  • 注2:Style-Text生成的数据主要应用于OCR识别场景。基于当前PaddleOCR识别模型的设计,我们主要支持高度在32左右的风格图像。

如果输入图像尺寸相差过多,效果可能不佳。

  • 注3:可以通过修改配置文件configs/config.yml中的use_gpu(true或者false)参数来决定是否使用GPU进行预测。

例如,输入如下图片和语料"PaddleOCR":

img

  • 5
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值