本博客仅供个人学习使用,欢迎学习原博客:https://blog.csdn.net/u012328159/article/details/81101074,如有侵权,联系作者删除。

原博客相关链接:

博主代码开源在github:https://github.com/tz28/Chinese-number-gestures-recognition

一步步做一个数字手势识别APP:https://blog.csdn.net/u012328159/article/details/81123018

Android Studio中配置OpenCV:https://blog.csdn.net/u012328159/article/details/81094436


注意:这篇文章用的应该是tensorflow的c++编译库,没有使用tensorflow lite。

将TensorFlow训练好的模型迁移到Android APP上(TensorFlowLite)
1. 写在前面
  最近在做一个数字手势识别的APP(关于这个项目,我会再写一篇博客仔细介绍,博客地址:一步步做一个数字手势识别APP,源代码已经开源在github上,地址:Chinese-number-gestures-recognition),要把在PC端训练好的模型放到Android APP上,调研了下,谷歌发布了TensorFlow Lite可以把TensorFlow训练好的模型迁移到Android APP上,百度也发布了移动端深度学习框架mobile-deep-learning(MDL),这个框架应该是paddlepaddle的手机版,具体的细节没有了解过。因为对TensorFlow稍微熟悉些,因此就决定用TensorFlow来做。 
  关于在PC端如何处理数据及训练模型,请参见博客:一步步做一个数字手势识别APP,代码已经开源在github上,上面有代码的说明和APP演示。这篇博客只介绍如何把TensorFlow训练好的模型迁移到Android Studio上进行APP的开发。

2. 模型训练注意事项
  第一步,首先在pc端训练模型的时候要模型保存为.pb模型,在保存的时候有一点非常非常重要,就是你待会再Android studio是使用这个模型用到哪个参数,那么你在保存pb模型的时候就把给哪个参数一个名字,再保存。否则,你在Android studio中很难拿出这个参数,因为TensorFlow Lite的fetch()函数是根据保存在pb模型中的名字去寻找这个参数的。(如果你已经训练好了模型,并且没有给参数名字,且你不想再训练模型了,那么你可以尝试下面的方法去找到你需要使用的变量的默认名字,见下面的代码):

#输出保存的模型中参数名字及对应的值with tf.gfile.GFile('model_50_200_c3//./digital_gesture.pb', "rb") as f:  #读取模型数据    graph_def = tf.GraphDef()    graph_def.ParseFromString(f.read()) #得到模型中的计算图和数据with tf.Graph().as_default() as graph:  # 这里的Graph()要有括号,不然会报TypeError    tf.import_graph_def(graph_def, name="")  #导入模型中的图到现在这个新的计算图中,不指定名字的话默认是 import    for op in graph.get_operations():  # 打印出图中的节点信息        print(op.name, op.values())

这段代码打出的变量的名字以及对应的值。

言归正传,通常情况该你应该保存参数的时候都给参数一个指定的名字,如下面这样(通过name参数给变量指定名字),关于训练CNN的完整代码请参见下一篇博客或者github:

X = tf.placeholder(tf.float32, [None, 64, 64, 3], name="input_x")y = tf.placeholder(tf.float32, [None, 11], name="input_y")kp = tf.placeholder_with_default(1.0, shape=(), name="keep_prob")lam = tf.placeholder(tf.float32, name="lamda")#中间略过若干代码z_fc2 = tf.add(tf.matmul(z_fc1_drop, W_fc2),b_fc2, name="outlayer")prob = tf.nn.softmax(z_fc2, name="probability")pred = tf.argmax(prob, 1, output_type="int32", name="predict")

3. 在Android Studio中配置
  第二步,开始把pb模型移植到Android Studio上,网上绝大部分资料都是说用bazel重新编译模型生成依赖,这种方法难度太大。其实没必须这样做,TensorFlow Lite官方的例子中已经给我们展示了,我们其实只需要两个文件:libandroid_tensorflow_inference_java.jar 和 libtensorflow_inference.so。这两个文件我已经放到github上了,大家可以自行下载使用,下载地址:libandroid_tensorflow_inference_java.jar、libtensorflow_inference.so。

注:检神说,直接用aar依赖也可以,这个我没试过。。有兴趣的可以试一下。

准备工作已经完毕,下面正式开始Android Studio中的配置。

  首先把训练好的pb模型放到Android项目中app/src/main/assets下,若不存在assets目录,则自己新建一个。如图所示:       
                                                     

