-
Notifications
You must be signed in to change notification settings - Fork 414
/
TflitePlugin.mm
1501 lines (1295 loc) · 53.9 KB
/
TflitePlugin.mm
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
//#define CONTRIB_PATH
#define TFLITE2
#import "TflitePlugin.h"
#include <pthread.h>
#include <unistd.h>
#include <fstream>
#include <iostream>
#include <queue>
#include <sstream>
#include <string>
#ifdef CONTRIB_PATH
#include "tensorflow/contrib/lite/kernels/register.h"
#include "tensorflow/contrib/lite/model.h"
#include "tensorflow/contrib/lite/string_util.h"
#include "tensorflow/contrib/lite/op_resolver.h"
#elif defined TFLITE2
#import "TensorFlowLiteC.h"
#import "metal_delegate.h"
#else
#include "tensorflow/lite/kernels/register.h"
#include "tensorflow/lite/model.h"
#include "tensorflow/lite/string_util.h"
#include "tensorflow/lite/op_resolver.h"
#endif
#include "ios_image_load.h"
#define LOG(x) std::cerr
typedef void (^TfLiteStatusCallback)(TfLiteStatus);
NSString* loadModel(NSObject<FlutterPluginRegistrar>* _registrar, NSDictionary* args);
void runTflite(NSDictionary* args, TfLiteStatusCallback cb);
void runModelOnImage(NSDictionary* args, FlutterResult result);
void runModelOnBinary(NSDictionary* args, FlutterResult result);
void runModelOnFrame(NSDictionary* args, FlutterResult result);
void detectObjectOnImage(NSDictionary* args, FlutterResult result);
void detectObjectOnBinary(NSDictionary* args, FlutterResult result);
void detectObjectOnFrame(NSDictionary* args, FlutterResult result);
void runPix2PixOnImage(NSDictionary* args, FlutterResult result);
void runPix2PixOnBinary(NSDictionary* args, FlutterResult result);
void runPix2PixOnFrame(NSDictionary* args, FlutterResult result);
void runSegmentationOnImage(NSDictionary* args, FlutterResult result);
void runSegmentationOnBinary(NSDictionary* args, FlutterResult result);
void runSegmentationOnFrame(NSDictionary* args, FlutterResult result);
void runPoseNetOnImage(NSDictionary* args, FlutterResult result);
void runPoseNetOnBinary(NSDictionary* args, FlutterResult result);
void runPoseNetOnFrame(NSDictionary* args, FlutterResult result);
void close();
@implementation TflitePlugin {
NSObject<FlutterPluginRegistrar>* _registrar;
}
+ (void)registerWithRegistrar:(NSObject<FlutterPluginRegistrar>*)registrar {
FlutterMethodChannel* channel = [FlutterMethodChannel
methodChannelWithName:@"tflite"
binaryMessenger:[registrar messenger]];
TflitePlugin* instance = [[TflitePlugin alloc] initWithRegistrar:registrar];
[registrar addMethodCallDelegate:instance channel:channel];
}
- (instancetype)initWithRegistrar:(NSObject<FlutterPluginRegistrar>*)registrar {
self = [super init];
if (self) {
_registrar = registrar;
}
return self;
}
- (void)handleMethodCall:(FlutterMethodCall*)call result:(FlutterResult)result {
if ([@"loadModel" isEqualToString:call.method]) {
NSString* load_result = loadModel(_registrar, call.arguments);
result(load_result);
} else if ([@"runModelOnImage" isEqualToString:call.method]) {
runModelOnImage(call.arguments, result);
} else if ([@"runModelOnBinary" isEqualToString:call.method]) {
runModelOnBinary(call.arguments, result);
} else if ([@"runModelOnFrame" isEqualToString:call.method]) {
runModelOnFrame(call.arguments, result);
} else if ([@"detectObjectOnImage" isEqualToString:call.method]) {
detectObjectOnImage(call.arguments, result);
} else if ([@"detectObjectOnBinary" isEqualToString:call.method]) {
detectObjectOnBinary(call.arguments, result);
} else if ([@"detectObjectOnFrame" isEqualToString:call.method]) {
detectObjectOnFrame(call.arguments, result);
} else if ([@"runPix2PixOnImage" isEqualToString:call.method]) {
runPix2PixOnImage(call.arguments, result);
} else if ([@"runPix2PixOnBinary" isEqualToString:call.method]) {
runPix2PixOnBinary(call.arguments, result);
} else if ([@"runPix2PixOnFrame" isEqualToString:call.method]) {
runPix2PixOnFrame(call.arguments, result);
} else if ([@"runSegmentationOnImage" isEqualToString:call.method]) {
runSegmentationOnImage(call.arguments, result);
} else if ([@"runSegmentationOnBinary" isEqualToString:call.method]) {
runSegmentationOnBinary(call.arguments, result);
} else if ([@"runSegmentationOnFrame" isEqualToString:call.method]) {
runSegmentationOnFrame(call.arguments, result);
} else if ([@"runPoseNetOnImage" isEqualToString:call.method]) {
runPoseNetOnImage(call.arguments, result);
} else if ([@"runPoseNetOnBinary" isEqualToString:call.method]) {
runPoseNetOnBinary(call.arguments, result);
} else if ([@"runPoseNetOnFrame" isEqualToString:call.method]) {
runPoseNetOnFrame(call.arguments, result);
} else if ([@"close" isEqualToString:call.method]) {
close();
} else {
result(FlutterMethodNotImplemented);
}
}
@end
std::vector<std::string> labels;
#ifdef TFLITE2
TfLiteInterpreter *interpreter = nullptr;
TfLiteModel *model = nullptr;
TfLiteDelegate *delegate = nullptr;
#else
std::unique_ptr<tflite::FlatBufferModel> model;
std::unique_ptr<tflite::Interpreter> interpreter;
#endif
bool interpreter_busy = false;
static void LoadLabels(NSString* labels_path,
std::vector<std::string>* label_strings) {
if (!labels_path) {
LOG(ERROR) << "Failed to find label file at" << labels_path;
}
std::ifstream t;
t.open([labels_path UTF8String]);
label_strings->clear();
for (std::string line; std::getline(t, line); ) {
label_strings->push_back(line);
}
t.close();
}
NSString* loadModel(NSObject<FlutterPluginRegistrar>* _registrar, NSDictionary* args) {
NSString* graph_path;
NSString* key;
NSNumber* isAssetNumber = args[@"isAsset"];
bool isAsset = [isAssetNumber boolValue];
if(isAsset){
key = [_registrar lookupKeyForAsset:args[@"model"]];
graph_path = [[NSBundle mainBundle] pathForResource:key ofType:nil];
}else{
graph_path = args[@"model"];
}
const int num_threads = [args[@"numThreads"] intValue];
#ifdef TFLITE2
TfLiteInterpreterOptions *options = nullptr;
model = TfLiteModelCreateFromFile(graph_path.UTF8String);
if (!model) {
return [NSString stringWithFormat:@"%s %@", "Failed to mmap model", graph_path];
}
options = TfLiteInterpreterOptionsCreate();
TfLiteInterpreterOptionsSetNumThreads(options, num_threads);
bool useGpuDelegate = [args[@"useGpuDelegate"] boolValue];
if (useGpuDelegate) {
delegate = TFLGpuDelegateCreate(nullptr);
TfLiteInterpreterOptionsAddDelegate(options, delegate);
}
#else
model = tflite::FlatBufferModel::BuildFromFile([graph_path UTF8String]);
if (!model) {
return [NSString stringWithFormat:@"%s %@", "Failed to mmap model", graph_path];
}
LOG(INFO) << "Loaded model " << graph_path;
model->error_reporter();
LOG(INFO) << "resolved reporter";
#endif
if ([args[@"labels"] length] > 0) {
NSString* labels_path;
if(isAsset){
key = [_registrar lookupKeyForAsset:args[@"labels"]];
labels_path = [[NSBundle mainBundle] pathForResource:key ofType:nil];
}else{
labels_path = args[@"labels"];
}
LoadLabels(labels_path, &labels);
}
#ifdef TFLITE2
interpreter = TfLiteInterpreterCreate(model, options);
if (!interpreter) {
return @"Failed to construct interpreter";
}
if (TfLiteInterpreterAllocateTensors(interpreter) != kTfLiteOk) {
return @"Failed to allocate tensors!";
}
#else
tflite::ops::builtin::BuiltinOpResolver resolver;
tflite::InterpreterBuilder(*model, resolver)(&interpreter);
if (!interpreter) {
return @"Failed to construct interpreter";
}
if (interpreter->AllocateTensors() != kTfLiteOk) {
return @"Failed to allocate tensors!";
}
if (num_threads != -1) {
interpreter->SetNumThreads(num_threads);
}
#endif
return @"success";
}
void runTflite(NSDictionary* args, TfLiteStatusCallback cb) {
const bool asynch = [args[@"asynch"] boolValue];
if (asynch) {
interpreter_busy = true;
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^(void){
#ifdef TFLITE2
TfLiteStatus status = TfLiteInterpreterInvoke(interpreter);
#else
TfLiteStatus status = interpreter->Invoke();
#endif
dispatch_async(dispatch_get_main_queue(), ^(void){
interpreter_busy = false;
cb(status);
});
});
} else {
#ifdef TFLITE2
TfLiteStatus status = TfLiteInterpreterInvoke(interpreter);
#else
TfLiteStatus status = interpreter->Invoke();
#endif
cb(status);
}
}
NSMutableData *feedOutputTensor(int outputChannelsIn, float mean, float std, bool convertToUint8,
int *widthOut, int *heightOut) {
#ifdef TFLITE2
assert(TfLiteInterpreterGetOutputTensorCount(interpreter) == 1);
const TfLiteTensor* output_tensor = TfLiteInterpreterGetOutputTensor(interpreter, 0);
#else
assert(interpreter->outputs().size() == 1);
int output = interpreter->outputs()[0];
TfLiteTensor* output_tensor = interpreter->tensor(output);
#endif
const int width = output_tensor->dims->data[2];
const int channels = output_tensor->dims->data[3];
const int outputChannels = outputChannelsIn ? outputChannelsIn : channels;
assert(outputChannels >= channels);
if (widthOut) *widthOut = width;
if (heightOut) *heightOut = width;
NSMutableData *data = nil;
if (output_tensor->type == kTfLiteUInt8) {
int size = width*width*outputChannels;
data = [[NSMutableData dataWithCapacity: size] initWithLength: size];
uint8_t* out = (uint8_t*)[data bytes], *outEnd = out + width*width*outputChannels;
#ifdef TFLITE2
const uint8_t* bytes = output_tensor->data.uint8;
#else
const uint8_t* bytes = interpreter->typed_tensor<uint8_t>(output);
#endif
while (out != outEnd) {
for (int c = 0; c < channels; c++)
*out++ = *bytes++;
for (int c = 0; c < outputChannels - channels; c++)
*out++ = 255;
}
} else { // kTfLiteFloat32
if (convertToUint8) {
int size = width*width*outputChannels;
data = [[NSMutableData dataWithCapacity: size] initWithLength: size];
uint8_t* out = (uint8_t*)[data bytes], *outEnd = out + width*width*outputChannels;
#ifdef TFLITE2
const float* bytes = output_tensor->data.f;
#else
const float* bytes = interpreter->typed_tensor<float>(output);
#endif
while (out != outEnd) {
for (int c = 0; c < channels; c++)
*out++ = (*bytes++ * std) + mean;
for (int c = 0; c < outputChannels - channels; c++)
*out++ = 255;
}
} else { // kTfLiteFloat32
int size = width*width*outputChannels*4;
data = [[NSMutableData dataWithCapacity: size] initWithLength: size];
float* out = (float*)[data bytes], *outEnd = out + width*width*outputChannels;
#ifdef TFLITE2
float* bytes = output_tensor->data.f;
#else
const float* bytes = interpreter->typed_tensor<float>(output);
#endif
while (out != outEnd) {
for (int c = 0; c < channels; c++)
*out++ = (*bytes++ * std) + mean;
for (int c = 0; c < outputChannels - channels; c++)
*out++ = 255;
}
}
}
return data;
}
void feedInputTensorBinary(const FlutterStandardTypedData* typedData, int* input_size) {
#ifdef TFLITE2
assert(TfLiteInterpreterGetInputTensorCount(interpreter) == 1);
TfLiteTensor* input_tensor = TfLiteInterpreterGetInputTensor(interpreter, 0);
#else
assert(interpreter->inputs().size() == 1);
int input = interpreter->inputs()[0];
TfLiteTensor* input_tensor = interpreter->tensor(input);
#endif
const int width = input_tensor->dims->data[2];
*input_size = width;
NSData* in = [typedData data];
if (input_tensor->type == kTfLiteUInt8) {
#ifdef TFLITE2
TfLiteTensorCopyFromBuffer(input_tensor, in.bytes, in.length);
#else
uint8_t* out = interpreter->typed_tensor<uint8_t>(input);
const uint8_t* bytes = (const uint8_t*)[in bytes];
for (int index = 0; index < [in length]; index++)
out[index] = bytes[index];
#endif
} else { // kTfLiteFloat32
#ifdef TFLITE2
TfLiteTensorCopyFromBuffer(input_tensor, in.bytes, in.length);
#else
float* out = interpreter->typed_tensor<float>(input);
const float* bytes = (const float*)[in bytes];
for (int index = 0; index < [in length]/4; index++)
out[index] = bytes[index];
#endif
}
}
void feedInputTensor(uint8_t* in, int* input_size, int image_height, int image_width, int image_channels, float input_mean, float input_std) {
#ifdef TFLITE2
assert(TfLiteInterpreterGetInputTensorCount(interpreter) == 1);
TfLiteTensor* input_tensor = TfLiteInterpreterGetInputTensor(interpreter, 0);
#else
assert(interpreter->inputs().size() == 1);
int input = interpreter->inputs()[0];
TfLiteTensor* input_tensor = interpreter->tensor(input);
#endif
const int input_channels = input_tensor->dims->data[3];
const int width = input_tensor->dims->data[2];
const int height = input_tensor->dims->data[1];
*input_size = width;
if (input_tensor->type == kTfLiteUInt8) {
#ifdef TFLITE2
uint8_t* out = input_tensor->data.uint8;
#else
uint8_t* out = interpreter->typed_tensor<uint8_t>(input);
#endif
for (int y = 0; y < height; ++y) {
const int in_y = (y * image_height) / height;
uint8_t* in_row = in + (in_y * image_width * image_channels);
uint8_t* out_row = out + (y * width * input_channels);
for (int x = 0; x < width; ++x) {
const int in_x = (x * image_width) / width;
uint8_t* in_pixel = in_row + (in_x * image_channels);
uint8_t* out_pixel = out_row + (x * input_channels);
for (int c = 0; c < input_channels; ++c) {
out_pixel[c] = in_pixel[c];
}
}
}
} else { // kTfLiteFloat32
#ifdef TFLITE2
float* out = input_tensor->data.f;
#else
float* out = interpreter->typed_tensor<float>(input);
#endif
for (int y = 0; y < height; ++y) {
const int in_y = (y * image_height) / height;
uint8_t* in_row = in + (in_y * image_width * image_channels);
float* out_row = out + (y * width * input_channels);
for (int x = 0; x < width; ++x) {
const int in_x = (x * image_width) / width;
uint8_t* in_pixel = in_row + (in_x * image_channels);
float* out_pixel = out_row + (x * input_channels);
for (int c = 0; c < input_channels; ++c) {
out_pixel[c] = (in_pixel[c] - input_mean) / input_std;
}
}
}
}
}
void feedInputTensorImage(const NSString* image_path, float input_mean, float input_std, int* input_size) {
int image_channels;
int image_height;
int image_width;
std::vector<uint8_t> image_data = LoadImageFromFile([image_path UTF8String], &image_width, &image_height, &image_channels);
uint8_t* in = image_data.data();
feedInputTensor(in, input_size, image_height, image_width, image_channels, input_mean, input_std);
}
void feedInputTensorFrame(const FlutterStandardTypedData* typedData, int* input_size,
int image_height, int image_width, int image_channels, float input_mean, float input_std) {
uint8_t* in = (uint8_t*)[[typedData data] bytes];
feedInputTensor(in, input_size, image_height, image_width, image_channels, input_mean, input_std);
}
NSMutableArray* GetTopN(const float* prediction, const unsigned long prediction_size, const int num_results,
const float threshold) {
std::priority_queue<std::pair<float, int>, std::vector<std::pair<float, int>>,
std::greater<std::pair<float, int>>> top_result_pq;
std::vector<std::pair<float, int>> top_results;
const long count = prediction_size;
for (int i = 0; i < count; ++i) {
const float value = prediction[i];
if (value < threshold) {
continue;
}
top_result_pq.push(std::pair<float, int>(value, i));
if (top_result_pq.size() > num_results) {
top_result_pq.pop();
}
}
while (!top_result_pq.empty()) {
top_results.push_back(top_result_pq.top());
top_result_pq.pop();
}
std::reverse(top_results.begin(), top_results.end());
NSMutableArray* predictions = [NSMutableArray array];
for (const auto& result : top_results) {
const float confidence = result.first;
const int index = result.second;
NSString* labelObject = [NSString stringWithUTF8String:labels[index].c_str()];
NSNumber* valueObject = [NSNumber numberWithFloat:confidence];
NSMutableDictionary* res = [NSMutableDictionary dictionary];
[res setValue:[NSNumber numberWithInt:index] forKey:@"index"];
[res setObject:labelObject forKey:@"label"];
[res setObject:valueObject forKey:@"confidence"];
[predictions addObject:res];
}
return predictions;
}
void runModelOnImage(NSDictionary* args, FlutterResult result) {
const NSString* image_path = args[@"path"];
const float input_mean = [args[@"imageMean"] floatValue];
const float input_std = [args[@"imageStd"] floatValue];
NSMutableArray* empty = [@[] mutableCopy];
if (!interpreter || interpreter_busy) {
NSLog(@"Failed to construct interpreter or busy.");
return result(empty);
}
int input_size;
feedInputTensorImage(image_path, input_mean, input_std, &input_size);
runTflite(args, ^(TfLiteStatus status) {
if (status != kTfLiteOk) {
NSLog(@"Failed to invoke!");
return result(empty);
}
#ifdef TFLITE2
float* output = TfLiteInterpreterGetOutputTensor(interpreter, 0)->data.f;
#else
float* output = interpreter->typed_output_tensor<float>(0);
#endif
if (output == NULL)
return result(empty);
const unsigned long output_size = labels.size();
const int num_results = [args[@"numResults"] intValue];
const float threshold = [args[@"threshold"] floatValue];
return result(GetTopN(output, output_size, num_results, threshold));
});
}
void runModelOnBinary(NSDictionary* args, FlutterResult result) {
const FlutterStandardTypedData* typedData = args[@"binary"];
NSMutableArray* empty = [@[] mutableCopy];
if (!interpreter || interpreter_busy) {
NSLog(@"Failed to construct interpreter or busy.");
return result(empty);
}
int input_size;
feedInputTensorBinary(typedData, &input_size);
runTflite(args, ^(TfLiteStatus status) {
if (status != kTfLiteOk) {
NSLog(@"Failed to invoke!");
return result(empty);
}
#ifdef TFLITE2
float* output = TfLiteInterpreterGetOutputTensor(interpreter, 0)->data.f;
#else
float* output = interpreter->typed_output_tensor<float>(0);
#endif
if (output == NULL)
return result(empty);
const unsigned long output_size = labels.size();
const int num_results = [args[@"numResults"] intValue];
const float threshold = [args[@"threshold"] floatValue];
return result(GetTopN(output, output_size, num_results, threshold));
});
}
void runModelOnFrame(NSDictionary* args, FlutterResult result) {
const FlutterStandardTypedData* typedData = args[@"bytesList"][0];
const int image_height = [args[@"imageHeight"] intValue];
const int image_width = [args[@"imageWidth"] intValue];
const float input_mean = [args[@"imageMean"] floatValue];
const float input_std = [args[@"imageStd"] floatValue];
NSMutableArray* empty = [@[] mutableCopy];
if (!interpreter || interpreter_busy) {
NSLog(@"Failed to construct interpreter or busy.");
return result(empty);
}
int input_size;
int image_channels = 4;
feedInputTensorFrame(typedData, &input_size, image_height, image_width, image_channels, input_mean, input_std);
runTflite(args, ^(TfLiteStatus status) {
if (status != kTfLiteOk) {
NSLog(@"Failed to invoke!");
return result(empty);
}
#ifdef TFLITE2
float* output = TfLiteInterpreterGetOutputTensor(interpreter, 0)->data.f;
#else
float* output = interpreter->typed_output_tensor<float>(0);
#endif
if (output == NULL)
return result(empty);
const unsigned long output_size = labels.size();
const int num_results = [args[@"numResults"] intValue];
const float threshold = [args[@"threshold"] floatValue];
return result(GetTopN(output, output_size, num_results, threshold));
});
}
NSMutableArray* parseSSDMobileNet(float threshold, int num_results_per_class) {
#ifdef TFLITE2
assert(TfLiteInterpreterGetOutputTensorCount(interpreter) == 4);
#else
assert(interpreter->outputs().size() == 4);
#endif
NSMutableArray* results = [NSMutableArray array];
#ifdef TFLITE2
float* output_locations = TfLiteInterpreterGetOutputTensor(interpreter, 0)->data.f;
float* output_classes = TfLiteInterpreterGetOutputTensor(interpreter, 1)->data.f;
float* output_scores = TfLiteInterpreterGetOutputTensor(interpreter, 2)->data.f;
float* num_detections = TfLiteInterpreterGetOutputTensor(interpreter, 3)->data.f;
#else
float* output_locations = interpreter->typed_output_tensor<float>(0);
float* output_classes = interpreter->typed_output_tensor<float>(1);
float* output_scores = interpreter->typed_output_tensor<float>(2);
float* num_detections = interpreter->typed_output_tensor<float>(3);
#endif
NSMutableDictionary* counters = [NSMutableDictionary dictionary];
for (int d = 0; d < *num_detections; d++)
{
const int detected_class = output_classes[d];
float score = output_scores[d];
if (score < threshold) continue;
NSMutableDictionary* res = [NSMutableDictionary dictionary];
NSString* class_name = [NSString stringWithUTF8String:labels[detected_class + 1].c_str()];
NSObject* counter = [counters objectForKey:class_name];
if (counter) {
int countValue = [(NSNumber*)counter intValue] + 1;
if (countValue > num_results_per_class) {
continue;
}
[counters setObject:@(countValue) forKey:class_name];
} else {
[counters setObject:@(1) forKey:class_name];
}
[res setObject:@(score) forKey:@"confidenceInClass"];
[res setObject:class_name forKey:@"detectedClass"];
const float ymin = fmax(0, output_locations[d * 4]);
const float xmin = fmax(0, output_locations[d * 4 + 1]);
const float ymax = output_locations[d * 4 + 2];
const float xmax = output_locations[d * 4 + 3];
NSMutableDictionary* rect = [NSMutableDictionary dictionary];
[rect setObject:@(xmin) forKey:@"x"];
[rect setObject:@(ymin) forKey:@"y"];
[rect setObject:@(fmin(1 - xmin, xmax - xmin)) forKey:@"w"];
[rect setObject:@(fmin(1 - ymin, ymax - ymin)) forKey:@"h"];
[res setObject:rect forKey:@"rect"];
[results addObject:res];
}
return results;
}
float sigmoid(float x) {
return 1.0 / (1.0 + exp(-x));
}
void softmax(float vals[], int count) {
float max = -FLT_MAX;
for (int i=0; i<count; i++) {
max = fmax(max, vals[i]);
}
float sum = 0.0;
for (int i=0; i<count; i++) {
vals[i] = exp(vals[i] - max);
sum += vals[i];
}
for (int i=0; i<count; i++) {
vals[i] /= sum;
}
}
NSMutableArray* parseYOLO(int num_classes, const NSArray* anchors, int block_size, int num_boxes_per_bolock,
int num_results_per_class, float threshold, int input_size) {
#ifdef TFLITE2
float* output = TfLiteInterpreterGetOutputTensor(interpreter, 0)->data.f;
#else
float* output = interpreter->typed_output_tensor<float>(0);
#endif
NSMutableArray* results = [NSMutableArray array];
std::priority_queue<std::pair<float, NSMutableDictionary*>, std::vector<std::pair<float, NSMutableDictionary*>>,
std::less<std::pair<float, NSMutableDictionary*>>> top_result_pq;
int grid_size = input_size / block_size;
for (int y = 0; y < grid_size; ++y) {
for (int x = 0; x < grid_size; ++x) {
for (int b = 0; b < num_boxes_per_bolock; ++b) {
int offset = (grid_size * (num_boxes_per_bolock * (num_classes + 5))) * y
+ (num_boxes_per_bolock * (num_classes + 5)) * x
+ (num_classes + 5) * b;
float confidence = sigmoid(output[offset + 4]);
float classes[num_classes];
for (int c = 0; c < num_classes; ++c) {
classes[c] = output[offset + 5 + c];
}
softmax(classes, num_classes);
int detected_class = -1;
float max_class = 0;
for (int c = 0; c < num_classes; ++c) {
if (classes[c] > max_class) {
detected_class = c;
max_class = classes[c];
}
}
float confidence_in_class = max_class * confidence;
if (confidence_in_class > threshold) {
NSMutableDictionary* rect = [NSMutableDictionary dictionary];
NSMutableDictionary* res = [NSMutableDictionary dictionary];
float xPos = (x + sigmoid(output[offset + 0])) * block_size;
float yPos = (y + sigmoid(output[offset + 1])) * block_size;
float anchor_w = [[anchors objectAtIndex:(2 * b + 0)] floatValue];
float anchor_h = [[anchors objectAtIndex:(2 * b + 1)] floatValue];
float w = (float) (exp(output[offset + 2]) * anchor_w) * block_size;
float h = (float) (exp(output[offset + 3]) * anchor_h) * block_size;
float x = fmax(0, (xPos - w / 2) / input_size);
float y = fmax(0, (yPos - h / 2) / input_size);
[rect setObject:@(x) forKey:@"x"];
[rect setObject:@(y) forKey:@"y"];
[rect setObject:@(fmin(1 - x, w / input_size)) forKey:@"w"];
[rect setObject:@(fmin(1 - y, h / input_size)) forKey:@"h"];
[res setObject:rect forKey:@"rect"];
[res setObject:@(confidence_in_class) forKey:@"confidenceInClass"];
NSString* class_name = [NSString stringWithUTF8String:labels[detected_class].c_str()];
[res setObject:class_name forKey:@"detectedClass"];
top_result_pq.push(std::pair<float, NSMutableDictionary*>(confidence_in_class, res));
}
}
}
}
NSMutableDictionary* counters = [NSMutableDictionary dictionary];
while (!top_result_pq.empty()) {
NSMutableDictionary* result = top_result_pq.top().second;
top_result_pq.pop();
NSString* detected_class = [result objectForKey:@"detectedClass"];
NSObject* counter = [counters objectForKey:detected_class];
if (counter) {
int countValue = [(NSNumber*)counter intValue] + 1;
if (countValue > num_results_per_class) {
continue;
}
[counters setObject:@(countValue) forKey:detected_class];
} else {
[counters setObject:@(1) forKey:detected_class];
}
[results addObject:result];
}
return results;
}
void detectObjectOnImage(NSDictionary* args, FlutterResult result) {
const NSString* image_path = args[@"path"];
const NSString* model = args[@"model"];
const float threshold = [args[@"threshold"] floatValue];
const float input_mean = [args[@"imageMean"] floatValue];
const float input_std = [args[@"imageStd"] floatValue];
const int num_results_per_class = [args[@"numResultsPerClass"] intValue];
const NSArray* anchors = args[@"anchors"];
const int num_boxes_per_block = [args[@"numBoxesPerBlock"] intValue];
const int block_size = [args[@"blockSize"] floatValue];
NSMutableArray* empty = [@[] mutableCopy];
if (!interpreter || interpreter_busy) {
NSLog(@"Failed to construct interpreter or busy.");
return result(empty);
}
int input_size;
feedInputTensorImage(image_path, input_mean, input_std, &input_size);
runTflite(args, ^(TfLiteStatus status) {
if (status != kTfLiteOk) {
NSLog(@"Failed to invoke!");
return result(empty);
}
if ([model isEqual: @"SSDMobileNet"])
return result(parseSSDMobileNet(threshold, num_results_per_class));
else
return result(parseYOLO((int)labels.size(), anchors, block_size, num_boxes_per_block, num_results_per_class,
threshold, input_size));
});
}
void detectObjectOnBinary(NSDictionary* args, FlutterResult result) {
const FlutterStandardTypedData* typedData = args[@"binary"];
const NSString* model = args[@"model"];
const float threshold = [args[@"threshold"] floatValue];
const int num_results_per_class = [args[@"numResultsPerClass"] intValue];
const NSArray* anchors = args[@"anchors"];
const int num_boxes_per_block = [args[@"numBoxesPerBlock"] intValue];
const int block_size = [args[@"blockSize"] floatValue];
NSMutableArray* empty = [@[] mutableCopy];
if (!interpreter || interpreter_busy) {
NSLog(@"Failed to construct interpreter or busy.");
return result(empty);
}
int input_size;
feedInputTensorBinary(typedData, &input_size);
runTflite(args, ^(TfLiteStatus status) {
if (status != kTfLiteOk) {
NSLog(@"Failed to invoke!");
return result(empty);
}
if ([model isEqual: @"SSDMobileNet"])
return result(parseSSDMobileNet(threshold, num_results_per_class));
else
return result(parseYOLO((int)(labels.size() - 1), anchors, block_size, num_boxes_per_block, num_results_per_class,
threshold, input_size));
});
}
void detectObjectOnFrame(NSDictionary* args, FlutterResult result) {
const FlutterStandardTypedData* typedData = args[@"bytesList"][0];
const NSString* model = args[@"model"];
const int image_height = [args[@"imageHeight"] intValue];
const int image_width = [args[@"imageWidth"] intValue];
const float input_mean = [args[@"imageMean"] floatValue];
const float input_std = [args[@"imageStd"] floatValue];
const float threshold = [args[@"threshold"] floatValue];
const int num_results_per_class = [args[@"numResultsPerClass"] intValue];
const NSArray* anchors = args[@"anchors"];
const int num_boxes_per_block = [args[@"numBoxesPerBlock"] intValue];
const int block_size = [args[@"blockSize"] floatValue];
NSMutableArray* empty = [@[] mutableCopy];
if (!interpreter || interpreter_busy) {
NSLog(@"Failed to construct interpreter or busy.");
return result(empty);
}
int input_size;
int image_channels = 4;
feedInputTensorFrame(typedData, &input_size, image_height, image_width, image_channels, input_mean, input_std);
runTflite(args, ^(TfLiteStatus status) {
if (status != kTfLiteOk) {
NSLog(@"Failed to invoke!");
return result(empty);
}
if ([model isEqual: @"SSDMobileNet"])
return result(parseSSDMobileNet(threshold, num_results_per_class));
else
return result(parseYOLO((int)labels.size(), anchors, block_size, num_boxes_per_block, num_results_per_class,
threshold, input_size));
});
}
void runPix2PixOnImage(NSDictionary* args, FlutterResult result) {
const NSString* image_path = args[@"path"];
const float input_mean = [args[@"imageMean"] floatValue];
const float input_std = [args[@"imageStd"] floatValue];
const NSString* outputType = args[@"outputType"];
NSMutableArray* empty = [@[] mutableCopy];
if (!interpreter || interpreter_busy) {
NSLog(@"Failed to construct interpreter or busy.");
return result(empty);
}
int input_size;
feedInputTensorImage(image_path, input_mean, input_std, &input_size);
runTflite(args, ^(TfLiteStatus status) {
if (status != kTfLiteOk) {
NSLog(@"Failed to invoke!");
return result(empty);
}
int width = 0, height = 0;
NSMutableData* output = feedOutputTensor(4, input_mean, input_std, true, &width, &height);
if (output == NULL)
return result(empty);
if ([outputType isEqual: @"png"]) {
return result(CompressImage(output, width, height, 1));
} else {
return result(output);
}
});
}
void runPix2PixOnBinary(NSDictionary* args, FlutterResult result) {
const FlutterStandardTypedData* typedData = args[@"binary"];
NSMutableArray* empty = [@[] mutableCopy];
if (!interpreter || interpreter_busy) {
NSLog(@"Failed to construct interpreter or busy.");
return result(empty);
}
int input_size;
feedInputTensorBinary(typedData, &input_size);
runTflite(args, ^(TfLiteStatus status) {
if (status != kTfLiteOk) {
NSLog(@"Failed to invoke!");
return result(empty);
}
int width = 0, height = 0;
NSMutableData* output = feedOutputTensor(0, 0, 1, false, &width, &height);
if (output == NULL)
return result(empty);
return result(output);
});
}
void runPix2PixOnFrame(NSDictionary* args, FlutterResult result) {
const FlutterStandardTypedData* typedData = args[@"bytesList"][0];
const int image_height = [args[@"imageHeight"] intValue];
const int image_width = [args[@"imageWidth"] intValue];
const float input_mean = [args[@"imageMean"] floatValue];
const float input_std = [args[@"imageStd"] floatValue];
const NSString* outputType = args[@"outputType"];
NSMutableArray* empty = [@[] mutableCopy];
if (!interpreter || interpreter_busy) {
NSLog(@"Failed to construct interpreter or busy.");
return result(empty);
}
int input_size;
int image_channels = 4;
feedInputTensorFrame(typedData, &input_size, image_height, image_width, image_channels, input_mean, input_std);
runTflite(args, ^(TfLiteStatus status) {
if (status != kTfLiteOk) {
NSLog(@"Failed to invoke!");
return result(empty);
}
int width = 0, height = 0;
NSMutableData* output = feedOutputTensor(image_channels, input_mean, input_std, true, &width, &height);
if (output == NULL)
return result(empty);
if ([outputType isEqual: @"png"]) {
return result(CompressImage(output, width, height, 1));
} else {
return result(output);
}
});
}
void setPixel(char* rgba, int index, long color) {
rgba[index * 4] = (color >> 16) & 0xFF;
rgba[index * 4 + 1] = (color >> 8) & 0xFF;
rgba[index * 4 + 2] = color & 0xFF;
rgba[index * 4 + 3] = (color >> 24) & 0xFF;
}
NSData* fetchArgmax(const NSArray* labelColors, const NSString* outputType) {
#ifdef TFLITE2
const TfLiteTensor* output_tensor = TfLiteInterpreterGetOutputTensor(interpreter, 0);
#else
int output = interpreter->outputs()[0];
TfLiteTensor* output_tensor = interpreter->tensor(output);
#endif
const int height = output_tensor->dims->data[1];
const int width = output_tensor->dims->data[2];
const int channels = output_tensor->dims->data[3];
NSMutableData *data = nil;
int size = height * width * 4;
data = [[NSMutableData dataWithCapacity: size] initWithLength: size];
char* out = (char*)[data bytes];
if (output_tensor->type == kTfLiteUInt8) {
#ifdef TFLITE2
const uint8_t* bytes = output_tensor->data.uint8;
#else
const uint8_t* bytes = interpreter->typed_tensor<uint8_t>(output);
#endif
for (int i = 0; i < height; ++i) {
for (int j = 0; j < width; ++j) {
int index = i * width + j;
int maxIndex = 0;
int maxValue = 0;
for (int c = 0; c < channels; ++c) {
int outputValue = bytes[index* channels + c];
if (outputValue > maxValue) {
maxIndex = c;
maxValue = outputValue;
}
}
long labelColor = [[labelColors objectAtIndex:maxIndex] longValue];
setPixel(out, index, labelColor);
}
}
} else { // kTfLiteFloat32
#ifdef TFLITE2
const float* bytes = output_tensor->data.f;
#else
const float* bytes = interpreter->typed_tensor<float>(output);
#endif
for (int i = 0; i < height; ++i) {
for (int j = 0; j < width; ++j) {
int index = i * width + j;
int maxIndex = 0;
float maxValue = .0f;
for (int c = 0; c < channels; ++c) {
float outputValue = bytes[index * channels + c];