更新记录

2.0.3(2026-10-14)

  • 新增 Android UTS API 插件,支持在 uni-app 项目中通过 import 调用。
  • 支持 PP-OCRv4、ML Kit 和 auto 双引擎自动复核。
  • 新增 getEngineInfo、initEngine、identify、release API。
  • 支持本地图片、网络图片、相册图片识别和进度回调。
  • 更新示例工程、使用说明和效果截图。

平台兼容性

离线 OCR 文字识别 UTS 版

ysh-ocr-uts 是 Android 离线 OCR UTS API 插件,支持中文、英文、数字和常用符号识别,内置 PP-OCRv4、Google ML Kit 双引擎,并支持 Auto 模式自动复核。

平台与兼容性

项目 值
类型 uni-app UTS API 插件
平台 Android
minSdkVersion 21
Android 最低版本 Android 5.0
ABI armeabi-v7a、arm64-v8a、x86
HBuilderX 最低版本 ^3.91.0
uni-app 支持 uni-app,暂不支持 uni-app x
iOS / HarmonyOS 暂不支持
离线能力 OCR 引擎和模型离线运行;网络图片识别需要应用联网

依赖:

com.microsoft.onnxruntime:onnxruntime-android:1.17.1
com.google.mlkit:text-recognition:16.0.0
com.google.mlkit:text-recognition-chinese:16.0.0

集成方式

  1. 从插件市场安装本插件,或将 uni_modules/ysh-ocr-uts 放入 uni-app 项目。
  2. 如使用网络图片,请在 manifest.json 中声明 android.permission.INTERNET。
  3. 修改 UTS、AAR 或依赖后,请重新制作包含 UTS 插件的自定义调试基座,或重新云打包。
  4. 页面中直接 import:
import { getEngineInfo, initEngine, identify, release } from '@/uni_modules/ysh-ocr-uts';

三种识别模式

1. auto:自动复核模式(推荐)

auto 是默认模式。插件先使用 PP-OCRv4 识别,并根据结果质量分判断是否足够可靠;当 PP-OCRv4 质量不足时,会调用 ML Kit 进行复核和结果比较,最终返回质量更优的文本。

适合场景:

  • 普通中文、英文、数字、日期、短文本识别。
  • 开发者不想手动选择引擎。
  • 对稳定性要求高于极致速度的场景。

特点:

  • 中文短文本表现较好。
  • 对低质量、小字、符号结果会尝试 ML Kit 复核。
  • 速度比单引擎慢,因为可能触发第二次 ML Kit 推理。

2. paddle / pp-ocrv4:PP-OCRv4 单引擎模式

直接调用 PP-OCRv4 OCR 引擎,不进入 ML Kit 复核流程。

适合场景:

  • 中文、数字、常见标点识别。
  • 图片较清晰、文字较大。
  • 不需要双引擎复核,追求可预测耗时。

特点:

  • 中文短文本识别效果较好。
  • 对部分英文空格、标点、复杂密集文段仍可能误识别。
  • 速度通常优于 auto,因为不会自动触发 ML Kit 第二次识别。

3. mlkit:Google ML Kit 单引擎模式

直接调用 Google ML Kit 文本识别能力,当前使用 text-recognition-chinese 中文识别模型。

适合场景:

  • 英文、数字、常见符号。
  • 不希望使用 PP-OCRv4 的机型或场景。
  • 作为 auto 复核链路的单独测试模式。

特点:

  • 英文、数字和常见符号较稳定。
  • 中文标点、密集小字、特殊符号容易漏识别或替换。
  • 部分样本速度优于 PP-OCRv4,但耗时受机型影响较大。

技术实现

插件识别链路如下:

UTS API -> Android AAR -> ImageLoader -> AutoOcrEngine -> PP-OCRv4 / ML Kit -> 质量评分 -> 返回文本

主要技术:

