Tensorflow MobileNet移植到Android 1 CKPT模型轉換pb文件 2 移植到Android中 3 模型測試

最近看到一個巨牛的人工智能教程,分享一下給大家。教程不僅是零基礎,通俗易懂,而且非常風趣幽默,像看小說一樣!覺得太牛了,所以分享給大家。平時碎片時間可以當小說看,【點這裏可以去膜拜一下大神的“小說”】

1 CKPT模型轉換pb文件

使用上一篇博客《MobileNet V1官方預訓練模型的使用》中下載的MobileNet V1官方預訓練的模型《MobileNet_v1_1.0_192》。雖然打包下載的文件中包含已經轉換過的pb文件,但是官方提供的pb模型輸出是1001類別對應的概率,我們需要的是概率最大的3類。可在原始網絡中使用函數tf.nn.top_k獲取概率最大的3類,將函數tf.nn.top_k作爲網絡中的一個計算節點。模型轉換代碼如下所示。

import tensorflow as tf
from mobilenet_v1 import mobilenet_v1,mobilenet_v1_arg_scope 
import numpy as np
slim = tf.contrib.slim
CKPT = 'mobilenet_v1_1.0_192.ckpt'  

def build_model(inputs):   
    with slim.arg_scope(mobilenet_v1_arg_scope(is_training=False)):
        logits, end_points = mobilenet_v1(inputs, is_training=False, depth_multiplier=1.0, num_classes=1001)
    scores = end_points['Predictions']
    print(scores)
    #取概率最大的5個類別及其對應概率
    output = tf.nn.top_k(scores, k=3, sorted=True)
    #indices爲類別索引,values爲概率值
    return output.indices,output.values

def load_model(sess):
    loader = tf.train.Saver()
    loader.restore(sess,CKPT)
   
inputs=tf.placeholder(dtype=tf.float32,shape=(1,192,192,3),name='input')
classes_tf,scores_tf = build_model(inputs)  
classes = tf.identity(classes_tf, name='classes')
scores = tf.identity(scores_tf, name='scores') 
with tf.Session() as sess:
    load_model(sess)
    graph = tf.get_default_graph()
    output_graph_def = tf.graph_util.convert_variables_to_constants(
        sess, graph.as_graph_def(), [classes.op.name,scores.op.name]) 
    tf.train.write_graph(output_graph_def, 'model', 'mobilenet_v1_1.0_192.pb', as_text=False)

上面代碼中,單一的所有類別概率經過計算節點tf.nn.top_k後分爲兩個輸出:概率最大的3個類別classes,概率最大的3個類別的概率scores。執行上面代碼後,在目錄“model”中得到文件mobilenet_v1_1.0_192.pb

2 移植到Android中

2.1 AndroidStudio中使用Tensorflow Mobile

首先,AndroidStudio版本必須是3.0及以上。創建Android Project後,在Module:appbuild.gradle文件中的dependencies中加入如下:

 compile 'org.tensorflow:tensorflow-android:+'

2.2 Tensorflow Mobile接口

使用Tensorflow Mobile庫中模型調用封裝類org.tensorflow.contrib.android.TensorFlowInferenceInterface完成模型的調用,主要使用的如下函數。

 public TensorFlowInferenceInterface(AssetManager assetManager, String model){...}
 public void feed(String inputName, float[] src, long... dims) {...}
 public void run(String[] outputNames) {...}
 public void fetch(String outputName, int[] dst) {...}

其中,構造函數中的參數model表示目錄“assets”中模型名稱。feed函數中參數inputName表示輸入節點的名稱,即對應模型轉換時指定輸入節點的名稱“input”,參數src表示輸入數據數組,變長參數dims表示輸入的維度,如傳入1,192,192,3則表示輸入數據的Shape=[1,192,192,3]。函數run的參數outputNames表示執行從輸入節點到outputNames中節點的所有路徑。函數fetch中參數outputName表示輸出節點的名稱,將指定的輸出節點的數據拷貝到dst中。

2.3 Bitmap對象轉float[]

注意到,在2.1小節中函數feed傳入到輸入節點的數據對象是float[]。因此有必要將Bitmap轉爲float[]對象,示例代碼如下所示。

    //讀取Bitmap像素值,並放入到浮點數數組中。歸一化到[-1,1]
    private float[] getFloatImage(Bitmap bitmap){
        Bitmap bm = getResizedBitmap(bitmap,inputWH,inputWH);
        bm.getPixels(inputIntData, 0, bm.getWidth(), 0, 0, bm.getWidth(), bm.getHeight());
        for (int i = 0; i < inputIntData.length; ++i) {
            final int val = inputIntData[i];
            inputFloatData[i * 3 + 0] =(float) (((val >> 16) & 0xFF)/255.0-0.5)*2;
            inputFloatData[i * 3 + 1] = (float)(((val >> 8) & 0xFF)/255.0-0.5)*2;
            inputFloatData[i * 3 + 2] = (float)(( val & 0xFF)/255.0-0.5)*2 ;
        }
        return inputFloatData;
    }

