編寫一個移動物體檢測 iOS 應用程式

學習如何使用 ONNX Runtime 構建 iOS 物體檢測應用程式。此應用程式會持續檢測您的 iOS 裝置後置攝像頭所看到的幀中的物體,並顯示

  • 檢測到的物體的類別(型別)
  • 檢測到的物體的邊界框
  • 推理置信度

該應用程式使用預訓練的量化 MobileNet SSD V1 模型。

此示例主要基於 Google Tensorflow lite - 物體檢測示例

以下是該應用程式的示例截圖

Screenshot showing iOS objection detection app

目錄

先決條件

  • Xcode 12.5 及更高版本(最好是最新版本)
  • 有效的 Apple 開發者 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 格式
    • 進一步將其轉換為 ONNX Mobile Runtime 可執行的 ORT 格式

    該指令碼會輸出一個 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 標誌的應用程式。執行應用程式會開啟您的攝像頭並執行物體檢測。«插入截圖»