關(guān)鍵詞:
Core ML,熱更新馏锡,動態(tài)部署雷蹂,動態(tài)加載
在《二、使用Core ML加載.mlmodel模型文件》中我們介紹了如何加載并使用.mlmodel模型文件杯道,但是這里是在coding階段匪煌,將模型文件加入到項目中的,這里存在一些問題:
- 模型文件動輒幾十兆蕉饼,這將增加安裝包的大小
- 很多模型會被在線數(shù)據(jù)不停的訓(xùn)練虐杯,參數(shù)經(jīng)常發(fā)生變化,每次跟新都要打一個包發(fā)版昧港,這是非常麻煩的事情
于是我們想:mlmodel文件擎椰,能不能通過下載的方式加載到項目中呢?為了解決這個問題创肥,我們需要做兩件事情:
- mlmodel文件达舒,要以下載的方式獲取叹侄;
- 我們需要自己生成模型對應(yīng)的類巩搏;
本文將探索如何達(dá)成此目的。
本文中會將mlmodel以資源文件的形式加入到項目中趾代,以此模擬下載贯底。另外,請首先閱讀《二撒强、使用Core ML加載.mlmodel模型文件》
一禽捆、準(zhǔn)備一個Core ML模型
Core ML模型文件一般以.mlmodel作為后綴笙什,我們可以通過很多途徑獲得一個已經(jīng)訓(xùn)練好的模型,最直接的方式胚想,就是從蘋果官網(wǎng)上直接下載琐凭。
二、查看.mlmodel對應(yīng)的類
首先浊服,我們將一個mlmodel模型拖到項目中统屈,然后查看對應(yīng)類的頭文件(具體請參考《二、使用Core ML加載.mlmodel模型文件》)牙躺。
在頭文件任意位置右擊鼠標(biāo)愁憔,點擊Show in Finder,我們可以看到一對文件述呐,我們把它們加入到項目中來惩淳。
打開m文件蕉毯,我們找到他的init方法以及init方法中調(diào)用的一個類方法:
+ (NSURL *)urlOfModelInThisBundle {
NSString *assetPath = [[NSBundle bundleForClass:[self class]] pathForResource:@"MobileNet" ofType:@"mlmodelc"];
return [NSURL fileURLWithPath:assetPath];
}
- (nullable instancetype)init {
return [self initWithContentsOfURL:self.class.urlOfModelInThisBundle error:nil];
}
三乓搬、模型編譯
我們注意到,這里的type是一個mlmodelc文件代虾,這個c是什么意思呢进肯?我們可以看一下蘋果官方的這篇文檔:
https://developer.apple.com/documentation/coreml/mlmodel/2921516-compilemodelaturl?language=objc
也就是說,mlmodel文件棉磨,是要首先被編譯成mlmodelc文件江掩,才可以被加載的。那么乘瓤,我們的思路就很清晰了环形,我們只需要做如下幾件事情:
- 從服務(wù)器上獲取最新的.mlmodel模型文件,存到本地沙盒中衙傀。
- 使用compileModelAtURL:error:方法抬吟,編譯mlmodel文件,并獲得mlmodelc文件的路徑URL统抬。
- 自己寫一個模型類火本,來封裝一些方法,比如我們可以直接將之前自動生成的類拷貝過來即可聪建,如果對Coding Style有要求的同學(xué)可以自行修改一下命名钙畔。
- 使用initWithContentsOfURL:error:方法初始化模型類并使用他進(jìn)行預(yù)測。
有英文閱讀能力的同學(xué)金麸,也可以看這篇蘋果的官方介紹擎析。值得注意的是,這邊官方介紹中提到:
To limit the use of bandwidth, avoid repeating the download and compile processes when possible. The model is compiled to a temporary location. If the compiled model can be reused, move it to a permanent location, such as your app's support directory.
compileModelAtURL:error:方法會將編譯后的文件存儲到臨時文件夾中挥下,如果希望編譯后的文件被復(fù)用揍魂,可以將其移動到持久化存儲的文件夾中挪鹏。文中還給出了一段示例代碼:
// find the app support directory
let fileManager = FileManager.default
let appSupportDirectory = try! fileManager.url(for: .applicationSupportDirectory,
in: .userDomainMask, appropriateFor: compiledUrl, create: true)
// create a permanent URL in the app support directory
let permanentUrl = appSupportDirectory.appendingPathComponent(compiledUrl.lastPathComponent)
do {
// if the file exists, replace it. Otherwise, copy the file to the destination.
if fileManager.fileExists(atPath: permanentUrl.absoluteString) {
_ = try fileManager.replaceItemAt(permanentUrl, withItemAt: compiledUrl)
} else {
try fileManager.copyItem(at: compiledUrl, to: permanentUrl)
}
} catch {
print("Error during copy: \(error.localizedDescription)")
}
接下來,讓我們嘗試完成Demo愉烙。
四讨盒、準(zhǔn)備服務(wù)器
首先我們需要準(zhǔn)備一個可供下載MobileNet.mlmodel的服務(wù)器,我是借助于http-server步责,用自己的電腦提供MobileNet.mlmodel的下載返顺。這一步大家就各憑本事,自由發(fā)揮了蔓肯。
五遂鹊、準(zhǔn)備一個iOS項目
同樣,大家可以自己創(chuàng)建一個項目蔗包,或者直接clone我的初始項目:
git clone git@github.com:yangchenlarkin/CoreML.git
我們需要在DynamicLoading/DLViewController.m文件最末的download方法中添加代碼秉扑,完成模型下載和編譯,并將編譯后的mlmodelc文件调限,移動到documents文件夾中舟陆。
然后在ObjectRecognition/ORViewController.m最末的predict中加載mlmodelc文件,并完成預(yù)測耻矮。
六秦躯、下載并編譯模型文件
首先打開DynamicLoading/DLViewController.m文件,添加如下代碼:
#import <CoreML/CoreML.h>
在最末實現(xiàn)download函數(shù):
- (void)download {
NSData *data = nil;
//下載數(shù)據(jù)裆装,下載鏈接請?zhí)鎿Q成自己的
NSURL *url = [NSURL URLWithString:@"http://192.168.31.121:8080/MobileNet.mlmodel"];
data = [NSData dataWithContentsOfURL:url];
//我們暫時就將文件存儲到存到臨時文件夾中吧
NSString *tmpPath = NSTemporaryDirectory();
NSString *tmpModelPath = [tmpPath stringByAppendingPathComponent:@"MobileNet.mlmodel"];
[data writeToFile:tmpModelPath atomically:YES];
//編譯文件
NSError *error = nil;
NSURL *tmpModelcPathURL = [MLModel compileModelAtURL:[NSURL fileURLWithPath:tmpModelPath] error:nil];
if (error) {
NSLog(@"%@", error);
return;
}
//拷貝文件到Document文件夾
NSString *docPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) firstObject];
NSString *docModelcPath = [docPath stringByAppendingPathComponent:@"MobileNet.mlmodelc"];
NSFileManager *fileManager = [NSFileManager defaultManager];
[fileManager moveItemAtURL:tmpModelcPathURL toURL:[NSURL fileURLWithPath:docModelcPath] error:&error];
if (error) {
NSLog(@"%@", error);
return;
}
}
七踱承、編寫模型類
我們可以直接使用二、查看.mlmodel對應(yīng)的類中找到的MobileNet類哨免,也可以自己重新寫一個茎活,我這里將直接使用這個類:
八、讀取mlmodelc文件并完成預(yù)測
打開ObjectRecognition/ORViewController.m文件琢唾,首先你需要引入MobileNet類:
#import "MobileNet.h"
然后參考《二载荔、使用Core ML加載.mlmodel模型文件》添加圖像處理代碼:
#pragma mark - predict
- (UIImage *)scaleImage:(UIImage *)image size:(CGFloat)size {
UIGraphicsBeginImageContextWithOptions(CGSizeMake(size, size), YES, 1);
CGFloat x, y, w, h;
CGFloat imageW = image.size.width;
CGFloat imageH = image.size.height;
if (imageW > imageH) {
w = imageW / imageH * size;
h = size;
x = (size - w) / 2;
y = 0;
} else {
h = imageH / imageW * size;
w = size;
y = (size - h) / 2;
x = 0;
}
[image drawInRect:CGRectMake(x, y, w, h)];
UIImage * scaledImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
return scaledImage;
}
- (CVPixelBufferRef)pixelBufferFromCGImage:(CGImageRef)image {
NSDictionary *options = @{
(NSString *)kCVPixelBufferCGImageCompatibilityKey : @YES,
(NSString *)kCVPixelBufferCGBitmapContextCompatibilityKey : @YES,
(NSString *)kCVPixelBufferIOSurfacePropertiesKey: [NSDictionary dictionary]
};
CVPixelBufferRef pxbuffer = NULL;
CGFloat frameWidth = CGImageGetWidth(image);
CGFloat frameHeight = CGImageGetHeight(image);
CVReturn status = CVPixelBufferCreate(kCFAllocatorDefault,
frameWidth,
frameHeight,
kCVPixelFormatType_32ARGB,
(__bridge CFDictionaryRef) options,
&pxbuffer);
NSParameterAssert(status == kCVReturnSuccess && pxbuffer != NULL);
CVPixelBufferLockBaseAddress(pxbuffer, 0);
void *pxdata = CVPixelBufferGetBaseAddress(pxbuffer);
NSParameterAssert(pxdata != NULL);
CGColorSpaceRef rgbColorSpace = CGColorSpaceCreateDeviceRGB();
CGContextRef context = CGBitmapContextCreate(pxdata,
frameWidth,
frameHeight,
8,
CVPixelBufferGetBytesPerRow(pxbuffer),
rgbColorSpace,
(CGBitmapInfo)kCGImageAlphaNoneSkipFirst);
NSParameterAssert(context);
CGContextConcatCTM(context, CGAffineTransformIdentity);
CGContextDrawImage(context, CGRectMake(0,
0,
frameWidth,
frameHeight),
image);
CGColorSpaceRelease(rgbColorSpace);
CGContextRelease(context);
CVPixelBufferUnlockBaseAddress(pxbuffer, 0);
return pxbuffer;
}
最后實現(xiàn)predict方法:
- (void)predict:(UIImage *)image {
//獲取input
UIImage *scaleImage = [self scaleImage:image size:224];
CVPixelBufferRef buffer = [self pixelBufferFromCGImage:scaleImage.CGImage];
//讀取沙盒中的mlmodelc文件
NSString *docPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) firstObject];
NSString *docModelcPath = [docPath stringByAppendingPathComponent:@"MobileNet.mlmodelc"];
NSURL *url = [NSURL fileURLWithPath:docModelcPath];
NSError *error = nil;
MobileNet *model = [[MobileNet alloc] initWithContentsOfURL:url error:&error];
if (error) {
NSLog(@"%@", error);
return;
}
//predict
MobileNetOutput *output = [model predictionFromImage:buffer error:&error];
if (error) {
NSLog(@"%@", error);
return;
}
//顯示
NSMutableArray *result = [NSMutableArray arrayWithCapacity:output.classLabelProbs.count + 1];
[result addObject:@[@"這張圖片可能包含:", output.classLabel]];
[output.classLabelProbs enumerateKeysAndObjectsUsingBlock:^(NSString * _Nonnull key, NSNumber * _Nonnull obj, BOOL * _Nonnull stop) {
NSString *title = [NSString stringWithFormat:@"%@的概率:", key];
[result addObject:@[title, obj.stringValue]];
}];
self.array = result;
}
至此蛮寂,可以運(yùn)行項目肠骆,并嘗試拍照識別物體了抵皱!