coreml之通过URL加载模型
在xcode中使用mlmodel模型,之前说的最简单的方法是将模型拖进工程中即可,xcode会自动生成有关模型的前向预测接口,这种方式非常简单,但是更新模型就很不方便。
今天说下另外一种通过URL加载mlmodel的方式。具体可以查阅apple开发者官方文档 https://developer.apple.com/documentation/coreml/mlmodel:

流程如下:
1.提供mlmodel的文件所在路径model_path
NSString *model_path = "path_to/.mlmodel"
2.将NSSting类型转换为NSURL,并根据路径对模型进行编译(编译出的为.mlmodelc 文件, 这是一个临时文件,如果需要,可以将其保存到一个固定位置:https://developer.apple.com/documentation/coreml/core_ml_api/downloading_and_compiling_a_model_on_the_user_s_device)
NSURL *url = [NSURL fileURLWithPath:model_path isDirectory:FALSE];
NSURL *compile_url = [MLModel compileModelAtURL:url error:&error];
3.根据编译后模型所在路径,加载模型,类型为MLModel
MLModel *compiled_model = [MLModel modelWithContentsOfURL:compile_url configuration:model_config error:&error];
4.需要注意的是采用动态编译方式,coreml只是提供了一种代理方式MLFeatureProvider,类似于C++中的虚函数。因此需要自己重写模型输入和获取模型输出的类接口(该类继承自MLFeatureProvider)。如下自己封装的MLModelInput和MLModelOutput类。MLModelInput类可以根据模型的输入名称InputName,传递data给模型。而MLModelOutput可以根据不同的输出名称featureName获取预测结果。
这个是头文件:
#import <Foundation/Foundation.h>
#import <CoreML/CoreML.h> NS_ASSUME_NONNULL_BEGIN /// Model Prediction Input Type
API_AVAILABLE(macos(10.13), ios(11.0), watchos(4.0), tvos(11.0))
@interface MLModelInput : NSObject<MLFeatureProvider> //the input name,default is image
@property (nonatomic, strong) NSString *inputName; //data as color (kCVPixelFormatType_32BGRA) image buffer
@property (readwrite, nonatomic) CVPixelBufferRef data; - (instancetype)init NS_UNAVAILABLE; - (instancetype)initWithData:(CVPixelBufferRef)data inputName:(NSString *)inputName; @end API_AVAILABLE(macos(10.13), ios(11.0), watchos(4.0), tvos(11.0))
@interface MLModelOutput : NSObject<MLFeatureProvider> //the output name, defalut is feature
@property (nonatomic, strong) NSString *outputName; // feature as multidimensional array of doubles
@property (readwrite, nonatomic) MLMultiArray *feature; - (instancetype)init NS_UNAVAILABLE; - (instancetype)initWithFeature:(MLMultiArray *)feature;
@end NS_ASSUME_NONNULL_END
这个是类方法实现的文件:
@implementation MLModelInput
- (instancetype)initWithData:(CVPixelBufferRef)data inputName:(nonnull NSString *)inputName {
if (self) {
_data = data;
_inputName = inputName;
}
return self;
}
- (NSSet<NSString *> *)featureNames {
return [NSSet setWithArray:@[self.inputName]];
}
- (nullable MLFeatureValue *)featureValueForName:(nonnull NSString *)featureName {
if ([featureName isEqualToString:self.inputName]) {
return [MLFeatureValue featureValueWithPixelBuffer:_data];
}
return nil;
}
@end
@implementation MLModelOutput
- (instancetype)initWithFeature:(MLMultiArray *)feature{
if (self) {
_feature = feature;
_outputName = DefalutOutputValueName;
}
return self;
}
- (NSSet<NSString *> *)featureNames{
return [NSSet setWithArray:@[self.outputName]];
}
- (nullable MLFeatureValue *)featureValueForName:(nonnull NSString *)featureName {
if ([featureName isEqualToString:self.outputName]) {
return [MLFeatureValue featureValueWithMultiArray:_feature];
}
return nil;
}
@end
5. 模型预测,获取预测结果。上面这两个类接口写完后,就可以整理输入数据为CvPixelBuffer,然后通过获取模型描述MLModelDescription得到输入名称,根据输入名称创建MLModelInput,预测,然后再根据MLModelOutput中的featureNames获取对应的预测输出数据,类型为MLMultiArray:
MLModelDescription *model_description = compiled_model.modelDescription;
NSDictionary *dict = model_description.inputDescriptionsByName;
NSArray<NSString *> *feature_names = [dict allKeys];
NSString *input_feature_name = feature_names[];
NSError *error;
MLModelInput *model_input = [[MLModelInput alloc] initWithData:buffer inputName:input_feature_name];
id<MLFeatureProvider> model_output = [compiled_model predictionFromFeatures:model_input options:option error:&error];
NSSet<NSString *> *out_feature_names = [model_output featureNames];
NSArray<NSString *> *name_list = [out_feature_names allObjects];
NSUInteger size = [name_list count];
std::vector<MLMultiArray *> feature_list;
for (NSUInteger i = 0; i < size; i++) {
NSString *name = [name_list objectAtIndex:i];
MLMultiArray *feature = [model_output featureValueForName:name].multiArrayValue;
feature_list.push_back(feature);
}
6.读取MLMultiArray中的预测结果数据做后续处理..
coreml之通过URL加载模型的更多相关文章
- tensorflowjs下载源文件到本地不能加载模型解决方案
大多数情况(非源文件错误)下载源文件到本地不能加载模型,那么你可能需要搭建一个本地WEB服务器. 1.安装apache或ngnix,可以参照这个博客 2.强烈推荐一个Chrome插件Web Serve ...
- C#开发BIMFACE系列37 网页集成开发1:审图系统中加载模型或图纸
系列目录 [已更新最新开发文章,点击查看详细] 在之前的<C#开发BIMFACE系列>中主要介绍了BIMFACE平台提供的服务端API接口的封装开发与测试过程. 服务端API测试通 ...
- C#开发BIMFACE系列50 Web网页中使用jQuery加载模型与图纸
BIMFACE二次开发系列目录 [已更新最新开发文章,点击查看详细] 在前一篇博客<C#开发BIMFACE系列49 Web网页集成BIMFACE应用的技术方案>中介绍了目前市场主流 ...
- C#开发BIMFACE系列53 WinForm程序中使用CefSharp加载模型图纸1 简单应用
BIMFACE二次开发系列目录 [已更新最新开发文章,点击查看详细] 在我的博客<C#开发BIMFACE系列52 CS客户端集成BIMFACE应用的技术方案>中介绍了多种集成BIM ...
- NeHe OpenGL教程 第三十一课:加载模型
转自[翻译]NeHe OpenGL 教程 前言 声明,此 NeHe OpenGL教程系列文章由51博客yarin翻译(2010-08-19),本博客为转载并稍加整理与修改.对NeHe的OpenGL管线 ...
- URL加载系统----iOS工程师必须熟练掌握
URL加载系统----iOS工程师必须熟练掌握 iOS根本离不开网络——不论是从服务端读写数据.向系统分发计算任务,还是从云端加载图片.音频.视频等. 当应用程序面临处理问题的抉择时,通常 ...
- tensorflow学习笔记2:c++程序静态链接tensorflow库加载模型文件
首先需要搞定tensorflow c++库,搜了一遍没有找到现成的包,于是下载tensorflow的源码开始编译: tensorflow的contrib中有一个makefile项目,极大的简化的接下来 ...
- 深度学习原理与框架-猫狗图像识别-卷积神经网络(代码) 1.cv2.resize(图片压缩) 2..get_shape()[1:4].num_elements(获得最后三维度之和) 3.saver.save(训练参数的保存) 4.tf.train.import_meta_graph(加载模型结构) 5.saver.restore(训练参数载入)
1.cv2.resize(image, (image_size, image_size), 0, 0, cv2.INTER_LINEAR) 参数说明:image表示输入图片,image_size表示变 ...
- PyTorch保存模型与加载模型+Finetune预训练模型使用
Pytorch 保存模型与加载模型 PyTorch之保存加载模型 参数初始化参 数的初始化其实就是对参数赋值.而我们需要学习的参数其实都是Variable,它其实是对Tensor的封装,同时提供了da ...
随机推荐
- Python连载41-yield from详解、委派生成器
一. 1.yield from (1)调用协程为了得到返回值,协程必须正常终止 (2)生成器正常终止会发出StopIteration异常,异常对象的value属性保存返回值. (3)yield fro ...
- python中pkl用法
原文连接:https://www.jianshu.com/p/2ecadebe6d13 python中pkl用法 经常遇到在Python程序运行得到了一些字符串.列表.字典等数据,想要长久的保存下来, ...
- Chrome 手动安装.crx插件
在网上自己下载.crx的离线插件文件.或者通过朋友打包.crx文件.打包方式可参照Chrome 打包扩展程序 方法一: 打开Chrome浏览器,地址栏输入 chrome://extensions/ 将 ...
- sql server中的临时表、表变量和公用表表达式
在编写T-SQL语句的时候,SQL Server提供了三种方法临时存储某些结果集,分别是临时表.表变量和公用表表达式. 临时表 临时表需要在临时数据库TempDB中通过I/O操作来创建表结构,一旦用户 ...
- Lambda 表达式构建初级示例(不完整)
直接贴代码了: using System; using System.Collections.Generic; using System.Linq; using System.Linq.Express ...
- 【Wannafly挑战赛29F】最后之作(Trie树,动态规划,斜率优化)
[Wannafly挑战赛29F]最后之作(Trie树,动态规划,斜率优化) 题面 牛客 题解 首先考虑怎么计算\([l,r]\)这个子串的不同的串的个数. 如果\(l=1\),我们构建\(Trie\) ...
- 【JS】---5 JS通过事件隐藏显示元素
JS通过事件隐藏显示元素 在开发中,很多时候我们需要点击事件,才显示隐藏元素.那如何做到页面刚开始就把标签隐藏. 有两种方法: (1) display:none <div id=" ...
- mask-rcnn代码解读(六):resize_image()函数的解析
我已经根据resize_image()函数的解析对原图像与resize图像进行了解析, 若有读者想对原图像与目标图像不同尺寸验证,可根据以下代码,调整函数参数, 其细节如下: import cv2 a ...
- Python进阶----异步同步,阻塞非阻塞,线程池(进程池)的异步+回调机制实行并发, 线程队列(Queue, LifoQueue,PriorityQueue), 事件Event,线程的三个状态(就绪,挂起,运行) ,***协程概念,yield模拟并发(有缺陷),Greenlet模块(手动切换),Gevent(协程并发)
Python进阶----异步同步,阻塞非阻塞,线程池(进程池)的异步+回调机制实行并发, 线程队列(Queue, LifoQueue,PriorityQueue), 事件Event,线程的三个状态(就 ...
- Spring Data Jpa:分页、Specification、Criteria
分页的主要接口与类 PagingAndSortingRepository 继承自 CrudRepository 接口,提供了排序以及分页查询能力,提供了两个方法 Iterable<T> f ...