安卓端部署PPOCR的ncnn模型——模型部署

综述

最近在研究ocr模型(包括文本检测和文本识别)在安卓端的部署,由于工作中用到的算法是基于百度研发的PPOCR算法,最终需要在安卓端落地应用,部署框架使用的是ncnn框架,中间涉及模型转换和部署的问题,所以特意在此做一个记录,本文主要讲一下模型部署的问题,关于模型转换的讲解详见我的另一篇文章:安卓端部署PPOCR的ncnn模型——模型转换

说到模型部署,顾名思义,就是通过部署框架编写相关代码使模型能够在终端应用里推理和调用,本文主要讲的是安卓端的OCR模型部署。

以下是ncnn的官方介绍:

  • ncnn 是一个为手机端极致优化的高性能神经网络前向计算框架。ncnn 从设计之初深刻考虑手机端的部署和使用。无第三方依赖,跨平台,手机端 cpu 的速度快于目前所有已知的开源框架。基于 ncnn,开发者能够将深度学习算法轻松移植到手机端高效执行,开发出人工智能 APP,将 AI 带到你的指尖。ncnn 目前已在腾讯多款应用中使用,如 QQ,Qzone,微信,天天P图等。

在部署以前需要下载和编译相关库并将其放入安卓工程中,关于ncnn部署库的编译与使用可以详见我的另一篇文章:手写数字识别从训练到部署全流程详解——模型在Android端的部署

下面开始正题

文本检测模型

模型输入预处理

  • 图像尺寸变换:宽和高均为32的倍数
为何这样处理:
  • 以检测中的resnet骨干网络为例,图像输入网络之后,需要经过5次2倍降采样,共32倍,因此建议输入的图像尺寸为32的倍数
关键代码:
public static Bitmap resizeWithStep(Bitmap bitmap, int maxLength, int step) {
    int width = bitmap.getWidth();
    int height = bitmap.getHeight();
    int maxWH = Math.max(width, height);
    float ratio = 1;
    int newWidth = width;
    int newHeight = height;
    if (maxWH > maxLength) {
        ratio = maxLength * 1.0f / maxWH;
        newWidth = (int) Math.floor(ratio * width);
        newHeight = (int) Math.floor(ratio * height);
    }
    newWidth = newWidth - newWidth % step;
    if (newWidth == 0) {
        newWidth = step;
    }
    newHeight = newHeight - newHeight % step;
    if (newHeight == 0) {
        newHeight = step;
    }
    return Bitmap.createScaledBitmap(bitmap, newWidth, newHeight, true);
}

以上变换方式是目前最通用的方式,虽然比较简单,但有个缺点就是可能会稍微改变原图比例,使原图内容产生一定形变,尤其在原图本身尺寸比较小的情况,从而影响文本区域检测精度,目前我还研究了一种通过边缘扩展的方式以保持原图的比例。

[En]

The above transformation method is the most common way at present, although it is relatively simple, but there is a disadvantage that it may slightly change the proportion of the original image and make the content of the original image deform to a certain extent, especially when the size of the original image itself is relatively small, thus affecting the accuracy of text region detection. At present, I have also studied a way to maintain the proportion of the original image through edge expansion.

关键代码如下:

