简介:本文详细介绍如何使用PaddleOCR框架,从数据标注、数据集制作、模型训练到实际应用,完成一个针对行驶证识别的OCR模型训练全流程。内容涵盖工具准备、环境配置、关键步骤操作及优化建议,适合开发者及企业用户参考。
OCR(光学字符识别)技术在证件识别、文档处理等领域应用广泛。PaddleOCR作为开源的OCR工具库,支持中英文、多语言识别,且提供预训练模型和训练接口。本文以行驶证识别为例,详细介绍如何基于PaddleOCR训练一个自定义的OCR模型,覆盖数据标注、数据集制作、模型训练及部署应用的全流程。
通过pip安装PaddleOCR及依赖:
pip install paddlepaddle-gpu==2.2.2.post112 -f https://www.paddlepaddle.org.cn/whl/linux/mkl/avx/stable.html # GPU版本pip install paddleocr
或使用CPU版本:
pip install paddlepaddle==2.2.2
行驶证样本需覆盖不同场景(如光照、角度、分辨率),建议收集200-500张真实图片。数据来源需合法合规,避免隐私泄露。
git clone https://github.com/PaddlePaddle/PaddleOCR.gitcd PaddleOCR/PPOCRLabelpip install -r requirements.txtpython PPOCRLabel.py --image_dir ./imgs/
PaddleOCR支持两种数据集格式:
训练集目录/├── img_1.jpg├── img_1.txt # 标注文件,内容为 "x1,y1,x2,y2,x3,y3,x4,y4,文本内容"└── ...
使用
{"version": "4.5.6","shapes": [{"label": "文本内容","points": [[x1,y1], [x2,y2], [x3,y3], [x4,y4]],"shape_type": "rectangle"}]}
tools/convert_dataset.py转换为ICDAR格式。按7
1比例划分训练集、验证集、测试集:
import osimport shutildef split_dataset(img_dir, ratio=[0.7, 0.2, 0.1]):imgs = os.listdir(img_dir)train_size = int(len(imgs) * ratio[0])val_size = int(len(imgs) * ratio[1])train_imgs = imgs[:train_size]val_imgs = imgs[train_size:train_size+val_size]test_imgs = imgs[train_size+val_size:]# 创建目录并移动文件for split, split_imgs in zip(['train', 'val', 'test'], [train_imgs, val_imgs, test_imgs]):os.makedirs(f'./dataset/{split}', exist_ok=True)for img in split_imgs:shutil.copy(f'{img_dir}/{img}', f'./dataset/{split}/')
修改configs/rec/rec_icdar15_train.yml,关键参数:
Global:use_gpu: Trueepoch_num: 100save_model_dir: ./output/rec_ppocr_v3/eval_batch_step: [0, 2000]Optimizer:name: Adambeta1: 0.9beta2: 0.999lr:name: Cosinelearning_rate: 0.001Architecture:model_type: recalgorithm: CRNNTransform:Backbone:name: MobileNetV3scale: 0.5Head:name: CTCHeadhead_num: 2
python tools/train.py -c configs/rec/rec_icdar15_train.yml \-o Global.pretrained_model=./pretrain_models/ch_ppocr_mobile_v2.0_rec_train/best_accuracy
-c:指定配置文件。-o:覆盖配置参数(如加载预训练模型)。Cosine或Linear衰减策略。RandomRotate、RandomDistort等增强操作。将训练好的模型导出为推理模型:
python tools/export_model.py -c configs/rec/rec_icdar15_train.yml \-o Global.pretrained_model=./output/rec_ppocr_v3/best_accuracy \Global.save_inference_dir=./inference/
from paddleocr import PaddleOCRocr = PaddleOCR(rec_model_dir='./inference/rec_ppocr_v3/',rec_char_dict_path='./ppocr/utils/dict/chinese_cht_dict.txt',use_angle_cls=True)result = ocr.ocr('driving_license.jpg', cls=True)for line in result:print(line)
解析识别结果,提取关键字段:
def parse_driving_license(result):fields = {'plate_number': None,'owner': None,'valid_date': None}for line in result:text = line[1][0]if '号牌号码' in text:fields['plate_number'] = text.split(':')[-1]elif '所有人' in text:fields['owner'] = text.split(':')[-1]elif '有效期至' in text:fields['valid_date'] = text.split('至')[-1]return fields
通过本文的指导,开发者可以快速上手PaddleOCR,训练出高精度的行驶证识别模型,并应用于实际业务场景。