• 安卓调用onnx模型并计算


    安卓平台可以通过调用onnx模型来进行计算,这为移动设备提供了更多的计算能力和应用场景。通过使用onnx模型,安卓设备可以进行复杂的计算任务,例如图像识别、语音识别等。这为移动应用的功能和性能提升提供了新的可能性。同时,开发者可以利用onnx模型来开发更加智能和高效的安卓应用,为用户提供更好的体验。总的来说,安卓调用onnx模型并进行计算的能力为移动设备的发展带来了新的机遇和挑战。

     

    依赖

    build.gradle

    1. plugins {
    2. id 'com.android.application'
    3. }
    4. repositories {
    5. jcenter()
    6. maven {
    7. url "https://oss.sonatype.org/content/repositories/snapshots"
    8. }
    9. }
    10. android {
    11. signingConfigs {
    12. release {
    13. storeFile file('myapp.keystore')
    14. storePassword '123456'
    15. keyAlias 'myapp'
    16. keyPassword '123456'
    17. }
    18. }
    19. packagingOptions {
    20. pickFirst 'lib/arm64-v8a/libc++_shared.so'
    21. }
    22. configurations {
    23. extractForNativeBuild
    24. }
    25. compileSdkVersion 28
    26. buildToolsVersion "30.0.3"
    27. defaultConfig {
    28. applicationId "com.mobvoi.myapp"
    29. minSdkVersion 21
    30. targetSdkVersion 28
    31. versionCode 1
    32. versionName "1.0"
    33. testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
    34. externalNativeBuild {
    35. cmake {
    36. targets "myapp", "decoder_main"
    37. cppFlags "-std=c++11", "-DC10_USE_GLOG", "-DC10_USE_MINIMAL_GLOG", "-DANDROID", "-Wno-c++11-narrowing", "-fexceptions"
    38. }
    39. }
    40. ndkVersion '21.3.6528147'
    41. ndk {
    42. abiFilters 'arm64-v8a'
    43. }
    44. }
    45. buildTypes {
    46. release {
    47. minifyEnabled false
    48. signingConfig signingConfigs.release
    49. proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
    50. }
    51. }
    52. externalNativeBuild {
    53. cmake {
    54. path "src/main/cpp/CMakeLists.txt"
    55. }
    56. }
    57. compileOptions {
    58. sourceCompatibility JavaVersion.VERSION_1_8
    59. targetCompatibility JavaVersion.VERSION_1_8
    60. }
    61. ndkVersion '21.3.6528147'
    62. }
    63. dependencies {
    64. implementation 'androidx.appcompat:appcompat:1.2.0'
    65. implementation 'com.google.android.material:material:1.2.1'
    66. implementation 'androidx.constraintlayout:constraintlayout:2.0.4'
    67. testImplementation 'junit:junit:4.+'
    68. androidTestImplementation 'androidx.test.ext:junit:1.1.2'
    69. androidTestImplementation 'androidx.test.espresso:espresso-core:3.3.0'
    70. implementation 'org.pytorch:pytorch_android:1.10.0'
    71. extractForNativeBuild 'org.pytorch:pytorch_android:1.10.0'
    72. implementation group: 'com.microsoft.onnxruntime', name: 'onnxruntime-android', version: '1.15.1'
    73. }
    74. task extractAARForNativeBuild {
    75. doLast {
    76. configurations.extractForNativeBuild.files.each {
    77. def file = it.absoluteFile
    78. copy {
    79. from zipTree(file)
    80. into "$buildDir/$file.name"
    81. include "headers/**"
    82. include "jni/**"
    83. }
    84. }
    85. }
    86. }
    87. tasks.whenTaskAdded { task ->
    88. if (task.name.contains('externalNativeBuild')) {
    89. task.dependsOn(extractAARForNativeBuild)
    90. }
    91. }

    准备好onnx放在assert目录下

    api介绍

    地址

    api文档icon-default.png?t=N7T8https://javadoc.io/doc/com.microsoft.onnxruntime/onnxruntime/latest/index.html

    常用的api

    api作用
    OrtEnvironment.getEnvironment()
    创建onnx上下文的运行环境
    new OrtSession.SessionOptions()
    创建会话(配置)
    environment.createSession(bytes, options)
    创建会话,第一个参数是模型数据,第二个是配置的参数
    LongBuffer.wrap(inputValues)
    将输入转换成onnx识别的输入,输入是模型识别的数据
    OnnxTensor.createTensor(environment, wrap, new long[]{1, inputValues.length})
    创建tensor,第一个参数是上面定义的环境,第二个参数是输入转换成模型的格式,第三个根据实际设置,为入参的矩阵格式
    session.run(map)
    推理,map是整合起来的数据
    (long[][]) output.get(1).getValue()
    获取推理结果,这里以二维数组为例

    使用案例

    1. private String getOnnx(String text) {
    2. OrtEnvironment environment = OrtEnvironment.getEnvironment();
    3. AssetManager assetManager = getAssets();
    4. try {
    5. // 创建会话
    6. OrtSession.SessionOptions options = new OrtSession.SessionOptions();
    7. // 读取模型
    8. InputStream stream = assetManager.open("youonnx.onnx");
    9. ByteArrayOutputStream byteStream = new ByteArrayOutputStream();
    10. byte[] buffer = new byte[4096];
    11. int bytesRead;
    12. while ((bytesRead = stream.read(buffer)) != -1) {
    13. byteStream.write(buffer, 0, bytesRead);
    14. }
    15. byteStream.flush();
    16. byte[] bytes = byteStream.toByteArray();
    17. OrtSession session = environment.createSession(bytes, options);
    18. String vocab = "vocab";
    19. String puncVocab = "punc_vocab";
    20. Map vocabMap = getFormFile(vocab, new String[]{"", ""});
    21. Map puncVocabMap = getFormFile(vocab, new String[]{" "});
    22. DataSet.NoPuncTextDataset dataset = new DataSet.NoPuncTextDataset(vocabMap, puncVocabMap);
    23. List list = dataset.word2seq(text);
    24. // 准备输入数据
    25. long[] inputValues = new long[list.size()];
    26. for (int i = 0; i < list.size(); i++) {
    27. inputValues[i] = list.get(i);
    28. }
    29. LongBuffer wrap = LongBuffer.wrap(inputValues);
    30. OnnxTensor inputTensor = OnnxTensor.createTensor(environment, wrap, new long[]{1, inputValues.length});
    31. long[] len = new long[]{inputValues.length};
    32. LongBuffer wrap2 = LongBuffer.wrap(len);
    33. OnnxTensor inputTensor_len = OnnxTensor.createTensor(environment, wrap2, new long[]{1});
    34. // 准备数据
    35. Map map = new HashMap<>();
    36. map.put("inputs", inputTensor);
    37. map.put("inputs_len", inputTensor_len);
    38. // 运行推理
    39. OrtSession.Result output = session.run(map);
    40. // 获取输出结果
    41. long[][] value = (long[][]) output.get(1).getValue();
    42. // 处理输出结果
    43. // todo
    44. session.close();
    45. return "you_answer"
    46. } catch (IOException | OrtException e) {
    47. throw new RuntimeException(e);
    48. }
    49. }

    通过调用此函数,可以实现安卓调用onnx

  • 相关阅读:
    Java Excel转PDF,支持xlsx和xls两种格式, itextpdf【即取即用】
    基于协同过滤算法的东北特产销售系统的设计
    基于springboot乐器视频学习网站设计与实现(源码齐全可用)
    题目0010:整数转二进制(附二进制转整数与字符串知识点)
    Linux网络编程:IP协议
    36、Flink 的 WindowAssigner之滑动窗口示例
    Bean作用域和生命周期-------JavaEE(Spring)
    荟味齐鲁鲁菜网站/美食网站/菜谱网站
    fba海运详解:fba海运是什么意思,FBA海运费用怎么算
    聚丙烯酸/Fe3O4纳米复合材料PAA/Fe3O4|α-Fe2O3和Fe3O4不同尺寸的纳米复合材料|齐岳
  • 原文地址:https://blog.csdn.net/weixin_44808225/article/details/134405865