iOS 物件偵測指南

「物件偵測器」工作可讓您偵測多個實體是否存在和位置 物件的種類。舉例來說,物件偵測器可以找出 圖片。以下操作說明會示範如何在 iOS 中使用物件偵測器工作。 您可以在 GitHub 取得本操作說明中所述的程式碼範例。

如要查看這項工作的實際運作情形,請參閱這個網頁 示範。適用對象 進一步瞭解 請參閱 總覽

程式碼範例

MediaPipe 工作範例程式碼是物件的基本實作 iOS 版偵測器應用程式。這個範例使用實體 iOS 裝置的相機 持續偵測物件,也可能使用裝置上的圖片和影片 靜態偵測物件

你可以將這個應用程式做為起點,開始使用 iOS 應用程式,也可以參照這個應用程式 做出決定物件偵測器程式碼範例 GitHub

下載程式碼

以下說明如何建立範例的本機副本 git 指令列工具編寫程式碼。

如要下載範例程式碼,請按照下列步驟操作:

  1. 使用下列指令複製 git 存放區:

    git clone https://github.com/google-ai-edge/mediapipe-samples
    
  2. 您也可以設定 Git 執行個體來使用稀疏結帳功能, 僅限物件偵測器範例應用程式的檔案:

    cd mediapipe
    git sparse-checkout init --cone
    git sparse-checkout set examples/object_detection/ios/
    

建立範例程式碼的本機版本後,您可以安裝 MediaPipe 工作程式庫,使用 Xcode 開啟專案,然後執行應用程式。適用對象 操作說明,請參閱 iOS 設定指南

重要元件

下列檔案包含物件偵測器範例的重要程式碼 應用程式:

設定

本節說明設定開發環境的重要步驟,以及 程式碼專案,即可使用物件偵測器。如需設定 使用 MediaPipe 工作 (包括平台版本) 的開發環境 規定,請參閱 iOS 設定指南

依附元件

物件偵測器會使用 MediaPipeTasksVision 程式庫 (必須安裝) 開發應用程式這個程式庫同時與 Swift 和 Objective-C 應用程式相容 且不需要額外設定任何特定語言

如需在 macOS 上安裝 CocoaPods 的操作說明,請參閱 CocoaPods 安裝指南。 有關如何建立包含所需 Pod 的 Podfile 的操作說明 請參閱使用 CocoaPods

使用下列程式碼在 Podfile 中新增 MediaPipeTasksVision Pod:

target 'MyObjectDetectorApp' do
  use_frameworks!
  pod 'MediaPipeTasksVision'
end

如果您的應用程式包含單元測試目標,請參閱設定指南: iOS,進一步瞭解設定方式 您的 Podfile

型號

MediaPipe 物件偵測器工作需要經過訓練且彼此相容的模型 透過這項工作如要進一步瞭解 物件偵測工具,請參閱工作總覽模型 專區

選取並下載模型,然後用 Xcode 將模型新增到專案目錄。 如需將檔案新增至 Xcode 專案的操作說明,請參閱管理 Xcode 中的檔案和資料夾 專案

使用 BaseOptions.modelAssetPath 屬性指定模型的路徑 。如需程式碼範例,請參閱下一節。

建立工作

您可以呼叫其中一項初始化器來建立物件偵測器工作。 ObjectDetector(options:) 初始化器會設定設定選項的值 包括執行模式、顯示名稱語言代碼、結果數量上限、信賴水準 門檻、類別許可清單和拒絕清單

如果您不需要透過自訂設定初始化物件偵測器 您可以使用 ObjectDetector(modelPath:) 初始化器建立 使用預設選項的物件偵測工具。進一步瞭解設定 選項,請參閱設定總覽

物件偵測器工作支援 3 種輸入資料類型:靜態圖片、影片檔案 和即時影像串流根據預設,ObjectDetector(modelPath:) 會初始化 靜態圖片如要初始化工作以處理影片 檔案或直播影片串流,請使用 ObjectDetector(options:) 指定影片 或即時串流執行模式使用直播模式時, objectDetectorLiveStreamDelegate 設定選項,以便啟用 物件偵測工具,會以非同步方式將偵測結果傳送給委派代表。

選擇與執行中模式對應的分頁,瞭解如何建立工作 然後執行推論

Swift

圖片

import MediaPipeTasksVision

let modelPath = Bundle.main.path(forResource: "model",
                                      ofType: "tflite")

