ARTICLE DETAIL

资讯详情

深耕编程入门与网站建设的一线实战洞察。

TensorFlow Lite 如何构建一个用摄像头做实时目标检测的 Android 应用?

TensorFlow Lite 如何构建一个用摄像头做实时目标检测的 Android 应用? TensorFlow Lite 如何构建一个用摄像头做实时目标检测的 Android 应用【免费下载链接】tensorflowAn Open Source Machine Learning Framework for Everyone项目地址: https://gitcode.com/GitHub_Trending/te/tensorflow如果你的任务是在 Android 设备上读取摄像头画面、逐帧运行目标检测模型并把识别出的物体框画在画面上TensorFlow Lite 官方提供了完整文档和示例工程来支持这个场景。官方教程 Object detection with Android 描述了一个持续检测设备摄像头帧中物体的应用模型对每一帧输出检测到的物体列表、每个物体的边界框位置和一个 0~1 的置信度分数。完成这篇文章后你可以先跑通官方示例应用确认环境可用再把目标检测功能按文档步骤集成到自己的 Android 应用中。注意一个硬前提示例使用摄像头必须运行在带摄像头的实体 Android 设备上不能用模拟器。环境要求以下要求来自教程文档的系统要求一节Android Studio 2021.1.1 (Bumblebee) 或更高版本Android SDK 31 或更高最低 Android 7.0 (SDK 24) 的实体设备并开启开发者模式文档同时说明示例代码使用 Android Studio 4.2.2 构建如果使用的 Studio 版本更低可以尝试把build.gradle中的 Android 插件版本从com.android.tools.build:gradle:4.2.2调整为4.1.2然后执行File Sync Project with Gradle Files重新同步而不是升级 Studio。运行官方示例确认环境可用获取示例代码示例代码位于tensorflow/examples仓库的lite/examples/object_detection/android目录。克隆整个仓库git clone https://github.com/tensorflow/examples.git可选如果只需要对象检测示例的文件可以配置 sparse checkout 减少检出内容cd examples git sparse-checkout init --cone git sparse-checkout set lite/examples/object_detection/android导入并构建项目打开 Android Studio选择File New Import Project。定位到示例目录下包含build.gradle的那一层目录.../examples/lite/examples/object_detection/android/选中该目录。如果 Android Studio 提示 Gradle Sync选择 OK。确认实体设备已通过 USB 连接并开启开发者模式点击绿色Run箭头运行。构建过程可能持续几分钟。判断构建成功的依据Android Studio 的Build Output状态面板显示BUILD SUCCESSFUL。运行后选择带摄像头的已连接设备App 启动后即可看到摄像头实时画面上的检测结果。把目标检测加到你自己的 Android 应用以下各节以示例应用为参照说明在自己的应用中添加同等功能所需的修改。添加模块依赖在使用 TensorFlow Lite 的 app 模块的build.gradle中添加依赖dependencies { ... implementation org.tensorflow:tensorflow-lite-task-vision:0.4.0 // Import the GPU delegate plugin Library for GPU inference implementation org.tensorflow:tensorflow-lite-gpu-delegate-plugin:0.4.0 implementation org.tensorflow:tensorflow-lite-gpu:2.9.0 }其中tensorflow-lite-task-vision是视觉 Task 库必选tensorflow-lite-gpu-delegate-plugin提供在 GPU 上运行的基础设施tensorflow-lite-gpu提供设备兼容性列表。之后在 Android Studio 中执行File Sync Project with Gradle Files同步依赖。准备模型模型文件.tflite应放在开发项目的src/main/assets目录。Task 库在只指定模型文件名时会自动到该目录查找所以文件名就是接口参数。教程基于 COCO 数据集训练的模型提供四个预训练模型可选模型COCO 2017 验证集 mAP说明EfficientDet-Lite025.69%轻量模型教程推荐尺寸与精度平衡较好EfficientDet-Lite130.55%中等规模EfficientDet-Lite233.97%更大规模MobileNetV1-SSD21%极轻量为 TensorFlow Lite 对象检测优化示例工程中多个模型由download_models.gradle在构建时自动下载并放入 assets 目录无需手动下载示例用modelName变量做模型选择val modelName when (currentModel) { MODEL_MOBILENETV1 - mobilenetv1.tflite MODEL_EFFICIENTDETV0 - efficientdet-lite0.tflite MODEL_EFFICIENTDETV1 - efficientdet-lite1.tflite MODEL_EFFICIENTDETV2 - efficientdet-lite2.tflite else - mobilenetv1.tflite }如果你的模型是自己转换的需注意 ObjectDetector API 的模型兼容性要求模型必须带 TFLite Model Metadata输入张量为[1 x height x width x 3]的 RGB 图像batch 固定为 1不支持批量输出必须是DetectionPostProcessop 的 4 个输出张量。初始化检测器并配置硬件加速初始化由设置选项、构建ObjectDetector对象两部分组成val optionsBuilder ObjectDetector.ObjectDetectorOptions.builder() .setScoreThreshold(threshold) .setMaxResults(maxResults) objectDetector ObjectDetector.createFromFileAndOptions( context, modelName, optionsBuilder.build())setScoreThreshold是预测置信度阈值setMaxResults限制每帧返回的最大结果数。硬件加速delegates可选。示例在setupObjectDetector()中按当前设置分支when (currentDelegate) { DELEGATE_CPU - { // Default } DELEGATE_GPU - { if (CompatibilityList().isDelegateSupportedOnThisDevice) { baseOptionsBuilder.useGpu() } else { objectDetectorListener?.onError(GPU is not supported on this device) } } DELEGATE_NNAPI - { baseOptionsBuilder.useNnapi() } }文档指出线程约束在主线程创建、后台线程使用的检测器可以用 CPU 和 NNAPI delegate但使用 GPU delegate 的检测器必须在初始化它的同一个线程上使用。从摄像头取帧并预处理模型以 EfficientDet-Lite0 为例接受 320 x 320、每像素 3 通道、每值 0~255 单字节的 Tensor。应用通过 CameraX 的ImageAnalysis从摄像头子系统取帧Task 库的ImageProcessor负责缩放、旋转和格式转换。示例的处理链是构建ImageAnalysis指定 4:3 宽高比、目标旋转角、只保留最新帧的背压策略输出格式为 RGBA_8888imageAnalyzer ImageAnalysis.Builder() .setTargetAspectRatio(AspectRatio.RATIO_4_3) .setTargetRotation(fragmentCameraBinding.viewFinder.display.rotation) .setBackpressureStrategy(ImageAnalysis.STRATEGY_KEEP_ONLY_LATEST) .setOutputImageFormat(OUTPUT_IMAGE_FORMAT_RGBA_8888) .build() ...把 analyzer 接到摄像头为每帧创建/复用 bitmap 缓冲并触发检测.also { it.setAnalyzer(cameraExecutor) { image - if (!::bitmapBuffer.isInitialized) { bitmapBuffer Bitmap.createBitmap( image.width, image.height, Bitmap.Config.ARGB_8888 ) } detectObjects(image) } }把图像像素拷入共享 bitmap 缓冲并记录旋转角度传给检测逻辑private fun detectObjects(image: ImageProxy) { //Copy out RGB bits to the shared bitmap buffer image.use {bitmapBuffer.copyPixelsFromBuffer(image.planes[0].buffer) } val imageRotation image.imageInfo.rotationDegrees objectDetectorHelper.detect(bitmapBuffer, imageRotation) }完成最终变换并生成TensorImageval imageProcessor ImageProcessor.Builder().add(Rot90Op(-imageRotation / 90)).build() // Preprocess the image and convert it into a TensorImage for detection. val tensorImage imageProcessor.process(TensorImage.fromBitmap(image))文档强调从摄像头取出的图像必须是 RGB 格式这是ImageProcessor的要求如果带 Alpha 通道其中的透明数据会被忽略。运行预测拿到正确格式的TensorImage后调用detect()val results objectDetector?.detect(tensorImage)摄像头连接后imageAnalyzer会随每一帧自动把数据送入模型实现连续实时检测。处理并展示结果示例通过监听器把结果从ObjectDetectorHelper传回 UICameraFragment实现DetectorListenerobjectDetectorListener.onResults( results, inferenceTime, tensorImage.height, tensorImage.width)override fun onResults( results: MutableListDetection?, inferenceTime: Long, imageHeight: Int, imageWidth: Int ) { activity?.runOnUiThread { fragmentCameraBinding.bottomSheetLayout.inferenceTimeVal.text String.format(%d ms, inferenceTime) // Pass necessary information to OverlayView for drawing on the canvas fragmentCameraBinding.overlay.setResults( results ?: LinkedListDetection(), imageHeight, imageWidth ) // Force a redraw fragmentCameraBinding.overlay.invalidate() } }每条预测包含物体边界框、类别标签和 0~1 的 Float 置信度分数1 为最高。文档的一般性说明低于 0.5 的预测可视为结论不确定但低分结果如何处理由你的应用自行决定。界面上的验证信号是底部面板显示每帧推理耗时%d ms预览窗口上画出物体边界框并标注类别名。ObjectDetector API 文档 中还给出了一份文档示例输出对 dogs.jpg 图像用 ssd mobilenet v1 模型可用来对照结果字段的形态Results: Detection #0 (red): Box: (x: 355, y: 133, w: 190, h: 206) Top-1 class: index : 17 score : 0.73828 class name : dog以上数值来自文档示例不同模型、画面下你的结果会不同不要把它当作固定预期。限制与可选分支Play services 运行时是可选分支Quickstart for Android 展示了另一条路径——通过 Google Play services 运行 TensorFlow Lite不打包 TFLite 库进 App。它要求依赖改为org.tensorflow:tensorflow-lite-task-vision-play-services:0.4.2与com.google.android.gms:play-services-tflite-gpu:16.1.0并在调用 API 前先用TfLiteVision.initialize(context, options)初始化 Play services 运行时失败时按示例回退到不带 GPU delegate 的初始化。该运行时只支持文档列出的硬件加速 delegate不支持实验性或已废弃的 API包括 custom ops。两条路径的系统要求也不完全相同Quickstart 标注 Android Studio 4.2、Android SDK 21按你实际选用的文档对照即可。必须实体设备两条路径的文档都明确示例使用摄像头需在实体设备上运行。模型输入格式只支持 RGB 输入、batch 为 1见上文模型兼容性要求。下一步文档给出的延伸方向了解 Task Library 支持的任务列表与 delegates 配置、TensorFlow Lite Delegates本文引用路径以教程文档链接为准以及 TensorFlow Lite in Google Play services 的完整限制与隐私说明。【免费下载链接】tensorflowAn Open Source Machine Learning Framework for Everyone项目地址: https://gitcode.com/GitHub_Trending/te/tensorflow创作声明:本文部分内容由AI辅助生成(AIGC),仅供参考
返回列表