一、TensorFlow  Lite

TensorFlow Lite 是用于移动设备和嵌入式设备的轻量级解决方案。TensorFlow Lite 支持 Android、iOS 甚至树莓派等多种平台。

二、tflite格式

TensorFlow 生成的模型是无法直接给移动端使用的,需要离线转换成.tflite文件格式。

tflite 存储格式是 flatbuffers。

FlatBuffers 是由Google开源的一个免费软件库,用于实现序列化格式。它类似于Protocol Buffers、Thrift、Apache Avro。

因此,如果要给移动端使用的话,必须把 TensorFlow 训练好的 protobuf 模型文件转换成 FlatBuffers 格式。官方提供了 toco 来实现模型格式的转换。

三、API

TensorFlow Lite 提供了 C ++ 和 Java 两种类型的 API。无论哪种 API 都需要加载模型和运行模型。

而 TensorFlow Lite 的 Java API 使用了 Interpreter 类(解释器)来完成加载模型和运行模型的任务。后面的例子会看到如何使用 Interpreter。

四、TensorFlow Lite实现手写数字识别

下面的 demo 中已经包含了 mnist.tflite 模型文件。(如果没有的话,需要自己训练保存成pb文件,再转换成tflite 格式)

对于一个识别类,首先需要初始化 TensorFlow Lite 解释器,以及输入、输出。
    // The tensorflow lite file
private lateinit var tflite: Interpreter // Input byte buffer
private lateinit var inputBuffer: ByteBuffer // Output array [batch_size, 10]
private lateinit var mnistOutput: Array<FloatArray> init { try {
tflite = Interpreter(loadModelFile(activity)) inputBuffer = ByteBuffer.allocateDirect(
BYTE_SIZE_OF_FLOAT * DIM_BATCH_SIZE * DIM_IMG_SIZE_X * DIM_IMG_SIZE_Y * DIM_PIXEL_SIZE)
inputBuffer.order(ByteOrder.nativeOrder())
mnistOutput = Array(DIM_BATCH_SIZE) { FloatArray(NUMBER_LENGTH) }
Log.d(TAG, "Created a Tensorflow Lite MNIST Classifier.")
} catch (e: IOException) {
Log.e(TAG, "IOException loading the tflite file failed.")
} }

从 asserts 文件中加载 mnist.tflite 模型:

    /**
* Load the model file from the assets folder
*/
@Throws(IOException::class)
private fun loadModelFile(activity: Activity): MappedByteBuffer { val fileDescriptor = activity.assets.openFd(MODEL_PATH)
val inputStream = FileInputStream(fileDescriptor.fileDescriptor)
val fileChannel = inputStream.channel
val startOffset = fileDescriptor.startOffset
val declaredLength = fileDescriptor.declaredLength
return fileChannel.map(FileChannel.MapMode.READ_ONLY, startOffset, declaredLength)
}

真正识别手写数字是在 classify() 方法:

val digit = mnistClassifier.classify(Bitmap.createScaledBitmap(paintView.bitmap, PIXEL_WIDTH, PIXEL_WIDTH, false))

classify() 方法包含了预处理用于初始化 inputBuffer、运行 mnist 模型、识别出数字。

    /**
* Classifies the number with the mnist model.
*
* @param bitmap
* @return the identified number
*/
fun classify(bitmap: Bitmap): Int { if (tflite == null) {
Log.e(TAG, "Image classifier has not been initialized; Skipped.")
} preProcess(bitmap)
runModel()
return postProcess()
} /**
* Converts it into the Byte Buffer to feed into the model
*
* @param bitmap
*/
private fun preProcess(bitmap: Bitmap?) { if (bitmap == null || inputBuffer == null) {
return
} // Reset the image data
inputBuffer.rewind() val width = bitmap.width
val height = bitmap.height // The bitmap shape should be 28 x 28
val pixels = IntArray(width * height)
bitmap.getPixels(pixels, 0, width, 0, 0, width, height) for (i in pixels.indices) {
// Set 0 for white and 255 for black pixels
val pixel = pixels[i]
// The color of the input is black so the blue channel will be 0xFF.
val channel = pixel and 0xff
inputBuffer.putFloat((0xff - channel).toFloat())
}
} /**
* Run the TFLite model
*/
private fun runModel() = tflite.run(inputBuffer, mnistOutput) /**
* Go through the output and find the number that was identified.
*
* @return the number that was identified (returns -1 if one wasn't found)
*/
private fun postProcess(): Int { for (i in 0 until mnistOutput[0].size) {
val value = mnistOutput[0][i]
if (value == 1f) {
return i
}
} return -1
}

对于 Android 有一个地方需要注意,必须在 app 模块的 build.gradle 中添加如下的语句,否则无法加载模型。

android {
......
aaptOptions {
noCompress "tflite"
}
}

效果:

五、总结

本文 demo 的 github 地址:https://github.com/fengzhizi715/TFLite-MnistDemo

当然,也可以跑一下官方的例子:https://github.com/tensorflow/tensorflow/tree/master/tensorflow/lite/examples/android/app

虽然准确度都不咋地。。。

更多有趣的TensorFlow Lite示例:https://www.tensorflow.org/lite/examples/

参考链接:https://www.jianshu.com/p/e96f80c80e43

 

