pytorch 在Android平台特定代码中未找到Flutter资产

imzjd6km  于 2023-05-17  发布在  Android
关注(0)|答案(1)|浏览(197)

我想加载一个'. ptl'-Pytorch模型文件在android特定的代码. pubspec.yaml

flutter:
  uses-material-design: true
  assets:
    - assets/mobilenetv3.ptl

到目前为止一切顺利。。在我的Android平台特定代码中,我想加载这个模型:

FlutterLoader loader = FlutterInjector.instance().flutterLoader();
loader.startInitialization(getApplicationContext());
loader.ensureInitializationComplete(getApplicationContext(), new String[] {});
String key = loader.getLookupKeyForAsset("assets/mobilenetv3.ptl");

try{
    module = LiteModuleLoader.load(key);
} catch (Exception e) {
    Log.e("myapp", "Error reading assets", e);
    finish();
}

但是每次我执行这个命令时,我都会得到:

java.io.FileNotFoundException: /data/user/0/com.example.dacl/files/flutter_assets/assets/mobilenetv3.ptl: open failed: ENOENT (No such file or directory)
        at libcore.io.IoBridge.open(IoBridge.java:575)
        at java.io.FileOutputStream.<init>(FileOutputStream.java:236)
        at java.io.FileOutputStream.<init>(FileOutputStream.java:186)
        at com.example.dacl.MainActivity.assetFilePath(MainActivity.java:85)
        at com.example.dacl.MainActivity.configureFlutterEngine(MainActivity.java:62)
...

该文件包含在:rootdir/assets/mobilenetv3.ptl
有人知道我错过了什么吗?不幸的是,Flutter文档不是最新的,无法加载平台特定的资产。
谢谢你

uxhixvfz

uxhixvfz1#

找到你的ptl文件到文件夹“android/app/src/main/assets”
(so java包在项目文件夹中的位置)
你可以通过下面的代码加载模型

module = LiteModuleLoader.load(MainActivity().assetFilePath(getApplicationContext(), "your_model_name.ptl"))
public static String assetFilePath(Context context, String assetName) {
    File file = new File(context.getFilesDir(), assetName);
    if (file.exists() && file.length() > 0) {
      return file.getAbsolutePath();
    }

    try (InputStream is = context.getAssets().open(assetName)) {
      try (OutputStream os = new FileOutputStream(file)) {
        byte[] buffer = new byte[4 * 1024];
        int read;
        while ((read = is.read(buffer)) != -1) {
          os.write(buffer, 0, read);
        }
        os.flush();
      }
      return file.getAbsolutePath();
    } catch (IOException e) {
      Log.e(TAG, "Error process asset " + assetName + " to file path");
    }
    return null;
  }

希望对你有帮助!

相关问题