其次,把刚刚下载的 libandroid_tensorflow_inference_java.jar 文件放到 app/libs 目下,把libtensorflow_inference.so 放到 app/libs/armeabi-v7a 目录下,如下图所示: 

                                                        

然后在app/build.gradle里进行如下配置: 
  在defaultConfig里添加

multiDexEnabled true        ndk {            abiFilters "armeabi-v7a"        }

 在android里添加 

sourceSets {        main {            jni.srcDirs = []            jniLibs.srcDirs = ['libs']        }    }

 如图所示: 

 在dependencies中添加libandroid_tensorflow_inference_java.jar,即:

implementation files('libs/libandroid_tensorflow_inference_java.jar')

 如图所示: 

至此,所有配置已经完成,下面是模型调用。

4. 在Android Studio中调用模型

在要用到模型的地方,首先要加载libtensorflow_inference.so库和初始化TensorFlowInferenceInterface对象,代码为:

TensorFlowInferenceInterface inferenceInterface;    static {        //加载libtensorflow_inference.so库文件        System.loadLibrary("tensorflow_inference");        Log.e("tensorflow","libtensorflow_inference.so库加载成功");    }    Classifier(AssetManager assetManager, String modePath) {        //初始化TensorFlowInferenceInterface对象        inferenceInterface = new TensorFlowInferenceInterface(assetManager,modePath);        Log.e("tf","TensoFlow模型文件加载成功");    }

如图所示: 

 下面来多看一点东西,看看TensorFlow Lite里提供了哪几个接口,官网地址:Here’s what a typical Inference Library sequence looks like on Android.

// Load the model from disk.TensorFlowInferenceInterface inferenceInterface =new TensorFlowInferenceInterface(assetManager, modelFilename);// Copy the input data into TensorFlow.inferenceInterface.feed(inputName, floatValues, 1, inputSize, inputSize, 3);// Run the inference call.inferenceInterface.run(outputNames, logStats);// Copy the output Tensor back into the output array.inferenceInterface.fetch(outputName, outputs);

下面就可以愉快地使用模型了。放一段我调用模型的代码,以供大家参考:

public ArrayList predict(Bitmap bitmap)    {        ArrayList list = new ArrayList<>();        float[] inputdata = getPixels(bitmap);        for(int i = 0; i <30; ++i)        {            Log.d("matrix",inputdata[i] + "");        }        inferenceInterface.feed(inputName, inputdata, 1, IMAGE_SIZE, IMAGE_SIZE, 3);        //运行模型,run的参数必须是String[]类型        String[] outputNames = new String[]{outputName,probabilityName,outlayerName};        inferenceInterface.run(outputNames);        //获取结果        int[] labels = new int[1];        inferenceInterface.fetch(outputName,labels);        int label = labels[0];        float[] prob = new float[11];        inferenceInterface.fetch(probabilityName, prob);//        float[] outlayer = new float[11];//        inferenceInterface.fetch(outlayerName, outlayer);//        for(int i = 0; i <11; ++i)//        {//            Log.d("matrix",outlayer[i] + "");//        }        for(int i = 0; i <11; ++i)        {            Log.d("matrix",prob[i] + "");        }        DecimalFormat df = new DecimalFormat("0.000000");        float label_prob = prob[label];        //返回值        list.add(Integer.toString(label));        list.add(df.format(label_prob));        return list;    }

最后放一张做的数字手势识别APP的效果,全部代码,将会开源在github上,欢迎star。  

更多相关文章

  1. Android(安卓)Animation之ScaleAnimation用法详解
  2. Android——MVP架构
  3. Android(安卓)OKHTTP3.4版本封装
  4. Android基于ViewPager实现类似微信页面切换效果
  5. Android(安卓)网络编程——HTTP请求的封装
  6. android Paint 渐变色
  7. android赚钱 植入有米广告方法
  8. Android(安卓)Button setTextColor()参数调用分析
  9. 宏定义中的特殊参数(#、##、...和__VA_ARGS__)

随机推荐

  1. Android(安卓)5.1 Settings模块源码分析
  2. 你的Android不好用,都是因为这几点原因
  3. android xml中 颜色透明度(不透明度)参照表
  4. Android修改Eclipse 中的Default debug k
  5. 我也分享一下我Android的收入数据
  6. android之如何使用Android的搜索框架
  7. Android面试经验二:
  8. 【Android休眠】之Android休眠机制
  9. android进行主题切换不重启整个应用(styl
  10. Android:增强目录选择器对话框