模块 技术
UTS 接口层 getEngineInfo、initEngine、identify、release,使用 UTS Android 调度器异步执行
OCR 主引擎 PP-OCRv4 文字检测 + PP-OCRv4 文字识别
推理运行时 ONNX Runtime Android 1.17.1
备用复核引擎 Google ML Kit Text Recognition Chinese 16.0.0
自动模式 PP-OCRv4 先识别,低质量时 ML Kit 复核,并按质量分选择结果
质量评分 根据识别区域、检测分数、文本长度、中英标点、疑似乱码等规则计算 qualityScore
图片来源 本地文件路径、应用沙箱路径、网络 URL
图片处理 ImageLoader 加载 Bitmap、recycle 释放、异常回调
进度回调 queued、engine、image、recognize、result、done、error 等阶段

API

getEngineInfo(): EngineInfo

同步返回插件版本、默认引擎、支持引擎列表等信息。

const info = getEngineInfo();
console.log(info.version, info.defaultEngine, info.engines);

initEngine(options)

初始化或切换 OCR 引擎。

initEngine({
  engine: 'auto',
  success(res) {
    console.log(res.engine, res.version);
  },
  fail(err) {
    console.error(err);
  }
});

engine 可选值:

值 说明
auto 默认,PP-OCRv4 优先,低质量时 ML Kit 复核
paddle / pp-ocrv4 PP-OCRv4 引擎
mlkit Google ML Kit 中文识别引擎

identify(options)

识别本地图片或网络图片。

identify({
  url: 'https://example.com/demo.png',
  engine: 'auto',
  speed: 'balanced',
  fallback: true,
  progress(res) {
    console.log(res.stage, res.percent, res.message);
  },
  success(res) {
    console.log(res.text, res.processTime, res.selectedEngine, res.qualityScore);
  },
  fail(err) {
    console.error(err);
  }
});

参数:

参数 类型 必填 说明
path string 否 Android 可读取的图片文件路径,与 url 二选一
url string 否 网络图片地址,与 path 二选一
engine string 否 auto、paddle、mlkit,默认 auto
speed string 否 fast、balanced、accurate,默认 balanced
fallback boolean 否 Auto 模式是否允许双引擎复核,默认 true
progress function 否 进度回调
success function 否 成功回调
fail function 否 失败回调

返回字段:

type IdentifyResult = {
  text: string,
  processTime: number,
  imageWidth: number,
  imageHeight: number,
  engine: string,
  selectedEngine: string,
  confidence: number,
  qualityScore: number,
  comparisonInfo: string
}

release()

释放 OCR 引擎资源。建议在页面 onUnload 中调用。

onUnload() {
  release();
}

快速示例

完整示例以 pages/native-plugin/ocr-test-uts.vue 为基础,包含批量测试、本地图片、网络图片、相册和识别日志。

<template>
  <view>
    <button :disabled="loading" @click="run">识别网络图片</button>
    <text v-if="loading">识别中 {{ progress }}%</text>
    <text v-else>{{ text }}</text>
    <text v-if="selectedEngine">实际引擎:{{ selectedEngine }}</text>
    <text v-if="qualityScore">质量分:{{ qualityScore }}</text>
  </view>
</template>

<script>
import { initEngine, identify, release } from '@/uni_modules/ysh-ocr-uts';

export default {
  data() {
    return {
      loading: false,
      progress: 0,
      text: '',
      selectedEngine: '',
      qualityScore: ''
    };
  },
  onUnload() {
    release();
  },
  methods: {
    run() {
      this.loading = true;
      initEngine({
        engine: 'auto',
        success: () => {
          identify({
            url: 'https://www.baidu.com/img/PCtm_d9c8750bed0b3c7d089fa7d55720d6cf.png',
            engine: 'auto',
            speed: 'balanced',
            progress: (p) => {
              this.progress = p.percent || 0;
            },
            success: (res) => {
              this.loading = false;
              this.text = res.text || '';
              this.selectedEngine = res.selectedEngine || '';
              this.qualityScore = res.qualityScore || '';
            },
            fail: (err) => {
              this.loading = false;
              console.error(err);
            }
          });
        },
        fail: (err) => {
          this.loading = false;
          console.error(err);
        }
      });
    }
  }
};
</script>