public static ResizeInfoEntity resizeWithBorder(Bitmap currentBitmap, int maxLength, int step){
    ResizeInfoEntity resizeInfoEntity = new ResizeInfoEntity();
    resizeInfoEntity.setOriginBitmap(currentBitmap);
    int width = currentBitmap.getWidth();
    int height = currentBitmap.getHeight();
    int newWidth = width;
    int newHeight = height;
    float newWidthRatio = 1.0f;
    float newHeightRatio = 1.0f;
    float ratio = 1.0f;

    if (newWidth % step != 0) {
        newWidth = (newWidth / step + 1) * step;
        newWidth = Math.max(newWidth, step);
    }
    if(newWidth>maxLength){
        newWidthRatio = maxLength * 1.0f / newWidth;
    }
    if (newHeight % step != 0) {
        newHeight = (newHeight / step + 1) * step;
        newHeight = Math.max(newHeight, step);
    }
    if(newHeight>maxLength){
        newHeightRatio = maxLength * 1.0f / newHeight;
    }
    Bitmap targetBitmap = null;
    Canvas tgCanvas = null;
    int newWidthTemp = newWidth;
    int newHeightTemp = newHeight;
    ratio = Math.min(newWidthRatio, newHeightRatio);
    if(ratio<1.0f){

        newWidth = (int) Math.floor(ratio * newWidth);
        newHeight = (int) Math.floor(ratio * newHeight);
        if (newWidth % step != 0) {
            newWidth = (newWidth / step) * step;
            newWidth = Math.max(newWidth, step);
        }
        newWidthRatio = newWidth * 1.0f / newWidthTemp;
        if (newHeight % step != 0) {
            newHeight = (newHeight / step) * step;
            newHeight = Math.max(newHeight, step);
        }
        newHeightRatio = newHeight * 1.0f / newHeightTemp;
        ratio = Math.min(newWidthRatio, newHeightRatio);
        targetBitmap = Bitmap.createBitmap(newWidth, newHeight, Bitmap.Config.ARGB_8888);
        tgCanvas = new Canvas(targetBitmap);
        tgCanvas.drawARGB(255, 255, 255, 255);
        tgCanvas.drawBitmap(Bitmap.createScaledBitmap(currentBitmap, (int) Math.floor(currentBitmap.getWidth()*ratio), (int) Math.floor(currentBitmap.getHeight()*ratio), true), 0, 0, null);
        resizeInfoEntity.setTargetBitmap(targetBitmap);
    }else{
        targetBitmap = Bitmap.createBitmap(newWidth, newHeight, Bitmap.Config.ARGB_8888);
        tgCanvas = new Canvas(targetBitmap);
        tgCanvas.drawARGB(255, 255, 255, 255);
        tgCanvas.drawBitmap(currentBitmap, 0, 0, null);
        resizeInfoEntity.setTargetBitmap(targetBitmap);
    }
    resizeInfoEntity.setRatio(ratio);
    return resizeInfoEntity;
}

模型推理:

  • 输入节点:x
  • 运行推理
  • 输出节点:save_infer_model/scale_0.tmp_1
  • 关键代码
    ncnn::Mat input = ncnn::Mat::from_android_bitmap(env, inputBitmap, ncnn::Mat::PIXEL_BGR2RGB);
    ncnn::Extractor extractor = net->create_extractor();
    ncnn::Mat out;
    const float meanValues[3] = {127.5f, 127.5f, 127.5f};
    const float normValues[3] = {1.0f / 127.5f, 1.0f / 127.5f, 1.0f / 127.5f};
    input.substract_mean_normalize(meanValues, normValues);
    extractor.input("x", input);
    extractor.extract("save_infer_model/scale_0.tmp_1", out);

模型输出后处理:单通道二维矩阵转为文本四边形区域顶点坐标值

  • 单通道二维矩阵转为单通道cv::Mat
  • 对转换的cv::Mat进行阈值为boxThresh的二值化处理
  • 通过cv::findContours方法寻找可能为文本框区域的轮廓
  • 获取文本框为四边形区域并通过boxScoreThresh过滤掉不符合要求的文本框
  • 根据unClipRatio对四边形文本框区域进行放大处理
  • 确定文本区域最小四边形顶点坐标
  • 关键代码
    cv::Mat pred_map = cv::Mat::zeros(pred_height, pred_width, CV_32FC1);
    memcpy(pred_map.data, pred, pred_size * sizeof(float));
    cv::Mat norfMapMat;
    norfMapMat = pred_map > boxThresh;
    cv::Mat cbuf_map;
    norfMapMat.convertTo(cbuf_map, CV_8UC1);
    cv::Mat mask_map;
    cv::Mat dilation_kernel = (cv::Mat_<uint8_t>(2,2) << 1, 1, 1, 1);
    cv::dilate(cbuf_map, mask_map, dilation_kernel);
    std::vector<TextBox> boxes = boxes_from_bitmap(pred_map, mask_map, boxScoreThresh, unClipRatio);

