一、集成
用pod集成直接如下
pod 'TensorFlowLiteObjC'
二、使用简介
#import <TFLTensorFlowLite.h>
//获取模型路径
NSString *modelPath = [[NSBundle mainBundle] pathForResource:@"model" ofType:@"tflite"];
NSError *error;
// 用模型初始化解释器
TFLInterpreter *interpreter = [[TFLInterpreter alloc] initWithModelPath:modelPath error:&error];
if (error != nil) { /* Error handling... */ }
// 为模型的输入“TFLTensor”分配内存。
[interpreter allocateTensorsWithError:&error];
if (error != nil) { /* Error handling... */ }
NSMutableData *inputData; // Should be initialized
// 输入数据准备...
// 将输入数据复制到输入TFLTensor.
[interpreter copyData:inputData toInputTensorAtIndex:0 error:&error];
if (error != nil) { /* Error handling... */ }
// Run inference by invoking the TFLInterpreter.
//通过调用“TFLInterpreter”运行推断
[interpreter invokeWithError:&error];
if (error != nil) { /* Error handling... */ }
// Get the output TFLTensor
//获取输出的 TFLTensor
TFLTensor *outputTensor = [interpreter outputTensorAtIndex:0 error:&error];
if (error != nil) { /* Error handling... */ }
//把输出复制到“NSData”以处理推断结果
NSData *outputData = [outputTensor dataWithError:&error];
if (error != nil) { /* Error handling... */ }
三、在实际项目中的应用
1、创建 TFLInterpreter实例对象
TFLInterpreterOptions *options = [[TFLInterpreterOptions alloc] init];
self.interpreter = [[TFLInterpreter alloc] initWithModelPath:filePath options:options error:nil];
NSError *allocError;
BOOL isSuccess = [self.interpreter allocateTensorsWithError:&allocError];
2.用TFLTensor对输入的数据进行预测输出预测结果
TFLTensor *inputTensor = [self.interpreter inputTensorAtIndex:0 error:&error];
[inputTensor copyData:currentData error:&error];
[self.interpreter invokeWithError:&error];
TFLTensor *outputTensor = [self.interpreter outputTensorAtIndex:0 error:&error];
NSData *outputData = [outputTensor dataWithError:&error];