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

安卓端部署PPOCR的ncnn模型——模型部署,第1张

综述

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

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

部署框架:ncnn

以下是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);
}

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

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;
	//构造32倍数尺寸背景图
	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){
		//构造32倍数尺寸缩放背景图
		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 为何这样处理: 缩小识别区域,使之更为集中,规范输入图像,达到算法识别输入要求字符识别网络对文本高度的要求为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};
结果信息封装: 预处理耗时:原图数据->推理输入数据推理耗时:推理输入->推理输出后处理耗时:推理输出->结果输出全流程耗时:原图数据->结果数据后处理结果数据:耗时、文本区域字符串、文本区域字符串分数 全流程示例图演示(以身份z号码识别为例)

模型测试 性能测试 benchmark: 框架自带benchmark代码修改与测试,固定输入尺寸,推理运行耗时benchmark原代码详见:benchncnn.cpp可自行修改关键代码
    ...
    // input params
    fprintf(stderr, "loop_count = %d\n", g_loop_count);//100
    fprintf(stderr, "num_threads = %d\n", num_threads);//4
    fprintf(stderr, "powersave = %d\n", ncnn::get_cpu_powersave());//0
    fprintf(stderr, "gpu_device = %d\n", gpu_device);//-1
    fprintf(stderr, "cooling_down = %d\n", (int)g_enable_cooling_down);//1
    // run det benchmark
    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);
    // run rec benchmark
    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: 可同时测试单流程(预处理/推理/后处理)与全流程(图像输入到结果输出)耗时关键代码参见模型部署代码 精度测试 测试素材选择: 可尝试使用包含身份z、护照、机读码图像的图片文件/相机自拍的图片 评价标准选择: 直观评判:
在素材符合质量要求的前提下其内所有应检区域内容做到准确检测的概率(文本区域/文本区域内的具体字符)按阶段评判:
(1)检测阶段:先按照检测框和标注框的IOU评估,IOU大于某个阈值判断为检测准确。这里检测框和标注框不同于一般的通用目标检测框,是采用多边形进行表示。检测准确率:正确的检测框个数在全部检测框的占比,主要是判断检测指标。检测召回率:正确的检测框个数在全部标注框的占比,主要是判断漏检的指标。
(2)识别阶段: 字符识别准确率,即正确识别的文本行占标注的文本行数量的比例,只有整行文本识别对才算正确识别。
(3)端到端统计: 端对端召回率:准确检测并正确识别文本行在全部标注文本行的占比; 端到端准确率:准确检测并正确识别文本行在 检测到的文本行数量 的占比; 准确检测的标准是检测框与标注框的IOU大于某个阈值,正确识别的的检测框中的文本与标注的文本相同。 模型部署相关问题 预/后处理方式对性能、精度的影响与选择: 根据检测目标、检测场景灵活调整模型输入与可调参数全图检测:提高尺寸阈值、适当调低检测文本框分数阈值特定区域检测:截取特定区域图像数据作为输入、降低尺寸阈值、提升文本框分数阈值特定目标检测:设定敏感区域检测条件,保证敏感区域图像质量、字符识别图像尺寸还原、检测目标特征核对 字符识别模型性能测试表现异常: 框架自带benchmark对输出节点定位不够合理、模型输入尺寸影响推理性能 参考资料 移动端部署框架:ncnn百度超轻量级OCR:PaddleOCR超轻量级中文OCR:chineseocr_lite

欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/web/992902.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-05-21
下一篇 2022-05-21

发表评论

登录后才能评论

评论列表(0条)

保存