示例页面说明:ocr-test-uts.vue

完整示例页面为插件实测页:

pages/native-plugin/ocr-test-uts.vue

该页面基于本插件真实运行逻辑编写,覆盖本插件主要能力,适合作为业务接入参考和验收测试页。

页面入口

将页面复制到你的 uni-app 项目后,在 pages.json 中增加:

{
  "pages": [
    {
      "path": "pages/native-plugin/ocr-test-uts",
      "style": {
        "navigationBarTitleText": "OCR UTS 识别"
      }
    }
  ]
}

页面依赖同目录下的:

pages/native-plugin/ocr-test-data.js

如果需要使用批量测试能力,还需要保留:

static/test-images/

页面区域说明

区域 功能 对应插件能力
引擎区域 点击 Auto、PP-OCRv4、ML Kit 初始化不同引擎 initEngine({ engine })
识别入口 相册识别、拍照识别、网络图片、清除结果 identify({ path })、identify({ url })
网络图片 URL 输入图片 URL 并发起网络图片识别 identify({ url })
识别速度 选择快速、标准、精准 speed: fast/balanced/accurate
批量测试 对本地 60 张图片和长文段图片批量识别 identify({ path }) 多次调用
批量结果 展示成功数、失败数、通过率、平均识别率、平均耗时和失败样本 示例页统计逻辑
识别结果 展示识别文本、请求引擎、实际引擎、质量分、耗时 success(res) 返回字段
运行日志 展示识别进度、耗时、错误信息 progress(res)、fail(err)

关键调用逻辑

页面核心调用如下:

import { getEngineInfo, initEngine, identify, release } from '@/uni_modules/ysh-ocr-uts';

getEngineInfo();

initEngine({
  engine: 'auto',
  success(res) {
    console.log('引擎就绪', res);
  },
  fail(err) {
    console.error('引擎初始化失败', err);
  }
});

identify({
  url: imageUrl,
  engine: 'auto',
  speed: 'balanced',
  fallback: true,
  progress(res) {
    console.log(res.percent, res.message);
  },
  success(res) {
    console.log('识别文本', res.text);
    console.log('实际引擎', res.selectedEngine);
    console.log('质量分', res.qualityScore);
  },
  fail(err) {
    console.error('识别失败', err);
  }
});

release();

批量测试说明

示例页提供两个批量入口:

按钮 说明
批量识别本地图片 遍历 static/test-images 中的 60 张样本,使用 ocr-test-data.js 的期望结果统计通过率
批量识别文段图片 专门跑长文段样本,用于观察密集文本、多行文本的识别表现

批量测试结果包括:

  • 成功数量、失败数量。
  • 通过率。
  • 平均识别率或片段匹配度。
  • 平均单张耗时。
  • 总耗时。
  • 失败样本名称与匹配度。

ocr-test-uts.vue 完整用法收录

以下使用说明以实际示例页 pages/native-plugin/ocr-test-uts.vue 为准,覆盖页面内出现过的插件调用方式、页面入口、图片来源、批量测试、路径处理、进度、结果字段、错误处理和资源释放。

1. 页面入口与依赖

示例页路径:

pages/native-plugin/ocr-test-uts.vue

pages.json 注册方式:

{
  "pages": [
    {
      "path": "pages/native-plugin/ocr-test-uts",
      "style": {
        "navigationBarTitleText": "OCR UTS 识别"
      }
    }
  ]
}

页面内插件导入:

import { getEngineInfo, initEngine, identify, release } from '@/uni_modules/ysh-ocr-uts';

批量测试数据依赖:

import {
  EXPECTED,
  LOCAL_SAMPLE_DIR,
  LOCAL_IMAGES,
  PARAGRAPH_IMAGES,
  MIN_SIMILARITY,
  MIN_FRAGMENT_RATIO,
  LONG_TEXT_MIN_CHARS
} from './ocr-test-data.js';

需要保留的图片目录:

static/test-images/

如果只做单张图片识别,可以不需要 ocr-test-data.js 和 static/test-images;批量测试需要它们。

2. 页面启动时获取插件信息

