六张图迅速搭建CoreML入门工程(Object-C)

环境

  • Xcode 9 Beta 及以上

过程

1.新建“Single View App”工程

《六张图迅速搭建CoreML入门工程(Object-C)》 1.png

2.去官网提供的模型资源中,下载模型文件(我下载的第一个):

《六张图迅速搭建CoreML入门工程(Object-C)》 2.jpeg

3.将下载后的“GoogLeNetPlaces.mlmodel”文件直接拖到工程中:

《六张图迅速搭建CoreML入门工程(Object-C)》 3.jpeg

4.工程对应的“Build Phases -> Compile Sources”中,添加上面拖进来的文件:

《六张图迅速搭建CoreML入门工程(Object-C)》 4.jpeg

5.在“Assets.xcassets”添加一张尺寸为“224*224”像素的png图,取名“test”:

《六张图迅速搭建CoreML入门工程(Object-C)》 5.jpeg

6.在“ViewContrller.m”中敲代码:

《六张图迅速搭建CoreML入门工程(Object-C)》 6.jpeg

其中的代码段包括:

#import "GoogLeNetPlaces.h"
@property (nonatomic, strong) GoogLeNetPlaces *model;

// 初始化模型对象
self.model = [[GoogLeNetPlaces alloc] init];
// 初始化需要输入的图片信息
UIImage *image = [UIImage imageNamed:@"test"];
CGImageRef cgImage = image.CGImage;
// 得到输出
GoogLeNetPlacesOutput *outPut = [self.model predictionFromSceneImage:[self pixelBufferFromCGImage:cgImage] error:nil];
// 打印输出结果
NSLog(@"Dict:%@, \n label:%@", outPut.sceneLabelProbs, outPut.sceneLabel);
- (CVPixelBufferRef)pixelBufferFromCGImage:(CGImageRef)image{
    NSDictionary *options = [NSDictionary dictionaryWithObjectsAndKeys:
                             [NSNumber numberWithBool:YES], kCVPixelBufferCGImageCompatibilityKey,
                             [NSNumber numberWithBool:YES], kCVPixelBufferCGBitmapContextCompatibilityKey,
                             nil];
    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;
}

工程代码下载地址:传送门

    原文作者:麟young
    原文地址: https://www.jianshu.com/p/fb92d1a57a43
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