Tensorflow Android demo 源码分析

1.TensorFlowMultiBoxDetector中部分代码如下

Bitmap转成矩阵数据

@Override
public List<Recognition> recognizeImage(final Bitmap bitmap) {
  // Log this method so that it can be analyzed with systrace.
  Trace.beginSection("recognizeImage");
  Trace.beginSection("preprocessBitmap");
  // Preprocess the image data from 0-255 int to normalized float based
  // on the provided parameters.
  bitmap.getPixels(intValues, 0, bitmap.getWidth(), 0, 0, bitmap.getWidth(), bitmap.getHeight());
  for (int i = 0; i < intValues.length; ++i) {
    floatValues[i * 3 + 0] = (((intValues[i] >> 16) & 0xFF) - imageMean) / imageStd;
    floatValues[i * 3 + 1] = (((intValues[i] >> 8) & 0xFF) - imageMean) / imageStd;
    floatValues[i * 3 + 2] = ((intValues[i] & 0xFF) - imageMean) / imageStd;
  }
  Trace.endSection(); // preprocessBitmap
  // Copy the input data into TensorFlow.
  Trace.beginSection("feed");
  inferenceInterface.feed(inputName, floatValues, 1, inputSize, inputSize, 3);

getPixels()函数把一张图片,从指定的偏移位置(offset),指定的位置(x,y)截取指定的宽高(width,height ),把所得图像的每个像素颜色转为int值,存入pixels。

2.实现自己的Android模型

1.定义TensorFlowInferenceInterface 接口,加载xx.pb模型

2.inferenceInterface.feed(INPUT_NODE, inputs, WIDTH, HEIGHT);加载数据

3.inferenceInterface.run(outputNames);运行

4.inferenceInterface.fetch(OUTPUT_NODE, outputs);返回数据

关键代码如下:

private TensorFlowInferenceInterface inferenceInterface;

    ministmodel(AssetManager assetManager) {
        //接口定义
        inferenceInterface = new TensorFlowInferenceInterface(assetManager,MODEL_FILE);
    }
    public float[] getAddResult(float[]inputs) {

        inferenceInterface.feed(INPUT_NODE, inputs, WIDTH, HEIGHT);
        String[] outputNames = new String[] {OUTPUT_NODE};
        inferenceInterface.run(outputNames);
        inferenceInterface.fetch(OUTPUT_NODE, outputs);
        return outputs;

    }

    原文作者:Android源码分析
    原文地址: https://blog.csdn.net/u011489887/article/details/79821331
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