• 首页 首页 icon
  • 工具库 工具库 icon
    • IP查询 IP查询 icon
  • 内容库 内容库 icon
    • 快讯库 快讯库 icon
    • 精品库 精品库 icon
    • 问答库 问答库 icon
  • 更多 更多 icon
    • 服务条款 服务条款 icon

Tensorflowlite图像识别模型--安卓端部署教程

武飞扬头像
出门吃三碗饭
帮助3

前言:

(1)如果文章对大家有帮助的话,可以关注公众号 AI知识物语 来获取第一手文章信息资料,以及相应资源项目地址
(2)本文章后续将在 B站 出门吃三碗饭 账号下更新讲解视频,可以同时观看食用

Abstract:

本文将通过介绍使用TensorflowLite框架,利用AndroidStudio工具来实现识别模型的移动端部署(获取方式在文末)。

1.Introduction:

因为最近有粉丝有反应的一个需求,训练好了一个模型如何迁移到移动端使用,于是我忙活了三四天,有了此文~

2.RelatedWorks:

TensorflowLite官网,很好的学习文档
AndroidStudio工具安装教程
TensorflowLite相关案例项目Github

3.Method:

3.1

本文以tensorflow代码为例子(pytorch代码同理,格式为pt),粉丝提供的代码是使用keras代码在Kaggle写的一个猫狗识别python脚本。
首先要做的是通过保存训练好的模型,并将其转换为tflite 格式。

import tensorflow as tf

#加载模型 tensorflow训练好保存的h5模型
model = tf.keras.models.load_model('M:\Edit\pythonProject1\cat_and_dog\model_design.h5')

#使用 convert()  from_keras_model(model) 方法进行转换
converter = tf.lite.TFLiteConverter.from_keras_model(model)
tflite_model = converter.convert()

#保存新的模型,下面是地址
open('M:\Edit\pythonProject1\cat_and_dog\detect3.tflite', 'wb').write(tflite_model)

代码注释如上,补充下:
小编在第一次运行的时候会报错,表示from_keras_model这个函数找不到。

我这里给出的答案是试着调一下tensorflow的版本,我这里的版本是2.11.0.

3.2

打开Android,新建一个项目EmptyActivity

学新通

然后按照下图,设置好目录,下面这几个是比较重要的文件。

学新通

下面我一个一个来分析

assets文件,在新建的时候,其右下角是没有标志的,我们需要右键按照下图操作,把其设为Resources Root.

这个文件用来存放模型的标签,lable

学新通

同理,ml文件,也需要设置为ResourcesRoot,用来存放训练好的模型文件

学新通

重点

创建两个Activity(创建一个也可以),MainActivity用来执行识别的活动,SplashActivity是页面加载的活动(可以忽略)

对应两个Activity创建它们的布局文件,就是layout下面的两个文件,这里主要介绍MainAcitivity和activity_main.xml

学新通

根据下面页面的需求,我们开始编程

学新通

1代表的ImageView组件,2代表的是TextView组件,34代表是Button组件

Talk is cheap.Show me your code

<ImageView
        android:id="@ id/imgPredict"
        android:layout_width="373dp"
        android:layout_height="400dp"
        android:layout_marginTop="20dp"
        android:scaleType="fitXY"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        android:src="https://blog.csdn.net/qq_40514113/article/details/@drawable/logo1" />

    <TextView
        android:id="@ id/textResultPredict"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="1:选择照片2:点击识别"
        android:textColor="#100F0F"
        android:textSize="20sp"
        app:layout_constraintBottom_toTopOf="@ id/buttonPredict"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@ id/imgPredict" />

    <Button
        android:id="@ id/buttonPredict"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="识别"
        android:background="#EFB9B9"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toEndOf="@ id/buttonSelect"
        app:layout_constraintTop_toBottomOf="@ id/textResultPredict" />

    <Button
        android:id="@ id/buttonSelect"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="选择"
        android:background="#EFB9B9"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toStartOf="@ id/buttonPredict"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@id/textResultPredict" />

效果图如下

学新通

现在页面已经设计完成了,我们需要去使用Kotlin完成各个组件的业务逻辑。

首先我们需要绑定四个组件,分别代表2个按钮button,图片imagview和textView

 selectImage = findViewById(R.id.buttonSelect)
 letsPredict = findViewById(R.id.buttonPredict)
 imageToPredict = findViewById(R.id.imgPredict)
 resultPredict = findViewById(R.id.textResultPredict)

我们给两个按钮写上相应点击的业务逻辑。通俗来说就是用户只要点击了按钮,就能触发哪些业。

下面的一个是选择图片按钮,点击后通过intent跳转到手机本地相册,并返回图片;一个是识别图片按钮,先加载再调用模型对返回的图片进行实时的识别。

selectImage.setOnClickListener(View.OnClickListener {
            Log.d("mssg", "button pressed")
            var intent: Intent = Intent(Intent.ACTION_GET_CONTENT)
            intent.type = "image/*"

            startActivityForResult(intent, 100)
        })

letsPredict.setOnClickListener(View.OnClickListener {
            var resized = Bitmap.createScaledBitmap(bitmap, 224, 224, true)
            val model = com.example.iclassify.ml.MobilenetV110224Quant.newInstance(this)

            var tbuffer = TensorImage.fromBitmap(resized)
            var byteBuffer = tbuffer.buffer

加载标签文件labels.txt

Care!这里的标签文件需要与训练的模型的标签相互对应,顺序不能随意改变!

val labels =
            application.assets.open("labels.txt").bufferedReader().use { it.readText() }.split("\n")

下面这段代码分别用来处理输入以及输出流数据,以及最后模型资源的释放

// Creates inputs for reference.
            val inputFeature0 =
                TensorBuffer.createFixedSize(intArrayOf(1, 224, 224, 3), DataType.UINT8)
            inputFeature0.loadBuffer(byteBuffer)

// Runs model inference and gets result.
            val outputs = model.process(inputFeature0)
            val outputFeature0 = outputs.outputFeature0AsTensorBuffer

            var max = getMax(outputFeature0.floatArray)

            resultPredict.setText(labels[max])

// Releases model resources if no longer used.
            model.close()

4.Experiments:

学新通

5.Conclusion:

学新通

学新通

识别结果还不错!就先到这里了。

6.References:

TensorflowLite官网,很好的学习文档
AndroidStudio工具安装教程
TensorflowLite相关案例项目Github

额外知识补充

如何在AndroidStudio中向虚拟机传照片?

View–>ToolWindow–>Device File Explorer

学新通

找到sdcard文件,并在其目录下传照片

学新通

上传完照片后,记得重新启动虚拟机才会有效果!!!

学新通

重新启动后,在首页输入 File,点击File文件并进入相册,Image,即可看到自己上传的文件

学新通

最后如果想要完整项目的话可以在公众号AI知识物语 输入关键字:图像识别项目 来获取项目地址

我的项目模型可以识别1001个物种或者物品,包括动物,以及生活用品,下面是部分标签。

学新通

学新通

在教室写完这篇文章的时候,隔壁教室应该是给一个同学过SurpriseBirthdayParty,哈哈,也祝那个同学生日快乐()

这篇好文章是转载于:学新通技术网

  • 版权申明: 本站部分内容来自互联网,仅供学习及演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,请提供相关证据及您的身份证明,我们将在收到邮件后48小时内删除。
  • 本站站名: 学新通技术网
  • 本文地址: /boutique/detail/tanhgcajec
系列文章
更多 icon
同类精品
更多 icon
继续加载