您可以使用 ML Kit 偵測並追蹤連續影片畫面中的物件。
將圖片傳送至 ML Kit 時,系統可偵測圖片中的最多五個物件以及圖片中每個物件的位置。在偵測影片串流中的物件時,每個物件都有一組專屬 ID,可用來追蹤影格之間的物件。另外,您也可以選擇啟用粗略的物件分類功能,將物件分類為廣泛的類別說明。
立即體驗
- 請試用範例應用程式,查看這個 API 的使用範例。
- 請參閱 Material Design 展示應用程式,瞭解這個 API 的端對端實作方式。
事前準備
- 在 Podfile 中加入下列機器學習套件 Pod:
pod 'GoogleMLKit/ObjectDetection', '3.2.0'
- 安裝或更新專案的 Pod 後,使用
.xcworkspace
開啟 Xcode 專案。Xcode 12.4 以上版本支援機器學習套件。
1. 設定物件偵測工具
如要偵測及追蹤物件,請先建立 ObjectDetector
的例項,並視需要指定您要從預設值變更的任何偵測工具設定。
使用
ObjectDetectorOptions
物件為您的用途設定物件偵測工具。您可以變更下列設定:物件偵測工具設定 偵測模式 .stream
(預設) |.singleImage
在串流模式 (預設) 中,物件偵測工具的延遲時間極短,但在偵測工具的最初叫用中,可能會產生不完整的結果 (例如未指定的定界框或類別)。此外,在串流模式下,偵測工具會將追蹤 ID 指派給物件,以便用來追蹤跨影格的物件。當您想要追蹤物件,或有低延遲的需要 (例如即時處理影片串流) 時,請使用這個模式。
在單一圖片模式中,物件偵測工具會在決定物件的定界框後傳回結果。如果您同時啟用分類功能,系統會在定界框和類別標籤都可供使用時,傳回結果。因此,偵測延遲時間可能較長。此外,在單一圖片模式中,系統不會指派追蹤 ID。如果延遲時間不重要,且您不想處理部分結果,請使用這個模式。
偵測及追蹤多個物件 false
(預設) |true
偵測並追蹤最多 5 個物件,或僅追蹤最顯眼的物件 (預設)。
分類物件 false
(預設) |true
是否將偵測到的物件分類為概略類別。 啟用時,物件偵測工具會將物件分為下列類別:時尚商品、食物、居家用品、地點和植物。
物件偵測與追蹤 API 已針對以下兩個核心用途進行最佳化處理:
- 即時偵測及追蹤相機觀景窗中最顯眼的物件。
- 偵測靜態圖片中的多個物件。
如要針對這些用途設定 API,請按照下列步驟操作:
Swift
// Live detection and tracking let options = ObjectDetectorOptions() options.shouldEnableClassification = true // Multiple object detection in static images let options = ObjectDetectorOptions() options.detectorMode = .singleImage options.shouldEnableMultipleObjects = true options.shouldEnableClassification = true
Objective-C
// Live detection and tracking MLKObjectDetectorOptions *options = [[MLKObjectDetectorOptions alloc] init]; options.shouldEnableClassification = YES; // Multiple object detection in static images MLKObjectDetectorOptions *options = [[MLKOptions alloc] init]; options.detectorMode = MLKObjectDetectorModeSingleImage; options.shouldEnableMultipleObjects = YES; options.shouldEnableClassification = YES;
- 取得
ObjectDetector
的執行個體:
Swift
let objectDetector = ObjectDetector.objectDetector() // Or, to change the default settings: let objectDetector = ObjectDetector.objectDetector(options: options)
Objective-C
MLKObjectDetector *objectDetector = [MLKObjectDetector objectDetector]; // Or, to change the default settings: MLKObjectDetector *objectDetector = [MLKObjectDetector objectDetectorWithOptions:options];
2. 準備輸入圖片
如要偵測及追蹤物件,請對每個圖片或影格執行以下動作。
如果啟用了串流模式,則必須從 CMSampleBuffer
建立 VisionImage
物件。
使用 UIImage
或 CMSampleBuffer
建立 VisionImage
物件。
如果您使用 UIImage
,請按照下列步驟操作:
- 使用
UIImage
建立VisionImage
物件。請務必指定正確的.orientation
。Swift
let image = VisionImage(image: UIImage) visionImage.orientation = image.imageOrientation
Objective-C
MLKVisionImage *visionImage = [[MLKVisionImage alloc] initWithImage:image]; visionImage.orientation = image.imageOrientation;
如果您使用 CMSampleBuffer
,請按照下列步驟操作:
-
指定
CMSampleBuffer
中包含的圖片資料方向。如何取得圖片方向:
Swift
func imageOrientation( deviceOrientation: UIDeviceOrientation, cameraPosition: AVCaptureDevice.Position ) -> UIImage.Orientation { switch deviceOrientation { case .portrait: return cameraPosition == .front ? .leftMirrored : .right case .landscapeLeft: return cameraPosition == .front ? .downMirrored : .up case .portraitUpsideDown: return cameraPosition == .front ? .rightMirrored : .left case .landscapeRight: return cameraPosition == .front ? .upMirrored : .down case .faceDown, .faceUp, .unknown: return .up } }
Objective-C
- (UIImageOrientation) imageOrientationFromDeviceOrientation:(UIDeviceOrientation)deviceOrientation cameraPosition:(AVCaptureDevicePosition)cameraPosition { switch (deviceOrientation) { case UIDeviceOrientationPortrait: return cameraPosition == AVCaptureDevicePositionFront ? UIImageOrientationLeftMirrored : UIImageOrientationRight; case UIDeviceOrientationLandscapeLeft: return cameraPosition == AVCaptureDevicePositionFront ? UIImageOrientationDownMirrored : UIImageOrientationUp; case UIDeviceOrientationPortraitUpsideDown: return cameraPosition == AVCaptureDevicePositionFront ? UIImageOrientationRightMirrored : UIImageOrientationLeft; case UIDeviceOrientationLandscapeRight: return cameraPosition == AVCaptureDevicePositionFront ? UIImageOrientationUpMirrored : UIImageOrientationDown; case UIDeviceOrientationUnknown: case UIDeviceOrientationFaceUp: case UIDeviceOrientationFaceDown: return UIImageOrientationUp; } }
- 使用
CMSampleBuffer
物件和方向建立VisionImage
物件:Swift
let image = VisionImage(buffer: sampleBuffer) image.orientation = imageOrientation( deviceOrientation: UIDevice.current.orientation, cameraPosition: cameraPosition)
Objective-C
MLKVisionImage *image = [[MLKVisionImage alloc] initWithBuffer:sampleBuffer]; image.orientation = [self imageOrientationFromDeviceOrientation:UIDevice.currentDevice.orientation cameraPosition:cameraPosition];
3. 處理圖片
將VisionImage
傳遞至物件偵測工具的影像處理方法之一。您可以使用非同步 process(image:)
方法或同步 results()
方法。
如何非同步偵測物件:
Swift
objectDetector.process(image) { objects, error in guard error == nil else { // Error. return } guard !objects.isEmpty else { // No objects detected. return } // Success. Get object info here. // ... }
Objective-C
[objectDetector processImage:image completion:^(NSArray* _Nullable objects, NSError * _Nullable error) { if (error == nil) { return; } if (objects.count == 0) { // No objects detected. return; } // Success. Get object info here. }];
如何同步偵測物件:
Swift
var objects: [Object] do { objects = try objectDetector.results(in: image) } catch let error { print("Failed to detect object with error: \(error.localizedDescription).") return } guard !objects.isEmpty else { print("Object detector returned no results.") return } // Success. Get object info here.
Objective-C
NSError *error; NSArray*objects = [objectDetector resultsInImage:image error:&error]; if (error == nil) { return; } if (objects.count == 0) { // No objects detected. return; } // Success. Get object info here.
4. 取得偵測到物件的相關資訊
如果呼叫影像處理器成功執行,則系統會呼叫Object
的清單到完成處理常式,或傳回清單 (視您呼叫的是非同步或同步方法而定)。
每個 Object
都包含下列屬性:
frame |
CGRect 表示物件在圖片中的位置。 |
trackingID |
一個整數可以識別圖片中的物件,或是單一圖片模式中的「nil」。 |
labels |
描述偵測工具傳回的物件標籤陣列。如果偵測工具選項 shouldEnableClassification 設為 false ,則此屬性為空白。 |
Swift
// objects contains one item if multiple object detection wasn't enabled. for object in objects { let frame = object.frame let trackingID = object.trackingID // If classification was enabled: let description = object.labels.enumerated().map { (index, label) in "Label \(index): \(label.text), \(label.confidence)" }.joined(separator:"\n") }
Objective-C
// The list of detected objects contains one item if multiple // object detection wasn't enabled. for (MLKObject *object in objects) { CGRect frame = object.frame; NSNumber *trackingID = object.trackingID; for (MLKObjectLabel *label in object.labels) { NSString *labelString = [NSString stringWithFormat: @"%@, %f, %lu", label.text, label.confidence, (unsigned long)label.index]; ... } }
提高可用性和效能
為提供最佳使用者體驗,請在應用程式中遵守下列規範:
- 物件偵測是否成功,取決於物件的視覺複雜程度。系統偵測物件時,如果只有少量的視覺功能,可能就必須佔滿圖片中較大的部分。建議您提供指示,讓系統針對要偵測的物件類型擷取輸入資訊。
- 使用分類時,如果您想偵測不會完全排除在支援類別中的物件,請針對未知物件實作特殊處理方式。
另請參閱質感設計採用機器學習技術的模式集合。
在即時應用程式中使用串流模式時,請遵循以下準則,以達到最佳畫面更新率:
- 請勿在串流模式下使用多個物件偵測功能,因為多數裝置無法產生適當的畫面速率。
- 如果不需要分類,請停用分類功能。
- 如要處理影格,請使用偵測工具的
results(in:)
同步 API。從AVCaptureVideoDataOutputSampleBufferDelegate
的captureOutput(_, didOutput:from:)
函式呼叫此方法,即可同步取得特定影片影格的結果。將AVCaptureVideoDataOutput
的alwaysDiscardsLateVideoFrames
保留為true
,以限制對偵測工具的呼叫。假如在偵測器執行期間有新的視訊畫面可用,系統就會捨棄該影格。 - 如果您使用偵測工具的輸出內容,為輸入圖片上的圖像重疊,請先透過 ML Kit 取得結果,然後透過單一步驟算繪圖像和疊加層。如此一來,每個處理的輸入影格只會轉譯一次到顯示途徑一次。如需範例,請參閱 ML Kit 快速入門導覽課程範例中的 updatePreviewOverlayViewWithLastFrame。