示例页在 onLoad 中调用 getEngineInfo(),并读取插件版本、当前引擎名和默认引擎:

onLoad(options) {
  this.appendLog('UTS OCR 测试页加载');
  this.appendLog('getEngineInfo: ' + typeof getEngineInfo);
  this.appendLog('identify: ' + typeof identify);
  try {
    const info = getEngineInfo();
    this.engineName = info.engine || '-';
    this.version = info.version || '2.0.3';
    this.engine = info.defaultEngine || 'auto';
    this.appendLog('插件版本 ' + this.version + ',默认引擎 ' + this.engine);
  } catch (e) {
    this.error = '读取插件信息失败:' + this.errText(e);
    this.appendLog(this.error);
  }
}

页面支持通过 URL 参数自动执行测试:

参数 行为
?auto=1 自动初始化 auto 引擎并识别 /sdcard/ocr-test.png
?auto=images 或 ?auto=all 自动执行本地图片批量识别
?auto=paragraph 自动执行本地文段图片批量识别
if (options && (options.auto === '1' || options.auto === true)) {
  setTimeout(() => this.runAutoTest(), 200);
} else if (options && (options.auto === 'images' || options.auto === 'all')) {
  setTimeout(() => this.runAllLocalSamples(), 300);
} else if (options && options.auto === 'paragraph') {
  setTimeout(() => this.runParagraphSamples(), 300);
}

3. 初始化和切换引擎

示例页提供 Auto、PP-OCRv4、ML Kit 三个初始化按钮:

<button :disabled="loading" @click="doInit('auto')">Auto</button>
<button :disabled="loading" @click="doInit('paddle')">PP-OCRv4</button>
<button :disabled="loading" @click="doInit('mlkit')">ML Kit</button>

初始化逻辑:

doInit(kind) {
  this.loading = true;
  this.error = '';
  const started = Date.now();
  initEngine({
    engine: kind,
    success: (res) => {
      this.loading = false;
      this.engine = kind;
      this.engineName = res.engine || kind;
      this.version = res.version || this.version;
      this.appendLog('引擎就绪: ' + this.engineName + ',耗时 ' + (Date.now() - started) + 'ms');
      uni.showToast({ title: '引擎就绪', icon: 'none' });
    },
    fail: (err) => {
      this.loading = false;
      this.error = '初始化失败:' + this.errText(err);
      this.appendLog(this.error);
    }
  });
}

页面实际使用过的 engine 值:

调用 说明
initEngine({ engine: 'auto' }) 自动复核模式
initEngine({ engine: 'paddle' }) PP-OCRv4 单引擎
initEngine({ engine: 'mlkit' }) Google ML Kit 单引擎

4. 网络图片识别

示例页可以通过输入框识别网络图片:

<input class="input" type="text" v-model="imageUrl" placeholder="输入图片 URL" />
<button :disabled="loading" @click="runUrl">网络图片</button>

调用方式:

runUrl() {
  if (!this.imageUrl) {
    this.error = '请输入图片 URL';
    return;
  }
  this.previewImage = this.imageUrl;
  this.runIdentify({ url: this.imageUrl });
}

默认测试 URL:

const DEFAULT_URL = 'https://www.baidu.com/img/PCtm_d9c8750bed0b3c7d089fa7d55720d6cf.png';

5. 相册图片识别

页面通过 uni.chooseImage 从相册选择图片,然后取 tempFilePaths[0] 传给 identify({ path }):

pickAlbum() {
  uni.chooseImage({
    count: 1,
    sizeType: ['original'],
    sourceType: ['album'],
    success: (res) => {
      const path = res.tempFilePaths[0];
      this.previewImage = path;
      this.appendLog('相册图片: ' + path);
      this.runIdentify({ path: path });
    },
    fail: (err) => {
      this.appendLog('相册取消: ' + this.errText(err));
    }
  });
}

6. 拍照识别

拍照使用 uni.chooseImage({ sourceType: ['camera'] }),需要应用已配置相机权限:

