使用 AutoML Vision Edge 訓練您自己的模型後,您可以在您的應用程序中使用它來檢測圖像中的對象。
有兩種方法可以集成從 AutoML Vision Edge 訓練的模型。您可以通過將模型文件複製到您的 Xcode 項目中來捆綁模型,或者您可以從 Firebase 動態下載它。
模型捆綁選項 | |
---|---|
捆綁在您的應用程序中 |
|
使用 Firebase 託管 |
|
在你開始之前
如果您想下載模型,請確保將 Firebase 添加到您的 Apple 項目中(如果您尚未這樣做的話)。捆綁模型時不需要這樣做。
在 Podfile 中包含 TensorFlow 和 Firebase 庫:
要將模型與您的應用程序捆綁在一起:
迅速
pod 'TensorFlowLiteSwift'
目標-C
pod 'TensorFlowLiteObjC'
要從 Firebase 動態下載模型,請添加
Firebase/MLModelInterpreter
依賴項:迅速
pod 'TensorFlowLiteSwift' pod 'Firebase/MLModelInterpreter'
目標-C
pod 'TensorFlowLiteObjC' pod 'Firebase/MLModelInterpreter'
安裝或更新項目的 Pod 後,使用其
.xcworkspace
打開 Xcode 項目。
1.加載模型
配置本地模型源
要將模型與您的應用程序捆綁在一起,請將模型和標籤文件複製到您的 Xcode 項目,執行此操作時注意選擇創建文件夾引用。模型文件和標籤將包含在應用程序包中。
另外,查看與模型一起創建的tflite_metadata.json
文件。你需要兩個值:
- 模型的輸入維度。默認情況下為 320x320。
- 模型的最大檢測。默認情況下為 40。
配置 Firebase 託管的模型源
要使用遠程託管模型,請創建一個CustomRemoteModel
對象,指定您在發布模型時為其分配的名稱:
迅速
let remoteModel = CustomRemoteModel(
name: "your_remote_model" // The name you assigned in the Google Cloud Console.
)
目標-C
FIRCustomRemoteModel *remoteModel = [[FIRCustomRemoteModel alloc]
initWithName:@"your_remote_model"];
然後,啟動模型下載任務,指定允許下載的條件。如果模型不在設備上,或者有更新版本的模型可用,任務將從 Firebase 異步下載模型:
迅速
let downloadProgress = ModelManager.modelManager().download(
remoteModel,
conditions: ModelDownloadConditions(
allowsCellularAccess: true,
allowsBackgroundDownloading: true
)
)
目標-C
FIRModelDownloadConditions *conditions =
[[FIRModelDownloadConditions alloc] initWithAllowsCellularAccess:YES
allowsBackgroundDownloading:YES];
NSProgress *progress = [[FIRModelManager modelManager] downloadModel:remoteModel
conditions:conditions];
許多應用程序在其初始化代碼中開始下載任務,但您可以在需要使用該模型之前的任何時候執行此操作。
從您的模型創建對象檢測器
配置模型源後,從其中之一創建一個 TensorFlow Lite Interpreter
對象。
如果你只有一個本地綁定的模型,只需從模型文件創建一個解釋器:
迅速
guard let modelPath = Bundle.main.path(
forResource: "model",
ofType: "tflite"
) else {
print("Failed to load the model file.")
return true
}
let interpreter = try Interpreter(modelPath: modelPath)
try interpreter.allocateTensors()
目標-C
NSString *modelPath = [[NSBundle mainBundle] pathForResource:@"model"
ofType:@"tflite"];
NSError *error;
TFLInterpreter *interpreter = [[TFLInterpreter alloc] initWithModelPath:modelPath
error:&error];
if (error != NULL) { return; }
[interpreter allocateTensorsWithError:&error];
if (error != NULL) { return; }
如果您有一個遠程託管的模型,則必須在運行之前檢查它是否已下載。您可以使用模型管理器的isModelDownloaded(remoteModel:)
方法檢查模型下載任務的狀態。
儘管您只需要在運行解釋器之前確認這一點,但如果您同時擁有遠程託管模型和本地捆綁模型,則在實例化Interpreter
時執行此檢查可能是有意義的:如果是,則從遠程模型創建解釋器已下載,否則來自本地模型。
迅速
var modelPath: String?
if ModelManager.modelManager().isModelDownloaded(remoteModel) {
ModelManager.modelManager().getLatestModelFilePath(remoteModel) { path, error in
guard error == nil else { return }
guard let path = path else { return }
modelPath = path
}
} else {
modelPath = Bundle.main.path(
forResource: "model",
ofType: "tflite"
)
}
guard modelPath != nil else { return }
let interpreter = try Interpreter(modelPath: modelPath)
try interpreter.allocateTensors()
目標-C
__block NSString *modelPath;
if ([[FIRModelManager modelManager] isModelDownloaded:remoteModel]) {
[[FIRModelManager modelManager] getLatestModelFilePath:remoteModel
completion:^(NSString * _Nullable filePath,
NSError * _Nullable error) {
if (error != NULL) { return; }
if (filePath == NULL) { return; }
modelPath = filePath;
}];
} else {
modelPath = [[NSBundle mainBundle] pathForResource:@"model"
ofType:@"tflite"];
}
NSError *error;
TFLInterpreter *interpreter = [[TFLInterpreter alloc] initWithModelPath:modelPath
error:&error];
if (error != NULL) { return; }
[interpreter allocateTensorsWithError:&error];
if (error != NULL) { return; }
如果您只有一個遠程託管模型,則應禁用與模型相關的功能(例如,將部分 UI 灰顯或隱藏),直到您確認模型已下載。
您可以通過將觀察者附加到默認通知中心來獲取模型下載狀態。請務必在觀察者塊中使用對self
的弱引用,因為下載可能需要一些時間,並且原始對象可以在下載完成時被釋放。例如:
迅速
NotificationCenter.default.addObserver(
forName: .firebaseMLModelDownloadDidSucceed,
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: .firebaseMLModelDownloadDidFail,
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]
// ...
}
目標-C
__weak typeof(self) weakSelf = self;
[NSNotificationCenter.defaultCenter
addObserverForName:FIRModelDownloadDidSucceedNotification
object:nil
queue:nil
usingBlock:^(NSNotification *_Nonnull note) {
if (weakSelf == nil | note.userInfo == nil) {
return;
}
__strong typeof(self) strongSelf = weakSelf;
FIRRemoteModel *model = note.userInfo[FIRModelDownloadUserInfoKeyRemoteModel];
if ([model.name isEqualToString:@"your_remote_model"]) {
// The model was downloaded and is available on the device
}
}];
[NSNotificationCenter.defaultCenter
addObserverForName:FIRModelDownloadDidFailNotification
object:nil
queue:nil
usingBlock:^(NSNotification *_Nonnull note) {
if (weakSelf == nil | note.userInfo == nil) {
return;
}
__strong typeof(self) strongSelf = weakSelf;
NSError *error = note.userInfo[FIRModelDownloadUserInfoKeyError];
}];
2.準備輸入圖像
接下來,您需要為 TensorFlow Lite 解釋器準備圖像。
根據
tflite_metadata.json
文件中指定的模型的輸入尺寸裁剪和縮放圖像(默認為 320x320 像素)。您可以使用 Core Image 或第三方庫來執行此操作將圖像數據複製到
Data
(NSData
對象)中:迅速
guard let image: CGImage = // Your input image guard let context = CGContext( data: nil, width: image.width, height: image.height, bitsPerComponent: 8, bytesPerRow: image.width * 4, space: CGColorSpaceCreateDeviceRGB(), bitmapInfo: CGImageAlphaInfo.noneSkipFirst.rawValue ) else { return nil } context.draw(image, in: CGRect(x: 0, y: 0, width: image.width, height: image.height)) guard let imageData = context.data else { return nil } var inputData = Data() for row in 0 ..< 320 { // Model takes 320x320 pixel images as input for col in 0 ..< 320 { let offset = 4 * (col * context.width + row) // (Ignore offset 0, the unused alpha channel) var red = imageData.load(fromByteOffset: offset+1, as: UInt8.self) var green = imageData.load(fromByteOffset: offset+2, as: UInt8.self) var blue = imageData.load(fromByteOffset: offset+3, as: UInt8.self) inputData.append(&red, count: 1) inputData.append(&green, count: 1) inputData.append(&blue, count: 1) } }
目標-C
CGImageRef image = // Your input image long imageWidth = CGImageGetWidth(image); long imageHeight = CGImageGetHeight(image); CGContextRef context = CGBitmapContextCreate(nil, imageWidth, imageHeight, 8, imageWidth * 4, CGColorSpaceCreateDeviceRGB(), kCGImageAlphaNoneSkipFirst); CGContextDrawImage(context, CGRectMake(0, 0, imageWidth, imageHeight), image); UInt8 *imageData = CGBitmapContextGetData(context); NSMutableData *inputData = [[NSMutableData alloc] initWithCapacity:0]; for (int row = 0; row < 300; row++) { for (int col = 0; col < 300; col++) { long offset = 4 * (row * imageWidth + col); // (Ignore offset 0, the unused alpha channel) UInt8 red = imageData[offset+1]; UInt8 green = imageData[offset+2]; UInt8 blue = imageData[offset+3]; [inputData appendBytes:&red length:1]; [inputData appendBytes:&green length:1]; [inputData appendBytes:&blue length:1]; } }
3.運行物體檢測器
接下來,將準備好的輸入傳遞給解釋器:
迅速
try interpreter.copy(inputData, toInputAt: 0)
try interpreter.invoke()
目標-C
TFLTensor *input = [interpreter inputTensorAtIndex:0 error:&error];
if (error != nil) { return; }
[input copyData:inputData error:&error];
if (error != nil) { return; }
[interpreter invokeWithError:&error];
if (error != nil) { return; }
4.獲取檢測對象信息
如果對象檢測成功,模型將生成三個數組作為輸出,每個數組包含 40 個元素(或tflite_metadata.json
文件中指定的任何內容)。每個元素對應一個潛在對象。第一個數組是邊界框數組;第二,一組標籤;第三,一組置信度值。要獲得模型輸出:
迅速
var output = try interpreter.output(at: 0)
let boundingBoxes =
UnsafeMutableBufferPointer<Float32>.allocate(capacity: 4 * 40)
output.data.copyBytes(to: boundingBoxes)
output = try interpreter.output(at: 1)
let labels =
UnsafeMutableBufferPointer<Float32>.allocate(capacity: 40)
output.data.copyBytes(to: labels)
output = try interpreter.output(at: 2)
let probabilities =
UnsafeMutableBufferPointer<Float32>.allocate(capacity: 40)
output.data.copyBytes(to: probabilities)
目標-C
TFLTensor *output = [interpreter outputTensorAtIndex:0 error:&error];
if (error != nil) { return; }
NSData *boundingBoxes = [output dataWithError:&error];
if (error != nil) { return; }
output = [interpreter outputTensorAtIndex:1 error:&error];
if (error != nil) { return; }
NSData *labels = [output dataWithError:&error];
if (error != nil) { return; }
output = [interpreter outputTensorAtIndex:2 error:&error];
if (error != nil) { return; }
NSData *probabilities = [output dataWithError:&error];
if (error != nil) { return; }
然後,您可以將標籤輸出與標籤字典結合起來:
迅速
guard let labelPath = Bundle.main.path(
forResource: "dict",
ofType: "txt"
) else { return true }
let fileContents = try? String(contentsOfFile: labelPath)
guard let labelText = fileContents?.components(separatedBy: "\n") else { return true }
for i in 0 ..< 40 {
let top = boundingBoxes[0 * i]
let left = boundingBoxes[1 * i]
let bottom = boundingBoxes[2 * i]
let right = boundingBoxes[3 * i]
let labelIdx = Int(labels[i])
let label = labelText[labelIdx]
let confidence = probabilities[i]
if confidence > 0.66 {
print("Object found: \(label) (confidence: \(confidence))")
print(" Top-left: (\(left),\(top))")
print(" Bottom-right: (\(right),\(bottom))")
}
}
目標-C
NSString *labelPath = [NSBundle.mainBundle pathForResource:@"dict"
ofType:@"txt"];
NSString *fileContents = [NSString stringWithContentsOfFile:labelPath
encoding:NSUTF8StringEncoding
error:&error];
if (error != nil || fileContents == NULL) { return; }
NSArray<NSString*> *labelText = [fileContents componentsSeparatedByString:@"\n"];
for (int i = 0; i < 40; i++) {
Float32 top, right, bottom, left;
Float32 labelIdx;
Float32 confidence;
[boundingBoxes getBytes:&top range:NSMakeRange(16 * i + 0, 4)];
[boundingBoxes getBytes:&left range:NSMakeRange(16 * i + 4, 4)];
[boundingBoxes getBytes:&bottom range:NSMakeRange(16 * i + 8, 4)];
[boundingBoxes getBytes:&right range:NSMakeRange(16 * i + 12, 4)];
[labels getBytes:&labelIdx range:NSMakeRange(4 * i, 4)];
[probabilities getBytes:&confidence range:NSMakeRange(4 * i, 4)];
if (confidence > 0.5f) {
NSString *label = labelText[(int)labelIdx];
NSLog(@"Object detected: %@", label);
NSLog(@" Confidence: %f", confidence);
NSLog(@" Top-left: (%f,%f)", left, top);
NSLog(@" Bottom-right: (%f,%f)", right, bottom);
}
}
提高實時性能的技巧
如果您想在實時應用程序中標記圖像,請遵循以下準則以獲得最佳幀率:
- 限制對檢測器的調用。如果在檢測器運行時有新的視頻幀可用,則丟棄該幀。
- 如果您使用檢測器的輸出在輸入圖像上疊加圖形,請先獲取結果,然後一步渲染圖像和疊加。通過這樣做,您只需為每個輸入幀渲染到顯示表面一次。有關示例,請參閱展示示例應用程序中的previewOverlayView和FIRDetectionOverlayView類。