let options = ObjectDetectorOptions()
options.baseOptions.modelAssetPath = modelPath
options.runningMode = .image
options.maxResults = 5

let objectDetector = try ObjectDetector(options: options)
    

影片

import MediaPipeTasksVision

let modelPath = Bundle.main.path(forResource: "model",
                                      ofType: "tflite")

let options = ObjectDetectorOptions()
options.baseOptions.modelAssetPath = modelPath
options.runningMode = .video
options.maxResults = 5

let objectDetector = try ObjectDetector(options: options)
    

直播

import MediaPipeTasksVision

// Class that conforms to the `ObjectDetectorLiveStreamDelegate` protocol and
// implements the method that the object detector calls once it
// finishes performing detection on each input frame.
class ObjectDetectorResultProcessor: NSObject, ObjectDetectorLiveStreamDelegate {

  func objectDetector(
    _ objectDetector: ObjectDetector,
    didFinishDetection objectDetectionResult: ObjectDetectorResult?,
    timestampInMilliseconds: Int,
    error: Error?) {
    // Process the detection result or errors here.
  }
}

let modelPath = Bundle.main.path(forResource: "model",
                                      ofType: "tflite")

let options = ObjectDetectorOptions()
options.baseOptions.modelAssetPath = modelPath
options.runningMode = .liveStream
options.maxResults = 5

// Assign an object of the class to the `objectDetectorLiveStreamDelegate`
// property.
let processor = ObjectDetectorResultProcessor()
options.objectDetectorLiveStreamDelegate = processor

let objectDetector = try ObjectDetector(options: options)
    

Objective-C

圖片

@import MediaPipeTasksVision;

NSString *modelPath = [[NSBundle mainBundle] pathForResource:@"model"
                                                      ofType:@"tflite"];

MPPObjectDetectorOptions *options = [[MPPObjectDetectorOptions alloc] init];
options.baseOptions.modelAssetPath = modelPath;
options.runningMode = MPPRunningModeImage;
options.maxResults = 5;

MPPObjectDetector *objectDetector =
      [[MPPObjectDetector alloc] initWithOptions:options error:nil];
    

影片

@import MediaPipeTasksVision;

NSString *modelPath = [[NSBundle mainBundle] pathForResource:@"model"
                                                      ofType:@"tflite"];

MPPObjectDetectorOptions *options = [[MPPObjectDetectorOptions alloc] init];
options.baseOptions.modelAssetPath = modelPath;
options.runningMode = MPPRunningModeVideo;
options.maxResults = 5;

MPPObjectDetector *objectDetector =
      [[MPPObjectDetector alloc] initWithOptions:options error:nil];
    

直播

@import MediaPipeTasksVision;

// Class that conforms to the `ObjectDetectorLiveStreamDelegate` protocol and
// implements the method that the object detector calls once it
// finishes performing detection on each input frame.

@interface APPObjectDetectorResultProcessor : NSObject 

@end

@implementation MPPObjectDetectorResultProcessor

-   (void)objectDetector:(MPPObjectDetector *)objectDetector
    didFinishDetectionWithResult:(MPPObjectDetectorResult *)ObjectDetectorResult
         timestampInMilliseconds:(NSInteger)timestampInMilliseconds
                           error:(NSError *)error {

    // Process the detection result or errors here.

}

@end

NSString *modelPath = [[NSBundle mainBundle] pathForResource:@"model"
                                                      ofType:@"tflite"];

MPPObjectDetectorOptions *options = [[MPPObjectDetectorOptions alloc] init];
options.baseOptions.modelAssetPath = modelPath;
options.runningMode = MPPRunningModeLiveStream;
options.maxResults = 5;

// Assign an object of the class to the `objectDetectorLiveStreamDelegate`
// property.
APPObjectDetectorResultProcessor *processor = [APPObjectDetectorResultProcessor new];
options.objectDetectorLiveStreamDelegate = processor;

MPPObjectDetector *objectDetector =
      [[MPPObjectDetector alloc] initWithOptions:options error:nil];
    

設定選項

這項工作有下列 iOS 應用程式設定選項:

選項名稱 說明 值範圍 預設值
runningMode 設定任務的執行模式。在架構中 模式:

圖片:單一圖片輸入模式。

VIDEO:影片已解碼的影格模式。