pickCamera() {
  uni.chooseImage({
    count: 1,
    sizeType: ['original'],
    sourceType: ['camera'],
    success: (res) => {
      const path = res.tempFilePaths[0];
      this.previewImage = path;
      this.appendLog('拍照图片: ' + path);
      this.runIdentify({ path: path });
    },
    fail: (err) => {
      this.appendLog('拍照取消: ' + this.errText(err));
    }
  });
}

7. 核心识别调用:identify({ path }) 与 identify({ url })

示例页统一封装了 runIdentify,同时支持本地路径和网络 URL:

runIdentify(input) {
  this.loading = true;
  this.error = '';
  this.progress = 0;
  this.progressMessage = '';
  this.hasResult = false;
  this.processTime = 0;
  const started = Date.now();
  const usePath = input.path || '';
  const useUrl = input.url || '';

  identify({
    path: usePath,
    url: useUrl,
    engine: this.engine,
    speed: this.speed,
    fallback: true,
    progress: (res) => {
      this.progress = res.percent || 0;
      this.progressMessage = res.message || '';
    },
    success: (res) => {
      this.loading = false;
      this.progress = 100;
      this.hasResult = true;
      this.resultText = res.text || '';
      this.requestedEngine = res.engine || this.engine;
      this.selectedEngine = res.selectedEngine || this.engine;
      this.processTime = res.processTime || (Date.now() - started);
      this.qualityScore = typeof res.qualityScore === 'number' ? res.qualityScore.toFixed(3) : '-';
      this.appendLog('识别成功,实际引擎=' + this.selectedEngine + ',总耗时=' + (Date.now() - started) + 'ms');
    },
    fail: (err) => {
      this.loading = false;
      this.progress = 100;
      this.error = '识别失败:' + this.errText(err);
      this.appendLog(this.error);
    }
  });
}

页面展示的成功结果字段包括:

字段 页面用途
res.text 识别文本
res.engine 请求引擎
res.selectedEngine 实际使用引擎
res.processTime 识别耗时,单位 ms
res.qualityScore 结果质量分,页面显示 3 位小数

8. 识别速度选择

页面支持三种识别速度:

speedOptions: [
  { value: 'fast', label: '快速' },
  { value: 'balanced', label: '标准' },
  { value: 'accurate', label: '精准' }
]

页面将选中的值传入 identify:

identify({
  path: path,
  engine: this.engine,
  speed: this.speed,
  fallback: true
})

9. ADB / 自动化测试入口:识别设备本地文件

示例页支持 auto=1 自动识别设备本地文件,适合 adb 或自动化验收:

runAutoTest() {
  const imagePath = '/sdcard/ocr-test.png';
  this.appendLog('AUTOTEST_START path=' + imagePath);
  initEngine({
    engine: 'auto',
    success: (res) => {
      this.engine = 'auto';
      this.engineName = res.engine || 'auto';
      this.version = res.version || this.version;
      this.appendLog('AUTOTEST_INIT_OK engine=' + this.engineName);
      this.runAutoIdentify(imagePath);
    },
    fail: (err) => {
      this.appendLog('AUTOTEST_INIT_FAIL error=' + this.errText(err));
    }
  });
}
runAutoIdentify(imagePath) {
  const started = Date.now();
  identify({
    path: imagePath,
    engine: 'auto',
    speed: this.speed,
    fallback: true,
    progress: (res) => {
      this.appendLog('AUTOTEST_PROGRESS percent=' + (res.percent || 0) + ' message=' + this.oneLine(res.message || ''));
    },
    success: (res) => {
      this.hasResult = true;
      this.resultText = res.text || '';
      this.selectedEngine = res.selectedEngine || this.engine;
      this.processTime = res.processTime || (Date.now() - started);
      this.qualityScore = typeof res.qualityScore === 'number' ? res.qualityScore.toFixed(3) : '-';
      this.appendLog('AUTOTEST_PASS selectedEngine=' + this.selectedEngine + ' processTime=' + this.processTime + ' quality=' + this.qualityScore);
      this.appendLog('AUTOTEST_TEXT ' + this.oneLine(this.resultText));
    },
    fail: (err) => {
      this.appendLog('AUTOTEST_IDENTIFY_FAIL error=' + this.errText(err));
    }
  });
}

