• 欢迎访问搞代码网站,推荐使用最新版火狐浏览器和Chrome浏览器访问本网站!
  • 如果您觉得本站非常有看点,那么赶紧使用Ctrl+D 收藏搞代码吧

pytorch 移动端部署之helloworld的使用

python 搞代码 4年前 (2022-01-09) 40次浏览 已收录 0个评论

开始

安装Androidstudio 4.1

克隆此项目

git clone https://github.com/pytorch/android-demo-app.git

使用androidstudio 打开 android-demo-app 中的HelloWordApp

打开之后androidstudio 会自动创建依赖 只需要等待即可

这个代码已经是官方写好的故而

开一下官方教程中的代码都在什么位置

这句

repositories {
  jcenter()
}

dependencies {
  implementation 'org.pytorch:pytorch_android:1.4.0'
  implementation 'org.pytorch:pytorch_android_torchvision:1.4.0'
}

位置

HelloWorldApp\app\build.gradle

里面的全部代码

apply plugin: 'com.android.application'
repositories {
  jcenter()
}

android {
  compileSdkVersion 28
  buildToolsVersion "29.0.2"
  defaultConfig {
    applicationId "org.pytorch.helloworld"
    minSdkVersion 21
    targetSdkVersion 28
    versionCode 1
    versionName "1.0"
  }
  buildTypes {
    release {
      minifyEnabled false
    }
  }
}

dependencies {
  implementation 'androidx.appcompat:appcompat:1.1.0'
  implementation 'org.pytorch:pytorch_android:1.4.0'
  implementation 'org.pytorch:pytorch_android_torchvision:1.4.0'
}

这句

Bitmap bitmap = BitmapFactory.decodeStream(getAssets().open("image.jpg"));
Module module = Module.load(assetFilePath(this, "model.pt"));
Tensor inputTensor = TensorImageUtils.bitmapToFloat32Tensor(bitmap,
  TensorImageUtils.TORCHVISION_NORM_MEAN_RGB, TensorImageUtils.TORCHVISION_NORM_STD_RGB);
  Tensor outputTensor = module.forward(IValue.from(inputTensor)).toTensor();
float[] scores = outputTensor.getDataAsFloatArray();
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;
 }
}
String className = ImageNetClasses.IMAGENET_CLASSES[maxScoreIdx];

都在这里

HelloWorldApp\app\src\main\java\org\pytorch\helloworld\MainActivity.java

全部代码

package org.pytorch.helloworld;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.util.Log;
import android.widget.ImageView;
import android.widget.TextView;

import org.pytorch.IValue;
import org.pytorch.Module;
import org.pytorch.Tensor;
import org.pytorch.torchvision.TensorImageUtils;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

import androidx.appcompat.app.AppCompatActivity;

public class MainActivity extends AppCompatActivity {

 @Override
 protected void onCreate(Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);
  setContentView(R.layout.activity_main);

  Bitmap bitmap = null;
  Module module = null;
  try {
   // creating bitmap from packaged into app android asset 'image.jpg',
   // app/src/main/assets/image.jpg
   bitmap = BitmapFactory.decodeStream(getAssets().open("image.jpg"));
   // loading serialized torchscript module from packaged into app android asset model.pt,
   // app/src/model/assets/model.pt
   module = Module.load(assetFilePath(this, "model.pt"));
  } catch (IOException e) {
   Log.e("PytorchHelloWorld", "Error reading assets", e);
   finish();
  }

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

  // preparing input tensor
  final Tensor inputTensor = TensorImageUtils.bitmapToFloat32Tensor(bitmap,
    TensorImageUtils.TORCHVISION_NORM_MEAN_RGB, TensorImageUtils.TORCHVISION_NORM_STD_RGB);

  // running the model
  final Tensor outputTensor = module.forward(IValue.from(inputTensor)).toTensor();

  // getting tensor content as java array of floats
  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;
   }
  }

  String className = ImageNetClasse<div style="color:transparent">本文来源gaodai.ma#com搞#代!码(网</div>s.IMAGENET_CLASSES[maxScoreIdx];

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

 /**
  * 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();
  }
 }
}

搞代码网(gaodaima.com)提供的所有资源部分来自互联网,如果有侵犯您的版权或其他权益,请说明详细缘由并提供版权或权益证明然后发送到邮箱[email protected],我们会在看到邮件的第一时间内为您处理,或直接联系QQ:872152909。本网站采用BY-NC-SA协议进行授权
转载请注明原文链接:pytorch 移动端部署之helloworld的使用
喜欢 (0)
[搞代码]
分享 (0)
发表我的评论
取消评论

表情 贴图 加粗 删除线 居中 斜体 签到

Hi,您需要填写昵称和邮箱!

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址