LIVE_STREAM:輸入串流模式 擷取的資訊等。在此模式下, resultListener 設定接聽程式來接收結果 以非同步方式載入物件
{RunningMode.image, RunningMode.video, RunningMode.liveStream} RunningMode.image
displayNamesLocales 設定標籤語言,供 工作模型的中繼資料 (如有)。以下項目的預設值為 en: 英語。您可以在自訂模型的中繼資料中加入經本地化的標籤 使用 TensorFlow Lite Metadata Writer API 語言代碼 en
maxResults 將最高分數偵測結果的選用數量上限設為 傳回。 任何正數 -1 (傳回所有結果)
scoreThreshold 設定預測分數門檻,此門檻會覆寫 模型中繼資料 (如有)低於這個值的結果遭到拒絕。 任何浮點值 未設定
categoryAllowlist 設定允許使用的類別名稱清單 (選用)。如果非空白 如果偵測結果出的類別名稱不在這個組合中,系統就會將其 過濾掉。系統會忽略重複或不明的類別名稱。 這個選項與 categoryDenylist 互斥, 這兩個都會造成錯誤。 任何字串 未設定
categoryDenylist 設定不允許使用的類別名稱清單 (選填)。如果 非空白的偵測結果,如果偵測結果中屬於這個組合的類別名稱,系統就會加以篩選 。系統會忽略重複或不明的類別名稱。這個選項會互相影響 只使用 categoryAllowlist 且同時使用兩者都會發生錯誤。 任何字串 未設定

直播設定

當執行模式設為即時串流時,物件偵測器會要求 額外的 objectDetectorLiveStreamDelegate 設定選項 讓偵測工具以非同步方式提供偵測結果。委派代表 會實作 objectDetector(_objectDetector:didFinishDetection:timestampInMilliseconds:error:) 方法,物件偵測器在處理完 的每個影格

選項名稱 說明 值範圍 預設值
objectDetectorLiveStreamDelegate 啟用物件偵測器,以非同步方式接收偵測結果: 即時串流模式類別的執行個體必須設為此屬性 實作 objectDetector(_:didFinishDetection:timestampInMilliseconds:error:) 方法。 不適用 未設定

準備資料

您必須先將輸入圖片或影格轉換為 MPImage 物件。 並傳送給物件偵測器MPImage 支援不同類型的 iOS 圖片 並且可在任何執行模式中使用,以便進行推論。如要 關於「MPImage」的資訊,請參閱 MPImage API

根據您的用途和執行模式,選擇 iOS 圖片格式 應用程式需要。MPImage 接受 UIImageCVPixelBufferCMSampleBuffer iOS 圖片格式。

UIImage

UIImage 格式非常適合下列執行模式:

  • 圖片:應用程式套件、使用者圖片庫或檔案系統的圖片,格式為 UIImage 張圖片可轉換成 MPImage 物件。

  • 影片:使用 AVAssetImageGenerator 將影片影格擷取到 CGImage 格式,然後轉換為 UIImage 張圖片。

Swift

// Load an image on the user's device as an iOS `UIImage` object.

// Convert the `UIImage` object to a MediaPipe's Image object having the default
// orientation `UIImage.Orientation.up`.
let image = try MPImage(uiImage: image)
    

Objective-C

// Load an image on the user's device as an iOS `UIImage` object.

// Convert the `UIImage` object to a MediaPipe's Image object having the default
// orientation `UIImageOrientationUp`.
MPImage *image = [[MPPImage alloc] initWithUIImage:image error:nil];
    

本範例使用預設值來初始化 MPImage UIImage.Orientation.Up 方向。您可以使用任一支援的任一種初始化 MPImage UIImage.Orientation 輕鬆分配獎金物件偵測工具不支援鏡像螢幕方向,例如 .upMirrored.downMirrored.leftMirrored.rightMirrored

如要進一步瞭解 UIImage,請參閱 UIImage Apple 開發人員 說明文件

CVPixelBuffer

CVPixelBuffer 格式非常適合會產生影格的應用程式 並使用 iOS CoreImage 處理流程

CVPixelBuffer 格式非常適合下列執行模式:

  • 圖片:應用程式在經過處理後產生 CVPixelBuffer 張圖片 使用 iOS 的 CoreImage 架構,可傳送至 執行映像檔執行模式

  • 影片:您可以將影片影格轉換為 CVPixelBuffer 格式 然後再傳送到物件偵測器的視訊模式

  • 直播:系統可能會轉換使用 iOS 相機產生影格的應用程式。 轉換成 CVPixelBuffer 格式進行處理,才能傳送到 處於直播模式的物件偵測器。