自动化测试会输出以下日志关键字:

日志 含义
AUTOTEST_START 开始本地文件识别
AUTOTEST_INIT_OK 初始化成功
AUTOTEST_PROGRESS 识别进度
AUTOTEST_PASS 识别成功
AUTOTEST_TEXT 识别文本
AUTOTEST_IDENTIFY_FAIL 识别失败

10. 批量识别本地图片

页面提供两个批量入口:

runAllLocalSamples() {
  return this.runLocalSampleList(LOCAL_IMAGES, '批量识别本地图片', 60000);
}

runParagraphSamples() {
  return this.runLocalSampleList(PARAGRAPH_IMAGES, '批量识别本地文段图片', 60000);
}

LOCAL_IMAGES 和 PARAGRAPH_IMAGES 来自 ocr-test-data.js,对应 static/test-images/ 下的测试图片。

批量流程:

  1. 从 ocr-test-data.js 读取样本文件名。
  2. 通过 plus.io 将 _www/static/test-images/... 复制到 _doc/ocr_test_images/...。
  3. 将复制后的文件转换为 Android 可识别本地路径。
  4. 对每张图调用 identify({ path })。
  5. 使用期望文本计算相似度或片段匹配度。
  6. 汇总通过率、平均识别率、平均耗时、总耗时和失败样本。

11. 静态图片转成本地可识别路径

插件识别需要 Android 可读取的文件路径。示例页不直接把 _www/... 传给插件,而是通过 plus.io 复制到 _doc/ocr_test_images,再转换成普通文件路径。

复制逻辑:

resolveLocalSamplePath(name) {
  return new Promise((resolve, reject) => {
    const fail = (e) => reject(this.errText(e));
    const sourcePath = '_www/' + LOCAL_SAMPLE_DIR + name;
    plus.io.resolveLocalFileSystemURL(sourcePath, (srcEntry) => {
      plus.io.resolveLocalFileSystemURL('_doc', (docDir) => {
        docDir.getDirectory('ocr_test_images', { create: true }, (dirEntry) => {
          const doCopy = () => {
            srcEntry.copyTo(dirEntry, name, (copied) => {
              resolve(this.normalizeLocalPath(this.entryToLocalPath(copied)));
            }, (copyErr) => {
              dirEntry.getFile(name, {}, (existing) => {
                resolve(this.normalizeLocalPath(this.entryToLocalPath(existing)));
              }, () => {
                fail(copyErr);
              });
            });
          };
          dirEntry.getFile(name, {}, (fileEntry) => {
            fileEntry.remove(doCopy, doCopy);
          }, doCopy);
        }, fail);
      }, fail);
    }, fail);
  });
}

路径转换逻辑:

entryToLocalPath(entry) {
  if (!entry) {
    return '';
  }
  if (typeof entry.toLocalURL === 'function') {
    const url = entry.toLocalURL();
    return url && url.indexOf('file://') === 0 ? url.substring(7) : url;
  }
  return plus.io.convertLocalFileSystemURL(entry.fullPath || entry.toURL());
}

规范化路径:

normalizeLocalPath(path) {
  let p = String(path || '');
  try {
    if (typeof plus !== 'undefined' && plus.io && plus.io.convertLocalFileSystemURL &&
      (p.indexOf('_doc') === 0 || p.indexOf('_downloads') === 0 || p.indexOf('_www') === 0 ||
        p.indexOf('_temp') === 0 || p.indexOf('file://') === 0)) {
      p = plus.io.convertLocalFileSystemURL(p);
    }
  } catch (e) {
    this.appendLog('路径转换失败,使用原路径: ' + this.errText(e));
  }
  if (p.indexOf('file://') === 0) {
    p = p.substring(7);
  }
  return p;
}

如果业务项目没有使用 plus.io,也可以改用 uni.saveFile、plus.downloader、或自行把静态资源复制到应用私有目录后再传给 identify({ path })。

