环境
- Xcode 9 Beta 及以上
过程
1.新建“Single View App”工程
1.png2.去官网提供的模型资源中,下载模型文件(我下载的第一个):
2.jpeg3.将下载后的“GoogLeNetPlaces.mlmodel
”文件直接拖到工程中:
4.工程对应的“Build Phases -> Compile Sources”中,添加上面拖进来的文件:
4.jpeg5.在“Assets.xcassets
”添加一张尺寸为“224*224”像素的png图,取名“test”:
6.在“ViewContrller.m
”中敲代码:
其中的代码段包括:
#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;
}
工程代码下载地址:传送门
网友评论