由於MobileNet V1預訓練的模型輸入數據歸一化到[-1,1],因此在函數getFloatImage中轉換數據的同時將數據歸一化到[-1,1]

2.4 封裝模型調用

爲了便於調用,將與模型相關的調用函數封裝到類TFModelUtils中,通過TFModelUtilsrun函數完成模型的調用,示例代碼如下所示。

package com.huachao.mn_v1_192; 
import android.content.res.AssetManager;
import android.graphics.Bitmap;
import android.graphics.Matrix;
import android.util.Log; 
import org.tensorflow.contrib.android.TensorFlowInferenceInterface; 
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.HashMap;
import java.util.Map; 
public class TFModelUtils {
    private TensorFlowInferenceInterface inferenceInterface;
    private int[] inputIntData ;
    private float[] inputFloatData ;
    private int inputWH;
    private String inputName;
    private String[] outputNames; 
    private Map<Integer,String> dict;
    public TFModelUtils(AssetManager assetMngr,int inputWH,String inputName,String[]outputNames,String modelName){
        this.inputWH=inputWH;
        this.inputName=inputName;
        this.outputNames=outputNames;
        this.inputIntData=new int[inputWH*inputWH];
        this.inputFloatData = new float[inputWH*inputWH*3];
        //從assets目錄加載模型
        inferenceInterface= new TensorFlowInferenceInterface(assetMngr, modelName);
        this.loadLabel(assetMngr);
    }
    public Map<String,Object> run(Bitmap bitmap){ 
        float[] inputData = getFloatImage(bitmap);
        //將輸入數據複製到TensorFlow中,指定輸入Shape=[1,INPUT_WH,INPUT_WH,3]
        inferenceInterface.feed(inputName, inputData, 1, inputWH, inputWH, 3); 
        // 執行模型
        inferenceInterface.run( outputNames ); 
        //將輸出Tensor對象複製到指定數組中
        int[] classes=new int[3];
        float[] scores=new float[3];
        inferenceInterface.fetch(outputNames[0], classes);
        inferenceInterface.fetch(outputNames[1], scores);
        Map<String,Object> results=new HashMap<>();
        results.put("scores",scores);
        String[] classesLabel = new String[3];
        for(int i =0;i<3;i++){
            int idx=classes[i];
            classesLabel[i]=dict.get(idx);
//            System.out.printf("classes:"+dict.get(idx)+",scores:"+scores[i]+"\n");
        }
        results.put("classes",classesLabel);
        return results;


    }
    //讀取Bitmap像素值,並放入到浮點數數組中。歸一化到[-1,1]
    private float[] getFloatImage(Bitmap bitmap){
        Bitmap bm = getResizedBitmap(bitmap,inputWH,inputWH);
        bm.getPixels(inputIntData, 0, bm.getWidth(), 0, 0, bm.getWidth(), bm.getHeight());
        for (int i = 0; i < inputIntData.length; ++i) {
            final int val = inputIntData[i];
            inputFloatData[i * 3 + 0] =(float) (((val >> 16) & 0xFF)/255.0-0.5)*2;
            inputFloatData[i * 3 + 1] = (float)(((val >> 8) & 0xFF)/255.0-0.5)*2;
            inputFloatData[i * 3 + 2] = (float)(( val & 0xFF)/255.0-0.5)*2 ;
        }
        return inputFloatData;
    }
    //對圖像做Resize
    public Bitmap getResizedBitmap(Bitmap bm, int newWidth, int newHeight) {
        int width = bm.getWidth();
        int height = bm.getHeight();
        float scaleWidth = ((float) newWidth) / width;
        float scaleHeight = ((float) newHeight) / height;
        Matrix matrix = new Matrix();
        matrix.postScale(scaleWidth, scaleHeight);
        Bitmap resizedBitmap = Bitmap.createBitmap( bm, 0, 0, width, height, matrix, false);
        bm.recycle();
        return resizedBitmap;
    }

    private void loadLabel( AssetManager assetManager ) {
        dict=new HashMap<>();
        try {
            InputStream stream = assetManager.open("label.txt");
            InputStreamReader isr=new InputStreamReader(stream);
            BufferedReader br=new BufferedReader(isr);
            String line;
            while((line=br.readLine())!=null){
                line=line.trim();
                String[] arr = line.split(",");
                if(arr.length!=2)
                    continue;
                int key=Integer.parseInt(arr[0]);
                String value = arr[1];
                dict.put(key,value);
            }
        }catch (Exception e){
            e.printStackTrace();
            Log.e("ERROR",e.getMessage());
        }
    }
}

3 模型測試

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章