12. 批量识别中使用 Promise + 超时保护

批量测试不会直接依赖回调嵌套,而是将 identify 封装成 Promise,并给单张图片设置超时:

identifyPromise(options) {
  const timeout = typeof options.timeout === 'number' ? options.timeout : 120000;
  return new Promise((resolve, reject) => {
    let settled = false;
    const timer = setTimeout(() => {
      if (!settled) {
        settled = true;
        reject('识别超时(' + timeout + 'ms)');
      }
    }, timeout);
    identify({
      path: options.path || '',
      url: options.url || '',
      engine: options.engine || this.engine,
      speed: options.speed || this.speed,
      fallback: true,
      success: (res) => {
        if (settled) return;
        settled = true;
        clearTimeout(timer);
        resolve(res || {});
      },
      fail: (err) => {
        if (settled) return;
        settled = true;
        clearTimeout(timer);
        reject(this.errText(err));
      }
    });
  });
}

批量循环中单张识别超时为 60000ms:

const res = await this.identifyPromise({ path: path, timeout: timeout });

13. 批量统计逻辑

页面使用 ocr-test-data.js 中的阈值和期望文本统计识别结果:

matchScore(actual, expected) {
  if (!expected) {
    return { score: -1, passed: false, label: '识别率' };
  }
  const exactScore = this.similarity(actual, expected);
  const expectChars = this.normalize(expected).length;
  if (expectChars < LONG_TEXT_MIN_CHARS) {
    return { score: exactScore, passed: exactScore >= MIN_SIMILARITY, label: '相似度' };
  }
  const fragmentScore = this.fragmentSimilarity(actual, expected);
  const score = Math.max(exactScore, fragmentScore);
  return { score: score, passed: score >= MIN_FRAGMENT_RATIO, label: '片段匹配度' };
}

统计口径:

样本类型 判定方式
短文本 识别文本与期望文本做归一化后的相似度
长文段 使用关键片段命中率,计算片段匹配度
无期望文本 只要识别到文字即计入成功,不计入平均识别率

页面对外展示的批量结果:

this.batchStats = {
  title: this.batchTitle || '批量识别',
  engine: this.engine,
  total: items.length,
  ok: ok,
  bad: bad,
  rate: passRate.toFixed(2),
  matchRate: matchRate.toFixed(2),
  matchCount: simCount,
  avg: avg,
  totalCost: totalCost,
  failures: failures.slice(0, 10),
  failureTotal: failures.length
};

14. 进度、日志和错误处理

页面使用插件 progress 回调驱动进度条:

progress: (res) => {
  this.progress = res.percent || 0;
  this.progressMessage = res.message || '';
}

页面日志输出:

appendLog(text) {
  const time = new Date().toLocaleTimeString();
  this.logs.push('[' + time + '] ' + text);
  console.log(text);
}

错误文本统一转换:

errText(err) {
  if (err && err.message) {
    return err.message;
  }
  return String(err || '');
}

15. 页面卸载释放资源

示例页在 onUnload 中释放 OCR 引擎资源:

onUnload() {
  try {
    release();
  } catch (e) {
    console.warn('release failed', e);
  }
}

16. 示例页用到的插件能力总览

场景 页面入口 实际调用
读取版本和默认引擎 页面加载 getEngineInfo()
初始化 Auto Auto 按钮 initEngine({ engine: 'auto' })
初始化 PP-OCRv4 PP-OCRv4 按钮 initEngine({ engine: 'paddle' })
初始化 ML Kit ML Kit 按钮 initEngine({ engine: 'mlkit' })
网络图片识别 网络图片按钮 identify({ url })
相册图片识别 相册识别按钮 uni.chooseImage + identify({ path })
拍照识别 拍照识别按钮 uni.chooseImage + identify({ path })
本地 adb 文件测试 ?auto=1 identify({ path: '/sdcard/ocr-test.png' })
本地样本批量测试 批量识别本地图片按钮 plus.io 复制样本 + 多次 identify({ path })
文段样本批量测试 批量识别文段图片按钮 plus.io 复制样本 + 多次 identify({ path })
进度展示 识别中区域 identify({ progress })
结果展示 识别结果区域 success(res)
失败展示 错误框和日志 fail(err)
资源释放 页面卸载 release()

