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();