TorchMobile Android Helloworld 笔记

TorchMobile Android Helloworld 笔记

笔记为PyTorch官方示例HelloWorld学习笔记

1.获取图片

取图片
取模型

  bitmap = BitmapFactory.decodeStream(getAssets().open("image.jpg"));
  module = LiteModuleLoader.load(assetFilePath(this, "model.pt"));

2.在前端显示

 // showing image on UI
    ImageView imageView = findViewById(R.id.image);
    imageView.setImageBitmap(bitmap);

3.准备工作1

        // preparing input tensor 图片转换为张量的形式
    final Tensor inputTensor = TensorImageUtils.bitmapToFloat32Tensor(bitmap,
        TensorImageUtils.TORCHVISION_NORM_MEAN_RGB, TensorImageUtils.TORCHVISION_NORM_STD_RGB, MemoryFormat.CHANNELS_LAST);

    // running the model 图片张量输入网络 网络前向传播 
    final Tensor outputTensor = module.forward(IValue.from(inputTensor)).toTensor();

4.网络输出结果处理

  // getting tensor content as java array of floats  获取网络输出的scores
    final float[] scores = outputTensor.getDataAsFloatArray();

    // searching for the index with maximum score  
    float maxScore = -Float.MAX_VALUE;
    int maxScoreIdx = -1;
    for (int i = 0; i < scores.length; i++) {
      if (scores[i] > maxScore) {
        maxScore = scores[i];
        maxScoreIdx = i;
      }
    }
//ImageNetClasses.IMAGENET_CLASSES 是string数组  
//为classname赋值
    String className = ImageNetClasses.IMAGENET_CLASSES[maxScoreIdx];


 // showing className on UI 前端显示
    TextView textView = findViewById(R.id.text);
    textView.setText(className);
  }

5.读取指定文件地址

将指定的资源复制到/files app,并返回该文件的绝对路径。

  /**
   * Copies specified asset to the file in /files app directory and returns this file absolute path.
   *
   * @return absolute file path
   */
   
 public static String assetFilePath(Context context, String assetName) throws IOException {
    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();
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值