识别率与实测数据

1. 测试口径

本次测试使用项目内置 60 张本地图片,覆盖:

  • 中文短句、中文产品名、中文段落。
  • 英文单词、英文句子、英文邮箱、URL。
  • 日期、时间、手机号、身份证、订单号、价格、比例、重量。
  • 符号、大小写、字体颜色、手写风格。
  • 密集文段和多行长文本。

测试判定规则:

  • 短文本样本:按识别文本与期望文本的相似度判定。
  • 长文段样本:按关键片段命中率判定。
  • 只有达到业务阈值才计为通过,因此该通过率不是“字符级 OCR 准确率”,而是“业务样本通过率”。

2. 最近一次实测结果

测试模式:engine=auto,speed=balanced。

指标 结果
样本数 60
通过 53
失败 7
业务通过率 88.33%
平均识别率/匹配度 88.37%
平均单张耗时 534ms
最近一次总耗时 50684ms
FATAL EXCEPTION 0

补充性能参考:

引擎日志 平均单次耗时
PP-OCRv4 total 540ms
ML Kit OCR completed 681ms

3. 分类表现

类型 表现 说明
中文短文本 较好 如“这是一个测试句子”“你好世界”“智能手机显示器”等多数通过
英文短文本 较好 如 Hello、Practice makes perfect、www.example.com
数字与日期 较好 日期、时间、手机号、身份证、金额等多数通过
常用符号 一般 @#$%&* 可识别,复杂符号组合易错
中英标点混排 一般 中英文逗号、冒号、感叹号容易混淆
密集文段 一般 单行清晰文段表现较好,多行长文本容易漏行/串字
小字/低质量图片 不稳定 需要更高分辨率或预处理

4. 失败样本说明

本次失败的 7 个样本:

样本 主要问题
paragraph_04.png 多行混合内容,片段命中率 40.51%
paragraph_06.png 密集中文段落,片段命中率 12.06%
paragraph_07.png 复杂版面,片段命中率 3.79%
paragraph_08.png 小字和密集医疗字段,片段命中率 5.43%
price.png 价格符号/冒号附近误识别,相似度 75%
punctuation.png 中英文标点混淆,相似度 66.67%
symbol2.png 符号组合误识别,相似度 57.14%

隐私与权限

插件本身不主动采集或上传识别文本。

权限 使用场景
android.permission.INTERNET 使用 identify({url}) 下载网络图片
android.permission.READ_EXTERNAL_STORAGE 读取用户选择的本地图片
android.permission.CAMERA 调用拍照能力获取图片

注意事项

  • iOS 和 HarmonyOS 暂不提供原生实现。
  • 修改 UTS 原生代码、AAR 或远程依赖后,必须重新制作自定义调试基座。
  • 图片路径必须是 Android 可读取路径;Android 10+ 分区存储下建议先复制到应用私有目录。
  • 识别率与图片分辨率、字体、拍摄角度、背景、压缩噪声、机型性能强相关,复杂场景请结合 qualityScore 和业务规则做二次校验。
  • 本插件不承诺完全替代商业 OCR 服务。

隐私、权限声明

1. 本插件需要申请的系统权限列表:

android.permission.INTERNET:用于识别网络图片 URL。 android.permission.READ_EXTERNAL_STORAGE:用于读取开发者或用户选择的本地图片。 android.permission.CAMERA:用于拍照识别场景;如果宿主 App 未开启 camera 模块,则不触发该权限。

2. 本插件采集的数据、发送的服务器地址、以及数据用途说明:

插件不采集任何数据,不上传识别文本,不主动访问第三方统计服务。 本地图片 OCR 在设备端完成;网络图片识别仅根据开发者传入的 URL 下载图片,下载目标由开发者自行决定。

3. 本插件是否包含广告,如包含需详细说明广告表达方式、展示频率:

无