Swift

// Obtain a CVPixelBuffer.

// Convert the `CVPixelBuffer` object to a MediaPipe's Image object having the default
// orientation `UIImage.Orientation.up`.
let image = try MPImage(pixelBuffer: pixelBuffer)
    

Objective-C

// Obtain a CVPixelBuffer.

// Convert the `CVPixelBuffer` object to a MediaPipe's Image object having the
// default orientation `UIImageOrientationUp`.
MPImage *image = [[MPPImage alloc] initWithUIImage:image error:nil];
    

如要進一步瞭解 CVPixelBuffer,請參閱 CVPixelBuffer Apple 顯像組件 說明文件

CMSampleBuffer

CMSampleBuffer 格式會儲存統一媒體類型的媒體樣本, 也很適合使用直播模式iOS 攝影機的即時影格 由 iOS 以 CMSampleBuffer 格式非同步提供 AVCaptureVideoDataOutput.

Swift

// Obtain a CMSampleBuffer.

// Convert the `CMSampleBuffer` object to a MediaPipe's Image object having the default
// orientation `UIImage.Orientation.up`.
let image = try MPImage(sampleBuffer: sampleBuffer)
    

Objective-C

// Obtain a `CMSampleBuffer`.

// Convert the `CMSampleBuffer` object to a MediaPipe's Image object having the
// default orientation `UIImageOrientationUp`.
MPImage *image = [[MPPImage alloc] initWithSampleBuffer:sampleBuffer error:nil];
    

如要進一步瞭解 CMSampleBuffer,請參閱 CMSampleBuffer Apple 顯像組件 說明文件

執行工作

如要執行物件偵測器,請使用已指派的 detect() 方法 執行模式:

  • 靜態圖片:detect(image:)
  • 影片:detect(videoFrame:timestampInMilliseconds:)
  • 直播:detectAsync(image:)

以下程式碼範例顯示瞭如何在以下環境中執行物件偵測器的基本範例: 不同的跑步模式

Swift

圖片

let objectDetector.detect(image:image)
    

影片

let objectDetector.detect(videoFrame:image)
    

直播

let objectDetector.detectAsync(image:image)
    

Objective-C

圖片

MPPObjectDetectorResult *result = [objectDetector detectInImage:image error:nil];
    

影片

MPPObjectDetectorResult *result = [objectDetector detectInVideoFrame:image          timestampInMilliseconds:timestamp error:nil];
    

直播

BOOL success = [objectDetector detectAsyncInImage:image
                          timestampInMilliseconds:timestamp
                                            error:nil];
    

物件偵測器程式碼範例顯示這些模式的實作方式 進一步瞭解 detect(image:)detect(videoFrame:)detectAsync(image:)。程式碼範例可讓使用者在 可能不適用於您的用途的處理模式。

注意事項:

  • 以影片模式或直播模式執行時,您必須同時提供 「物件偵測器」工作的輸入框時間戳記。

  • 在圖片或影片模式中執行時,物件偵測器工作會封鎖 直到完成處理輸入圖片或影格為止。目的地: 為避免封鎖目前的執行緒,請在背景執行處理作業 使用 iOS 的執行緒 調度NSOperation 架構。

  • 在直播模式下執行時,物件偵測器工作會立即傳回 但不會封鎖目前的執行緒該函式會叫用 objectDetector(_objectDetector:didFinishDetection:timestampInMilliseconds:error:) 方法與偵測結果通訊。 物件偵測器會在專屬序列以非同步方式叫用這個方法 調度佇列。針對在使用者介面顯示結果,派出 結果傳送到主要佇列。如果detectAsync 物件偵測器工作正忙於處理其他工作 頁框,物件偵測器會忽略新的輸入畫面。

處理及顯示結果

執行推論時,物件偵測器工作會傳回 ObjectDetectorResult 物件,用來描述輸入圖片中存在的物件。

以下範例顯示這項工作的輸出資料範例:

ObjectDetectorResult:
 Detection #0:
  Box: (x: 355, y: 133, w: 190, h: 206)
  Categories:
   index       : 17
   score       : 0.73828
   class name  : dog
 Detection #1:
  Box: (x: 103, y: 15, w: 138, h: 369)
  Categories:
   index       : 17
   score       : 0.73047
   class name  : dog

下圖是工作輸出內容的視覺化呈現:

物件偵測器範例程式碼示範如何顯示偵測結果 請參閱程式碼範例