• 「PaddleOCR」 模型应用优化流程


    PaddleOCR 算是OCR算法里面较好用的,支持的内容多,而且社区维护的好(手把手教你,生怕你学不会),因此在国内常采用。目前已经更新到 2.8版本了,功能更加丰富、强大;目前支持通用OCR、表格识别、图片信息提取以及文档场景信息提取,基本覆盖了常用的场景

    首先下载模型代码 https://github.com/PaddlePaddle/PaddleOCR
    需要视频课程的可以看 https://aistudio.baidu.com/education/group/info/25207

    参考资料:https://github.com/PaddlePaddle/PaddleOCR/blob/main/doc/doc_ch/models_list.md

    在这里插入图片描述
    在这里插入图片描述

    1、安装环境

    首先PaddleOCR处理模型训练需要环境,数据打标工具PPOCRLabel也需要配置,因此一并配置好 conda 环境 paddle_ocr

    创建conda环境 paddle_ocr,可以参考 doc/doc_ch/environment.md、installation.md 文件

    # 推荐环境:
    PaddlePaddle >= 2.1.2
    Python 3.7
    CUDA10.1 / CUDA10.2
    CUDNN 7.6
    
    # 常规创建 conda环境
    conda create -n paddle_ocr python=3.7		# python 版本可自定义*
    
    # 使用清华源加速下载
    conda create --name paddle_ocr python=3.8 --channel https://mirrors.tuna.tsinghua.edu.cn/anaconda/pkgs/free/
    
    # 激活paddle_ocr环境
    conda activate paddle_ocr
    
    # 安装paddle等库
    pip3 install --upgrade pip
    
    #如果您的机器安装的是CUDA9或CUDA10,请运行以下命令安装
    python3 -m pip install paddlepaddle-gpu==2.0.0 -i https://mirror.baidu.com/pypi/simple
    
    #如果您的机器是CPU,请运行以下命令安装
    python3 -m pip install paddlepaddle==2.0.0 -i https://mirror.baidu.com/pypi/simple
    
    更多的版本需求,请参照[安装文档](https://www.paddlepaddle.org.cn/install/quick)中的说明进行操作。
    
    
    # 安装标注软件 PPOCRLabel
    pip install PPOCRLabel
    

    2、数据标注

    最新版的PaddleOCR内部不再包含PPOCRLabel,可以参考 https://github.com/ViatorSun/PPOCRLabel

    将conda环境切换成 paddle_ocr,然后在终端输入 PPOCRLabel --lang ch 即可启动 PPOCRLabel 标注工具, --lang 设置界面语言(默认英文,仅支持中英文,中文ch、英文en),如下图所示

    在这里插入图片描述

    1. PPOCRLabel 支持预标注,选择 PaddleOCR -> 选择模型,可以选择待识别文字的语言,如中英文、英文、法语等;
    2. 左下角的自动标注可以帮助将图片中的文字用 PaddleOCR模型检测并标注下,预标注的效果一般比较差,但是可以节省拉框的时间,还是有一定作用的
    3. 标注过程中会有几个txt文件用于保存数据,Cache.cach 用于保存预标注数据,fileState.txt记录图片标注状态,Label.txt 为导出的标记结果,rec_gt.txt 和 crop_img 为导出的识别结果,
    # 修改 fileState.txt 文件,免去一张一张确认
    import os
    import os.path as osp
    
    shuffixes = [".jpg", ".jpeg", ".png"]
    file_path = "/media/sun/Data/Dataset/OCR_Data/ocr_data"
    
    if osp.exists(file_path):
        with open(osp.join(file_path,"fileState.txt"), "w", encoding="utf-8") as f:
            for file in os.listdir(file_path):
                if osp.splitext(file)[-1].lower() in shuffixes:
                    img_dir = osp.join(file_path, file)
                    f.write(img_dir + "\t1\n")
                    print(f"save {img_dir} \t1")
    

    对于预标注的内容,未必全部适合项目需求,因此可以通过正则化将预标注内容筛选,降低手动删除目标框的低效

    import re
    import json
    import os.path as osp
    
    Label_dir = "/media/sun/DataYZ/DataSet/led_Digital/Label.txt"
    
    label_lst = []
    if osp.exists(Label_dir):
        with open(Label_dir, "r", encoding="utf-8") as f:
            for line in f.readlines():
                print(line)
                save_data = []
                data_list = json.loads(line.split('\t')[-1].replace('\n', ''))
                for data in data_list:
                    if bool(re.match(r'^[0-9.]+$', data["transcription"])):				# 只保留数字和小数点 的识别结果
                        save_data.append(data)
    
                save_label = line.split('\t')[0] + '\t' + str(save_data) + '\n'
                label_lst.append(save_label)
    
    # 重写
    with open(Label_dir, "w", encoding="utf-8") as f:
        for data in label_lst:
            f.write(data)
    

    注意
    发现标注工具有一个隐藏小问题(谈不上bug),可能跟后续的识别有关
    当标注框的高与宽的比例大于 1.5则进行 90度旋转(默认顺时针旋转),如果想避免这种情况将红框两行代码注释掉就可以了
    在这里插入图片描述

    标注完所有的数据之后,需要划分数据集,可以采用PaddeOCR/PPOCRLabel/gen_ocr_train_val_test.py 脚本进行处理,–trainValTestRatio 设置三个数据集的比例,–datasetRootPath设置标注好的数据集路径,–detRootPath 生成的检测数据集路径,–recRootPath 生成识别数据集路径 即可。注意,标注文件中的框只能是四个点坐标,过多过少都会无法识别

    至此,数据处理完成


    3、模型训练

    PaddleOCR 识别分为两个过程,目标区域的检测 det 以及 对目标区域的内容识别 rec

    训练脚本如下,配置好 yaml 文件,即可直接训练,此处的 data/ 路径是博主自己创建的,避免与官方提供的 config/ 下的yaml 文件冲突,可将需要的 config/*.yaml 拷贝到 ./data 路径下

    import os
    
    # detect 模型检测
    command = "python3 tools/train.py -c data/det_r50_vd_db.yml"
    print(command)
    os.system(command)
    
    # rec 模型识别
    command = "python tools/train.py -c data/ch_PP-OCRv3_rec.yml"
    print(command)
    os.system(command)
    

    det.yaml 文件与 rec.yaml 几乎一致

    其中 rec.yml 的 save_model_dir 为模型训练保存路径;pretrained_model 为预训练模型权重;save_inference_dir 为模型导出时的输出路径;character_dict_path 为字符词典路径;其余的就是 Train & Eval 数据集的路径需要修改;
    在生成的 模型训练保存路径中,有 train.log 、config.yaml 、best_model 和其他中间epoch 权重

    在这里插入图片描述


    导出推理模型

    训练过程中保存的模型权重

    path.pdopt:优化器状态
    path.states:训练中间信息
    path.pdparams:保存的模型的参数

    在这里插入图片描述

    导出的推理模型格式为 inference.pdmodel、inference.pdiparams,其中 Global.save_inference_dir 不需要重复设置 *yaml 文件中已经包含了,如果 *.yaml 中已经设置过了,模型转换就无需再赋值,当然赋值了会以重新赋值的参数运行

    注意!
    此处有一点需要注意的就是 Global.pretrained_model 必须从新赋值,因为 *yaml 文件中的 pretrained_model 为训练时的预训练权重,此处为待导出的模型权重路径;
    还有就是权重路径是 ./runs/20240703/det_r50_vd/best_model/model.pdopt/pdparams 省去后缀的路径,而不是文件夹的路径,因此必须填写到权重名

    import os
    
    # det
    os.system(f"python   tools/export_model.py    "
              f"-c data/det_r50_vd_db.yml   "
              f"-o Global.pretrained_model=./runs/20240703/det_r50_vd/best_model/model  "     	# 待转化权重
              f"Global.load_static_weights=False "
              # f"Global.save_inference_dir=./inference/20240704/db_r50/ "
              )
    
    
    # ocr
    os.system(f"python3 tools/export_model.py "
              f"-c data/ch_PP-OCRv3_rec.yml   "
              f"-o Global.pretrained_model=./runs/20240703/rec_ppocr/best_model/model ")     	# 待转化权重
              # f"Global.save_inference_dir=./inference/20240704/rec_ppocr/ "
              )
    

    模型推理

    最后是模型推理,此处可以使用如下脚本预测,生成的结果在 inference_results 路径下

    import os
    import os.path as osp
    
    
    if __name__ == '__main__':
        img_path = "./test"
        det_model_dir = "./inference/20240710/det_infer"
        rec_model_dir = "./inference/20240710/rec_infer"
    
        for i, file in enumerate(os.listdir(img_path)):
            img = osp.join(img_path, file)
    
            command = f"python3 tools/infer/predict_system.py --image_dir={img} --det_model_dir={det_model_dir} --rec_model_dir={rec_model_dir} --use_angle_cls=false"
    		
            print(command)
            os.system(command)
    

    在这里插入图片描述

  • 相关阅读:
    Windows下jupyter notebook配置默认路径及配置默认启动chrome浏览器
    在建筑设计方面3DMax和Maya哪一个更好?
    DPDK系列之三十一DPDK的并行机制简介
    性能测试 - 理论
    第三方软件测试报告原来有这么多用途?还不知道的你out了!
    平板用的触控笔什么牌子好?开学值得推荐的ipad手写笔
    Mysql详解
    【iOS】—— URL Scheme
    swift-基础
    TensorFlow 2.9的零零碎碎(一)
  • 原文地址:https://blog.csdn.net/ViatorSun/article/details/140175470