使用 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类。