结果信息封装:

  • 预处理耗时:原图数据->推理输入数据
  • 推理耗时:推理输入->推理输出
  • 后处理耗时:推理输出->结果输出
  • 全流程耗时:原图数据->结果数据
  • 后处理结果数据:耗时、文本区域坐标数组、文本区域检测分数

字符识别模型

模型输入预处理:

  • 词条区域图像倾斜校正(透视变换)
  • 词条区域图像尺寸变换:宽为16的倍数、高为32
为何这样处理:
  • 缩小识别区域,使之更为集中,规范输入图像,达到算法识别输入要求
    [En]

    reduce the recognition area to make it more centralized, standardize the input image, and meet the input requirements of the algorithm.*

  • 字符识别网络对文本高度的要求为32,宽为16的倍数主要是为了充分发挥推理过程中的cpu性能
关键代码
    std::vector<cv::Mat> partImages;    for (int i = 0; i < textBoxes.size(); ++i) {        cv::Mat partImg = getRotateCropImage(src, textBoxes[i].boxPoint);        partImages.emplace_back(partImg);    }    return partImages;    float scale = (float) 32 / (float) src.rows;    float dstWidth = int((float) src.cols * scale / (float) 16 + 0.5f) * 16;    cv::Mat srcResize;    cv::resize(src, srcResize, cv::Size(dstWidth, 32));

注:在精度测试中,宽为16的倍数的词条图像尺寸调整后会造成识别精度会下降,虽然影响性能发挥,但还是应优先保证精度,性能问题主要出在最后Softmax_0网络层耗时不稳定所致,正等ncnn作者来解决。故词条宽度的调整应根据原宽高比例来,关键代码如下

    float scale = (float)src.cols / (float)src.rows;
    int dstWidth = (int)((float)32 * scale);
    cv::Mat srcResize;
    cv::resize(src, srcResize, cv::Size(dstWidth, 32));

模型推理:

  • 输入节点:x
  • 运行推理
  • 输出节点:save_infer_model/scale_0.tmp_1
  • 关键代码
    ncnn::Mat input = ncnn::Mat::from_pixels(srcResize.data, ncnn::Mat::PIXEL_BGR2RGB, srcResize.cols, srcResize.rows);
    const float meanValues[3] = {127.5f, 127.5f, 127.5f};
    const float normValues[3] = {1.0f / 127.5f, 1.0f / 127.5f, 1.0f / 127.5f};
    input.substract_mean_normalize(meanValues, normValues);
    ncnn::Mat out;
    ncnn::Extractor extractor = net->create_extractor();
    extractor.input("x", input);
    extractor.extract("save_infer_model/scale_0.tmp_1", out);

