编写一个移动设备对象检测 iOS 应用

了解如何使用 ONNX Runtime 构建一个 iOS 对象检测应用。此应用会持续检测您的 iOS 设备后置摄像头看到的帧中的对象并显示

  • 检测到的对象的类别(类型)
  • 检测到的对象的边界框
  • 推理置信度

此应用使用了预训练的量化 MobileNet SSD V1 模型。

此示例在很大程度上基于 Google Tensorflow lite - 对象检测示例

以下是该应用的示例屏幕截图

Screenshot showing iOS objection detection app

目录

先决条件

  • Xcode 12.5 及以上版本(最好是最新版本)
  • 有效的 Apple Developer ID
  • 带有摄像头的真实 iOS 设备(最好是 iphone 12/iphone 12 pro)
  • Xcode 命令行工具 xcode-select --install
  • 克隆 onnxruntime-inference-examples 源代码仓库

为移动部署准备模型

  1. 创建单独的 Python 环境,以便此应用的依赖项与其他 Python 项目隔离

    conda create -n ios-app Python=3.8
    conda activate ios-app
    
  2. 安装 Python 依赖项

    cd <onnxruntime-inference-example-root>/mobile/examples/object_detection/ios/ORTObjectDetection
    pip install -r ./prepare_model.requirements.txt
    

    requirements 文件包含进行下一步模型转换所需的 onnxruntime、tf2onnx 和 tensorflow python 包。

  3. 下载模型并将其转换为 ORT 格式

    ./prepare_model.sh
    

    该脚本

    • 下载原始 tflite 模型及其模型元数据 labelmap.txt
    • 将其转换为 ONNX 格式
    • 进一步将其转换为 ORT 格式,ONNX Mobile Runtime 可以执行此格式的模型

    脚本输出一个 ModelsAndData 目录,其中包含 ORT 格式的模型 ssd_mobilenet_v1.all.ort 和模型标签数据文件 labelmap.txt

    此模型的转换是一个两阶段过程。原始模型为 tflite 格式。首先使用 tf2onnx 转换器 将其转换为 ONNX 格式。

    然后使用 onnx 到 ort 转换器 将模型转换为 ORT 格式。

    除了生成 ORT 格式的模型,转换脚本还输出一个操作符配置文件

创建 iOS 应用

  1. 安装 CocoaPods

    sudo gem install cocoapods
    
  2. 安装依赖项并生成工作区文件

    cd <onnxruntime-inference-example-root>/mobile/examples/object_detection/ios/
    pod install
    

    Podfile 文件包含 onnxruntime-objc 依赖项,这是包含 Objective C API 的 pod。

    在此步骤结束时,您应该在 mobile/examples/object_detection/ios 目录中看到一个名为 ORTObjectDetection.xcworkspace 的文件。

    本教程使用 ONNX Runtime 移动版的预构建包之一。如果您的目标环境有特殊要求,您也可以构建自己的自定义运行时。要在 iOS 应用中包含自定义构建的 ONNX Runtime,请参阅自定义 iOS 包

  3. 构建项目

    在 Xcode 中打开 <onnxruntime-inference-example-root>/mobile/examples/object_detection/ios/ORTObjectDetection.xcworkspace

    Signing & Capabilities 工作区设置中选择您的 Development Team

    点击 Product -> Build for Running 编译应用。

  4. 运行应用

    连接您的 iOS 设备并运行应用。您需要授予应用使用设备摄像头的权限。

    您应该在设备上看到带有 ONNX Runtime 标志的应用。运行应用会打开摄像头并执行对象检测。《插入屏幕截图》