【Android机器学习实战】1、用 MLKIT 机器学习库做图片分类

一、添加MLKIT机器学习库

首先,新建 FlowerClassifierApp 程序,项目github代码详见

MLKIT 是机器学习套件,其提供了预训练的模型,可识别600类图像。在 build.gradle(app) 中添加 implementation 'com.google.mlkit:image-labeling:17.0.7' 依赖

在 activity_main.xml 中设置如下布局:

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="vertical"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent">

        <ImageView
            android:id="@+id/imageToLabel"
            android:layout_width="match_parent"
            android:layout_height="match_parent" />

        <Button
            android:id="@+id/btnTest"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_gravity="center"
            android:text="Label Image" />

        <TextView
            android:id="@+id/txtOutput"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_gravity="start|top"
            android:ems="10" />
    </LinearLayout>

</androidx.constraintlayout.widget.ConstraintLayout>

activity_main.xml 布局设置后,效果如下:

在这里插入图片描述

然后,在 app 中新建 assetFolder,示例如下:

在这里插入图片描述

在网上下载图片,并放置在 app/assets/flower1.jpg 路径,示例如下:

在这里插入图片描述

放置后,效果如下:

在这里插入图片描述

二、实现图像分类

在 MainActivity 中初始化各控件,并利用 MLKIT 机器学习库,读取图像,做分类,代码如下:

package com.bignerdranch.android.flowerclassifierapp

import android.content.Context
import android.graphics.Bitmap
import android.graphics.BitmapFactory
import android.os.Bundle
import android.util.Log
import android.widget.Button
import android.widget.ImageView
import android.widget.TextView
import androidx.appcompat.app.AppCompatActivity
import com.google.mlkit.vision.common.InputImage
import com.google.mlkit.vision.label.ImageLabeling
import com.google.mlkit.vision.label.defaults.ImageLabelerOptions
import java.io.IOException

class MainActivity : AppCompatActivity() {
    
    
    private val TAG = "MainActivity"
    override fun onCreate(savedInstanceState: Bundle?) {
    
    
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        val img: ImageView = findViewById(R.id.imageToLabel)
        val fileName = "flower1.jpg"
        val bitmap: Bitmap? = assetsToBitmap(fileName)
        bitmap?.apply {
    
     img.setImageBitmap(this) }
        val txtOutput: TextView = findViewById(R.id.txtOutput)
        val btn: Button = findViewById(R.id.btnTest)
        btn.setOnClickListener {
    
    
            val labeler = ImageLabeling.getClient(ImageLabelerOptions.DEFAULT_OPTIONS) // 实例化 labeler
            val image = InputImage.fromBitmap(bitmap!!, 0)
            var outputText = ""
            labeler.process(image).addOnSuccessListener {
    
     labels ->
                for (label in labels) {
    
    
                    val text = label.text
                    val confidence = label.confidence
                    outputText += "$text : $confidence\n"
                }
                txtOutput.text = outputText
            }.addOnFailureListener {
    
     e ->
                Log.e(TAG, "failed $e")
            }
        }
    }
}

// extension function to get bitmap from assets
fun Context.assetsToBitmap(fileName: String): Bitmap? {
    
    
    return try {
    
    
        with(assets.open(fileName)) {
    
    
            BitmapFactory.decodeStream(this)
        }
    } catch (e: IOException) {
    
    
        null
    }
}

运行后,输入自然图片,其分类结果为花的 confidence 为 0.97,分类结果为 Sky 的 confidence 为 0.71,效果如下:

在这里插入图片描述

运行后,输入猫的图片,Cat 的 confidence 为 0.99,Dog 的 confidence 为 0.71,分类效果如下:

在这里插入图片描述

猜你喜欢

转载自blog.csdn.net/jiaoyangwm/article/details/127138450