TensorFlow Lite for Android示例的更多相关文章

  1. TensorFlow Lite demo——就是为嵌入式设备而存在的,底层调用NDK神经网络API,注意其使用的tf model需要转换下,同时提供java和C++ API,无法使用tflite的见后

    Introduction to TensorFlow Lite TensorFlow Lite is TensorFlow’s lightweight solution for mobile and ...

  2. android NDK 神经网络API——是给tensorflow lite调用的底层API,应用开发者使用tensorflow lite即可

    eural Networks API In this document show more Understanding the Neural Networks API Runtime Neural N ...

  3. object detection模型转换成TensorFlow Lite,在Android应用

    环境 tensorflow = 1.12.0 bazel = 0.18.1 ubuntu = 16.04 python = 3.6.2 安装 bazel (0.18.1) 如果tensorflow是1 ...

  4. 移动端目标识别(3)——使用TensorFlow Lite将tensorflow模型部署到移动端(ssd)之Running on mobile with TensorFlow Lite (写的很乱,回头更新一个简洁的版本)

    承接移动端目标识别(2) 使用TensorFlow Lite在移动设备上运行         在本节中,我们将向您展示如何使用TensorFlow Lite获得更小的模型,并允许您利用针对移动设备优化 ...

  5. 移动端目标识别(1)——使用TensorFlow Lite将tensorflow模型部署到移动端(ssd)之TensorFlow Lite简介

    平时工作就是做深度学习,但是深度学习没有落地就是比较虚,目前在移动端或嵌入式端应用的比较实际,也了解到目前主要有 caffe2,腾讯ncnn,tensorflow,因为工作用tensorflow比较多 ...

  6. 在 Flutter 中使用 TensorFlow Lite 插件实现文字分类

    如果您希望能有一种简单.高效且灵活的方式把 TensorFlow 模型集成到 Flutter 应用里,那请您一定不要错过我们今天介绍的这个全新插件 tflite_flutter.这个插件的开发者是 G ...

  7. Tensorflow Lite从入门到精通

    TensorFlow Lite 是 TensorFlow 在移动和 IoT 等边缘设备端的解决方案,提供了 Java.Python 和 C++ API 库,可以运行在 Android.iOS 和 Ra ...

  8. 谷歌发布 TensorFlow Lite [官方网站,文档]

    机器学习社区:http://tensorflow123.com/ 简介 TensorFlow Lite TensorFlow Lite 是 TensorFlow 针对移动和嵌入式设备的轻量级解决方案. ...

  9. 移动端目标识别(2)——使用TENSORFLOW LITE将TENSORFLOW模型部署到移动端(SSD)之TF Lite Developer Guide

    TF Lite开发人员指南 目录: 1 选择一个模型 使用一个预训练模型 使用自己的数据集重新训练inception-V3,MovileNet 训练自己的模型 2 转换模型格式 转换tf.GraphD ...

随机推荐

  1. C++中vector小学习,顺便查了下<stdio.h>(或<cstdio>)

    今天看书,邻桌在看<C++ Primer>,拿过来看了一会儿.以前比较少用vector容器,看了下后,瞬间觉得好腻害的样子,就想试一下.嗯,就是试一下而已.(代码可能网上都差不多,有参考) ...

  2. 《转载》仅需3分钟,你就能明白Kafka的工作原理

    仅需3分钟,你就能明白Kafka的工作原理 周末无聊刷着手机,某宝网 App 突然蹦出来一条消息“为了回馈老客户,女朋友买一送一,活动仅限今天!”. 买一送一还有这种好事,那我可不能错过!忍不住立马点 ...

  3. ROS融合IMU笔记

    ROS官网有一个叫robot_pose_ekf的包,是专门处理传感器融合的包,具体介绍:http://wiki.ros.org/robot_pose_ekf 其中主要功能是订阅主题包括odom(里程计 ...

  4. 2017 ACM/ICPC Asia Regional Shenyang Online E number number number 题解

    分析: 当n=1时ans=4=f(5)-1; n=2,ans=12=f(7)-1; n=3,ans=33=f(9)-1; 于是大胆猜想ans=f(2*k+3)-1. 之后用矩阵快速幂求解f(n)即可, ...

  5. ElasticSearch6.3.2 集群做节点冷(warm) 热(hot) 分离

    拿一个小规模的5节点ES集群做冷热分离尝试,它上面已经有60多个索引,有些索引按月.每月生成一个索引,随着数据的不断写入,历史数据(只需保留三个月数据,三个月之前的数据视为历史数据)越来越占磁盘空间和 ...

  6. sql server删除重复记录只保留一条

    今天遇到一个历史导入数据重复的问题,于是要删除重复的记录,一开始想用子查询的方式找到要删除记录的id删除,后来发现DELETE语句可以直接用外连接,这样更加简单,效率也更高. delete sys_p ...

  7. 三、hexo+github搭建个人博客的主题配置

    更换博客主题 主题可参考:https://hexo.io/themes/ hexo默认主题:Landscape 示例主题:Next 下载Next主题 进入Blog所在目录,输入下载命令 #进入Blog ...

  8. 使用VS Code远程开发

    今天看到园子里的一篇文章:VS Code Remote 发布!开启远程开发新时代,简单的看了一下,它可以直接利用本地的环境远程开发,最直接的好处有: 在部署相同的操作系统上进行开发,或者使用更大或更专 ...

  9. Jackson 序列化/反序列化时忽略某属性

    https://www.iteye.com/blog/wwwcomy-2397340 博客分类: Spring jacksonread_onlyjsonignore  基于Spring MVC的RES ...

  10. juc包下四大并发工具

    juc.CountDownLatch 闭锁 一个线程在等待一组线程后再恢复执行 await()等待其他线程执行完毕 被等待线程执行完毕后计数器-1 如何知道其他线程执行完了? 计数器,若一组线程为,C ...