2026/4/6 18:09:00
网站建设
项目流程
DAMOYOLO-S模型Android端集成实战移动端实时检测应用开发如果你是一名Android开发者想在自己的App里加入实时物体检测功能比如识别摄像头里的猫猫狗狗、车辆行人但又担心模型太大、速度太慢那今天这个实战项目就是为你准备的。我们将把一个轻量级的检测模型——DAMOYOLO-S塞进你的Android手机里。整个过程从拿到模型文件开始到最终在屏幕上看到实时画出的检测框我会一步步带你走通。你不需要有深厚的机器学习背景只要熟悉Android开发就能跟着做出一个离线、快速、可用的检测应用。咱们的目标很明确让模型跑起来让检测框画出来。1. 准备工作认识DAMOYOLO-S与选择推理引擎在动手写代码之前我们得先搞清楚两件事我们要用的模型是什么来头以及我们打算用什么工具在手机里运行它。DAMOYOLO-S是一个专门为移动端和边缘设备设计的物体检测模型。它的核心优势就一个字轻。相比那些动辄几百兆的庞然大物它通过一系列精巧的设计比如更高效的网络结构和模型压缩技术在保持不错检测精度的同时大幅减少了计算量和模型体积。这意味着它在你的手机上能跑得更快耗电更少这正是我们做移动端应用最看重的。接下来是推理引擎的选择。你可以把它理解成模型的“翻译官”和“执行器”。模型本身比如.pt的PyTorch文件手机可不认识需要转换成手机能理解的格式并由一个高效的引擎来执行计算。在Android生态里主流的选择有这么几个TensorFlow Lite (TFLite)谷歌的亲儿子生态最完善文档和社区支持都很好。它提供了完整的工具链转换、优化、部署和易于使用的Java/C API。MNN阿里巴巴开源的移动端推理引擎一个很大的亮点是它对国内常见芯片如华为麒麟NPU的适配可能更友好性能优化也做得不错。ncnn腾讯优图开源的同样以高性能和轻量级著称在社区里口碑很好。怎么选呢对于刚接触移动端AI的开发者我通常建议从TensorFlow Lite开始。理由很简单上手最容易遇到问题网上能找到的解决方案最多而且它的模型转换工具TFLite Converter功能非常强大内置了多种优化选项能帮你把模型“修剪”得更适合手机。我们这次的实战就选用TFLite。所以我们的技术路线就确定了将DAMOYOLO-S模型转换为TFLite格式然后在Android App中集成TFLite运行时库调用它来完成推理。2. 模型获取与格式转换第一步我们需要拿到模型文件并完成转换。DAMOYOLO的官方代码库通常提供PyTorch格式.pt或.pth的预训练模型。我们的任务就是把它变成.tflite文件。2.1 获取PyTorch模型你可以从DAMOYOLO的官方GitHub仓库例如https://github.com/tinyvision/DAMO-YOLO找到模型下载链接。通常他们会提供在COCO数据集上预训练好的模型权重。下载一个你需要的版本比如damoyolo_tinynasL20_S.pt。2.2 搭建转换环境转换工作一般在电脑上完成。你需要一个Python环境。我强烈建议使用Anaconda来管理环境避免包版本冲突。# 创建一个新的Python环境例如叫 damo-convert conda create -n damo-convert python3.8 conda activate damo-convert # 安装PyTorch (请根据你的CUDA版本去PyTorch官网选择对应命令) # 例如对于CPU版本 pip install torch torchvision # 安装TensorFlow这是使用TFLite转换器的前提 pip install tensorflow # 克隆或下载DAMOYOLO的官方仓库如果需要其模型定义来加载权重 git clone https://github.com/tinyvision/DAMO-YOLO.git cd DAMO-YOLO pip install -r requirements.txt2.3 编写转换脚本这是最关键的一步。我们不能直接用标准的PyTorch到TFLite转换因为需要模拟一个真实的输入流程。下面是一个转换脚本的核心思路和代码框架# convert_to_tflite.py import torch import tensorflow as tf import numpy as np # 假设你能导入DAMOYOLO的模型定义 from models.damoyolo import DAMOYOLO def convert(): # 1. 加载PyTorch模型和权重 model_path path/to/your/damoyolo_tinynasL20_S.pt # 注意你需要根据DAMOYOLO仓库的说明来正确初始化模型并加载权重 # 这里是一个示例实际情况可能更复杂 model DAMOYOLO(...) checkpoint torch.load(model_path, map_locationcpu) model.load_state_dict(checkpoint[model]) model.eval() # 设置为评估模式 # 2. 创建一个示例输入dummy input # DAMOYOLO-S的输入尺寸通常是640x6403通道 dummy_input torch.randn(1, 3, 640, 640) # 3. 使用TorchScript跟踪模型生成中间表示 traced_model torch.jit.trace(model, dummy_input) # 4. 将TorchScript模型转换为ONNX格式TFLite转换常经过ONNX这一步 onnx_path damoyolo_s.onnx torch.onnx.export( traced_model, dummy_input, onnx_path, input_names[input], output_names[output], opset_version12 # 选择一个合适的ONNX算子集版本 ) print(fModel exported to {onnx_path}) # 5. 使用tf.lite.TFLiteConverter从ONNX转换 # 注意你可能需要先使用 onnx-tf 或 onnx2tf 等工具将ONNX转为TensorFlow SavedModel # 然后再用TFLiteConverter。或者也可以探索其他直接转换的工具链。 # 这里展示一个概念性流程 # converter tf.lite.TFLiteConverter.from_saved_model(tf_saved_model_dir) # converter.optimizations [tf.lite.Optimize.DEFAULT] # 启用默认优化如量化 # tflite_model converter.convert() # 6. 保存TFLite模型 # with open(damoyolo_s.tflite, wb) as f: # f.write(tflite_model) # print(TFLite model saved.) if __name__ __main__: convert()重要提示上述转换步骤是一个简化示意图。实际中DAMOYOLO这类现代检测模型的转换可能涉及自定义算子过程会复杂一些。你可能需要仔细阅读DAMOYOLO仓库的导出说明。使用onnxruntime等工具验证ONNX模型的正确性。考虑使用TensorFlow Lite Model Maker或寻求社区已转换好的模型来跳过复杂的转换坑。一个更可行的捷径是直接寻找是否已有开源项目提供了DAMOYOLO的TFLite版本。如果转换遇到困难这能节省大量时间。2.4 模型优化可选但推荐在转换时我们可以通过TFLite Converter进行优化让模型在手机上跑得更快、更小。量化Quantization将模型参数从32位浮点数FP32转换为8位整数INT8。这能显著减小模型体积、加快推理速度对精度影响通常很小。在转换脚本中设置converter.optimizations [tf.lite.Optimize.DEFAULT]即可启用默认量化。选择性量化如果担心全量化影响精度可以对部分层保持浮点计算。转换并优化完成后你会得到一个damoyolo_s_quantized.tflite文件把它放到我们Android项目的app/src/main/assets/目录下。如果没这个目录就新建一个。3. 搭建Android项目与集成TFLite打开Android Studio新建一个空项目选择“Empty Activity”模板即可。3.1 添加依赖打开app/build.gradle文件在dependencies块中添加TensorFlow Lite的依赖。dependencies { implementation org.tensorflow:tensorflow-lite:2.14.0 // 使用最新稳定版 implementation org.tensorflow:tensorflow-lite-gpu:2.14.0 // 可选用于GPU加速 implementation org.tensorflow:tensorflow-lite-support:0.4.4 // 可选提供一些图像预处理等工具 // ... 其他依赖 }tensorflow-lite-support库非常有用它包含了处理图像、文本等常见任务的工具类能简化我们的预处理代码。3.2 加载模型与初始化解释器我们创建一个单例类TFLiteDetector来管理模型。// TFLiteDetector.kt import android.content.Context import android.graphics.Bitmap import org.tensorflow.lite.Interpreter import org.tensorflow.lite.support.common.FileUtil import java.nio.ByteBuffer import java.nio.ByteOrder class TFLiteDetector private constructor(context: Context) { private var interpreter: Interpreter private val inputSize 640 // 模型输入尺寸 private val pixelSize 3 // RGB通道 private val inputShape intArrayOf(1, inputSize, inputSize, pixelSize) // NHWC格式 private val inputBuffer: ByteBuffer init { // 1. 从assets加载TFLite模型文件 val modelFile FileUtil.loadMappedFile(context, damoyolo_s_quantized.tflite) val options Interpreter.Options() // 可选设置线程数 options.setNumThreads(4) // 可选尝试启用GPU代理需要添加GPU依赖 // try { // options.addDelegate(GpuDelegate()) // } catch (e: Exception) { // Log.e(TAG, GPU delegate failed: ${e.message}) // } interpreter Interpreter(modelFile, options) // 2. 为输入创建ByteBuffer inputBuffer ByteBuffer.allocateDirect(1 * inputSize * inputSize * pixelSize * 4) // 4 bytes per float inputBuffer.order(ByteOrder.nativeOrder()) } companion object { private var instance: TFLiteDetector? null fun getInstance(context: Context): TFLiteDetector { return instance ?: synchronized(this) { instance ?: TFLiteDetector(context.applicationContext).also { instance it } } } } // 推理方法将在下一步实现 fun detect(bitmap: Bitmap): ListDetectionResult { // ... 预处理和推理 } }4. 实现图像预处理与推理模型需要固定尺寸640x640的输入且数据需要经过归一化等处理。我们接着完善detect方法。// 在TFLiteDetector类中添加 data class DetectionResult( val bbox: RectF, // 检测框坐标已转换回原始图像尺寸 val label: String, val score: Float ) fun detect(bitmap: Bitmap): ListDetectionResult { // 1. 预处理将Bitmap缩放、裁剪或填充到640x640并转换为RGB格式的Float数组 val resizedBitmap Bitmap.createScaledBitmap(bitmap, inputSize, inputSize, true) // 使用TFLite Support库简化预处理 val imageProcessor ImageProcessor.Builder() .add(ResizeOp(inputSize, inputSize, ResizeOp.ResizeMethod.BILINEAR)) // 缩放 .add(NormalizeOp(0f, 255f)) // 归一化到[0,1]或根据模型要求调整 .build() val tensorImage TensorImage(DataType.FLOAT32) tensorImage.load(resizedBitmap) val processedImage imageProcessor.process(tensorImage) // 2. 将处理后的数据复制到输入Buffer inputBuffer.rewind() processedImage.buffer.rewind() inputBuffer.put(processedImage.buffer) // 3. 准备输出容器 // DAMOYOLO-S的输出格式需要根据模型确定。常见的是[1, N, 6] // 其中N是检测框数量6代表[x_center, y_center, width, height, confidence, class_id] // 这里我们假设输出形状为[1, 8400, 6]YOLO系列常见 val outputShape interpreter.getOutputTensor(0).shape() val outputSize outputShape[1] * outputShape[2] // 例如 8400 * 6 val outputBuffer ByteBuffer.allocateDirect(outputSize * 4) // Float outputBuffer.order(ByteOrder.nativeOrder()) val outputs mapOfInt, Any(0 to outputBuffer) // 4. 运行推理 interpreter.runForMultipleInputsOutputs(arrayOf(inputBuffer), outputs) // 5. 后处理解析输出Buffer应用置信度阈值、非极大值抑制(NMS) outputBuffer.rewind() val floatArray FloatArray(outputSize) outputBuffer.asFloatBuffer().get(floatArray) val results mutableListOfDetectionResult() val confThreshold 0.5f val nmsThreshold 0.5f // 解析floatArray将其转换为DetectionResult对象列表 // 注意坐标需要从640x640空间转换回原始bitmap的空间 for (i in 0 until outputShape[1]) { // 遍历8400个预测 val confidence floatArray[i * 6 4] if (confidence confThreshold) continue val classId floatArray[i * 6 5].toInt() val label COCO_LABELS[classId] ?: Unknown // 需要定义COCO_LABELS数组 // 解析bbox (cx, cy, w, h)并转换为(x1, y1, x2, y2)格式 val cx floatArray[i * 6 0] val cy floatArray[i * 6 1] val w floatArray[i * 6 2] val h floatArray[i * 6 3] val x1 (cx - w / 2) * bitmap.width / inputSize val y1 (cy - h / 2) * bitmap.height / inputSize val x2 (cx w / 2) * bitmap.width / inputSize val y2 (cy h / 2) * bitmap.height / inputSize results.add(DetectionResult(RectF(x1, y1, x2, y2), label, confidence)) } // 6. 应用非极大值抑制(NMS)过滤重叠框 return nms(results, nmsThreshold) } // 简单的NMS实现IoU计算 private fun nms(boxes: ListDetectionResult, iouThreshold: Float): ListDetectionResult { val sortedBoxes boxes.sortedByDescending { it.score } val selected mutableListOfDetectionResult() while (sortedBoxes.isNotEmpty()) { val current sortedBoxes.first() selected.add(current) val iterator sortedBoxes.listIterator(1) while (iterator.hasNext()) { val next iterator.next() if (calculateIoU(current.bbox, next.bbox) iouThreshold) { iterator.remove() } } sortedBoxes.remove(current) } return selected } private fun calculateIoU(a: RectF, b: RectF): Float { val interLeft maxOf(a.left, b.left) val interTop maxOf(a.top, b.top) val interRight minOf(a.right, b.right) val interBottom minOf(a.bottom, b.bottom) if (interRight interLeft || interBottom interTop) return 0.0f val interArea (interRight - interLeft) * (interBottom - interTop) val areaA (a.right - a.left) * (a.bottom - a.top) val areaB (b.right - b.left) * (b.bottom - b.top) return interArea / (areaA areaB - interArea) }5. 连接摄像头与实时渲染最后我们把所有部分串起来。使用CameraX库来简化摄像头操作它提供了稳定且易于使用的API。5.1 配置CameraX和预览在MainActivity中设置摄像头预览。// MainActivity.kt import androidx.camera.core.* import androidx.camera.lifecycle.ProcessCameraProvider import androidx.camera.view.PreviewView import androidx.core.content.ContextCompat class MainActivity : AppCompatActivity() { private lateinit var previewView: PreviewView private lateinit var overlayView: OverlayView // 一个自定义View用于绘制检测框 private lateinit var detector: TFLiteDetector override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) previewView findViewById(R.id.preview_view) overlayView findViewById(R.id.overlay_view) detector TFLiteDetector.getInstance(this) startCamera() } private fun startCamera() { val cameraProviderFuture ProcessCameraProvider.getInstance(this) cameraProviderFuture.addListener({ val cameraProvider cameraProviderFuture.get() val preview Preview.Builder().build().also { it.setSurfaceProvider(previewView.surfaceProvider) } // 选择后置摄像头 val cameraSelector CameraSelector.DEFAULT_BACK_CAMERA // 创建图像分析用例在这里进行推理 val imageAnalysis ImageAnalysis.Builder() .setTargetResolution(Size(640, 640)) // 设置分析分辨率匹配模型输入 .setBackpressureStrategy(ImageAnalysis.STRATEGY_KEEP_ONLY_LATEST) // 只处理最新帧 .build() .also { it.setAnalyzer(ContextCompat.getMainExecutor(this)) { imageProxy - // 在这里处理每一帧图像 processImage(imageProxy) } } try { cameraProvider.unbindAll() cameraProvider.bindToLifecycle(this, cameraSelector, preview, imageAnalysis) } catch (e: Exception) { Log.e(TAG, Use case binding failed, e) } }, ContextCompat.getMainExecutor(this)) } private fun processImage(imageProxy: ImageProxy) { // 将ImageProxy转换为Bitmap注意处理旋转和格式 val bitmap imageProxy.toBitmap() // 需要实现一个toBitmap的扩展函数 if (bitmap ! null) { // 在子线程运行检测避免阻塞UI CoroutineScope(Dispatchers.Default).launch { val results detector.detect(bitmap) // 将结果传回主线程更新UI withContext(Dispatchers.Main) { overlayView.setResults(results) overlayView.invalidate() // 触发重绘 } } } imageProxy.close() // 非常重要释放图像缓冲区 } }5.2 实现绘制检测框的OverlayView// OverlayView.kt import android.content.Context import android.graphics.* import android.util.AttributeSet import android.view.View class OverlayView JvmOverloads constructor( context: Context, attrs: AttributeSet? null, defStyleAttr: Int 0 ) : View(context, attrs, defStyleAttr) { private val paint Paint().apply { color Color.RED style Paint.Style.STROKE strokeWidth 4f textSize 32f } private val textPaint Paint().apply { color Color.WHITE style Paint.Style.FILL textSize 32f } private var results: ListDetectionResult emptyList() fun setResults(newResults: ListDetectionResult) { results newResults } override fun onDraw(canvas: Canvas) { super.onDraw(canvas) for (result in results) { // 绘制矩形框 canvas.drawRect(result.bbox, paint) // 绘制标签和置信度 val labelText ${result.label} ${String.format(%.2f, result.score)} canvas.drawText(labelText, result.bbox.left, result.bbox.top - 10, textPaint) } } }5.3 布局文件!-- activity_main.xml -- FrameLayout xmlns:androidhttp://schemas.android.com/apk/res/android android:layout_widthmatch_parent android:layout_heightmatch_parent androidx.camera.view.PreviewView android:idid/preview_view android:layout_widthmatch_parent android:layout_heightmatch_parent / com.yourpackage.OverlayView android:idid/overlay_view android:layout_widthmatch_parent android:layout_heightmatch_parent / /FrameLayout6. 总结与后续优化跟着上面的步骤走下来一个基本的移动端实时检测应用框架就搭好了。运行应用你应该能看到摄像头预览并且检测到的物体会被红框标出来。整个过程最花时间的部分可能是模型转换和环境配置一旦打通后面的集成和开发就会顺畅很多。实际用起来你可能会发现一些可以优化的点。比如在低端设备上全分辨率640x640的推理可能有点吃力导致帧率不高。这时候可以尝试把ImageAnalysis的分辨率调低一点比如480x480虽然精度会有一点点损失但流畅度会提升很多。另外TFLiteDetector里的后处理NMS如果直接用Kotlin实现在大量检测框时也可能成为瓶颈可以考虑用更高效的实现或者看看TFLite Support库有没有提供相关的Op。如果想进一步提升体验可以研究一下TFLite的GPU代理或者针对特定芯片的神经网络APINNAPI代理它们能利用手机的硬件加速让推理速度再上一个台阶。最后别忘了处理手机旋转、前后摄像头切换这些细节让应用更健壮。获取更多AI镜像想探索更多AI镜像和应用场景访问 CSDN星图镜像广场提供丰富的预置镜像覆盖大模型推理、图像生成、视频生成、模型微调等多个领域支持一键部署。