您可以使用 ML Kit 偵測並追蹤連續影格中的物件。
將圖片傳送至 ML Kit 時,ML Kit 會偵測圖片中最多五個物件,以及圖片中每個物件的位置。偵測影片串流中的物件時,每個物件都有專屬 ID,可用來追蹤影格之間的物件。您也可以選擇啟用概略的物件分類,為具有廣泛類別說明的物件加上標籤。
立即體驗
- 使用範例應用程式,查看這個 API 的使用範例。
- 如需這個 API 的端對端實作,請參閱 Material Design 展示應用程式。
事前準備
- 在 Podfile 中加入下列 ML Kit pod:
pod 'GoogleMLKit/ObjectDetection', '3.2.0'
- 安裝或更新專案的 Pod 後,請使用其
.xcworkspace
開啟 Xcode 專案。Xcode 12.4 以上版本支援 ML Kit。
1. 設定物件偵測工具
如要偵測及追蹤物件,請先建立 ObjectDetector
的執行個體,並視需要指定您要從預設值變更的任何偵測工具設定。
依據
ObjectDetectorOptions
物件設定用途的物件偵測工具。您可以變更下列設定:物件偵測器設定 偵測模式 .stream
(預設) |.singleImage
在串流模式 (預設) 中,物件偵測工具會以極短的延遲時間執行,但可能會在前幾次叫用偵測工具中產生不完整的結果,例如未指定的定界框或類別。此外,在串流模式下,偵測工具會為物件指派追蹤 ID,方便您跨影格追蹤物件。當您想追蹤物件或需要低延遲時間時 (例如處理影片串流時),請使用這個模式。
在單一圖片模式中,物件偵測工具會在判定物件的定界框後傳回結果。如果您同時啟用分類功能,系統會在同時提供定界框和類別標籤之後傳回結果。因此,偵測延遲時間可能較長。此外,如果採用單一圖片模式,系統不會指派追蹤 ID。如果延遲時間不是關鍵,而您不想處理部分結果,請使用這個模式。
偵測並追蹤多個物件 false
(預設) |true
偵測及追蹤最多五個物件,或是只追蹤最顯眼的物件 (預設)。
將物件分類 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。