// …
}
}
app/build.gradle
)中,在文件末尾添加一行内容。apply plugin: ‘com.android.application’
android {
// …
}
// 添加以下内容:
apply plugin: ‘com.google.gms.google-services’ // Google Play services Gradle plugin
在(应用级)Gradle 文件(通常是 app/build.gradle
)中,添加核心 Firebase SDK 的依赖项:
buildscript {
repositories {
// Check that you have the following line (if not, add it):
google() // Google’s Maven repository
}
dependencies {
…
// Add this line
classpath ‘com.google.gms:google-services:4.3.3’
}
}
allprojects {
…
repositories {
// Check that you have the following line (if not, add it):
google() // Google’s Maven repository
…
}
}
应用级 build.gradle(<项目>/<应用模块>/build.gradle
):
apply plugin: ‘com.android.application’
// Add this line
apply plugin: ‘com.google.gms.google-services’
dependencies {
// add the Firebase SDK for Google Analytics
implementation ‘com.google.firebase:firebase-analytics:17.2.2’
// add SDKs for any other desired Firebase products
// https://firebase.google.com/docs/android/setup#available-libraries
}
最后,按 IDE 中显示的栏中的“立即同步”:
同步您的应用以确保所有依赖项都具有必要的版本。
运行应用,向 Firebase 发送已成功集成 Firebase 的验证信息。
设备日志将显示说明初始化已完成的 Firebase 验证信息。如果我们是在具有网络访问权限的模拟器上运行应用,则 Firebase 控制台会通知说应用连接已完成。
使用 “ML KIT” 的 autoML 搭建训练发布模型
我这里使用的是使用 TensorFlow 的 flower-image 数据集,创建图像分类或标签模型,在训练了该模型后,将其用于应用程序中的设备上图像标签。
这个数据集又5种标签的雏菊,蒲公英,玫瑰,向日葵和郁金香花,这样后面的 app 就可以使用模型标识图像的标签之一。
下载花卉图像数据集。
转到 Firebase 控制台-> Machine Learning,然后单击 “AutoML” 。
现在,单击添加数据集。
给数据集命名并选择第二个选项,然后单击继续。
现在,单击浏览文件,然后为花朵图像数据集选择一个.zip文件,该文件已在前面的第一步中下载。
现在,等待所有三个步骤都已完成。
之后,点击训练模型
现在选择第三个选项(高精度),然后单击开始训练。
现在,等待模型训练完成。
在模型列表中单击第一个模型,并在模型名称上记下我们以后需要的名称
现在,就可以使用模型了
先查看一下刚刚训练完的模型的评估结果:
在 Android Studio 上编写 app 使用该模型
我们可以通过2种方式使用此模型
(1)远程(发布到firebase并在运行时从您的应用程序远程加载)
(2)本地(与应用程序下载并捆绑)
首先,通过单击“发布”按钮来发布模型,然后单击“下载”并将zip文件保存在所需的位置。
之后,解压缩下载的zip文件,然后复制所有三个文件。
现在转到Android Studio,然后
在应用程序上单击鼠标右键,选择“NEW”->“Folder”->“Assets”
然后单击完成。
现在,通过右键单击assss-> New-> Directory在assets文件夹中创建目录
给出一个名字,例如model,然后点击回车。
现在,将所有三个复制的文件粘贴到此文件夹中。
将以下内容添加到应用的build.gradle文件中,以确保Gradle在构建应用时不会压缩模型文件:
android {
// …
aaptOptions {
noCompress“ tflite”
}
}
如下所示:
现在,在应用程序级别build.gradle中为ML Kit Android库添加以下两个依赖项:
implementation ‘com.google.firebase:firebase-ml-vision:24.0.1’
implementation ‘com.google.firebase:firebase-ml-vision-automl:18.0.3’
现在添加一个Button,ImageView和TextView来选择图像,显示图像并在活动布局中显示带有谓词百分比的标签。
xmlns:android=“http://schemas.android.com/apk/res/android” android:layout_width=“match_parent” android:layout_height=“match_parent” android:background="@drawable/timg"> android:id="@+id/image" android:layout_width=“match_parent” android:layout_height=“wrap_content” android:layout_above="@+id/selectImage" android:layout_marginBottom=“50dp” />