Kotlin Android 第27天,从 0 到 ML - TensorFlow Lite -物体检测 (Object detection)

前言:

   物体检测是给定图像或视讯流,物件检测模型可以识别可能存在一组已知物件中的哪一个,并提供有关它们在图像中的位置的信息。
    

大纲 :

来看一下沙拉的物体检测codelab的实作

将 TensorFlow Lite 模型添加到assets文件夹

 salad.tflite
 

build.gradle(app)

dependencies {
   implementation 'org.tensorflow:tensorflow-lite-task-vision:0.2.0'}
}

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

在图像上设置和运行设备上的物件检测
只需 3 个简单的步骤,使用 3 个 API 即可加载和运行物件检测模型:

准备图像/流: TensorImage
创建检测器物件: ObjectDetector
连接上面的2个物件: detect(image)

创建检测器物件

private fun runObjectDetection(bitmap: Bitmap) {
    // Step 1: 创建图像物件
****    val image = TensorImage.fromBitmap(bitmap)

    // Step 2: 初始化检测器
    val options = ObjectDetector.ObjectDetectorOptions.builder()
        .setMaxResults(5)
        .setScoreThreshold(0.3f)
        .build()
    val detector = ObjectDetector.createFromFileAndOptions(
        this,
        "salad.tflite",
        options
    )

    // Step 3: 将图像馈送到检测器
    val results = detector.detect(image)

    // Step 4: 检测结果
    val resultToDisplay = results.map {
        // Get the top-1 category and craft the display text
        val category = it.categories.first()
        val text = "${category.label}, ${category.score.times(100).toInt()}%"

        // Create a data object to display the detection result
        DetectionResult(it.boundingBox, text)
    }
    // Draw the detection result on the bitmap and show it.
    val imgWithResult = drawDetectionResult(bitmap, resultToDisplay)
    runOnUiThread {
        inputImageView.setImageBitmap(imgWithResult)
    }
}

执行结果:
https://ithelp.ithome.com.tw/upload/images/20211002/20121643qPq7A1KHJt.png

参考:

https://codelabs.developers.google.com/tflite-object-detection-android


<<:  [day28] - Angular Component to Web Component

>>:  Day 17: SOLID 设计原则 — SRP (待改进中... )

Day 27:碰到困难问题,演算法也救不了?

上一回我们说旅行推销员问题(TSP)是一个NP困难问题,没有快速的演算法可以解决。 那一个问题怎样叫...

前人种树,後人乘凉之自动产生程序码片段 (上)

在前篇文章中介绍了写笔记的重要性,这篇文章则要介绍如何使用TAB或输入关键字後就会自动产生出范例程序...

《赖田捕手:追加篇》第 35 天:制造 Deploy to Heroku 按钮

第 35 天:制造 Deploy to Heroku 按钮 我打开信封,有张明信片在里面。明信片封面...

[DAY28]将Line讯息存入资料库(01)

#纪录主程序 def line_insert_record(record_list): #与post...