你可以使用 ML Kit 偵測及追蹤影片畫面中的物件。
傳遞 ML Kit 圖片時,ML Kit 會為每張圖片傳回清單,最多列出五個偵測到的物件,以及這些物件在圖片中的位置。偵測影片串流中的物件時,每個物件都有 ID,可用來追蹤所有圖片的物件。您也可以選擇啟用粗略的物件分類,將物件加上廣泛類別說明。
事前準備
- 如果您尚未將 Firebase 加入應用程式,請按照入門指南中的步驟進行。
- 在 Podfile 中加入 ML Kit 程式庫:
pod 'Firebase/MLVision', '6.25.0' pod 'Firebase/MLVisionObjectDetection', '6.25.0'
安裝或更新專案的 Pod 後,請務必使用.xcworkspace
開啟 Xcode 專案。 - 在應用程式中匯入 Firebase:
Swift
import Firebase
Objective-C
@import Firebase;
1. 設定物件偵測工具
如要開始偵測及追蹤物件,請先建立 VisionObjectDetector
的執行個體,並選擇性地指定要從預設值變更的任何偵測工具設定。
請使用
VisionObjectDetectorOptions
物件,根據您的用途設定物件偵測工具。您可以變更下列設定:物件偵測器設定 偵測模式 .stream
(預設) |.singleImage
在串流模式 (預設) 中,物件偵測工具會在極短的延遲時間下執行,但在前幾次叫用偵測工具時可能會產生不完整的結果 (例如未指定的定界框或類別)。此外,在串流模式中,偵測工具會將追蹤 ID 指派給物件,讓您用來跨影格追蹤物件。當您想要追蹤物件,或當低延遲時間 (例如即時處理影片串流) 時,請使用這個模式。
在單一圖片模式中,物件偵測工具會等到偵測到物件的定界框和 (如果您已啟用分類) 類別出現,然後才會傳回結果。因此,偵測延遲時間可能會更長。此外,在單一圖片模式中,系統不會指派追蹤 ID。如果延遲時間不重要,而且您不想處理部分結果,請使用這個模式。
偵測並追蹤多個物件 false
(預設) |true
可指定最多偵測及追蹤五個物件,還是僅偵測最顯眼的物件 (預設)。
將物件分類 false
(預設) |true
是否要將偵測到的物件歸類為粗略的類別。 啟用後,物件偵測工具會將物件分為下列類別:時尚商品、食品、居家用品、地點、植物和不明。
物件偵測和追蹤 API 已針對下列兩種核心用途進行最佳化:
- 在相機觀景窗中即時偵測及追蹤最顯眼的物件
- 偵測靜態圖片中的多個物件
如何針對這些用途設定 API:
Swift
// Live detection and tracking let options = VisionObjectDetectorOptions() options.detectorMode = .stream options.shouldEnableMultipleObjects = false options.shouldEnableClassification = true // Optional // Multiple object detection in static images let options = VisionObjectDetectorOptions() options.detectorMode = .singleImage options.shouldEnableMultipleObjects = true options.shouldEnableClassification = true // Optional
Objective-C
// Live detection and tracking FIRVisionObjectDetectorOptions *options = [[FIRVisionObjectDetectorOptions alloc] init]; options.detectorMode = FIRVisionObjectDetectorModeStream; options.shouldEnableMultipleObjects = NO; options.shouldEnableClassification = YES; // Optional // Multiple object detection in static images FIRVisionObjectDetectorOptions *options = [[FIRVisionObjectDetectorOptions alloc] init]; options.detectorMode = FIRVisionObjectDetectorModeSingleImage; options.shouldEnableMultipleObjects = YES; options.shouldEnableClassification = YES; // Optional
取得
FirebaseVisionObjectDetector
的例項:Swift
let objectDetector = Vision.vision().objectDetector() // Or, to change the default settings: let objectDetector = Vision.vision().objectDetector(options: options)
Objective-C
FIRVisionObjectDetector *objectDetector = [[FIRVision vision] objectDetector]; // Or, to change the default settings: FIRVisionObjectDetector *objectDetector = [[FIRVision vision] objectDetectorWithOptions:options];
2. 執行物件偵測工具
如要偵測及追蹤物件,請針對每張圖片或影格執行下列操作。
如果啟用串流模式,就必須從 CMSampleBufferRef
建立 VisionImage
物件。
使用
UIImage
或CMSampleBufferRef
建立VisionImage
物件。如何使用
UIImage
:- 視需要旋轉圖片,讓
imageOrientation
屬性為.up
。 - 使用正確旋轉的
UIImage
建立VisionImage
物件。請勿指定任何旋轉中繼資料,必須使用預設值.topLeft
。Swift
let image = VisionImage(image: uiImage)
Objective-C
FIRVisionImage *image = [[FIRVisionImage alloc] initWithImage:uiImage];
如何使用
CMSampleBufferRef
:-
建立
VisionImageMetadata
物件,指定CMSampleBufferRef
緩衝區中圖片資料的方向。如何取得圖片方向:
Swift
func imageOrientation( deviceOrientation: UIDeviceOrientation, cameraPosition: AVCaptureDevice.Position ) -> VisionDetectorImageOrientation { switch deviceOrientation { case .portrait: return cameraPosition == .front ? .leftTop : .rightTop case .landscapeLeft: return cameraPosition == .front ? .bottomLeft : .topLeft case .portraitUpsideDown: return cameraPosition == .front ? .rightBottom : .leftBottom case .landscapeRight: return cameraPosition == .front ? .topRight : .bottomRight case .faceDown, .faceUp, .unknown: return .leftTop } }
Objective-C
- (FIRVisionDetectorImageOrientation) imageOrientationFromDeviceOrientation:(UIDeviceOrientation)deviceOrientation cameraPosition:(AVCaptureDevicePosition)cameraPosition { switch (deviceOrientation) { case UIDeviceOrientationPortrait: if (cameraPosition == AVCaptureDevicePositionFront) { return FIRVisionDetectorImageOrientationLeftTop; } else { return FIRVisionDetectorImageOrientationRightTop; } case UIDeviceOrientationLandscapeLeft: if (cameraPosition == AVCaptureDevicePositionFront) { return FIRVisionDetectorImageOrientationBottomLeft; } else { return FIRVisionDetectorImageOrientationTopLeft; } case UIDeviceOrientationPortraitUpsideDown: if (cameraPosition == AVCaptureDevicePositionFront) { return FIRVisionDetectorImageOrientationRightBottom; } else { return FIRVisionDetectorImageOrientationLeftBottom; } case UIDeviceOrientationLandscapeRight: if (cameraPosition == AVCaptureDevicePositionFront) { return FIRVisionDetectorImageOrientationTopRight; } else { return FIRVisionDetectorImageOrientationBottomRight; } default: return FIRVisionDetectorImageOrientationTopLeft; } }
然後,建立中繼資料物件:
Swift
let cameraPosition = AVCaptureDevice.Position.back // Set to the capture device you used. let metadata = VisionImageMetadata() metadata.orientation = imageOrientation( deviceOrientation: UIDevice.current.orientation, cameraPosition: cameraPosition )
Objective-C
FIRVisionImageMetadata *metadata = [[FIRVisionImageMetadata alloc] init]; AVCaptureDevicePosition cameraPosition = AVCaptureDevicePositionBack; // Set to the capture device you used. metadata.orientation = [self imageOrientationFromDeviceOrientation:UIDevice.currentDevice.orientation cameraPosition:cameraPosition];
- 使用
CMSampleBufferRef
物件和旋轉中繼資料建立VisionImage
物件:Swift
let image = VisionImage(buffer: sampleBuffer) image.metadata = metadata
Objective-C
FIRVisionImage *image = [[FIRVisionImage alloc] initWithBuffer:sampleBuffer]; image.metadata = metadata;
- 視需要旋轉圖片,讓
將
VisionImage
傳遞至物件的其中一個物件偵測方法。您可以使用非同步process(image:)
方法或同步的results()
方法。如要非同步偵測物件:
Swift
objectDetector.process(image) { detectedObjects, error in guard error == nil else { // Error. return } guard let detectedObjects = detectedObjects, !detectedObjects.isEmpty else { // No objects detected. return } // Success. Get object info here. // ... }
Objective-C
[objectDetector processImage:image completion:^(NSArray<FIRVisionObject *> * _Nullable objects, NSError * _Nullable error) { if (error == nil) { return; } if (objects == nil | objects.count == 0) { // No objects detected. return; } // Success. Get object info here. // ... }];
若要同步偵測物件:
Swift
var results: [VisionObject]? = nil do { results = try objectDetector.results(in: image) } catch let error { print("Failed to detect object with error: \(error.localizedDescription).") return } guard let detectedObjects = results, !detectedObjects.isEmpty else { print("Object detector returned no results.") return } // ...
Objective-C
NSError *error; NSArray<FIRVisionObject *> *objects = [objectDetector resultsInImage:image error:&error]; if (error == nil) { return; } if (objects == nil | objects.count == 0) { // No objects detected. return; } // Success. Get object info here. // ...
如果對圖片處理工具的呼叫成功,則會根據您呼叫的是非同步或同步方法,將
VisionObject
清單傳送至完成處理常式,或是傳回清單。每個
VisionObject
都包含下列屬性:frame
CGRect
:表示物件在圖片中的位置。trackingID
一個整數,可在圖片中識別物件。在單一圖片模式下呈現空值。 classificationCategory
物件的概略類別。如果物件偵測工具未啟用分類功能,這個屬性一律為 .unknown
。confidence
物件分類的可信度值。如果物件偵測工具未啟用分類功能,或物件遭歸類為不明,一律為 nil
。Swift
// detectedObjects contains one item if multiple object detection wasn't enabled. for obj in detectedObjects { let bounds = obj.frame let id = obj.trackingID // If classification was enabled: let category = obj.classificationCategory let confidence = obj.confidence }
Objective-C
// The list of detected objects contains one item if multiple // object detection wasn't enabled. for (FIRVisionObject *obj in objects) { CGRect bounds = obj.frame; if (obj.trackingID) { NSInteger id = obj.trackingID.integerValue; } // If classification was enabled: FIRVisionObjectCategory category = obj.classificationCategory; float confidence = obj.confidence.floatValue; }
提升可用性和效能
為獲得最佳使用者體驗,請在應用程式中遵循以下規範:
- 是否成功偵測物件,取決於物件的視覺複雜度。如果物件只有少量視覺特徵,可能需要佔用較大的圖片部分才能偵測。您必須為使用者提供指引,瞭解如何擷取能與要偵測的物件類型搭配運作的輸入內容。
- 使用分類功能時,如果您想偵測無法正常歸入支援類別的物件,可以針對未知物件實作特殊處理。
此外,您也可以參考 [ML Kit Material Design 展示應用程式][showcase-link]{: .external },以及 Material Design 採用機器學習技術的功能模式系列文章。
在即時應用程式中使用串流模式時,請遵循下列準則,以達到最佳的影格速率:
在串流模式下,請勿使用多項物件偵測功能,因為大多數裝置無法產生適當的影格速率。
如果不需要分類功能,請停用分類功能。
- 限制對偵測工具的呼叫。如果在偵測工具執行時有新的影片影格,請捨棄影格。
- 如果您使用偵測工具的輸出內容,在輸入圖片上疊加圖像,請先從 ML Kit 取得結果,然後透過一個步驟算繪圖像和疊加層。如此一來,每個輸入影格都只會算繪到顯示介面一次。如需範例,請參閱展示範例應用程式中的 previewOverlayView 和 FIRDetectionOverlayView 類別。