TensorFlow模型移植Android识别手写数字(MNIST)

识别手写数字,前提是识别图片已进行预处理,即28×28二值化灰度图(黑底白字)

本人开发环境:

  • Windows 10
  • Python 3.6.6
  • TensorFlow 1.9.0
  • Android Studio 3.1

#一 训练模型成pb文件
下载MNIST数据集,代码详细可看官方文档:http://www.tensorfly.cn/tfdoc/tutorials/mnist_pros.html

注意:要定义模型的输入层和输出层节点的名字(通过形参 'name’指定,后面加载模型都是通过该name来传递数据的)

import input_data
import tensorflow as tf
from tensorflow.python.framework import graph_util
#mnist下载地址
mnist = input_data.read_data_sets('./mnist_data/', one_hot=True)

sess = tf.InteractiveSession()

x = tf.placeholder("float32", shape=[None, 784],name='x')
y_ = tf.placeholder("float32", shape=[None, 10],name='y_')


def weight_variable(shape):
    initial = tf.truncated_normal(shape, stddev=0.1)
    return tf.Variable(initial)

def bias_variable(shape):
    initial = tf.constant(0.1, shape=shape)
    return tf.Variable(initial)

def conv2d(x, W):
    return tf.nn.conv2d(x, W, strides=[1,1,1,1], padding="SAME")

def max_pool_2x2(x):
    return tf.nn.max_pool(x, ksize=[1,2,2,1],
                          strides=[1,2,2,1], padding="SAME")

W_conv1 = weight_variable([5,5,1,32])
b_conv1 = bias_variable([32])
x_image = tf.reshape(x, [-1,28,28,1])

h_conv1 = tf.nn.relu(conv2d(x_image, W_conv1) + b_conv1)
h_pool1 = max_pool_2x2(h_conv1)

W_conv2 = weight_variable([5,5,32,64])
b_conv2 = weight_variable([64])

h_conv2 = tf.nn.relu(conv2d(h_pool1, W_conv2) + b_conv2)
h_pool2 = max_pool_2x2(h_conv2)

#第3层, 全连接层
#这层是拥有1024个神经元的全连接层
#W的第1维size为7*7*64,7*7是h_pool2输出的size,64是第2层输出神经元个数
W_fc1 = weight_variable([7*7*64, 1024])
b_fc1 = bias_variable([1024])

h_pool2_flat = tf.reshape(h_pool2, [-1, 7*7*64])
h_fc1 = tf.nn.relu(tf.matmul(h_pool2_flat, W_fc1) + b_fc1)

keep_prob = tf.placeholder("float32",name='keep_prob')
h_fc1_drop = tf.nn.dropout(h_fc1, keep_prob)

W_fc2 = weight_variable([1024, 10])
b_fc2 = bias_variable([10])

y_conv = tf.nn.softmax(tf.matmul(h_fc1_drop, W_fc2) + b_fc2,name="y_conv")
y_conv2=tf.nn.softmax(tf.matmul(h_fc1, W_fc2) + b_fc2,name="y_conv2")
cross_entropy = -tf.reduce_sum(y_ * tf.log(y_conv))
train_step = tf.train.AdamOptimizer(1e-4).minimize(cross_entropy)
correct_predict = tf.equal(tf.argmax(y_conv, 1), tf.argmax(y_, 1))
accuracy = tf.reduce_mean(tf.cast(correct_predict, "float32"))

sess.run(tf.initialize_all_variables())

#开始训练模型,循环20000次,每次随机从训练集中抓取50幅图像
for i in range(20000):
  batch = mnist.train.next_batch(50)
  if i%100 == 0:
    train_accuracy = accuracy.eval(feed_dict={
        x:batch[0], y_: batch[1], keep_prob: 1.0})
    print ("step %d, training accuracy %g" % (i, train_accuracy))
  train_step.run(feed_dict={x: batch[0], y_: batch[1], keep_prob: 0.5})
  
print ("test accuracy %g" % accuracy.eval(feed_dict={
x:mnist.test.images, y_:mnist.test.labels, keep_prob:1.0}))

#保存为pb文件
constant_graph = graph_util.convert_variables_to_constants(sess, sess.graph_def, ["y_conv2"])
with tf.gfile.FastGFile('./Model_pb/grf.pb', mode='wb') as f:f.write(constant_graph.SerializeToString())

#二 Android studio配置
##1.在Android studio新建Android项目
注意:API最好大于18,因为Trace.beginSection(),Trace.endSection()调用的API最低为18。

##2.把训练好的pb文件放入Android项目app/src/main/assets下,若不存在assets目录,右键main->new->Directory,输入assets。

##3.将TensoFlow的jar包和so库放在app/libs文件夹下
(1).可从这下载 https://github.com/PanJinquan/Mnist-tensorFlow-AndroidDemo/tree/master/app/libs libtensorflow_inference.so和libandroid_tensorflow_inference_java.jar ;也可自己用bazel编译出so和jar文件。
(2).在/app/libs下新建armeabi-v7a文件夹,并将libtensorflow_inference.so放进去。 (文件夹名称 与 ARM处理器名称 相同即可)
(3).将libandroid_tensorflow_inference_java.jar放在/app/libs下,并且右键“add as Libary”。

目录

##4.app\build.gradle配置
(1).在defaultConfig中添加

ndk {
         abiFilters "armeabi-v7a"
}

(2).在android节点下添加soureSets,用于制定jniLibs的路径

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

(3).在dependencies中(若没有则)增加TensoFlow编译的jar文件libandroid_tensorflow_inference_java.jar

implementation files('libs/libandroid_tensorflow_inference_java.jar')

build.gradle

##5.在gradle.properties中添加下面一行

android.useDeprecatedNdk=true

#三 模型调用
##1. 新建类tsf.java,在这个类里面进行模型的调用,并且获取输出

package com.example.lenovo.android_tensorflow;

import android.content.res.AssetManager;
import android.graphics.Bitmap;
import android.os.Trace;
import android.util.Log;

import org.tensorflow.contrib.android.TensorFlowInferenceInterface;

public class tsf {

    static {
        //加载库文件
        System.loadLibrary("tensorflow_inference");
    }
    private static final String MODEL_FILE = "file:///android_asset/grf.pb";
    //数据的维度
    private static final int HEIGHT = 28;
    private static final int WIDTH = 28;
    private static final int MAXL = 10;

    //模型中输入变量的名称
    private static final String inputName = "x";
    //用于存储的模型输入数据
    private float[] inputs = new float[HEIGHT * WIDTH];

    //模型中输出变量的名称
    private static final String outputName = "y_conv2";
    //用于存储模型的输出数据,0-9
    private float[] outputs = new float[MAXL];

	TensorFlowInferenceInterface inferenceInterface;
    tsf(AssetManager assetManager) {
        //接口定义
        inferenceInterface = new TensorFlowInferenceInterface(assetManager,MODEL_FILE);
    }

	 public static float[] bitmapToFloatArray(Bitmap bitmap){
        int height = bitmap.getHeight();
        int width = bitmap.getWidth();
        // 计算缩放比例
        float scaleWidth = ((float) 28) / width;
        float scaleHeight = ((float) 28) / height;
        Matrix matrix = new Matrix();
        matrix.postScale(scaleWidth, scaleHeight);
        bitmap = Bitmap.createBitmap(bitmap, 0, 0, width, height, matrix, true);
        height = bitmap.getHeight();
        width = bitmap.getWidth();
        float[] result = new float[height*width];
        int k = 0;
        //行优先
        for(int j = 0;j < height;j++){
            for (int i = 0;i < width;i++){
                int argb = bitmap.getPixel(i,j);
                int r = Color.red(argb);
                int g = Color.green(argb);
                int b = Color.blue(argb);
                int a = Color.alpha(argb);
                //由于是灰度图,所以r,g,b分量是相等的。
                assert(r==g && g==b);
                result[k++] = r / 255.0f;
            }
        }
        return result;
    }
    
    //返回数组中最大值的索引
    public int argmax(float output[]){
        int maxIndex=0;
        for(int i=1;i<MAXL;++i){
            maxIndex=output[i]>output[maxIndex]? i: maxIndex;
        }
        return maxIndex;
    }

   


    //获得预测结果
    public int  getAddResult(Bitmap bitmap) {

        float[] pxs = bitmapToFloatArray(bitmap);
        Trace.beginSection("feed");
        inferenceInterface.feed(inputName, pxs,1, 784);
        Trace.endSection();


        //获得模型输出结果
        Trace.beginSection("run");
        String[] outputNames = new String[] {outputName};
        inferenceInterface.run(outputNames);
        Trace.endSection();

        //将输出结果存放到outputs中
        Trace.beginSection("fetch");
        inferenceInterface.fetch(outputName, outputs);
        Trace.endSection();

        //类似于tf.argmax()的功能,寻找output中最大值的index
        return argmax(outputs);
    }


}

##2.在MainActivity中使用tsf类
可在其它函数里调用tsf,获得识别结果
将已完成预处理的图片放进/app/src/main/res/drawable中


        tsf m=new tsf(getAssets());
        Bitmap bitmap= BitmapFactory.decodeResource(getResources(),R.drawable.pratice1_1);
        int result=m.getAddResult(bitmap);
        Log.i("MainActivity","*********** the digit is :    "+result);


最后,感谢相关博客参照学习:https://blog.csdn.net/guyuealian/article/details/79672257

  • 2
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
大学生参加学科竞赛有着诸多好处,不仅有助于个人综合素质的提升,还能为未来职业发展奠定良好基础。以下是一些分析: 首先,学科竞赛是提高专业知识和技能水平的有效途径。通过参与竞赛,学生不仅能够深入学习相关专业知识,还能够接触到最新的科研果和技术发展趋势。这有助于拓展学生的学科视野,使其对专业领域有更深刻的理解。在竞赛过程中,学生通常需要解决实际问题,这锻炼了他们独立思考和解决问题的能力。 其次,学科竞赛培养了学生的团队合作精神。许多竞赛项目需要团队协作来完,这促使学生学会有效地与他人合作、协调分工。在团队合作中,学生们能够学到如何有效沟通、共同制定目标和分工合作,这对于日后进入职场具有重要意义。 此外,学科竞赛是提高学生综合能力的一种途径。竞赛项目通常会涉及到理论知识、实际操作和创新思维等多个方面,要求参赛者具备全面的素质。在竞赛过程中,学生不仅需要展现自己的专业知识,还需要具备创新意识和解决问题的能力。这种全面的综合能力培养对于未来从事各类职业都具有积极作用。 此外,学科竞赛可以为学生提供展示自我、树立信心的机会。通过比赛的舞台,学生有机会展现自己在专业领域的优势,得到他人的认可和赞誉。这对于培养学生的自信心和自我价值感非常重要,有助于他们更加积极主动地投入学习和未来的职业生涯。 最后,学科竞赛对于个人职业发展具有积极的助推作用。在竞赛中脱颖而出的学生通常能够引起企业、研究机构等用人单位的关注。获得竞赛奖项不仅可以作为个人履历的亮点,还可以为进入理想的工作岗位提供有力的支持。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值