將圖片傳遞至 ML Kit 時,它會偵測圖片中最多五個物件,以及圖片中每個物件的位置。偵測影片串流中的物件時,每個物件都有專屬 ID,可用來追蹤影格之間的物件。
您可以使用自訂圖片分類模型,將偵測到的物件分類。如要瞭解模型相容性需求、如何尋找預先訓練模型,以及如何訓練自己的模型,請參閱「使用 ML Kit 自訂模型」一文。
整合自訂模型的方法有兩種。您可以將模型放到應用程式的資產資料夾中,也可以從 Firebase 動態下載。下表比較了這兩個選項。
組合模型 | 託管模型 |
---|---|
此模型是應用程式的 .ipa 檔案的一部分,會增加其大小。 |
這個模型不屬於應用程式的 .ipa 檔案。託管於 Firebase Machine Learning。 |
模型會立即可供使用,即使 Android 裝置處於離線狀態也沒問題 | 模型採隨選下載 |
不需要 Firebase 專案 | 需要 Firebase 專案 |
必須重新發布應用程式才能更新模型 | 不必重新發布應用程式就能推送模型更新 |
無內建 A/B 測試功能 | 透過 Firebase 遠端設定輕鬆進行 A/B 測試 |
立即體驗
- 請參閱視覺快速入門導覽課程應用程式,查看套裝組合模型的使用範例,以及 automl 快速入門導覽課程應用程式,查看託管模型的使用範例。
- 如需這個 API 的端對端實作,請參閱 Material Design 展示應用程式。
事前準備
在 Podfile 中加入 ML Kit 程式庫:
如需將模型與應用程式組合:
pod 'GoogleMLKit/ObjectDetectionCustom', '3.2.0'
如要從 Firebase 動態下載模型,請新增
LinkFirebase
依附元件:pod 'GoogleMLKit/ObjectDetectionCustom', '3.2.0' pod 'GoogleMLKit/LinkFirebase', '3.2.0'
安裝或更新專案的 Pod 後,請使用其
.xcworkspace
開啟 Xcode 專案。Xcode 13.2.1 以上版本支援 ML Kit。如要下載模型,請先將 Firebase 新增至 iOS 專案 (如果尚未新增)。組合模型時不需要這麼做。
1. 載入模型
設定本機模型來源
如要將模型與應用程式組合,請按照下列步驟操作:
將模型檔案 (通常以
.tflite
或.lite
結尾) 複製到 Xcode 專案,並在執行此操作時務必選取Copy bundle resources
。模型檔案將包含在應用程式套件中,以供 ML Kit 使用。建立
LocalModel
物件,指定模型檔案的路徑:Swift
let localModel = LocalModel(path: localModelFilePath)
Objective-C
MLKLocalModel *localModel = [[MLKLocalModel alloc] initWithPath:localModelFilePath];
設定 Firebase 託管的模型來源
如要使用遠端託管模型,請建立 CustomRemoteModel
物件,指定您在發布模型時指派的名稱:
Swift
let firebaseModelSource = FirebaseModelSource( name: "your_remote_model") // The name you assigned in // the Firebase console. let remoteModel = CustomRemoteModel(remoteModelSource: firebaseModelSource)
Objective-C
MLKFirebaseModelSource *firebaseModelSource = [[MLKFirebaseModelSource alloc] initWithName:@"your_remote_model"]; // The name you assigned in // the Firebase console. MLKCustomRemoteModel *remoteModel = [[MLKCustomRemoteModel alloc] initWithRemoteModelSource:firebaseModelSource];
接著,啟動模型下載工作,指定您允許下載的條件。如果模型不在裝置上,或是有新版模型可用,工作將以非同步方式從 Firebase 下載模型:
Swift
let downloadConditions = ModelDownloadConditions( allowsCellularAccess: true, allowsBackgroundDownloading: true ) let downloadProgress = ModelManager.modelManager().download( remoteModel, conditions: downloadConditions )
Objective-C
MLKModelDownloadConditions *downloadConditions = [[MLKModelDownloadConditions alloc] initWithAllowsCellularAccess:YES allowsBackgroundDownloading:YES]; NSProgress *downloadProgress = [[MLKModelManager modelManager] downloadModel:remoteModel conditions:downloadConditions];
許多應用程式會在其初始化程式碼中啟動下載工作,但在需要使用模型之前,您隨時可以執行此操作。
2. 設定物件偵測工具
設定模型來源後,請使用 CustomObjectDetectorOptions
物件設定用途的物件偵測工具。您可以變更下列設定:
物件偵測器設定 | |
---|---|
偵測模式 |
STREAM_MODE (預設) | SINGLE_IMAGE_MODE 在 在 |
偵測並追蹤多個物件 |
false (預設) | true 偵測及追蹤最多五個物件,或是只追蹤最顯眼的物件 (預設)。 |
將物件分類 |
false (預設) | true 是否要使用所提供自訂分類器模型,將偵測到的物件分類。如要使用自訂分類模型,您必須將這個屬性設為 |
分類可信度門檻 |
偵測到標籤的最低可信度分數。如未設定,系統會使用模型中繼資料指定的任何分類器門檻。如果模型不含任何中繼資料,或是中繼資料未指定分類器門檻,系統就會使用預設的 0.0 門檻。 |
每個物件的標籤數量上限 |
偵測器要傳回的每個物件標籤數量上限。如未設定,系統會使用預設值 10。 |
如果您只有本機組合的模型,請直接從 LocalModel
物件建立物件偵測工具:
Swift
let options = CustomObjectDetectorOptions(localModel: localModel) options.detectorMode = .singleImage options.shouldEnableClassification = true options.shouldEnableMultipleObjects = true options.classificationConfidenceThreshold = NSNumber(value: 0.5) options.maxPerObjectLabelCount = 3
Objective-C
MLKCustomObjectDetectorOptions *options = [[MLKCustomObjectDetectorOptions alloc] initWithLocalModel:localModel]; options.detectorMode = MLKObjectDetectorModeSingleImage; options.shouldEnableClassification = YES; options.shouldEnableMultipleObjects = YES; options.classificationConfidenceThreshold = @(0.5); options.maxPerObjectLabelCount = 3;
如果您使用遠端託管的模型,必須在執行前檢查模型是否已下載。您可以使用模型管理員的 isModelDownloaded(remoteModel:)
方法檢查模型下載工作的狀態。
雖然只有在執行物件偵測工具之前必須先確認這一點,但如果您同時擁有遠端託管模型和本機組合模型,則在執行個體化 ObjectDetector
時,可能還是執行這項檢查:如果您已下載遠端模型,並從本機模型建立偵測工具。
Swift
var options: CustomObjectDetectorOptions! if (ModelManager.modelManager().isModelDownloaded(remoteModel)) { options = CustomObjectDetectorOptions(remoteModel: remoteModel) } else { options = CustomObjectDetectorOptions(localModel: localModel) } options.detectorMode = .singleImage options.shouldEnableClassification = true options.shouldEnableMultipleObjects = true options.classificationConfidenceThreshold = NSNumber(value: 0.5) options.maxPerObjectLabelCount = 3
Objective-C
MLKCustomObjectDetectorOptions *options; if ([[MLKModelManager modelManager] isModelDownloaded:remoteModel]) { options = [[MLKCustomObjectDetectorOptions alloc] initWithRemoteModel:remoteModel]; } else { options = [[MLKCustomObjectDetectorOptions alloc] initWithLocalModel:localModel]; } options.detectorMode = MLKObjectDetectorModeSingleImage; options.shouldEnableClassification = YES; options.shouldEnableMultipleObjects = YES; options.classificationConfidenceThreshold = @(0.5); options.maxPerObjectLabelCount = 3;
如果您只有遠端託管模型,建議停用模型相關功能 (例如顯示為灰色或隱藏部分 UI),直到確認模型已下載為止。
將觀察器附加至預設通知中心,即可取得模型下載狀態。請務必在觀察器區塊中使用 self
的弱參照,因為下載可能需要一段時間,且來源物件可以在下載完成後釋出。例如:
Swift
NotificationCenter.default.addObserver( forName: .mlkitModelDownloadDidSucceed, object: nil, queue: nil ) { [weak self] notification in guard let strongSelf = self, let userInfo = notification.userInfo, let model = userInfo[ModelDownloadUserInfoKey.remoteModel.rawValue] as? RemoteModel, model.name == "your_remote_model" else { return } // The model was downloaded and is available on the device } NotificationCenter.default.addObserver( forName: .mlkitModelDownloadDidFail, object: nil, queue: nil ) { [weak self] notification in guard let strongSelf = self, let userInfo = notification.userInfo, let model = userInfo[ModelDownloadUserInfoKey.remoteModel.rawValue] as? RemoteModel else { return } let error = userInfo[ModelDownloadUserInfoKey.error.rawValue] // ... }
Objective-C
__weak typeof(self) weakSelf = self; [NSNotificationCenter.defaultCenter addObserverForName:MLKModelDownloadDidSucceedNotification object:nil queue:nil usingBlock:^(NSNotification *_Nonnull note) { if (weakSelf == nil | note.userInfo == nil) { return; } __strong typeof(self) strongSelf = weakSelf; MLKRemoteModel *model = note.userInfo[MLKModelDownloadUserInfoKeyRemoteModel]; if ([model.name isEqualToString:@"your_remote_model"]) { // The model was downloaded and is available on the device } }]; [NSNotificationCenter.defaultCenter addObserverForName:MLKModelDownloadDidFailNotification object:nil queue:nil usingBlock:^(NSNotification *_Nonnull note) { if (weakSelf == nil | note.userInfo == nil) { return; } __strong typeof(self) strongSelf = weakSelf; NSError *error = note.userInfo[MLKModelDownloadUserInfoKeyError]; }];
物件偵測和追蹤 API 已針對以下兩項核心用途進行最佳化:
- 即時偵測及追蹤相機觀景窗中最顯眼的物件。
- 偵測靜態圖片中的多個物件。
針對這些用途設定 API:
Swift
// Live detection and tracking let options = CustomObjectDetectorOptions(localModel: localModel) options.shouldEnableClassification = true options.maxPerObjectLabelCount = 3 // Multiple object detection in static images let options = CustomObjectDetectorOptions(localModel: localModel) options.detectorMode = .singleImage options.shouldEnableMultipleObjects = true options.shouldEnableClassification = true options.maxPerObjectLabelCount = 3
Objective-C
// Live detection and tracking MLKCustomObjectDetectorOptions *options = [[MLKCustomObjectDetectorOptions alloc] initWithLocalModel:localModel]; options.shouldEnableClassification = YES; options.maxPerObjectLabelCount = 3; // Multiple object detection in static images MLKCustomObjectDetectorOptions *options = [[MLKCustomObjectDetectorOptions alloc] initWithLocalModel:localModel]; options.detectorMode = MLKObjectDetectorModeSingleImage; options.shouldEnableMultipleObjects = YES; options.shouldEnableClassification = YES; options.maxPerObjectLabelCount = 3;
3. 準備輸入圖片
使用 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];
4. 建立及執行物件偵測工具
建立新的物件偵測工具:
Swift
let objectDetector = ObjectDetector.objectDetector(options: options)
Objective-C
MLKObjectDetector *objectDetector = [MLKObjectDetector objectDetectorWithOptions:options];
然後使用偵測工具:
非同步:
Swift
objectDetector.process(image) { objects, error in guard error == nil, let objects = objects, !objects.isEmpty else { // Handle the error. return } // Show results. }
Objective-C
[objectDetector processImage:image completion:^(NSArray
*_Nullable objects, NSError *_Nullable error) { if (objects.count == 0) { // Handle the error. return; } // Show results. }]; 同步:
Swift
var objects: [Object] do { objects = try objectDetector.results(in: image) } catch let error { // Handle the error. return } // Show results.
Objective-C
NSError *error; NSArray
*objects = [objectDetector resultsInImage:image error:&error]; // Show results or handle the error.
5. 取得已加上標籤的物件相關資訊
如果呼叫圖片處理工具成功,視呼叫非同步或同步方法而定,系統會將 Object
的清單傳遞至完成的處理常式,或傳回清單。
每個 Object
都包含下列屬性:
frame |
CGRect :表示物件在圖片中的位置。 |
||||||
trackingID |
用於識別不同圖片中物件的整數,或 SINGLE_IMAGE_MODE 中的「nil」。 | ||||||
labels |
|
Swift
// objects contains one item if multiple object detection wasn't enabled. for object in objects { let frame = object.frame let trackingID = object.trackingID let description = object.labels.enumerated().map { (index, label) in "Label \(index): \(label.text), \(label.confidence), \(label.index)" }.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]; } }
確保良好的使用者體驗
為獲得最佳使用者體驗,請在應用程式中遵循下列規範:
- 物件偵測成功取決於物件的視覺複雜度。含有少量視覺特徵的物件可能需要較大的部分才能偵測出來。您應該為使用者提供相關指引,說明如何擷取適用於要偵測的物件種類的輸入內容。
- 使用分類時,如要偵測未完全符合支援類別的物件,請針對未知物件採用特殊處理方式。
此外,也請查看 [ML Kit Material Design 展示應用程式][showcase-link]{: .external } 以及 Material Design「採用機器學習技術的功能的模式」集合。
提升效能
如果您想在即時應用程式中使用物件偵測功能,請按照下列指南操作,以達到最佳影格速率:在即時應用程式中使用串流模式時,請勿使用多個物件偵測功能,因為大多數裝置無法產生適當的影格速率。
- 如要處理影片畫面,請使用偵測工具的
results(in:)
同步 API。從AVCaptureVideoDataOutputSampleBufferDelegate
的captureOutput(_, didOutput:from:)
函式呼叫此方法,即可同步取得指定影片畫面的結果。將AVCaptureVideoDataOutput
的alwaysDiscardsLateVideoFrames
保留為true
,藉此調節對偵測工具的呼叫次數。如果在偵測工具執行期間提供新的影片畫面,該影格將遭到捨棄。 - 如果您使用偵測工具的輸出內容將輸入圖片上的圖形重疊,請先從 ML Kit 取得結果,然後再在單一步驟算繪影像和重疊。這樣一來,您只會在每個已處理的輸入影格轉譯一次螢幕介面。如需範例,請參閱 ML Kit 快速入門導覽課程範例中的 updatePreviewOverlayViewWithLastFrame。