模型输出后处理:

  • 字典解析(PPOCR字典文件地址:中文字典
  • 字符预测概率排序/对应/拼接
  • 关键代码

    char *buffer = readKeysFromAssets(mgr);
    if (buffer != nullptr) {
        std::istringstream inStr(buffer);
        std::string line;
        int size = 0;
        while (getline(inStr, line)) {
            keys.emplace_back(line);
            size++;
        }
        free(buffer);
        LOGI("keys size(%d)", size);
    }

    int keySize = keys.size();
    std::string strRes;
    std::vector<float> scores;
    int lastIndex = 0;
    int maxIndex;
    float maxValue;
    for (int i = 0; i < h; i++) {
        maxIndex = 0;
        maxValue = -1000.f;
        for (int j = 0; j < w; j++) {
            if (outputData[i * w + j] > maxValue) {
                maxValue = outputData[i * w + j];
                maxIndex = j;
            }
        }
        if (maxIndex > 0 && maxIndex < keySize && (!(i > 0 && maxIndex == lastIndex))) {
            scores.emplace_back(maxValue);
            strRes.append(keys[maxIndex - 1]);
        }
        lastIndex = maxIndex;
    }
    return {strRes, scores};

结果信息封装:

  • 预处理耗时:原图数据->推理输入数据
  • 推理耗时:推理输入->推理输出
  • 后处理耗时:推理输出->结果输出
  • 全流程耗时:原图数据->结果数据
  • 后处理结果数据:耗时、文本区域字符串、文本区域字符串分数

全流程示例图演示(以身份证号码识别为例)

安卓端部署PPOCR的ncnn模型——模型部署

; 模型测试

性能测试

benchmark:
  • 框架自带benchmark代码修改与测试,固定输入尺寸,推理运行耗时
  • benchmark原代码详见:benchncnn.cpp可自行修改
  • 关键代码
    ...

    fprintf(stderr, "loop_count = %d\n", g_loop_count);
    fprintf(stderr, "num_threads = %d\n", num_threads);
    fprintf(stderr, "powersave = %d\n", ncnn::get_cpu_powersave());
    fprintf(stderr, "gpu_device = %d\n", gpu_device);
    fprintf(stderr, "cooling_down = %d\n", (int)g_enable_cooling_down);

    benchmark("det_model", ncnn::Mat(320, 320, 3), opt);
    benchmark("det_model", ncnn::Mat(480, 480, 3), opt);
    benchmark("det_model", ncnn::Mat(640, 640, 3), opt);

    benchmark("rec_model", ncnn::Mat(272, 32, 3), opt);
    benchmark("rec_model", ncnn::Mat(592, 32, 3), opt);
    benchmark("rec_model", ncnn::Mat(816, 32, 3), opt);
app:
  • 可同时测试单流程(预处理/推理/后处理)与全流程(图像输入到结果输出)耗时
  • 关键代码参见模型部署代码

精度测试

测试素材选择:
  • 可尝试使用包含身份证、护照、机读码图像的图片文件/相机自拍的图片
评价标准选择:
  • 直观评判:
    在素材符合质量要求的前提下其内所有应检区域内容做到准确检测的概率(文本区域/文本区域内的具体字符)
    [En]

    On the premise that the material meets the quality requirements, the probability of accurate detection of all the contents in the inspection area (specific characters in the text area / text area)

  • 按阶段评判:
    (1)检测阶段:先按照检测框和标注框的IOU评估,IOU大于某个阈值判断为检测准确。这里检测框和标注框不同于一般的通用目标检测框,是采用多边形进行表示。检测准确率:正确的检测框个数在全部检测框的占比,主要是判断检测指标。检测召回率:正确的检测框个数在全部标注框的占比,主要是判断漏检的指标。
    (2)识别阶段: 字符识别准确率,即正确识别的文本行占标注的文本行数量的比例,只有整行文本识别对才算正确识别。
    (3)端到端统计: 端对端召回率:准确检测并正确识别文本行在全部标注文本行的占比; 端到端准确率:准确检测并正确识别文本行在 检测到的文本行数量 的占比; 准确检测的标准是检测框与标注框的IOU大于某个阈值,正确识别的的检测框中的文本与标注的文本相同。

模型部署相关问题

预/后处理方式对性能、精度的影响与选择:

  • 根据检测目标、检测场景灵活调整模型输入与可调参数
  • 全图检测:提高尺寸阈值、适当调低检测文本框分数阈值
  • 特定区域检测:截取特定区域图像数据作为输入、降低尺寸阈值、提升文本框分数阈值
    [En]

    specific region detection: intercept specific region image data as input, reduce the size threshold, and raise the text box score threshold*

  • 特定目标检测:设定敏感区域检测条件,保证敏感区域图像质量、字符识别图像尺寸还原、检测目标特征核对
    [En]

    specific target detection: set sensitive area detection conditions to ensure sensitive area image quality, character recognition image size reduction, detection target feature check*

字符识别模型性能测试表现异常:

  • 框架自带benchmark对输出节点定位不够合理、模型输入尺寸影响推理性能

参考资料

Original: https://blog.csdn.net/best2012power/article/details/124345918
Author: 彧侠
Title: 安卓端部署PPOCR的ncnn模型——模型部署

原创文章受到原创版权保护。转载请注明出处:https://www.johngo689.com/77944/

转载文章受原作者版权保护。转载请注明原作者出处!

(0)

大家都在看

亲爱的 Coder【最近整理,可免费获取】👉 最新必读书单  | 👏 面试题下载